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

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

Introduction

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

Prototype

public static String substringBefore(String str, String separator) 

Source Link

Document

Gets the substring before the first occurrence of a separator.

Usage

From source file:com.enonic.cms.core.preference.PreferenceKey.java

private void initScope(String scopePart) {

    this.scopePart = scopePart;

    String scopeName;/*from  w w  w . j av a2s .com*/
    String scopeKeyStr = null;
    if (StringUtils.contains(scopePart, ':')) {
        scopeName = StringUtils.substringBefore(scopePart, ":");
        scopeKeyStr = StringUtils.substringAfter(scopePart, ":");
    } else {
        scopeName = scopePart;
    }

    this.scopeType = PreferenceScopeType.parse(scopeName);
    if (this.scopeType == null) {
        throw new InvalidKeyException(rawKey, this.getClass(), "invalid scope");
    }

    if (scopeType != PreferenceScopeType.GLOBAL) {
        this.scopeKey = new PreferenceScopeKey(scopeKeyStr);
    }
}

From source file:edu.monash.merc.system.parser.gpm.GPMRSSReader.java

private GPMSyndEntry createGPMSyndEntry(String ftpLink, Date publishedDate) {
    if (publishedDate == null) {
        return null;
    }/*from   w ww. j  av  a 2s  .  c  om*/

    if (StringUtils.isBlank(ftpLink)) {
        return null;
    }

    GPMSyndEntry gpmSyndEntry = new GPMSyndEntry();
    gpmSyndEntry.setReleasedTime(publishedDate);

    String tmpFtpDir = StringUtils.substringBeforeLast(ftpLink, PATH_SEPARATOR);
    String ftpPath = StringUtils.substringAfter(tmpFtpDir, FTP_PROTOCOL);
    String ftpServerName = StringUtils.substringBefore(ftpPath, PATH_SEPARATOR);
    String workdir = StringUtils.substringAfter(ftpPath, PATH_SEPARATOR);
    String fileName = StringUtils.substringAfterLast(ftpLink, PATH_SEPARATOR);
    gpmSyndEntry.setGmpFtpServer(ftpServerName);
    gpmSyndEntry.setTpbWorkDir(PATH_SEPARATOR + workdir);
    gpmSyndEntry.setReleasedTpbFileName(fileName);
    return gpmSyndEntry;
}

From source file:com.contrastsecurity.ide.eclipse.ui.internal.model.RecommendationTab.java

public void setRecommendationResource(RecommendationResource recommendationResource) {
    this.recommendationResource = recommendationResource;
    Composite control = getControl();
    Control[] children = control.getChildren();
    for (Control child : children) {
        child.dispose();//from  ww w . java2s  . c  o  m
    }

    if (recommendationResource != null && recommendationResource.getRecommendation() != null
            && recommendationResource.getCustomRecommendation() != null
            && recommendationResource.getRuleReferences() != null
            && recommendationResource.getCustomRuleReferences() != null) {

        String formattedRecommendationText = recommendationResource.getRecommendation().getFormattedText();
        String openTag = null;
        String closeTag = null;

        if (formattedRecommendationText.contains(Constants.OPEN_TAG_C_SHARP_BLOCK)) {
            openTag = Constants.OPEN_TAG_C_SHARP_BLOCK;
            closeTag = Constants.CLOSE_TAG_C_SHARP_BLOCK;
        } else if (formattedRecommendationText.contains(Constants.OPEN_TAG_HTML_BLOCK)) {
            openTag = Constants.OPEN_TAG_HTML_BLOCK;
            closeTag = Constants.CLOSE_TAG_HTML_BLOCK;
        } else if (formattedRecommendationText.contains(Constants.OPEN_TAG_JAVA_BLOCK)) {
            openTag = Constants.OPEN_TAG_JAVA_BLOCK;
            closeTag = Constants.CLOSE_TAG_JAVA_BLOCK;
        } else if (formattedRecommendationText.contains(Constants.OPEN_TAG_XML_BLOCK)) {
            openTag = Constants.OPEN_TAG_XML_BLOCK;
            closeTag = Constants.CLOSE_TAG_XML_BLOCK;
        } else if (formattedRecommendationText.contains(Constants.OPEN_TAG_JAVASCRIPT_BLOCK)) {
            openTag = Constants.OPEN_TAG_JAVASCRIPT_BLOCK;
            closeTag = Constants.CLOSE_TAG_JAVASCRIPT_BLOCK;
        }

        String[] codeBlocks = StringUtils.substringsBetween(formattedRecommendationText, openTag, closeTag);
        String[] textBlocks = StringUtils.substringsBetween(formattedRecommendationText, closeTag, openTag);

        String textBlockFirst = StringUtils.substringBefore(formattedRecommendationText, openTag);
        String textBlockLast = StringUtils.substringAfterLast(formattedRecommendationText, closeTag);

        insertTextBlock(control, textBlockFirst);

        if (codeBlocks != null && codeBlocks.length > 0) {
            for (int i = 0; i < codeBlocks.length; i++) {

                String textToInsert = StringEscapeUtils.unescapeHtml(codeBlocks[i]);
                createStyledTextCodeBlock(control, textToInsert);

                if (textBlocks != null && textBlocks.length > 0 && i < codeBlocks.length - 1) {
                    insertTextBlock(control, textBlocks[i]);
                }
            }
        }

        insertTextBlock(control, textBlockLast);

        CustomRecommendation customRecommendation = recommendationResource.getCustomRecommendation();
        String customRecommendationText = customRecommendation.getText() == null ? Constants.BLANK
                : customRecommendation.getText();
        if (!customRecommendationText.isEmpty()) {
            customRecommendationText = parseMustache(customRecommendationText);

            createLabel(control, customRecommendationText);
        }

        Composite cweComposite = new Composite(control, SWT.NONE);
        cweComposite.setLayout(new RowLayout());

        Label cweHeaderLabel = createLabel(cweComposite, "CWE:");
        cweHeaderLabel.setLayoutData(new RowData(100, 15));
        Link cweLink = createLinkFromUrlString(cweComposite, recommendationResource.getCwe());
        cweLink.setLayoutData(new RowData());

        Composite owaspComposite = new Composite(control, SWT.NONE);
        owaspComposite.setLayout(new RowLayout());

        Label owaspHeaderLabel = createLabel(owaspComposite, "OWASP:");
        owaspHeaderLabel.setLayoutData(new RowData(100, 15));
        Link owaspLink = createLinkFromUrlString(owaspComposite, recommendationResource.getOwasp());
        owaspLink.setLayoutData(new RowData());

        RuleReferences ruleReferences = recommendationResource.getRuleReferences();
        String ruleReferencesText = ruleReferences.getText() == null ? Constants.BLANK
                : ruleReferences.getText();
        if (!ruleReferencesText.isEmpty()) {

            Composite referencesComposite = new Composite(control, SWT.NONE);
            referencesComposite.setLayout(new RowLayout());

            Label referencesHeaderLabel = createLabel(referencesComposite, "References:");
            referencesHeaderLabel.setLayoutData(new RowData(100, 15));

            String firstLink = StringUtils.substringBefore(ruleReferencesText, Constants.MUSTACHE_NL);
            Link referencesLink = createLinkFromUrlString(referencesComposite, firstLink);
            referencesLink.setLayoutData(new RowData());

            String[] links = StringUtils.substringsBetween(ruleReferencesText, Constants.MUSTACHE_NL,
                    Constants.MUSTACHE_NL);

            if (links != null && links.length > 0) {
                for (String link : links) {
                    Link linkObject = createLinkFromUrlString(referencesComposite, link);
                    linkObject.setLayoutData(new RowData());
                }
            }
        }
        CustomRuleReferences customRuleReferences = recommendationResource.getCustomRuleReferences();
        if (StringUtils.isNotEmpty(customRuleReferences.getText())) {
            String customRuleReferencesText = parseMustache(customRuleReferences.getText());
            createLabel(control, customRuleReferencesText);
        }
    }

    ScrolledComposite sc = (ScrolledComposite) control.getParent();

    Rectangle r = sc.getClientArea();
    Control content = sc.getContent();
    if (content != null && r != null) {
        Point minSize = content.computeSize(r.width, SWT.DEFAULT);
        sc.setMinSize(minSize);
        ScrollBar vBar = sc.getVerticalBar();
        vBar.setPageIncrement(r.height);
    }

}

From source file:cn.heu.hmps.util.web.Struts2Utils.java

/**
 * ?contentTypeheaders.//  w  w  w  .ja  v a  2s .c o m
 */
private static HttpServletResponse initResponseHeader(final String contentType, final String... headers) {
    //?headers?
    String encoding = DEFAULT_ENCODING;
    boolean noCache = DEFAULT_NOCACHE;
    for (String header : headers) {
        String headerName = StringUtils.substringBefore(header, ":");
        String headerValue = StringUtils.substringAfter(header, ":");

        if (StringUtils.equalsIgnoreCase(headerName, HEADER_ENCODING)) {
            encoding = headerValue;
        } else if (StringUtils.equalsIgnoreCase(headerName, HEADER_NOCACHE)) {
            noCache = Boolean.parseBoolean(headerValue);
        } else {
            throw new IllegalArgumentException(headerName + "??header");
        }
    }

    HttpServletResponse response = ServletActionContext.getResponse();

    //headers?
    String fullContentType = contentType + ";charset=" + encoding;
    response.setContentType(fullContentType);
    if (noCache) {
        ServletUtils.setDisableCacheHeader(response);
    }

    return response;
}

From source file:com.adobe.acs.commons.wcm.impl.PropertyMergePostProcessor.java

/**
 * Gets the corresponding list of PropertyMerge directives from the
 * RequestParams./*  w w w.  j  a  v  a2s.c  om*/
 *
 * @param requestParameters the Request Param Map
 * @return a list of the PropertyMerge directives by Destination
 */
@SuppressWarnings("squid:S3776")
private List<PropertyMerge> getPropertyMerges(final SlingHttpServletRequest request) {
    final RequestParameterMap requestParameters = request.getRequestParameterMap();
    final HashMap<String, Set<String>> mapping = new HashMap<>();
    boolean isBulkUpdate = Boolean.valueOf(getParamValue(requestParameters, "dam:bulkUpdate"));

    // Collect the Destination / Source mappings
    requestParameters.forEach((key, values) -> {
        if (!StringUtils.endsWith(key, AT_SUFFIX)) {
            // Not a @PropertyMerge request param
            return;
        }

        Function<String, String> stripPrefix = (s -> StringUtils.removeStart(StringUtils.stripToNull(s),
                IGNORE_PREFIX));
        final String source = stripPrefix.apply(StringUtils.substringBefore(key, AT_SUFFIX));

        Stream.of(values).map(RequestParameter::getString).map(stripPrefix).filter(Objects::nonNull)
                .forEach(destination -> {
                    if (source.equalsIgnoreCase(OPERATION_ALL_TAGS)) {
                        // if this is a request for merging all tags, look at everyting that might be a tag
                        trackAllTagsMergeParameters(request, destination, mapping);
                    } else if (isBulkUpdate) {
                        // if this is a DAM bulk update, search all request params ending with this value
                        trackAssetMergeParameters(requestParameters, source, destination, mapping);
                    } else {
                        trackMergeParameters(mapping, source, destination);
                    }
                });
    });

    // Convert the Mappings into PropertyMerge objects
    return mapping.entrySet().stream()
            .map(entry -> new PropertyMerge(entry.getKey(), entry.getValue(),
                    areDuplicatesAllowed(requestParameters, entry.getKey()),
                    getFieldTypeHint(requestParameters, entry.getKey())))
            .collect(Collectors.toList());
}

From source file:com.closertag.smartmove.server.service.pearson.DeafultPearsonService.java

/**
 * Get and save the single entry into the database
 * // w ww  . j  a va 2 s  .  c  o m
 * @param manager
 * @param it
 * @throws Exception
 */
private boolean getSingleEntry(HttpConnectionManager manager, JsonNode entry) throws Exception {
    String id = entry.get("@id").getTextValue();
    /*If a coordinate is missing exit */
    if (entry.get("@latitude") == null) {
        return false;

    }
    String category = StringUtils.substringBefore(entry.get("@categories").getTextValue(), ",");

    try {

        // Chiamo la singola string per eseguire la query
        // https://api.pearson.com/eyewitness/london/block/EWTG_LONDON097APSHOU_001.json?apikey=d14b9d3c132ba476437046de8b1395a8
        ObjectMapper mapper_item = new ObjectMapper();
        JsonNode itemNode = mapper_item.readValue(
                new String(manager.getByteArrayResourcePost(
                        "/eyewitness/london/block/" + id + ".json?apikey=" + getApikey(), null, null)),
                JsonNode.class);
        JsonNode block = itemNode.get("block");
        String text = block.get("title").get("#text").getTextValue();

        Item item = new Item();

        item.setGid(new Gid("PEARSON"));
        item.setItemId(id);

        JsonNode tagInfo = block.get("tg_info");
        Category c = new Category(category);
        item.setCategory(c);

        if (tagInfo == null) {
            return false;
        }
        Cost cost = new Cost();
        if (tagInfo.get("admission_charge") != null) {
            cost.setItem(item);
            cost.setLocale(Locale.ENGLISH);
            cost.setValue(tagInfo.get("admission_charge").getTextValue());
            item.setWebsite(tagInfo.get("url").get("#text").getTextValue());
            item.getCosts().add(cost);
        }

        String description = text;
        if (tagInfo.get("opening_info") != null) {
            description += " Opening: " + tagInfo.get("opening_info").get("#text").getTextValue();
        }
        if (tagInfo.get("closing_info") != null) {
            description += " Closing: " + tagInfo.get("closing_info").get("#text").getTextValue();
        }
        if (tagInfo.get("additional_info") != null) {

            if (!tagInfo.get("additional_info").isArray()) {
                description += "Additional info: " + tagInfo.get("additional_info").get("#text").getTextValue();
            } else {
                for (int i = 0; i < tagInfo.get("additional_info").size(); i++) {
                    JsonNode node = tagInfo.get("additional_info").get(i);
                    if (node.get("#text") != null) {
                        description += " " + node.get("#text").getTextValue();
                    }
                }
            }
        }

        if (tagInfo.get("phone") != null) {
            if (tagInfo.get("phone").isArray()) {

                item.setTelephone(tagInfo.get("phone").get(0).get("#text").getTextValue());

            } else {

                item.setTelephone(tagInfo.get("phone").get("#text").getTextValue());

            }
        }

        if (tagInfo.get("tg_data") != null) {
            if (tagInfo.get("tg_data").isArray()) {
                for (int i = 0; i < tagInfo.get("tg_data").size(); i++) {
                    JsonNode data = tagInfo.get("tg_data").get(i);

                    Extra e = new Extra();
                    e.setItem(item);
                    e.setLabel(data.get("@role").getTextValue());
                    e.setValue("present");
                    item.getExtras().add(e);

                }
            } else {
                Extra e = new Extra();
                e.setItem(item);
                e.setLabel(tagInfo.get("tg_data").get("@role").getTextValue());
                e.setValue("present");
                item.getExtras().add(e);

            }
        }

        item.getLocalizedItems().add(new LocalizedItem(item, Label.Description, Locale.ENGLISH, description));
        item.getLocalizedItems().add(new LocalizedItem(item, Label.Title, Locale.ENGLISH, text));
        if (tagInfo.get("url") != null) {
            item.setWebsite(tagInfo.get("url").get("#text").getTextValue());
        }

        String address = tagInfo.get("address") != null ? tagInfo.get("address").get("#text").getTextValue()
                : null;
        item.getGpsPositions().add(new GpsPosition(item, Float.valueOf(tagInfo.get("@lat").getTextValue()),
                Float.valueOf(tagInfo.get("@long").getTextValue()), address, "London"));

        if (LOG.isDebugEnabled()) {

            LOG.debug("Importing content id:" + id + " " + text);

        }
        itemService.saveOrUpdate(item);
        return true;
    } catch (Exception e) {
        if (LOG.isDebugEnabled()) {

            LOG.debug("Error importing content " + e.toString());

        }
        e.printStackTrace();
        throw new Exception(e.toString() + " import dell'id  " + id);

    }
}

From source file:hydrograph.ui.expression.editor.dialogs.AddCategoreisDialog.java

public boolean createPropertyFileForSavingData() {
    IProject iProject = BuildExpressionEditorDataSturcture.INSTANCE.getCurrentProject();
    IFolder iFolder = iProject.getFolder(PathConstant.PROJECT_RESOURCES_FOLDER);
    FileOutputStream file = null;
    Properties properties = new Properties();
    try {// ww w  .j av  a  2s  . c  om
        if (!iFolder.exists()) {
            iFolder.create(true, true, new NullProgressMonitor());
        }
        for (String items : categoriesDialogTargetComposite.getTargetList().getItems()) {
            String jarFileName = StringUtils.trim(StringUtils.substringAfter(items, Constants.DASH));
            String packageName = StringUtils.trim(StringUtils.substringBefore(items, Constants.DASH));
            properties.setProperty(packageName, jarFileName);
        }

        file = new FileOutputStream(iFolder.getLocation().toString() + File.separator
                + PathConstant.EXPRESSION_EDITOR_EXTERNAL_JARS_PROPERTIES_FILES);
        properties.store(file, "");
        return true;
    } catch (IOException | CoreException exception) {
        LOGGER.error("Exception occurred while saving jar file path at projects setting folder", exception);
    } finally {
        if (file != null) {
            try {
                file.close();
            } catch (IOException e) {
                LOGGER.warn("Exception in closing output stream. The error message is " + e.getMessage());
            }
        }
    }
    return false;
}

From source file:cn.newtouch.util.Struts2Utils.java

/**
 * ?contentTypeheaders./*from w  w w  . j  ava  2s  .c  o m*/
 */
private static HttpServletResponse initResponseHeader(final String contentType, final String... headers) {
    // ?headers?
    String encoding = DEFAULT_ENCODING;
    boolean noCache = DEFAULT_NOCACHE;
    for (String header : headers) {
        String headerName = StringUtils.substringBefore(header, ":");
        String headerValue = StringUtils.substringAfter(header, ":");

        if (StringUtils.equalsIgnoreCase(headerName, HEADER_ENCODING)) {
            encoding = headerValue;
        } else if (StringUtils.equalsIgnoreCase(headerName, HEADER_NOCACHE)) {
            noCache = Boolean.parseBoolean(headerValue);
        } else {
            throw new IllegalArgumentException(headerName + "??header");
        }
    }

    HttpServletResponse response = ServletActionContext.getResponse();

    // headers?
    String fullContentType = contentType + ";charset=" + encoding;
    response.setContentType(fullContentType);
    if (noCache) {
        ServletUtils.setDisableCacheHeader(response);
    }

    return response;
}

From source file:info.magnolia.importexport.BootstrapUtil.java

/**
 * I.e. given a resource path like <code>/mgnl-bootstrap/foo/config.server.i18n.xml</code> it will return <code>config</code>.
 *///from   w w  w . j a v a  2  s  . c  o  m
public static String getWorkspaceNameFromResource(final String resourcePath) {
    String resourceName = StringUtils.replace(resourcePath, "\\", "/");

    String name = getFilenameFromResource(resourceName, ".xml");
    String fullPath = DataTransporter.revertExportPath(name);
    return StringUtils.substringBefore(fullPath, "/");
}

From source file:com.shallop.codedrill.common.web.struts2.Struts2Utils.java

/**
 * ?contentTypeheaders./*from ww  w.  j  a v  a2  s. c  o m*/
 */
private static HttpServletResponse initResponseHeader(final String contentType, final String... headers) {
    //?headers?
    String encoding = DEFAULT_ENCODING;
    boolean noCache = DEFAULT_NOCACHE;
    for (String header : headers) {
        String headerName = StringUtils.substringBefore(header, ":");
        String headerValue = StringUtils.substringAfter(header, ":");

        if (StringUtils.equalsIgnoreCase(headerName, HEADER_ENCODING)) {
            encoding = headerValue;
        } else if (StringUtils.equalsIgnoreCase(headerName, HEADER_NOCACHE)) {
            noCache = Boolean.parseBoolean(headerValue);
        } else {
            throw new IllegalArgumentException(headerName + "??header");
        }
    }

    //      HttpServletResponse response = ServletActionContext.getResponse();
    HttpServletResponse response = null;

    //headers?
    String fullContentType = contentType + ";charset=" + encoding;
    response.setContentType(fullContentType);
    if (noCache) {
        ServletUtils.setDisableCacheHeader(response);
    }

    return response;
}