Example usage for org.apache.commons.lang StringUtils stripEnd

List of usage examples for org.apache.commons.lang StringUtils stripEnd

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils stripEnd.

Prototype

public static String stripEnd(String str, String stripChars) 

Source Link

Document

Strips any of a set of characters from the end of a String.

Usage

From source file:com.opengamma.component.tool.ToolContextUtils.java

private static ToolContext createToolContextByHttp(String configResourceLocation,
        Class<? extends ToolContext> toolContextClazz, List<String> classifierChain) {
    configResourceLocation = StringUtils.stripEnd(configResourceLocation, "/");
    if (configResourceLocation.endsWith("/jax") == false) {
        configResourceLocation += "/jax";
    }/*  w  w  w.j  ava 2  s . c om*/

    // Get the remote component server using the supplied URI
    RemoteComponentServer remoteComponentServer = new RemoteComponentServer(URI.create(configResourceLocation));
    ComponentServer componentServer = remoteComponentServer.getComponentServer();

    // Attempt to build a tool context of the specified type
    ToolContext toolContext;
    try {
        toolContext = toolContextClazz.newInstance();
    } catch (Throwable t) {
        return null;
    }

    // Populate the tool context from the remote component server
    for (MetaProperty<?> metaProperty : toolContext.metaBean().metaPropertyIterable()) {
        if (!metaProperty.name().equals("contextManager")) {
            try {
                ComponentInfo componentInfo = getComponentInfo(componentServer, classifierChain,
                        metaProperty.propertyType());
                if (componentInfo == null) {
                    s_logger.warn("Unable to populate tool context '" + metaProperty.name()
                            + "', no appropriate component found on the server");
                    continue;
                }
                if (ViewProcessor.class.equals(componentInfo.getType())) {
                    final JmsConnector jmsConnector = createJmsConnector(componentInfo);
                    final ScheduledExecutorService scheduler = Executors
                            .newSingleThreadScheduledExecutor(new NamedThreadFactory("rvp"));
                    ViewProcessor vp = new RemoteViewProcessor(componentInfo.getUri(), jmsConnector, scheduler);
                    toolContext.setViewProcessor(vp);
                    toolContext.setContextManager(new Closeable() {
                        @Override
                        public void close() throws IOException {
                            scheduler.shutdownNow();
                            jmsConnector.close();
                        }
                    });
                } else {
                    String clazzName = componentInfo.getAttribute(ComponentInfoAttributes.REMOTE_CLIENT_JAVA);
                    if (clazzName == null) {
                        s_logger.warn("Unable to populate tool context '" + metaProperty.name()
                                + "', no remote access class found");
                        continue;
                    }
                    Class<?> clazz = Class.forName(clazzName);
                    metaProperty.set(toolContext,
                            clazz.getConstructor(URI.class).newInstance(componentInfo.getUri()));
                    s_logger.info("Populated tool context '" + metaProperty.name() + "' with "
                            + metaProperty.get(toolContext));
                }
            } catch (Throwable ex) {
                s_logger.warn(
                        "Unable to populate tool context '" + metaProperty.name() + "': " + ex.getMessage());
            }
        }
    }
    return toolContext;
}

From source file:edu.ku.brc.specify.tools.FixMetaTags.java

static public String getContents(File aFile) {
    //...checks on aFile are elided
    StringBuffer contents = new StringBuffer();

    //System.out.println(aFile.getName());
    //declared here only to make visible to finally clause
    BufferedReader input = null;/*from  ww w  . java 2s.  c o m*/
    try {
        String eol = System.getProperty("line.separator");

        System.out.println("\n" + aFile.getName());
        //use buffering
        //this implementation reads one line at a time
        //FileReader always assumes default encoding is OK!
        input = new BufferedReader(new FileReader(aFile));
        String line = null; //not declared within while loop
        //boolean doIt = false;
        int cnt = 0;
        boolean doComment = true;
        boolean doClassDesc = true;
        while ((line = input.readLine()) != null) {
            cnt++;
            boolean addLine = true;

            if (doComment) {
                int inx = line.indexOf("<!--");
                if (inx > -1) {
                    do {
                        line = input.readLine();
                        cnt++;
                    } while (line.indexOf("-->") == -1);
                    doComment = false;
                    continue;
                }
            }

            if (doComment && line.indexOf("<class") > -1) {
                doComment = false;
            }

            if (doClassDesc) {
                int inx = line.indexOf("class-description");
                if (inx > -1) {
                    do {
                        line = input.readLine();
                        cnt++;
                    } while (line.indexOf("</meta>") == -1);
                    contents.append("    <meta attribute=\"class-description\" inherit=\"false\"/>");
                    contents.append(eol);
                    doClassDesc = false;
                    continue;
                }
            }

            int ccInx = line.indexOf("class-code");
            int inx = line.indexOf("<meta");
            if (inx > -1 && ccInx == -1) {
                inx = line.indexOf("</meta>");
                if (inx == -1) {
                    String textLine = input.readLine();
                    cnt++;
                    String endTag = null;
                    if (textLine.indexOf("</meta>") == -1) {
                        endTag = input.readLine();
                        cnt++;
                    }

                    if (endTag != null && endTag.indexOf("</meta>") == -1) {
                        throw new RuntimeException("Assumption bad about end tab. line " + cnt);
                    }
                    contents.append(StringUtils.stripEnd(line, " "));
                    contents.append(StringUtils.strip(textLine));
                    if (endTag != null) {
                        contents.append(StringUtils.strip(endTag));
                    }
                    contents.append(eol);

                    addLine = false;
                }
            }

            if (addLine) {
                contents.append(line);
                contents.append(System.getProperty("line.separator"));
            }
        }
    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        try {
            if (input != null) {
                //flush and close both "input" and its underlying FileReader
                input.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    return contents.toString();
}

From source file:com.adobe.communities.ugc.migration.export.GenericExportServlet.java

@Override
protected void doGet(final SlingHttpServletRequest request, final SlingHttpServletResponse response)
        throws ServletException, IOException {

    if (!request.getRequestParameterMap().containsKey("path")) {
        throw new ServletException("No path specified for export. Exiting.");
    }//  www  .  j ava2  s .c  om
    final String path = StringUtils.stripEnd(request.getRequestParameter("path").getString(), "/");
    final Resource resource = request.getResourceResolver().getResource(path);
    if (resource == null) {
        throw new ServletException("Could not find a valid resource for export");
    }
    File outFile = null;
    try {
        outFile = File.createTempFile(UUID.randomUUID().toString(), ".zip");
        if (!outFile.canWrite()) {
            throw new ServletException("Cannot write to specified output file");
        }
        response.setContentType("application/octet-stream");
        final String headerKey = "Content-Disposition";
        final String headerValue = "attachment; filename=\"export.zip\"";
        response.setHeader(headerKey, headerValue);

        FileOutputStream fos = new FileOutputStream(outFile);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        zip = new ZipOutputStream(bos);
        OutputStream outStream = null;
        InputStream inStream = null;
        try {
            exportContent(resource, path);
            IOUtils.closeQuietly(zip);
            IOUtils.closeQuietly(bos);
            IOUtils.closeQuietly(fos);
            // obtains response's output stream
            outStream = response.getOutputStream();
            inStream = new FileInputStream(outFile);
            // copy from file to output
            IOUtils.copy(inStream, outStream);
        } catch (final IOException e) {
            throw new ServletException(e);
        } catch (final Exception e) {
            throw new ServletException(e);
        } finally {
            IOUtils.closeQuietly(zip);
            IOUtils.closeQuietly(bos);
            IOUtils.closeQuietly(fos);
            IOUtils.closeQuietly(inStream);
            IOUtils.closeQuietly(outStream);
        }
    } finally {
        if (outFile != null) {
            outFile.delete();
        }
    }
}

From source file:com.adobe.communities.ugc.migration.legacyExport.GenericExportServlet.java

@Override
protected void doGet(final SlingHttpServletRequest request, final SlingHttpServletResponse response)
        throws ServletException, IOException {

    if (!request.getRequestParameterMap().containsKey("path")) {
        throw new ServletException("No path specified for export. Exiting.");
    }/*from   ww  w.  j av a  2  s  .com*/
    final String path = StringUtils.stripEnd(request.getRequestParameter("path").getString(), "/");
    final Resource resource = request.getResourceResolver().getResource(path);
    if (resource == null) {
        throw new ServletException("Could not find a valid resource for export");
    }
    entries = new HashMap<String, Boolean>();
    entriesToSkip = new HashMap<String, Boolean>();
    File outFile = null;
    try {
        outFile = File.createTempFile(UUID.randomUUID().toString(), ".zip");
        if (!outFile.canWrite()) {
            throw new ServletException("Cannot write to specified output file");
        }
        response.setContentType("application/octet-stream");
        final String headerKey = "Content-Disposition";
        final String headerValue = "attachment; filename=\"export.zip\"";
        response.setHeader(headerKey, headerValue);

        FileOutputStream fos = new FileOutputStream(outFile);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        zip = new ZipOutputStream(bos);
        OutputStream outStream = null;
        InputStream inStream = null;
        try {
            exportContent(resource, path);
            if (entries.size() > 0) {
                exportCommentSystems(entries, entriesToSkip, resource, path);
            }
            IOUtils.closeQuietly(zip);
            IOUtils.closeQuietly(bos);
            IOUtils.closeQuietly(fos);
            // obtains response's output stream
            outStream = response.getOutputStream();
            inStream = new FileInputStream(outFile);
            // copy from file to output
            IOUtils.copy(inStream, outStream);
        } catch (final IOException e) {
            throw new ServletException(e);
        } catch (final Exception e) {
            throw new ServletException(e);
        } finally {
            IOUtils.closeQuietly(zip);
            IOUtils.closeQuietly(bos);
            IOUtils.closeQuietly(fos);
            IOUtils.closeQuietly(inStream);
            IOUtils.closeQuietly(outStream);
        }
    } finally {
        if (outFile != null) {
            outFile.delete();
        }
    }
}

From source file:edu.ku.brc.af.ui.ESTermParser.java

@Override
public boolean parse(final String searchTermArg, final boolean parseAsSingleTerm) {
    instance.fields.clear();/*  w w w. ja va  2s .  co  m*/

    //DateWrapper scrDateFormat = AppPrefsCache.getDateWrapper("ui", "formatting", "scrdateformat");
    int currentYear = Calendar.getInstance().get(Calendar.YEAR);
    String searchTerm = searchTermArg;
    DateParser dd = new DateParser(instance.scrDateFormat.getSimpleDateFormat().toPattern());

    //----------------------------------------------------------------------------------------------
    // NOTE: If a full date was type in and it was parsed as such
    // and it couldn't be something else, then it only searches date fields.
    //----------------------------------------------------------------------------------------------

    int cnt = 0;

    if (searchTerm.length() > 0) {
        if (StringUtils.contains(searchTerm, '\\')) {
            return false;
        }

        String[] terms;

        boolean startWith = searchTerm.startsWith("*");
        boolean endsWith = searchTerm.endsWith("*");

        searchTerm = StringUtils.remove(searchTerm, '*');

        if (searchTerm.startsWith("\"") || searchTerm.startsWith("'") || searchTerm.startsWith("`")) {
            searchTerm = StringUtils.stripStart(searchTerm, "\"'`");
            searchTerm = StringUtils.stripEnd(searchTerm, "\"'`");
            terms = new String[] { searchTerm };

        } else if (parseAsSingleTerm) {
            terms = new String[] { searchTerm };

        } else {
            terms = StringUtils.split(searchTerm, ' ');
        }

        if (terms.length == 1) {
            terms[0] = (startWith ? "*" : "") + terms[0] + (endsWith ? "*" : "");
        } else {

            terms[0] = (startWith ? "*" : "") + terms[0];
            terms[terms.length - 1] = terms[terms.length - 1] + (endsWith ? "*" : "");
        }

        for (String term : terms) {
            if (StringUtils.isEmpty(term)) {
                continue;
            }

            SearchTermField stf = new SearchTermField(term);

            if (stf.isSingleChar()) {
                return false;
            }
            instance.fields.add(stf);

            cnt += !stf.isSingleChar() ? 1 : 0;

            //log.debug(term);
            String termStr = term;

            if (termStr.startsWith("*")) {
                stf.setOption(SearchTermField.STARTS_WILDCARD);
                termStr = termStr.substring(1);
                stf.setTerm(termStr);
            }

            if (termStr.endsWith("*")) {
                stf.setOption(SearchTermField.ENDS_WILDCARD);
                termStr = termStr.substring(0, termStr.length() - 1);
                stf.setTerm(termStr);
            }

            // First check to see if it is all numeric.
            if (StringUtils.isNumeric(termStr)) {
                stf.setOption(SearchTermField.IS_NUMERIC);
                if (StringUtils.contains(termStr, '.')) {
                    stf.setOption(SearchTermField.HAS_DEC_POINT);
                }

                if (!stf.isOn(SearchTermField.HAS_DEC_POINT) && termStr.length() == 4) {
                    int year = Integer.parseInt(termStr);
                    if (year > 1000 && year <= currentYear) {
                        stf.setOption(SearchTermField.IS_YEAR_OF_DATE);
                    }
                }
            } else {
                // Check to see if it is date
                Date searchDate = dd.parseDate(searchTermArg);
                if (searchDate != null) {
                    try {
                        termStr = dbDateFormat.format(searchDate);
                        stf.setTerm(termStr);
                        stf.setOption(SearchTermField.IS_DATE);

                    } catch (Exception ex) {
                        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ESTermParser.class, ex);
                        // should never get here
                    }
                }
            }
        }
    }

    return instance.fields.size() > 0 && cnt > 0;
}

From source file:com.thoughtworks.gauge.scan.RegistryMethodVisitor.java

private String trimQuotes(String text) {
    return StringUtils.stripEnd(StringUtils.stripStart(text, "\""), "\"");
}

From source file:com.opengamma.integration.viewer.RemoteEngine.java

private void init(String baseUrl) {
    baseUrl = StringUtils.stripEnd(baseUrl, "/");
    if (baseUrl.endsWith("/jax") == false) {
        baseUrl += "/jax";
    }// w  w  w.  j  a  v  a2  s. c  om

    _fudgeContext = OpenGammaFudgeContext.getInstance();
    final URI componentsUri = URI.create(baseUrl);
    final RemoteComponentServer remote = new RemoteComponentServer(componentsUri);
    _components = remote.getComponentServer();
    _configurationURI = URI.create(baseUrl + "/configuration/0");
    _configuration = FudgeRestClient.create().accessFudge(_configurationURI).get(FudgeMsg.class);
    final String activeMQBroker = _configuration.getString("activeMQ");
    final JmsConnectorFactoryBean factory = new JmsConnectorFactoryBean();
    factory.setName(getClass().getSimpleName());
    factory.setClientBrokerUri(URI.create(activeMQBroker));
    factory.setConnectionFactory(new ActiveMQConnectionFactory(factory.getClientBrokerUri()));
    _jmsConnector = factory.getObjectCreating();
}

From source file:com.intuit.tank.vm.common.util.JSONBuilder.java

private Object findValueOfType(String value) {
    if (StringUtils.isEmpty(value) || "null".equalsIgnoreCase(value)) {
        return JSONObject.NULL;
    }//from w  w  w. ja v  a 2 s. com
    try {
        if (!value.startsWith("0")) {
            if (value.matches("^\\d*$")) {
                return Long.valueOf(value);
            }
            if (value.matches("^\\d*\\.\\d+")) {
                return Double.valueOf(value);
            }

            if (value.equalsIgnoreCase("true")) {
                return Boolean.TRUE;
            }
            if (value.equalsIgnoreCase("false")) {
                return Boolean.FALSE;
            }
        }
    } catch (NumberFormatException e) {
        LOG.warn("Error rying to parse a number  value: " + e);
    }
    // strip leading and trainling quotes
    value = StringUtils.stripEnd(value, "\"");
    value = StringUtils.stripStart(value, "\"");
    return value;
}

From source file:edu.ku.brc.specify.tasks.subpane.images.ImageDataItem.java

/**
 * @param bd//from   w  w w  .  j av a 2s  .com
 * @return
 */
private String convert(final Object obj) {
    if (obj != null) {
        String str = null;
        if (obj instanceof BigDecimal) {
            str = StringUtils.stripEnd(obj.toString(), "0");
        } else if (obj instanceof Double) {
            str = String.format("%7.3f", (Double) obj);
        } else if (obj instanceof Float) {
            str = String.format("%7.3f", (Float) obj);
        }

        if (str != null) {
            return str.endsWith(".") ? str + "0" : str;
        }
    }
    return null;
}

From source file:gda.jython.logger.RedirectableFileLogger.java

@Override
public void log(String msg) {
    String lines[] = msg.split("\\r?\\n");
    for (String line : lines) {
        String stripEnd = StringUtils.stripEnd(line, null);
        if (logger.isDebugEnabled()) {
            logger.debug(" | " + stripEnd);
        }//from   ww w .  j a  va  2  s. co  m
        localLogger.info(stripEnd);
    }
}