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

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

Introduction

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

Prototype

public static String trim(String str) 

Source Link

Document

Removes control characters (char <= 32) from both ends of this String, handling null by returning null.

Usage

From source file:com.taobao.android.builder.tasks.app.prepare.PreparePackageIdsTask.java

/**
 * ?packageId/*from   w  ww .  j  av  a  2 s  .c  o  m*/
 *
 * @param packageIdFile
 * @return
 */
private Map<String, String> loadPackageIdProperties(File packageIdFile) throws IOException {
    Map<String, String> values = new HashMap<String, String>();
    if (null != packageIdFile && packageIdFile.exists() && packageIdFile.isFile()) {
        List<String> lines = FileUtils.readLines(packageIdFile);
        for (String line : lines) {
            String[] lineValues = StringUtils.split(line, "=");
            if (null != lineValues && lineValues.length >= 2) {
                String key = StringUtils.trim(lineValues[0]);
                String value = StringUtils.trim(lineValues[1]);
                values.put(key, value);
            }
        }
    }
    return values;
}

From source file:com.ibm.jaggr.core.impl.modulebuilder.css.CSSModuleBuilder.java

/**
 * Processes the input CSS to replace &#064;import statements with the
 * contents of the imported CSS.  The imported CSS is minified, image
 * URLs in-lined, and this method recursively called to in-line nested
 * &#064;imports./*from   ww  w.  j a va  2  s  .  c  o m*/
 *
 * @param req
 *            The request associated with the call.
 * @param css
 *            The current CSS containing &#064;import statements to be
 *            processed
 * @param res
 *            The resource for the CSS file.
 * @param path
 *            The path, as specified in the &#064;import statement used to
 *            import the current CSS, or null if this is the top level CSS.
 *
 * @return The input CSS with &#064;import statements replaced with the
 *         contents of the imported files.
 *
 * @throws IOException
 */
protected String inlineImports(HttpServletRequest req, String css, IResource res, String path)
        throws IOException {

    // In-lining of imports can be disabled by request parameter for debugging
    if (!TypeUtil.asBoolean(req.getParameter(INLINEIMPORTS_REQPARAM_NAME), true)) {
        return css;
    }

    StringBuffer buf = new StringBuffer();
    IAggregator aggregator = (IAggregator) req.getAttribute(IAggregator.AGGREGATOR_REQATTRNAME);
    IOptions options = aggregator.getOptions();
    /*
     * True if we should include the name of imported CSS files in a comment at
     * the beginning of the file.
     */
    boolean includePreamble = TypeUtil.asBoolean(req.getAttribute(IHttpTransport.SHOWFILENAMES_REQATTRNAME))
            && (options.isDebugMode() || options.isDevelopmentMode());
    if (includePreamble && path != null && path.length() > 0) {
        buf.append("/* @import " + path + " */\r\n"); //$NON-NLS-1$ //$NON-NLS-2$
    }
    Matcher m = importPattern.matcher(css);
    while (m.find()) {
        String fullMatch = m.group(0);
        String importNameMatch = m.group(2);
        String mediaTypes = m.group(4);
        /*
         * CSS rules require that all @import statements appear before any
         * style definitions within a document. Most browsers simply ignore
         * @import statements which appear following any styles definitions.
         * This means that once we've inlined an @import, then we can't not
         * inline any subsequent @imports. The implication is that all
         * @imports which cannot be inlined (i.e. non-relative url or device
         * specific media types) MUST appear before any @import that is
         * inlined. For this reason, we throw an error if we encounter an
         * @import which we cannot inline if we have already inlined a
         * previous @import.
         */

        //Only process media type "all" or empty media type rules.
        if (mediaTypes.length() > 0 && !"all".equals(StringUtils.trim(mediaTypes))) { //$NON-NLS-1$
            m.appendReplacement(buf, ""); //$NON-NLS-1$
            buf.append(fullMatch);
            continue;
        }
        // remove quotes.
        importNameMatch = dequote(importNameMatch);
        importNameMatch = forwardSlashPattern.matcher(importNameMatch).replaceAll("/"); //$NON-NLS-1$

        if (importNameMatch.startsWith("/") || protocolPattern.matcher(importNameMatch).find()) { //$NON-NLS-1$
            m.appendReplacement(buf, ""); //$NON-NLS-1$
            buf.append(fullMatch);
            continue;
        }

        IResource importRes = res.resolve(importNameMatch);
        URI uri = null;
        if (importRes.exists()) {
            uri = importRes.getURI();
        } else if (includeAMDPaths && importNameMatch.contains("/") && !importNameMatch.startsWith(".")) { //$NON-NLS-1$ //$NON-NLS-2$
            // Resource not found using relative path to res.  If path is not relative (starts with .)
            // then try to find the resource using config paths and packages.
            uri = aggregator.getConfig().locateModuleResource(importNameMatch);
            if (uri != null) {
                uri = aggregator.newResource(uri).getURI();
            }
        }
        if (uri == null) {
            throw new NotFoundException(importNameMatch);
        }

        String importCss = null;
        importCss = readToString(
                new CommentStrippingReader(new InputStreamReader(uri.toURL().openStream(), "UTF-8" //$NON-NLS-1$
                )));
        importCss = minify(importCss, importRes);
        // Inline images
        importCss = inlineImageUrls(req, importCss, importRes);

        if (inlineImports) {
            importCss = inlineImports(req, importCss, importRes, importNameMatch);
        }
        m.appendReplacement(buf, ""); //$NON-NLS-1$
        buf.append(importCss);
    }
    m.appendTail(buf);

    css = buf.toString();
    /*
     * Now re-write all relative URLs in url(...) statements to make them relative
     * to the importing CSS
     */
    if (path != null && path.length() > 0) {
        int idx = path.lastIndexOf("/"); //$NON-NLS-1$
        //Make a file path based on the last slash.
        //If no slash, so must be just a file name. Use empty string then.
        path = (idx != -1) ? path.substring(0, idx + 1) : ""; //$NON-NLS-1$
        buf = new StringBuffer();
        m = urlPattern.matcher(css);
        while (m.find()) {
            String fullMatch = m.group(0);
            String urlMatch = m.group(1);

            urlMatch = StringUtils.trim(urlMatch.replace("\\", "/")); //$NON-NLS-1$ //$NON-NLS-2$
            String quoted = ""; //$NON-NLS-1$
            if (urlMatch.charAt(0) == '"' && urlMatch.charAt(urlMatch.length() - 1) == '"') {
                quoted = "\""; //$NON-NLS-1$
                urlMatch = urlMatch.substring(1, urlMatch.length() - 1);
            } else if (urlMatch.charAt(0) == '\'' && urlMatch.charAt(urlMatch.length() - 1) == '\'') {
                quoted = "'"; //$NON-NLS-1$
                urlMatch = urlMatch.substring(1, urlMatch.length() - 1);
            }

            // Don't modify non-relative URLs
            if (urlMatch.startsWith("/") || urlMatch.startsWith("#") //$NON-NLS-1$//$NON-NLS-2$
                    || protocolPattern.matcher(urlMatch).find()) {
                m.appendReplacement(buf, ""); //$NON-NLS-1$
                buf.append(fullMatch);
                continue;
            }

            String fixedUrl = path + ((path.endsWith("/") || path.length() == 0) ? "" : "/") + urlMatch; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
            //Collapse '..' and '.'
            String[] parts = fixedUrl.split("/"); //$NON-NLS-1$
            for (int i = parts.length - 1; i > 0; i--) {
                if (".".equals(parts[i])) { //$NON-NLS-1$
                    parts = (String[]) ArrayUtils.remove(parts, i);
                } else if ("..".equals(parts[i])) { //$NON-NLS-1$
                    if (i != 0 && !"..".equals(parts[i - 1])) { //$NON-NLS-1$
                        parts = (String[]) ArrayUtils.remove(parts, i - 1);
                        parts = (String[]) ArrayUtils.remove(parts, i - 1);
                    }
                }
            }
            m.appendReplacement(buf, ""); //$NON-NLS-1$
            buf.append("url(") //$NON-NLS-1$
                    .append(quoted).append(StringUtils.join(parts, "/")) //$NON-NLS-1$
                    .append(quoted).append(")"); //$NON-NLS-1$
        }
        m.appendTail(buf);
        css = buf.toString();
    }
    return css;
}

From source file:com.openteach.diamond.service.DiamondServiceFactory.java

/**
 * //from  w  ww .  j a v  a  2s  .  c o  m
 * @param properties
 * @param repositoryClient
 * @return
 */
private static MetadataWriteService newMetadataWriteService(Properties properties,
        RepositoryClient repositoryClient) {
    String factoryClassName = StringUtils.trim(properties.getProperty(METADATA_WRITE_FACTORY));
    if (StringUtils.isBlank(factoryClassName)) {
        throw new IllegalArgumentException(String.format("Please set %s", METADATA_WRITE_FACTORY));
    }
    try {
        Class<?> clazz = Class.forName(factoryClassName);
        MetadataWriteServiceFactory factory = (MetadataWriteServiceFactory) clazz.newInstance();
        return factory.newMetadataWriteService(repositoryClient);
    } catch (ClassNotFoundException e) {
        throw new IllegalArgumentException("OOPS, new metadata write service failed", e);
    } catch (InstantiationException e) {
        throw new IllegalArgumentException("OOPS, new metadata write service failed", e);
    } catch (IllegalAccessException e) {
        throw new IllegalArgumentException("OOPS, new metadata write service failed", e);
    }
}

From source file:com.hangum.tadpole.manager.core.editor.executedsql.SQLAuditEditor.java

/**
 * search//  w ww  .  ja v a  2s  . c o  m
 */
private void search() {
    //  ? ?? .
    clearGrid();
    mapSQLHistory.clear();

    String strEmail = "%" + StringUtils.trim(textEmail.getText()) + "%"; //$NON-NLS-1$ //$NON-NLS-2$

    // check all db
    String db_seq = ""; //$NON-NLS-1$
    if (!comboDatabase.getText().equals("All")) { //$NON-NLS-1$
        searchUserDBDAO = (UserDBDAO) comboDatabase.getData(comboDatabase.getText());
        db_seq = "" + searchUserDBDAO.getSeq(); //$NON-NLS-1$
    } else {
        searchUserDBDAO = null;
        for (int i = 0; i < listUserDBDAO.size(); i++) {
            UserDBDAO userDB = listUserDBDAO.get(i);
            if (i == (listUserDBDAO.size() - 1))
                db_seq += ("" + userDB.getSeq()); //$NON-NLS-1$
            else
                db_seq += userDB.getSeq() + ","; //$NON-NLS-1$
        }
    }

    Calendar cal = Calendar.getInstance();
    cal.set(dateTimeStart.getYear(), dateTimeStart.getMonth(), dateTimeStart.getDay(), 0, 0, 0);
    long startTime = cal.getTimeInMillis();

    cal.set(dateTimeEnd.getYear(), dateTimeEnd.getMonth(), dateTimeEnd.getDay(), 23, 59, 59);
    long endTime = cal.getTimeInMillis();
    int duringExecute = 0;
    try {
        duringExecute = Integer.parseInt(textMillis.getText());
    } catch (Exception e) {
        // ignore exception
    }

    String strSearchTxt = "%" + StringUtils.trimToEmpty(textSearch.getText()) + "%"; //$NON-NLS-1$ //$NON-NLS-2$

    try {
        List<RequestResultDAO> listSQLHistory = TadpoleSystem_ExecutedSQL.getExecuteQueryHistoryDetail(strEmail,
                comboTypes.getText(), db_seq, startTime, endTime, duringExecute, strSearchTxt);
        //         for (RequestResultDAO reqResultDAO : listSQLHistory) {
        for (int i = 0; i < listSQLHistory.size(); i++) {
            RequestResultDAO reqResultDAO = (RequestResultDAO) listSQLHistory.get(i);
            mapSQLHistory.put("" + i, reqResultDAO); //$NON-NLS-1$

            GridItem item = new GridItem(gridHistory, SWT.V_SCROLL | SWT.H_SCROLL);

            String strSQL = StringUtils.strip(reqResultDAO.getStrSQLText());
            int intLine = StringUtils.countMatches(strSQL, "\n"); //$NON-NLS-1$
            if (intLine >= 1) {
                int height = (intLine + 1) * 24;
                if (height > 100)
                    item.setHeight(100);
                else
                    item.setHeight(height);
            }

            item.setText(0, "" + i); //$NON-NLS-1$
            item.setText(1, reqResultDAO.getDbName());
            item.setText(2, reqResultDAO.getUserName());
            item.setText(3, Utils.dateToStr(reqResultDAO.getStartDateExecute()));
            //            logger.debug(Utils.convLineToHtml(strSQL));
            item.setText(4, Utils.convLineToHtml(strSQL));
            item.setToolTipText(4, strSQL);

            try {
                item.setText(5, "" + ((reqResultDAO.getEndDateExecute().getTime() //$NON-NLS-1$
                        - reqResultDAO.getStartDateExecute().getTime())));
            } catch (Exception e) {
                item.setText(5, "-"); //$NON-NLS-1$
            }
            item.setText(6, "" + reqResultDAO.getRows()); //$NON-NLS-1$
            item.setText(7, reqResultDAO.getResult());

            item.setText(8, Utils.convLineToHtml(reqResultDAO.getMesssage()));
            item.setToolTipText(8, reqResultDAO.getMesssage());

            item.setText(9, reqResultDAO.getIpAddress());

            if ("F".equals(reqResultDAO.getResult())) { //$NON-NLS-1$
                item.setBackground(SWTResourceManager.getColor(240, 180, 167));
            }
        }
    } catch (Exception ee) {
        logger.error("Executed SQL History call", ee); //$NON-NLS-1$
    }
}

From source file:com.myGengo.alfresco.translate.MyGengoTranslationServiceImpl.java

@Override
public void addJobComment(NodeRef jobRef, String comment, MyGengoAccount accountInfo)
        throws MyGengoServiceException {
    MyGengoClient myGengo = new MyGengoClient(accountInfo.getPublicKey(), accountInfo.getPrivateKey(),
            this.useSandbox);
    try {/* w w  w .  j av  a2 s . c o  m*/
        String jobId = (String) nodeService.getProperty(jobRef, MyGengoModel.PROP_JOBID);
        String commentAsText = HtmlToText.htmlToPlainText(StringUtils.trim(comment));
        JSONObject response = myGengo.postTranslationJobComment(Integer.valueOf(jobId), commentAsText);
        if (response.has("response")) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("comment job: " + response.toString());
            }
        } else {
            throw new MyGengoServiceException("adding comment failed");
        }
    } catch (Exception e) {
        LOGGER.error("adding comment failed", e);
        throw new MyGengoServiceException("refreshJobComments failed", e);
    }
}

From source file:com.prowidesoftware.swift.utils.SwiftFormatUtils.java

/**
 * Return the number of decimals for a string with a swift formatted amount.
 * //from  w w  w.  j  a  v  a 2  s .c  o m
 * @param amountString may be <code>null</code> or empty, in which case this method returns 0 
 * @return the number of digits after the last , or 0 in any other case.
 * @since 7.8
 */
public static int decimalsInAmount(final String amountString) {
    if (StringUtils.isNotEmpty(amountString)) {
        final String tail = StringUtils.trim(StringUtils.substringAfterLast(amountString, ","));
        return tail.length();
    }
    return 0;
}

From source file:com.openteach.diamond.service.DiamondServiceFactory.java

/**
 * /*from   w w w.j  a va  2s  . c o m*/
 * @param properties
 * @param metadataReadService
 * @return
 */
private static AddressingService newAddressingService(Properties properties,
        MetadataReadService metadataReadService) {
    String factoryClassName = StringUtils.trim(properties.getProperty(ADDRESSING_FACTORY));
    if (StringUtils.isBlank(factoryClassName)) {
        throw new IllegalArgumentException(String.format("Please set %s", ADDRESSING_FACTORY));
    }
    try {
        Class<?> clazz = Class.forName(factoryClassName);
        AddressingServiceFactory factory = (AddressingServiceFactory) clazz.newInstance();
        return factory.newAddressingService(metadataReadService);
    } catch (ClassNotFoundException e) {
        throw new IllegalArgumentException("OOPS, new addressing service failed", e);
    } catch (InstantiationException e) {
        throw new IllegalArgumentException("OOPS, new addressing service failed", e);
    } catch (IllegalAccessException e) {
        throw new IllegalArgumentException("OOPS, new addressing service failed", e);
    }
}

From source file:com.houghtonassociates.bamboo.plugins.GerritRepositoryAdapter.java

@Override
public ErrorCollection validate(BuildConfiguration buildConfiguration) {
    boolean error = false;
    ErrorCollection errorCollection = super.validate(buildConfiguration);

    String hostame = StringUtils.trim(buildConfiguration.getString(REPOSITORY_GERRIT_REPOSITORY_HOSTNAME));
    if (!StringUtils.isNotBlank(hostame)) {
        errorCollection.addError(REPOSITORY_GERRIT_REPOSITORY_HOSTNAME, "Hostname null!");
        error = true;/*  w  w w  .ja  v  a 2 s  .  c om*/
    }

    String strPort = buildConfiguration.getString(REPOSITORY_GERRIT_REPOSITORY_PORT, "").trim();
    if (!StringUtils.isNotBlank(strPort)) {
        errorCollection.addError(REPOSITORY_GERRIT_REPOSITORY_PORT, "Port null!");
        error = true;
    }

    String strProject = buildConfiguration.getString(REPOSITORY_GERRIT_PROJECT, "").trim();

    if (!StringUtils.isNotBlank(strProject)) {
        errorCollection.addError(REPOSITORY_GERRIT_PROJECT, "Project null!");
        error = true;
    }

    String username = StringUtils.trim(buildConfiguration.getString(REPOSITORY_GERRIT_USERNAME));

    if (!StringUtils.isNotBlank(username)) {
        errorCollection.addError(REPOSITORY_GERRIT_USERNAME, "Username null!");
        error = true;
    }

    if (buildConfiguration.getBoolean(TEMPORARY_GERRIT_SSH_KEY_CHANGE)) {
        final Object o = buildConfiguration.getProperty(TEMPORARY_GERRIT_SSH_KEY_FROM_FILE);

        if (o == null) {
            errorCollection.addError(REPOSITORY_GERRIT_REPOSITORY_HOSTNAME,
                    textProvider.getText("repository.gerrit.messages.error.ssh.key.missing"));
            error = true;
        }
    }

    String key = encryptionService.decrypt(buildConfiguration.getString(REPOSITORY_GERRIT_SSH_KEY, ""));
    if (!StringUtils.isNotBlank(key)) {
        errorCollection.addError(REPOSITORY_GERRIT_REPOSITORY_HOSTNAME,
                textProvider.getText("repository.gerrit.messages.error.ssh.key.missing"));
        error = true;
    }

    String strPhrase;
    if (buildConfiguration.getBoolean(TEMPORARY_GERRIT_SSH_PASSPHRASE_CHANGE)) {
        strPhrase = buildConfiguration.getString(TEMPORARY_GERRIT_SSH_PASSPHRASE);
    } else {
        strPhrase = buildConfiguration.getString(REPOSITORY_GERRIT_SSH_PASSPHRASE, "");
        if (StringUtils.isNotBlank(strPhrase))
            strPhrase = encryptionService.decrypt(strPhrase);
    }

    String keyFilePath = buildConfiguration.getString(REPOSITORY_GERRIT_SSH_KEY_FILE);

    if (!StringUtils.isNotBlank(keyFilePath)) {
        errorCollection.addError(REPOSITORY_GERRIT_SSH_KEY_FILE,
                "Your SSH private key is required for connection!");
        error = true;
    }

    if (error) {
        return errorCollection;
    }

    try {
        ErrorCollection e2 = testGerritConnection(keyFilePath, key, hostame, Integer.valueOf(strPort), username,
                strProject, strPhrase);
        errorCollection.addErrorCollection(e2);
    } catch (RepositoryException e) {
        errorCollection.addError(REPOSITORY_GERRIT_REPOSITORY_HOSTNAME, e.getMessage());
    }

    return errorCollection;
}

From source file:com.hello2morrow.sonarplugin.SonarJSensor.java

private int handleTasks(XsdTasks tasks, String buildUnitName) {
    Map<String, RulePriority> priorityMap = new HashMap<String, RulePriority>();

    Rule rule = rulesManager.getPluginRule(SonarJPluginBase.PLUGIN_KEY, SonarJPluginBase.TASK_RULE_KEY);
    int count = 0;

    if (rule == null) {
        LOG.error("SonarJ task rule not found");
        return 0;
    }//from ww  w  .  j av  a2 s.  c  o m

    ActiveRule activeRule = rulesProfile.getActiveRule(SonarJPluginBase.PLUGIN_KEY,
            SonarJPluginBase.TASK_RULE_KEY);

    if (activeRule == null) {
        LOG.info("SonarJ task rule not activated");
    }

    priorityMap.put("Low", RulePriority.INFO);
    priorityMap.put("Medium", RulePriority.MINOR);
    priorityMap.put("High", RulePriority.MAJOR);

    for (XsdTask task : tasks.getTask()) {
        String bu = getAttribute(task.getAttribute(), "Build unit");

        bu = getBuildUnitName(bu);
        if (bu.equals(buildUnitName)) {
            String priority = getAttribute(task.getAttribute(), "Priority");
            String description = getAttribute(task.getAttribute(), "Description");
            String assignedTo = getAttribute(task.getAttribute(), "Assigned to");

            description = handleDescription(description); // This should not be needed, but the current description sucks

            int index = description.indexOf(" package");

            if (index > 0 && index < 8) {
                // Package refactorings won't get markers - this would create to many non relevant markers
                count++;
            } else {
                if (assignedTo != null) {
                    assignedTo = '[' + StringUtils.trim(assignedTo) + ']';
                    if (assignedTo.length() > 2) {
                        description += ' ' + assignedTo;
                    }
                }
                for (XsdPosition pos : task.getPosition()) {
                    String relFileName = pos.getFile();

                    if (relFileName != null) {
                        String fqName = relativeFileNameToFqName(relFileName);
                        int line = Integer.valueOf(pos.getLine());

                        if (line == 0) {
                            line = 1;
                        }
                        if (activeRule != null) {
                            saveViolation(rule, priorityMap.get(priority), fqName, line, description);
                        }
                    }
                    count++;
                }
            }
        }
    }
    return count;
}

From source file:de.forsthaus.webui.InitApplicationCtrl.java

/**
 * Creates a new separator to a parent component.<br>
 * // ww w .ja  v a  2  s  .c o  m
 * @param parent
 * @param orientation
 * @param isBarVisible
 * @param spacing
 * @param bkgrColor
 * @return
 */
private Separator createNewSeparator(Component parent, String orientation, boolean isBarVisible, String spacing,
        String bkgrColor) {

    final Separator sep = new Separator();

    sep.setOrient(orientation);
    sep.setBar(isBarVisible);

    if (!StringUtils.trim(bkgrColor).isEmpty()) {
        sep.setStyle("background-color:" + bkgrColor);
    }

    if (StringUtils.isEmpty(spacing)) {
        sep.setSpacing(0 + "px");
    } else {
        sep.setSpacing(spacing + "px");
    }

    sep.setParent(parent);

    return sep;
}