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

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

Introduction

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

Prototype

public static String replace(String text, String searchString, String replacement) 

Source Link

Document

Replaces all occurrences of a String within another String.

Usage

From source file:com.fluidops.iwb.ui.templates.ServletPageParameters.java

/**
 * Configures the search box with a default value. 
 * //from   w w w . j  av a  2s  .  co m
 * This method is invoked when the user is on the main search page.
 * 
 * @param pc
 */
private static void configureSearchInput(SearchPageContext pc, SearchTextInput searchInput) {

    // configure the search input dependent on the request
    // Check if the query did not come from the SparqlServlet (in this case, SPARQL is provided as a request parameter)
    String preSetLanguage = pc.getRequestParameter("queryLanguage");
    if (StringUtil.isNullOrEmpty(preSetLanguage) || !preSetLanguage.equalsIgnoreCase("SPARQL")) {
        // If keyword search, just display in the search input box
        if (pc.queryLanguage.equals("KEYWORD")) {
            searchInput.setSearchString(pc.query);
        } else {
            // Otherwise (SPARQL, SQL, ...), display together with the prefix
            // TODO: replace with a proper helper method, if such one exists: 
            // there is no dedicated method in StringUtils.
            // Currently, System.lineSeparator() does not work on Windows: default separator is "\r\n", 
            // while the query received from a SearchWidget only contains "\n"
            // So, for now deleting both \r and \n.
            String sQuery = StringUtils.remove(pc.query, "\r");
            sQuery = StringUtils.replace(sQuery, "\n", " ");
            searchInput.setSearchString(pc.queryLanguage + ": " + sQuery);
        }
    }
}

From source file:info.magnolia.cms.filters.Mapping.java

/**
 * See SRV.11.2 Specification of Mappings in the Servlet Specification for the syntax of
 * mappings. Additionally, you can also use plain regular expressions to map your servlets, by
 * prefix the mapping by "regex:". (in which case anything in the request url following the
 * expression's match will be the pathInfo - if your pattern ends with a $, extra pathInfo won't
 * match)//from   w  ww.j  av  a 2 s . com
 */
public void addMapping(final String mapping) {
    final String pattern;

    // we're building a Pattern with 3 groups: (1) servletPath (2) ignored (3) pathInfo

    if (isDefaultMapping(mapping)) {
        // the mapping is exactly '/*', the servlet path should be
        // an empty string and everything else should be the path info
        pattern = "^()(/)(" + SimpleUrlPattern.MULTIPLE_CHAR_PATTERN + ")";
    } else if (isPathMapping(mapping)) {
        // the pattern ends with /*, escape out metacharacters for
        // use in a regex, and replace the ending * with MULTIPLE_CHAR_PATTERN
        final String mappingWithoutSuffix = StringUtils.removeEnd(mapping, "/*");
        pattern = "^(" + escapeMetaCharacters(mappingWithoutSuffix) + ")(/)("
                + SimpleUrlPattern.MULTIPLE_CHAR_PATTERN + ")";
    } else if (isExtensionMapping(mapping)) {
        // something like '*.jsp', everything should be the servlet path
        // and the path info should be null
        final String regexedMapping = StringUtils.replace(mapping, "*.",
                SimpleUrlPattern.MULTIPLE_CHAR_PATTERN + "\\.");
        pattern = "^(" + regexedMapping + ")$";
    } else if (isRegexpMapping(mapping)) {
        final String mappingWithoutPrefix = StringUtils.removeStart(mapping, "regex:");
        pattern = "^(" + mappingWithoutPrefix + ")($|/)(" + SimpleUrlPattern.MULTIPLE_CHAR_PATTERN + ")";
    } else {
        // just literal text, ensure metacharacters are escaped, and that only
        // the exact string is matched.
        pattern = "^(" + escapeMetaCharacters(mapping) + ")$";
    }
    log.debug("Adding new mapping for {}", mapping);

    mappings.add(Pattern.compile(pattern));
}

From source file:info.magnolia.link.LinkUtil.java

/**
 * Parses provided html and transforms all the links to the magnolia format. Used during storing.
 * @param html html code with links to be converted
 * @return html with changed hrefs/*from  ww w .  j  a  v a 2s. c om*/
 */
public static String convertAbsoluteLinksToUUIDs(String html) {
    // get all link tags
    Matcher matcher = LINK_OR_IMAGE_PATTERN.matcher(html);
    StringBuffer res = new StringBuffer();
    while (matcher.find()) {
        final String href = matcher.group(4);
        if (!isExternalLinkOrAnchor(href)) {
            try {
                Link link = parseLink(href);
                String linkStr = toPattern(link);
                linkStr = StringUtils.replace(linkStr, "\\", "\\\\");
                linkStr = StringUtils.replace(linkStr, "$", "\\$");
                matcher.appendReplacement(res, "$1" + linkStr + "$5");
            } catch (LinkException e) {
                // this is expected if the link is an absolute path to something else
                // than content stored in the repository
                matcher.appendReplacement(res, "$0");
                log.debug("can't parse link", e);
            }
        } else {
            matcher.appendReplacement(res, "$0");
        }
    }
    matcher.appendTail(res);
    return res.toString();
}

From source file:edu.ku.brc.specify.extras.FixSQLString.java

/**
 * //from  w  ww .  j  a  v  a  2  s  .c  o m
 */
private void fix() {
    StringBuilder sb = new StringBuilder("sql = \"");
    String srcStr = srcTA.getText();
    boolean wasInner = false;
    for (String line : StringUtils.splitByWholeSeparator(srcStr, "\n")) {
        String str = line;//StringUtils.deleteWhitespace(line);

        //            while (str.startsWith("  INNER"))
        //            {
        //                str = 
        //            }

        if (str.toUpperCase().startsWith("INNER") || str.toUpperCase().startsWith("ORDER")
                || str.toUpperCase().startsWith("GROUP")) {
            if (!wasInner) {
                sb.append(" \" +");
                wasInner = false;
            }
            sb.append("\n    \"" + line.trim() + " \" +");
            wasInner = true;
        } else {
            if (wasInner) {
                sb.append("    \"");
                wasInner = false;
            }
            sb.append(' ');
            sb.append(StringUtils.replace(line.trim(), "\n", " "));
            //sb.append(StringUtils.replace(line.trim(), "\r\n", " "));
            //sb.append(StringUtils.replace(line.trim(), "\r", " "));
        }
    }

    if (wasInner) {
        sb.setLength(sb.length() - 3);
        sb.append("\";");
    } else {
        sb.append("\";");
    }
    dstTA.setText(sb.toString());

    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            dstTA.requestFocus();
            dstTA.selectAll();
            UIHelper.setTextToClipboard(dstTA.getText());
        }
    });

}

From source file:net.sf.clickclick.examples.page.SourceViewer.java

private String getEncodedLine(String line) {

    if (isHtml) {
        line = ClickUtils.escapeHtml(line);

        for (String keyword : HTML_KEYWORDS) {
            line = renderHtmlKeywords(line, keyword);
        }/*from w w w.jav a2 s .co m*/

        for (String keyword : VELOCITY_KEYWORDS) {
            line = renderVelocityKeywords(line, keyword);
        }

        String renderedDollar = "<font color=\"red\">$</font>";

        line = StringUtils.replace(line, "$", renderedDollar);

    } else if (isXml) {
        line = ClickUtils.escapeHtml(line);

        for (String keyword : XML_KEYWORDS) {
            line = renderXmlKeywords(line, keyword);
        }

    } else {
        line = ClickUtils.escapeHtml(line);
    }

    return line;
}

From source file:com.voa.weixin.task.Task.java

@Override
public void generateUrl(String[] keys, String[] values) {
    if (keys != null) {
        for (int i = 0; i < keys.length; i++) {
            this.url = StringUtils.replace(this.url, keys[i], values[i]);
        }/*from www  .j  av a 2 s.  c  om*/
    }
}

From source file:com.weibo.api.OAuth2.java

private String parseSignedRequest(String signedRequest, String appSecret) {
    String tokenInfoValue = null;
    String[] tokens = StringUtils.split(signedRequest, "\\.", 2);
    // base64Token
    String base64Token = tokens[0];
    //  url encode/decode ??base64url ??
    // '+''/'??'-''_''=' ???base64?'='?
    int padding = (4 - base64Token.length() % 4);
    for (int i = 0; i < padding; i++) {
        base64Token += "=";
    }/*www. ja  v  a2s  .co m*/
    base64Token = StringUtils.replace(base64Token, "-", "+");
    base64Token = StringUtils.replace(base64Token, "_", "/");
    // base64Token1
    String token1 = tokens[1];
    SecretKey key = new SecretKeySpec(appSecret.getBytes(), ALGORITHM_HMACSHA256);
    try {
        Mac mac = Mac.getInstance(ALGORITHM_HMACSHA256);
        mac.init(key);
        mac.update(token1.getBytes());
        byte[] macResult = mac.doFinal();
        String base64Token1 = Base64.encodeBase64String(macResult);
        // access token
        if (StringUtils.equals(base64Token, base64Token1)) {
            tokenInfoValue = new String(Base64.decodeBase64(token1));
            log.info(tokenInfoValue);
        }
    } catch (NoSuchAlgorithmException e) {
        log.error(ExceptionUtils.getFullStackTrace(e));
    } catch (InvalidKeyException e) {
        log.error(ExceptionUtils.getFullStackTrace(e));
    }
    return tokenInfoValue;
}

From source file:eionet.cr.web.action.UploadCSVActionBean.java

/**
 *
 * @return//w w w. j  av  a 2  s.  co  m
 * @throws DAOException
 */
public Resolution upload() throws DAOException {

    // Prepare resolution.
    ForwardResolution resolution = new ForwardResolution(JSP_PAGE);

    fileName = fileBean.getFileName();

    FolderDAO folderDAO = DAOFactory.get().getDao(FolderDAO.class);
    if (overwrite) {

        // If doing overwrite, load wizard inputs from previous upload
        loadWizardInputsFromPreviousUpload();

        if (folderDAO.fileOrFolderExists(folderUri, StringUtils.replace(fileName, " ", "%20"))) {
            String oldFileUri = folderUri + "/" + StringUtils.replace(fileName, " ", "%20");
            // Delete existing data
            FileStore fileStore = FileStore.getInstance(FolderUtil.getUserDir(folderUri, getUserName()));
            folderDAO.deleteFileOrFolderUris(folderUri, Collections.singletonList(oldFileUri));
            DAOFactory.get().getDao(HarvestSourceDAO.class)
                    .removeHarvestSources(Collections.singletonList(oldFileUri));
            fileStore.delete(FolderUtil.extractPathInUserHome(folderUri + "/" + fileName));
        }
    } else {
        if (folderDAO.fileOrFolderExists(folderUri, StringUtils.replace(fileName, " ", "%20"))) {
            addCautionMessage("File or folder with the same name already exists.");
            return new RedirectResolution(UploadCSVActionBean.class).addParameter("folderUri", folderUri);
        }
    }

    try {
        // Save the file into user's file-store.
        long fileSize = fileBean.getSize();
        relativeFilePath = FolderUtil.extractPathInUserHome(folderUri + "/" + fileName);
        // FileStore fileStore = FileStore.getInstance(getUserName());
        FileStore fileStore = FileStore.getInstance(FolderUtil.getUserDir(folderUri, getUserName()));
        fileStore.addByMoving(relativeFilePath, true, fileBean);

        CsvImportHelper helper = new CsvImportHelper(uniqueColumns, fileUri, fileLabel, fileType, objectsType,
                publisher, license, attribution, source);

        // Store file as new source, but don't harvest it
        helper.insertFileMetadataAndSource(fileSize, getUserName());

        // Add metadata about user folder update
        helper.linkFileToFolder(folderUri, getUserName());

        // Prepare data linkins scripts dropdown
        dataLinkingScripts = new ArrayList<DataLinkingScript>();
        dataLinkingScripts.add(new DataLinkingScript());

        // If not given, the file's label equals the file's name
        if (StringUtils.isEmpty(fileLabel)) {
            fileLabel = fileName;
        }

        // Tell the JSP page that it should display the wizard.
        resolution.addParameter(PARAM_DISPLAY_WIZARD, "");

    } catch (Exception e) {
        LOGGER.error("Error while reading the file: ", e);
        addWarningMessage(e.getMessage());
    }

    return resolution;
}

From source file:info.magnolia.link.UUIDLinkTest.java

@Test
public void testUUIDToBinaryAfterRenaming() throws Exception {
    // now rename the the page
    session.getNode("/parent/sub").setPrimaryType(NodeTypes.Resource.NAME);
    session.getNode("/parent/sub").setProperty("fileName", "test");
    MockNode renameNode = (MockNode) session.getNode("/parent/sub");
    renameNode.setName("subRenamed");

    Link link = LinkUtil.parseUUIDLink(UUID_PATTERN_BINARY);
    assertEquals(StringUtils.replace(HREF_BINARY, "sub", "subRenamed"), NOP_TRANSFORMER.transform(link));
}

From source file:com.adguard.compiler.LocaleUtils.java

public static void writeLocalesToFirefoxInstallRdf(File dest, String extensionNamePostfix) throws IOException {
    //      <em:localized>
    //      <Description>
    //      <em:locale>en</em:locale>
    //      <em:name>Adguard AdBlocker</em:name>
    //      <em:description>Adguard AdBlocker</em:description>
    //      </Description>
    //      </em:localized>
    File installManifest = new File(dest, "install.rdf");
    if (!installManifest.exists()) {
        return;//from   w  ww . j a v  a 2  s.  c  om
    }

    StringBuilder sb = new StringBuilder();
    for (SupportedLocales locale : SupportedLocales.values()) {
        File localeFile = new File(dest, "locale/" + locale.code.replace("_", "-") + ".properties");
        String[] messages = StringUtils.split(FileUtils.readFileToString(localeFile), System.lineSeparator());
        String name = findMessage(messages, "name") + extensionNamePostfix;
        String description = findMessage(messages, "description");
        sb.append("<em:localized>").append(System.lineSeparator());
        sb.append("\t<Description>").append(System.lineSeparator());
        sb.append("\t\t<em:locale>").append(locale.code).append("</em:locale>").append(System.lineSeparator());
        sb.append("\t\t<em:name>").append(name).append("</em:name>").append(System.lineSeparator());
        sb.append("\t\t<em:description>").append(description).append("</em:description>")
                .append(System.lineSeparator());
        sb.append("\t</Description>").append(System.lineSeparator());
        sb.append("</em:localized>").append(System.lineSeparator());
    }

    String content = FileUtils.readFileToString(installManifest);
    content = StringUtils.replace(content, "${localised}", sb.toString());
    FileUtils.writeStringToFile(installManifest, content, "utf-8");
}