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

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

Introduction

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

Prototype

public static String[] substringsBetween(String str, String open, String close) 

Source Link

Document

Searches a String for substrings delimited by a start and end tag, returning all matching substrings in an array.

Usage

From source file:com.haulmont.cuba.security.global.UserUtils.java

public static String formatName(String pattern, String firstName, String lastName, String middleName)
        throws ParseException {
    if (pattern == null || pattern.length() == 0)
        throw new ParseException("Pattern error", 0);
    if (firstName == null || firstName.equals("null"))
        firstName = "";
    if (lastName == null || lastName.equals("null"))
        lastName = "";
    if (middleName == null || middleName.equals("null"))
        middleName = "";
    String[] params = StringUtils.substringsBetween(pattern, "{", "}");
    int i;/*from   ww  w  .  j a  v a2 s  .c  o  m*/
    for (i = 0; i < params.length; i++) {
        pattern = StringUtils.replace(pattern, "{" + params[i] + "}", "{" + i + "}", 1);
        params[i] = parseParam(params[i], firstName, lastName, middleName);
    }
    for (i = 0; i < params.length; i++) {
        pattern = StringUtils.replace(pattern, "{" + i + "}", params[i], 1);
    }
    return pattern;
}

From source file:com.aionemu.packetsamurai.parser.valuereader.ClientStringReader.java

public static void load() {
    //PacketSamurai.getUserInterface().log("Loading Client strings... Please wait.");
    Util.drawTitle("Client Strings");
    File stringsFolder = new File("./data/client_strings");
    if (!stringsFolder.exists()) {
        stringsFolder.mkdir();//w ww  .j  a v  a2  s .c o m
    }
    try {
        File[] files = stringsFolder.listFiles();
        File[] arrayOfFile1;
        int j = (arrayOfFile1 = files).length;
        for (int i = 0; i < j; i++) {
            File sFile = arrayOfFile1[i];
            File xml = new File(sFile.getPath());

            String stringFile = FileUtils.readFileToString(xml);
            String[] strings = StringUtils.substringsBetween(stringFile, "<string>", "</string>");
            if (strings != null) {
                String[] arrayOfString1;
                int m = (arrayOfString1 = strings).length;
                for (int k = 0; k < m; k++) {
                    String string = arrayOfString1[k];
                    int stringId = Integer.parseInt(StringUtils.substringBetween(string, "<id>", "</id>"));
                    String stringBody = StringUtils.substringBetween(string, "<body>", "</body>");
                    stringsById.put(Integer.valueOf(stringId), stringBody);
                }
            }
        }
        PacketSamurai.getUserInterface().log(
                "Strings [Client] - Loaded " + stringsById.size() + " strings from " + files.length + " Files");
    } catch (IOException e) {
        PacketSamurai.getUserInterface().log("ERROR: Failed to load client_strings.xsd: " + e.toString());
        e.printStackTrace();
    }
}

From source file:de.tudarmstadt.ukp.csniper.webapp.search.cqp.CqpContextProvider.java

@Override
public ItemContext getContext(EvaluationItem aItem, int aLeftSize, int aRightSize) {
    StringBuilder[] sb = { new StringBuilder(), new StringBuilder() };
    int idx = 0;/*from   ww w . j  a v a2s. co  m*/

    int contextWidth = 1;
    CqpQuery cqpManager = new CqpQuery(engine, aItem.getType(), aItem.getCollectionId());
    List<String> output = cqpManager.getContextAround(aItem, contextWidth);

    String[] context = StringUtils.substringsBetween(output.get(0), "<sentence>", "</sentence>");

    if (context.length < 1 + 2 * contextWidth) {
        // this method of extracting the context is not error prone
        // TODO find a better one...
        for (int i = 0; i < context.length; i++) {
            if (context[i].equals(aItem.getCoveredText())) {
                idx = 1;
            } else {
                sb[idx].append(context[i] + " ");
            }
        }
    } else {
        // this can only be used when we have full context
        for (int i = 0; i < (context.length - 1) / 2; i++) {
            sb[0].append(context[i] + " ");
            sb[1].append(context[i + (context.length - 1) / 2 + 1] + " ");
        }
    }

    return null;
    //      return new String[] { sb[0].toString(), sb[1].toString() };
}

From source file:com.siberhus.ngai.EntityQueryMap.java

/**
 * //  w  w  w.  j av  a2s. c o  m
 * <p>
 * Pass query string as parameter then this method will create {@link javax.persistence.Query} <br/>
 * object from that query, execute the query and return the entity list as the result.
 * </p>
 * 
 * @param queryString (JPQL)
 * @return List of entity
 * @since 0.9
 */
@SuppressWarnings("unchecked")
@Override
public List<Object> get(Object q) {

    String queryStr = q + " ";
    Query query = getEntityManager().createQuery(queryStr);
    String paramNames[] = StringUtils.substringsBetween(queryStr, ":", " ");
    if (paramNames != null) {
        for (String paramName : paramNames) {
            query.setParameter(paramName, findAttribute(paramName));
        }
    }
    return query.getResultList();
}

From source file:gov.nij.bundles.intermediaries.ers.EntityResolutionNamespaceContextHelpers.java

/**
 * This method returns all prefixes that are in an xpath expression
 * //from ww  w .  jav a2 s  .  c o m
 * @param xpath
 * @return
 */
public static Set<String> returnPrefixes(String xpath) {
    //Return all the strings by splitting on the regular expression that will find '/' and '//'
    //TODO: improve this regular expression, it will return empty strings in some use cases.
    String[] xpathValue = xpath.split("/|//");

    //Use a hashset for prefixes so we don't repeat namespaces
    Set<String> prefixes = new HashSet<String>();

    for (int i = 0; i < xpathValue.length; i++) {

        //Check to see if string is empty, regular expression will return empty strings in some cases
        if (StringUtils.isNotEmpty(xpathValue[i])) {
            String prefixAndElement = xpathValue[i];

            //If we have an '@', we need to get that prefix as well
            if (prefixAndElement.contains("@")) {
                String[] prefixesFromAttributes = StringUtils.substringsBetween(prefixAndElement, "@", ":");

                for (int j = 0; j < prefixesFromAttributes.length; j++) {
                    prefixes.add(prefixesFromAttributes[j]);
                }

            } else {
                //If there are no attributes, just get the namespace prefix which will appear before the ':'
                String prefix = StringUtils.substringBefore(prefixAndElement, ":");
                prefixes.add(prefix);
            }
        }
    }

    return prefixes;

}

From source file:com.gs.tools.doc.extractor.core.html.HTMLDocumentExtractor.java

private long processBody(final File rootDir, final String rootLocation, final String bodyContent)
        throws Exception {
    long fileCount = 0;
    String imgLinks[] = StringUtils.substringsBetween(bodyContent, "<img", ">");
    if (null != imgLinks && imgLinks.length > 0) {
        for (String imgLink : imgLinks) {
            String img = StringUtils.substringBetween(imgLink, "src=\"", "\"");
            if (null != img && img.length() > 0) {
                File imgFile = new File(rootDir, img);
                File imgFolder = new File(rootDir.getAbsolutePath());
                String hrefLocation = rootLocation;
                if (img.contains("/")) {
                    String path = img.substring(0, img.lastIndexOf("/"));
                    hrefLocation += "/" + path;
                    String name = img.substring(img.lastIndexOf("/") + 1);
                    imgFolder = new File(rootDir, path);
                    if (!imgFolder.exists()) {
                        imgFolder.mkdirs();
                    }/*  w  w  w .  j a  va 2 s.  co  m*/
                    imgFile = new File(imgFolder, name);
                }
                if (!sourceUrlCache.contains(rootLocation + "/" + img)) {
                    sourceUrlCache.add(rootLocation + "/" + img);
                    byte[] cssContentByte = downloadManager.readContentFromGET(rootLocation + "/" + img);
                    if (null != cssContentByte && cssContentByte.length > 0) {
                        logger.info("Save to: " + imgFile.getAbsolutePath());
                        writeTo(cssContentByte, new BufferedOutputStream(new FileOutputStream(imgFile)));
                        fileCount++;
                    }
                }
            }
        }
    }
    String[] anchors = StringUtils.substringsBetween(bodyContent, "<a", "</a>");
    if (null != anchors && anchors.length > 0) {
        for (String anchor : anchors) {
            String href = StringUtils.substringBetween(anchor, "href=\"", "\"");
            if (null != href && href.length() > 0 && href.endsWith(getFileExtension())) {
                File hrefFile = new File(rootDir, href);
                File hrefFolder = new File(rootDir.getAbsolutePath());
                String hrefLocation = rootLocation;
                if (href.contains("/")) {
                    String path = href.substring(0, href.lastIndexOf("/"));
                    hrefLocation += "/" + path;
                    String name = href.substring(href.lastIndexOf("/") + 1);
                    hrefFolder = new File(rootDir, path);
                    if (!hrefFolder.exists()) {
                        hrefFolder.mkdirs();
                    }
                    hrefFile = new File(hrefFolder, name);
                }
                if (!sourceUrlCache.contains(rootLocation + "/" + href)) {
                    sourceUrlCache.add(rootLocation + "/" + href);
                    byte[] cssContentByte = downloadManager.readContentFromGET(rootLocation + "/" + href);
                    if (null != cssContentByte && cssContentByte.length > 0) {
                        logger.info("Save to: " + hrefFile.getAbsolutePath());
                        writeTo(cssContentByte, new BufferedOutputStream(new FileOutputStream(hrefFile)));
                        fileCount++;
                        logger.info("File count: " + fileCount);
                        String hrefContent = new String(cssContentByte, Charset.forName("UTF-8"));
                        String bodySection = StringUtils.substringBetween(hrefContent, "<body", "</body>");
                        fileCount += processBody(hrefFolder, hrefLocation, bodySection);
                    }
                }
            }
        }
    }

    return fileCount;
}

From source file:com.liferay.qa.MarkdownBuilder.java

private void imageValidate(String content, String file) {
    String srcString = "/src/";

    if (_OS_UNIX) {
        srcString = "/src/";
    }/*from   ww w.ja v a  2s.  co  m*/

    int x = file.indexOf(srcString) + 1;
    int y = x + 4;

    String fileDir = file.substring(0, x);
    String fileName = file.substring(y);

    x = fileName.indexOf(".markdown");

    String testName = fileName.substring(0, x);

    String[] imageNames = StringUtils.substringsBetween(content, "../images/", ")");
    try {
        for (int i = 0; i < imageNames.length; i++) {
            File imageFile = new File(fileDir + "images/" + imageNames[i]);
            boolean exists = imageFile.exists();

            if (!exists) {
                System.out.println(imageNames[i] + " does not exist!");
                System.exit(-1);
            }
        }
    } catch (Exception e) {
    }
}

From source file:it.openutils.mgnlaws.magnolia.init.ClasspathMgnlServletContextListener.java

private static String[] getNamesBetweenPlaceholders(String propertiesFilesString,
        String contextNamePlaceHolder) {
    final String[] names = StringUtils.substringsBetween(propertiesFilesString,
            PropertiesInitializer.PLACEHOLDER_PREFIX + contextNamePlaceHolder,
            PropertiesInitializer.PLACEHOLDER_SUFFIX);
    return StringUtils.stripAll(names);
}

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 w  w  w . ja  va  2  s.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:de.awtools.config.AbstractGlueConfig.java

/**
 * Ersetzt die ${...} Platzhalter in einem String. Die Ersetzung werden
 * in einer Map gelagert. Die Schlssel reprsentieren die Platzhalter
 * im String. Die Ersetzungen sind die Werte der Schlssel in der
 * <code>placeholders</code> Map.
 *
 * @param string Der zu prfende String.//from ww w  .  j  a  v  a 2  s  . com
 * @param placeholders Die Ersetzungen.
 * @return Der berarbeitete String.
 */
public static String replacePlaceholder(final String string, final Map<String, String> placeholders) {

    String result = string;
    String[] keys = StringUtils.substringsBetween(string, "${", "}");

    if (keys != null) {
        for (String key : keys) {
            String value = placeholders.get(key);
            if (value != null) {
                StringBuilder sb = new StringBuilder("${").append(key).append("}");
                result = StringUtils.replace(result, sb.toString(), value);
            }
        }
    }

    return result;
}