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

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

Introduction

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

Prototype

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

Source Link

Document

Replaces a String with another String inside a larger String, once.

Usage

From source file:org.exoplatform.services.wcm.utils.WCMCoreUtils.java

public static String getActiveStylesheet(Node webcontent) throws Exception {
    StringBuilder buffer = new StringBuilder();
    String cssQuery = StringUtils.replaceOnce(WEBCONTENT_CSS_QUERY, "{path}", webcontent.getPath());
    // Need re-login to get session because this node is get from template and the session is not live anymore.
    // If node is version (which is stored in system workspace) we have to login to system workspace to get data
    NodeLocation webcontentLocation = NodeLocation.getNodeLocationByNode(webcontent);
    ManageableRepository repository = (ManageableRepository) webcontent.getSession().getRepository();
    Session session;// ww w  .jav  a 2 s  . c o  m
    try {
        if (webcontentLocation.getPath().startsWith("/jcr:system"))
            session = WCMCoreUtils.getSystemSessionProvider()
                    .getSession(repository.getConfiguration().getSystemWorkspaceName(), repository);
        else {
            session = WCMCoreUtils.getSystemSessionProvider().getSession(webcontentLocation.getWorkspace(),
                    repository);
        }

        QueryManager queryManager = session.getWorkspace().getQueryManager();
        Query query = queryManager.createQuery(cssQuery, Query.SQL);
        QueryResult queryResult = query.execute();
        NodeIterator iterator = queryResult.getNodes();
        while (iterator.hasNext()) {
            Node registeredCSSFile = iterator.nextNode();
            buffer.append(registeredCSSFile.getNode(NodetypeConstant.JCR_CONTENT)
                    .getProperty(NodetypeConstant.JCR_DATA).getString());
        }
    } catch (Exception e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Unexpected problem happen when active stylesheet", e);
        }
    }
    return buffer.toString();
}

From source file:org.hupo.psi.mi.rdf.BioPaxUriFixer.java

private void fixURIs(Map<String, String> idMappings, Reader reader, Writer writer) throws IOException {
    BufferedReader in = new BufferedReader(reader);
    String line;/*from   w w  w.  ja  va2s  .  c  om*/
    while ((line = in.readLine()) != null) {

        if (line.contains("Reference")) {
            for (Map.Entry<String, String> protMapEntry : idMappings.entrySet()) {
                if (line.contains(protMapEntry.getKey())) {
                    line = line.replaceAll(protMapEntry.getKey(), protMapEntry.getValue());
                }
            }
        }

        if (line.contains("urn:miriam:")) {
            String[] tokens = line.split("urn:miriam:");
            // hack : only take first word
            if (tokens[1].contains(" <")) {
                int index = tokens[1].indexOf(" <");
                String uriToFix = tokens[1].substring(0, index);
                tokens[1] = StringUtils.replaceOnce(uriToFix, ":", "/") + tokens[1].substring(index);
            } else {
                tokens[1] = StringUtils.replaceOnce(tokens[1], ":", "/");
            }

            line = StringUtils.join(tokens, IDENTIFIERS_ORG);
        }

        writer.write(line + NEW_LINE);
    }

    // close bufferReader
    in.close();
}

From source file:org.jahia.ajax.gwt.helper.StubHelper.java

private String detectNodeTypeName(final String path, final JCRSessionWrapper session) {
    String ntName = null;/*from  w w  w  .j  a  v a2s .  c  om*/
    try {
        JCRNodeWrapper node = session.getNode(path);
        JCRNodeWrapper parent = node.isNodeType("jnt:nodeTypeFolder") ? node
                : JCRContentUtils.getParentOfType(node, "jnt:nodeTypeFolder");
        if (parent != null) {
            ntName = StringUtils.replaceOnce(parent.getName(), "_", ":");
        }
    } catch (RepositoryException e) {
        logger.error("Error while trying to find the node type associated with this path " + path, e);
    }
    return ntName;
}

From source file:org.jahia.modules.external.modules.ModulesDataSource.java

/**
 * Test if the name is a known node type in the system.
 *
 * @param name/* ww  w  .j a  v  a2s  . com*/
 * @return
 */
public boolean isNodeType(String name) {
    name = StringUtils.replaceOnce(name, "_", ":");
    final Set<Map.Entry<String, NodeTypeRegistry>> entries = new HashSet<Map.Entry<String, NodeTypeRegistry>>(
            nodeTypeRegistryMap.entrySet());
    for (Map.Entry<String, NodeTypeRegistry> entry : entries) {
        try {
            entry.getValue().getNodeType(name);
            return true;
        } catch (NoSuchNodeTypeException e) {
            // Continue with next registry
        }
    }
    // if not found, check in jahia registry
    try {
        NodeTypeRegistry.getInstance().getNodeType(name);
        return true;
    } catch (NoSuchNodeTypeException e) {
        return false;
    }
}

From source file:org.jahia.services.content.rules.RulesListener.java

public void addRules(Resource dsrlFile, JahiaTemplatesPackage aPackage) {
    long start = System.currentTimeMillis();
    try {/*from  w w  w . j  a va2s  .c  o m*/
        File compiledRulesDir = new File(SettingsBean.getInstance().getJahiaVarDiskPath() + "/compiledRules");
        if (aPackage != null) {
            compiledRulesDir = new File(compiledRulesDir, aPackage.getIdWithVersion());
        } else {
            compiledRulesDir = new File(compiledRulesDir, "system");
        }
        if (!compiledRulesDir.exists()) {
            compiledRulesDir.mkdirs();
        }

        ClassLoader packageClassLoader = aPackage != null ? aPackage.getClassLoader() : null;
        if (packageClassLoader != null) {
            ruleBaseClassLoader.addClassLoaderToEnd(packageClassLoader);
        }

        // first let's test if the file exists in the same location, if it was pre-packaged as a compiled rule
        File pkgFile = new File(compiledRulesDir,
                StringUtils.substringAfterLast(dsrlFile.getURL().getPath(), "/") + ".pkg");
        if (pkgFile.exists() && pkgFile.lastModified() > dsrlFile.lastModified()) {
            ObjectInputStream ois = null;
            try {
                ois = new DroolsObjectInputStream(new FileInputStream(pkgFile),
                        packageClassLoader != null ? packageClassLoader : null);
                Package pkg = new Package();
                pkg.readExternal(ois);
                if (ruleBase.getPackage(pkg.getName()) != null) {
                    ruleBase.removePackage(pkg.getName());
                }
                applyDisabledRulesConfiguration(pkg);
                ruleBase.addPackage(pkg);
                if (aPackage != null) {
                    modulePackageNameMap.put(aPackage.getName(), pkg.getName());
                }
            } finally {
                IOUtils.closeQuietly(ois);
            }
        } else {
            InputStream drlInputStream = dsrlFile.getInputStream();
            List<String> lines = Collections.emptyList();
            try {
                lines = IOUtils.readLines(drlInputStream);
            } finally {
                IOUtils.closeQuietly(drlInputStream);
            }
            StringBuilder drl = new StringBuilder(4 * 1024);
            for (String line : lines) {
                if (drl.length() > 0) {
                    drl.append("\n");
                }
                if (line.trim().length() > 0 && line.trim().charAt(0) == '#') {
                    drl.append(StringUtils.replaceOnce(line, "#", "//"));
                } else {
                    drl.append(line);
                }
            }

            PackageBuilderConfiguration cfg = packageClassLoader != null
                    ? new PackageBuilderConfiguration(packageClassLoader)
                    : new PackageBuilderConfiguration();

            PackageBuilder builder = new PackageBuilder(cfg);

            Reader drlReader = new StringReader(drl.toString());
            try {
                builder.addPackageFromDrl(drlReader, new StringReader(getDslFiles()));
            } finally {
                IOUtils.closeQuietly(drlReader);
            }

            PackageBuilderErrors errors = builder.getErrors();

            if (errors.getErrors().length == 0) {
                Package pkg = builder.getPackage();

                ObjectOutputStream oos = null;
                try {
                    pkgFile.getParentFile().mkdirs();
                    oos = new DroolsObjectOutputStream(new FileOutputStream(pkgFile));
                    pkg.writeExternal(oos);
                } catch (IOException e) {
                    logger.error("Error writing rule package to file " + pkgFile, e);
                } finally {
                    IOUtils.closeQuietly(oos);
                }

                if (ruleBase.getPackage(pkg.getName()) != null) {
                    ruleBase.removePackage(pkg.getName());
                }
                applyDisabledRulesConfiguration(pkg);
                ruleBase.addPackage(pkg);
                if (aPackage != null) {
                    modulePackageNameMap.put(aPackage.getName(), pkg.getName());
                }
                logger.info("Rules for " + pkg.getName() + " updated in " + (System.currentTimeMillis() - start)
                        + "ms.");
            } else {
                logger.error(
                        "---------------------------------------------------------------------------------");
                logger.error("Errors when compiling rules in " + dsrlFile + " : " + errors.toString());
                logger.error(
                        "---------------------------------------------------------------------------------");
            }
        }
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
}

From source file:org.jboss.community.sbs.plugin.struts.mapping.EnURLMapping.java

@Override
public void process(String uri, ActionMapping mapping) {
    super.process(StringUtils.replaceOnce(uri, getMappingPrefix(), "/community"), mapping);
}

From source file:org.kuali.kfs.module.external.kc.util.GlobalVariablesExtractHelper.java

public static String replaceTokens(String line, String... replacements) {
    int i = 0;/*from  w  w  w.j  av  a2  s  .c  o m*/
    for (String err : replacements) {
        String repl = "{" + String.valueOf(i++) + "}";
        line = StringUtils.replaceOnce(line, repl, err);
    }
    return line;
}

From source file:org.kuali.kfs.sys.batch.BatchFileUtils.java

/**
 * returns a path relative to the appropriate lookup root directory, while including the name of the root directory for example,
 * if the parameter is "c:\opt\staging\gl\somefile.txt" and the roots are "c:\opt\reports;c:\opt\staging", it will return
 * "staging\gl\somefile.txt" (the system-specific path separator will be used). If there are multiple matching roots, then the
 * first one to be matched will take precedence
 * // w  w w.j  a  va 2s.com
 * @param absolutePath an absolute path for a file/directory
 */
public static String pathRelativeToRootDirectory(String absolutePath) {
    for (File rootDirectory : retrieveBatchFileLookupRootDirectories()) {
        if (absolutePath.startsWith(rootDirectory.getAbsolutePath())) {
            return StringUtils.replaceOnce(absolutePath, rootDirectory.getAbsolutePath(),
                    rootDirectory.getName());
        }
    }
    throw new RuntimeException("Unable to find appropriate root directory)");
}

From source file:org.kuali.kfs.sys.batch.BatchFileUtils.java

/**
 * @param path a path string that was generated by {@link #pathRelativeToRootDirectory(String)}
 * @return an absolute path, including the root directory
 *///from   w  ww  .j a  va  2 s  . c o  m
public static String resolvePathToAbsolutePath(String path) {
    for (File rootDirectory : retrieveBatchFileLookupRootDirectories()) {
        if (path.startsWith(rootDirectory.getName())) {
            return new File(
                    StringUtils.replaceOnce(path, rootDirectory.getName(), rootDirectory.getAbsolutePath()))
                            .getAbsolutePath();
        }
    }
    throw new RuntimeException("Cannot resolve to absolute path");
}

From source file:org.kuali.kfs.sys.service.impl.ReportAggregatorServiceTextImpl.java

protected int dumpFileContents(Writer outputWriter, File file, int currentPageNumber) {
    try {//w  w  w.j  av  a 2 s . c o  m
        BufferedReader reader = new BufferedReader(new FileReader(file));
        while (reader.ready()) {
            String line = reader.readLine();
            while (line.contains(KFSConstants.REPORT_WRITER_SERVICE_PAGE_NUMBER_PLACEHOLDER)) {
                line = StringUtils.replaceOnce(line, KFSConstants.REPORT_WRITER_SERVICE_PAGE_NUMBER_PLACEHOLDER,
                        String.valueOf(currentPageNumber));
                currentPageNumber++;
            }
            outputWriter.write(line);
            outputWriter.write(newLineCharacter);
        }
        reader.close();
        return currentPageNumber;
    } catch (IOException e) {
        throw new RuntimeException("Error reading or writing file", e);
    }
}