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.edgenius.wiki.render.filter.ListFilter.java

/**
 * Adds a list to a buffer//w  ww  .ja va2s  . c  o  m
 */
private void addList(StringBuffer buffer, BufferedReader reader) throws IOException {
    char[] lastBullet = new char[0];
    String line = null;
    String trimLine = null;
    boolean requireLiEnd = false;
    while ((line = reader.readLine()) != null) {
        if (StringUtils.trim(line).length() == 0) {
            //new empty line - end of list
            break;
        }
        //only trim leading spaces, keep tailed spaces
        trimLine = StringUtil.trimStartSpace(line);

        int bulletEnd = StringUtils.indexOfAny(trimLine, new String[] { " ", "\t" });
        if (bulletEnd < 1) {
            //if this line is not valid bullet line, then means this li has multiple lines...
            //please note, here append original line rather than trimmed and with newline - that eat by read.readLine()
            buffer.append("\n").append(line);
            continue;
        }

        String bStr = trimLine.substring(0, bulletEnd).trim();
        if (!bulletPattern.matcher(bStr).matches()) {
            //if this line is not valid bullet line, then means this li has multiple lines...
            //please note, here append original line rather than trimmed and with newline - that eat by read.readLine()
            buffer.append("\n").append(line);
            continue;
        }

        //remove the possible dot, for example, #i. 
        if (bStr.charAt(bStr.length() - 1) == '.') {
            bStr = bStr.substring(0, bStr.length() - 1);
        }

        char[] bullet = bStr.toCharArray();
        if (requireLiEnd) {
            buffer.append("</li>");
            requireLiEnd = false;
        }

        // check whether we find a new sub list, for example 
        //* list
        //** sublist
        int sharedPrefixEnd;
        for (sharedPrefixEnd = 0;; sharedPrefixEnd++) {
            if (bullet.length <= sharedPrefixEnd || lastBullet.length <= sharedPrefixEnd
                    || bullet[sharedPrefixEnd] != lastBullet[sharedPrefixEnd]) {
                break;
            }
        }

        for (int i = sharedPrefixEnd; i < lastBullet.length; i++) {
            // Logger.log("closing " + lastBullet[i]);
            buffer.append(closeList.get(Character.valueOf(lastBullet[i])));
        }

        for (int i = sharedPrefixEnd; i < bullet.length; i++) {
            // Logger.log("opening " + bullet[i]);
            buffer.append(openList.get(Character.valueOf(bullet[i])));
        }
        buffer.append("<li>");
        buffer.append(trimLine.substring(StringUtils.indexOfAny(trimLine, new String[] { " ", "\t" }) + 1));
        requireLiEnd = true;
        lastBullet = bullet;
    }

    if (requireLiEnd) {
        buffer.append("</li>");
    }
    for (int i = lastBullet.length - 1; i >= 0; i--) {
        buffer.append(closeList.get(Character.valueOf(lastBullet[i])));
    }

}

From source file:hydrograph.ui.propertywindow.propertydialog.PropertyDialogBuilder.java

private void addCustomWidgetsToGroupWidget(LinkedHashMap<String, ArrayList<Property>> subgroupTree,
        String subgroupName, AbstractELTContainerWidget subGroupContainer) {
    boolean isError = false;
    for (final Property property : subgroupTree.get(subgroupName)) {
        AbstractWidget eltWidget = addCustomWidgetInGroupWidget(subGroupContainer, property);
        eltWidgetList.add(eltWidget);//from  w ww.j  a v a2  s. com

        if (!eltWidget.isWidgetValid()) {
            isError = true;
        }
    }

    if (isError) {
        for (CTabItem item : tabFolder.getItems()) {
            if (StringUtils.equalsIgnoreCase(StringUtils.trim(item.getText()),
                    subgroupTree.get(subgroupName).get(0).getPropertyGroup())) {
                item.setImage(ImagePathConstant.COMPONENT_ERROR_ICON.getImageFromRegistry());
            }
        }
    }

}

From source file:au.edu.anu.portal.portlets.basiclti.BasicLTIPortlet.java

/**
 * Helper to process EDIT mode actions// ww  w . ja  v  a2  s . com
 * @param request
 * @param response
 */
private void processEditAction(ActionRequest request, ActionResponse response) {
    log.debug("Basic LTI processEditAction()");

    boolean success = true;
    //get prefs and submitted values
    PortletPreferences prefs = request.getPreferences();
    String portletHeight = request.getParameter("portletHeight");
    String portletTitle = StringEscapeUtils.escapeHtml(StringUtils.trim(request.getParameter("portletTitle")));

    //validate
    try {
        prefs.setValue("portlet_height", portletHeight);

        //only save if portlet title is not blank
        if (StringUtils.isNotBlank(portletTitle)) {
            prefs.setValue("portlet_title", portletTitle);
        }
    } catch (ReadOnlyException e) {
        success = false;
        response.setRenderParameter("errorMessage", Messages.getString("error.form.readonly.error"));
        log.error(e);
    }

    //save them
    if (success) {
        try {
            prefs.store();
            response.setPortletMode(PortletMode.VIEW);
        } catch (ValidatorException e) {
            response.setRenderParameter("errorMessage", e.getMessage());
            log.error(e);
        } catch (IOException e) {
            response.setRenderParameter("errorMessage", Messages.getString("error.form.save.error"));
            log.error(e);
        } catch (PortletModeException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.streamreduce.core.model.Connection.java

/**
 * Merges the following properties from a JSON object in to the Connection object:
 * <ul>/* w  w  w.  ja  va  2  s . co m*/
 * <li>credentials</li>
 * <li>authType</li>
 * <li>alias</li>
 * <li>description</li>
 * <li>visibility</li>
 * <li>url</li>
 * </ul>
 *
 * @param json {@link JSONObject} used to defined properties of this Connection.
 */
@Override
public void mergeWithJSON(JSONObject json) {
    super.mergeWithJSON(json);

    // Allow changing credentials
    if (json.containsKey("credentials")) {
        JSONObject rawNewCredentials = json.getJSONObject("credentials");

        // If rawNewCredentials is empty, we risk clobbering the old credentials. Which is bad.
        if (!rawNewCredentials.isEmpty()) {
            ConnectionCredentials newCredentials = new ConnectionCredentials();

            if (rawNewCredentials.containsKey("identity") && rawNewCredentials.getString("identity") != null) {
                newCredentials.setIdentity(rawNewCredentials.getString("identity"));
            }

            if (rawNewCredentials.containsKey("credential")
                    && rawNewCredentials.getString("credential") != null) {
                newCredentials.setCredential(rawNewCredentials.getString("credential"));
            }

            if (rawNewCredentials.containsKey("api_key") && rawNewCredentials.getString("api_key") != null) {
                newCredentials.setApiKey(rawNewCredentials.getString("api_key"));
            }

            if (rawNewCredentials.containsKey("oauthToken")
                    && rawNewCredentials.getString("oauthToken") != null) {
                newCredentials.setOauthToken(rawNewCredentials.getString("oauthToken"));
            }

            if (rawNewCredentials.containsKey("oauthTokenSecret")
                    && rawNewCredentials.getString("oauthTokenSecret") != null) {
                newCredentials.setOauthTokenSecret(rawNewCredentials.getString("oauthTokenSecret"));
            }

            if (rawNewCredentials.containsKey("oauthVerifier")
                    && rawNewCredentials.getString("oauthVerifier") != null) {
                newCredentials.setOauthVerifier(rawNewCredentials.getString("oauthVerifier"));
            }

            setCredentials(newCredentials);
        }
    }

    if (json.containsKey("url")) {
        setUrl(StringUtils.trim(json.getString("url")));
    }

    if (json.containsKey("authType")) {
        setAuthType(AuthType.valueOf(json.getString("authType")));
    }
}

From source file:com.edgenius.wiki.gwt.server.PortalControllerImpl.java

public WidgetModel addWidgetToDashboardPortal(String widgetType, String widgetKey) {
    Widget widget = widgetService.getWidgetByKey(widgetKey);
    WidgetModel model = new WidgetModel();
    if (widget == null) {
        model.errorCode = ErrorCode.WIDGET_NOT_FOUND;
        return model;
    }/* ww  w.  j a v a  2  s .  c  o m*/

    securityDummy.checkInstanceRead();
    User viewer = WikiUtil.getUser();

    //get dashboard content and check if it has {portal} macro first
    InstanceSetting instance = settingService.getInstanceSetting();

    int count = 1;
    if (instance == null || StringUtil.isBlank(instance.getDashboardMarkup()) || StringUtil.equalsIgnoreCase(
            StringUtils.trim(instance.getDashboardMarkup()), SharedConstants.DEFAULT_DAHSBOARD_MARKUP)) {
        //default dashboard - then it must have {portal} - see SharedContants.DEFAULT_DAHSBOARD_MARKUP
    } else {
        List<RenderPiece> pieces = renderService.renderHTML(instance.getDashboardMarkup());
        for (RenderPiece renderPiece : pieces) {
            if (renderPiece instanceof MacroModel) {
                MacroModel rs = ((MacroModel) renderPiece);
                if (SharedConstants.MACRO_PORTAL.equals(rs.macroName)) {
                    //here try to confirm one and only one {portal} in Dashboard markup
                    count++;
                }
            }
        }
    }
    if (count != 1) {
        //we hope one and only one {portal} in Dashboard markup, otherwise, try to give some error here.
        model.errorCode = ErrorCode.WIDGET_TO_MULTIPLE_PORTAL;
        return model;
    }

    if (viewer.isAnonymous()) {
        model.errorCode = ErrorCode.WIDGET_ADD_TO_ANONYMOUS_PORTAL;
        return model;
    } else {
        //finally update this user's portal in Dashboard

        //reload user from Database rather than Cache. 
        viewer = userReadingService.getUser(viewer.getUid());
        UserSetting setting = viewer.getSetting();
        setting.addWidgetToHomelayout(widgetType, widgetKey, instance.getHomeLayout());
        settingService.saveOrUpdateUserSetting(viewer, setting);
    }

    return model;
}

From source file:jp.co.opentone.bsol.linkbinder.service.correspon.impl.CorresponFullTextSearchServiceImpl.java

protected boolean isAcceptableDateString(String keyword) {
    final DateTimeFormatter acceptableFormats[] = { DateTimeFormatter.ofPattern("yyyy-MM-dd"),
            DateTimeFormatter.ofPattern("yyyyMMdd") };

    return Stream.of(StringUtils.split(keyword, ' ')).allMatch(s -> {
        String str = StringUtils.trim(s);
        boolean parsed = false;
        for (DateTimeFormatter f : acceptableFormats) {
            try {
                LocalDate.parse(str, f);
                parsed = true;/*from www. ja v a  2s .  c o m*/
                break;
            } catch (DateTimeParseException ignore) {
            }
        }
        return parsed;
    });
}

From source file:hydrograph.ui.perspective.ApplicationWorkbenchWindowAdvisor.java

/**
 * This function will be return process ID which running on defined port
 *
 *///from www  .j a  v a  2  s .com
public String getServicePortPID(String portNumber) throws IOException {
    if (OSValidator.isWindows()) {
        ProcessBuilder builder = new ProcessBuilder(
                new String[] { "cmd", "/c", "netstat -a -o -n |findstr :" + portNumber });
        Process process = builder.start();
        InputStream inputStream = process.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String str = bufferedReader.readLine();
        str = StringUtils.substringAfter(str, "LISTENING");
        str = StringUtils.trim(str);
        return str;
    }
    return "";
}

From source file:com.edgenius.core.Global.java

/**
 * @param setting//from w  ww  . ja  v a2  s.  c  o m
 */
public static void syncFrom(GlobalSetting setting) {
    if (setting == null)
        return;

    Global.DefaultDirection = setting.getDefaultDirection();
    Global.DefaultLanguage = setting.getDefaultLanguage();
    Global.DefaultCountry = setting.getDefaultCountry();
    Global.DefaultTimeZone = setting.getDefaultTimeZone();
    Global.DefaultLoginKey = setting.getDefaultLoginKey();
    Global.PublicSearchEngineAllow = setting.isPublicSearchEngineAllow();
    Global.SysContextPath = setting.getContextPath();
    Global.SysHostProtocol = setting.getHostProtocol();
    if ((setting.getHostPort() == 80 && setting.getHostProtocol().startsWith("http:"))
            || (setting.getHostPort() == 443 && setting.getHostProtocol().startsWith("https:"))
            || setting.getHostPort() == 0)
        Global.SysHostAddress = setting.getHostName();
    else
        Global.SysHostAddress = setting.getHostName() + ":" + setting.getHostPort();

    Global.PasswordEncodingAlgorithm = setting.getEncryptAlgorithm();
    Global.EncryptPassword = setting.isEncryptPassword();
    Global.SpaceQuota = setting.getSpaceQuota();
    Global.DelayRemoveSpaceHours = setting.getDelayRemoveSpaceHours();
    Global.EnableAdminPermControl = setting.isEnableAdminPermControl();
    Global.DelayOfflineSyncMinutes = setting.getDelayOfflineSyncMinutes();
    Global.registerMethod = setting.getRegisterMethod();
    Global.MaintainJobCron = setting.getMaintainJobCron();
    Global.CommentsNotifierCron = setting.getCommentsNotifierCron();
    Global.MaxCommentsNotifyPerDay = setting.getMaxCommentsNotifyPerDay();
    Global.AutoFixLinks = setting.getAutoFixLinks();

    Global.DefaultNotifyMail = setting.getDefaultNotifyMail();
    Global.DefaultReceiverMail = setting.getDefaultReceiverMailAddress();
    Global.ccToSystemAdmin = setting.isCcToSystemAdmin();
    Global.SystemTitle = setting.getSystemTitle();

    Global.webServiceEnabled = isEnabled(setting.getWebservice());
    Global.webServiceAuth = StringUtils.isBlank(setting.getWebserviceAuthenticaton()) ? "basic"
            : StringUtils.trim(setting.getWebserviceAuthenticaton());

    Global.restServiceEnabled = isEnabled(setting.getRestservice());
    Global.restServiceAuth = StringUtils.isBlank(setting.getRestserviceAuthenticaton()) ? "basic"
            : StringUtils.trim(setting.getRestserviceAuthenticaton());

    Global.ADSENSE = isEnabled(setting.getAdsense());
    Global.TEXTNUT = isEnabled(setting.getTextnut());
    Global.Skin = setting.getSkin();

    //convert suppress name to values
    String supStr = setting.getSuppress();
    Global.suppress = 0;
    if (!StringUtils.isBlank(supStr)) {
        String[] supStrs = supStr.split(",");
        for (String supName : supStrs) {
            try {
                SUPPRESS sup = SUPPRESS.valueOf(supName.toUpperCase());
                Global.suppress |= sup.getValue();

                //need further confirm ???
                Global.setCurrentSuppress(Global.suppress);
            } catch (Exception e) {
                //skip invalid suppress
            }
        }
    }

    Global.DetectLocaleFromRequest = setting.isDetectLocaleFromRequest();
    Global.VersionCheck = setting.isVersionCheck();
    if (Global.VersionCheck && !StringUtils.isBlank(setting.getVersionCheckCron())) {
        //if version check is true, but cron is blank then keep its default value.
        Global.VersionCheckCron = setting.getVersionCheckCron();
    }
    Global.PurgeDaysOldActivityLog = setting.getPurgeDaysOldActivityLog();

    Global.TwitterOauthConsumerKey = setting.getTwitterOauthConsumerKey();
    Global.TwitterOauthConsumerSecret = setting.getTwitterOauthConsumerSecret();
}

From source file:io.ecarf.core.utils.LogParser.java

private double extractAndGetTimer(String line, String after, boolean ignoreMillis) {
    String timer = StringUtils.substringAfter(line, after);
    timer = StringUtils.remove(timer, ':');
    timer = StringUtils.trim(timer);

    return this.parseStopwatchTime(timer, ignoreMillis);
}

From source file:com.flexive.faces.components.content.FxContentList.java

private FxResultSet getResult(FacesContext context) throws IOException, FxApplicationException {
    if (result != null) {
        return result;
    }//from   w  w  w .ja va  2s  .  c o m
    final UIComponent groovyQuery = getFacet("groovyQuery");
    this.queryBuilder = this.getQueryBuilder() != null ? this.getQueryBuilder() : new SqlQueryBuilder();
    if (!queryBuilder.getColumnNames().contains("@pk")) {
        queryBuilder.select("@pk");
    }
    if (groovyQuery != null) {
        // get embedded groovy query
        final ResponseWriter oldWriter = context.getResponseWriter();
        try {
            final StringWriter queryWriter = new StringWriter();
            context.setResponseWriter(context.getResponseWriter().cloneWithWriter(queryWriter));
            groovyQuery.encodeAll(context);
            context.setResponseWriter(oldWriter);
            final GroovyShell shell = new GroovyShell();
            shell.setVariable("builder", queryBuilder);
            final QueryRootNode result = (QueryRootNode) shell.parse(
                    "new com.flexive.shared.scripting.groovy.GroovyQueryBuilder(builder).select([\"@pk\"]) {"
                            + StringUtils.trim(queryWriter.toString()).replace("&quot;", "\"") + "}")
                    .run();
            result.buildSqlQuery(queryBuilder);
        } finally {
            context.setResponseWriter(oldWriter);
        }
    }
    result = queryBuilder.getResult();
    return result;
}