Example usage for org.apache.commons.lang3 StringUtils replaceEach

List of usage examples for org.apache.commons.lang3 StringUtils replaceEach

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringUtils replaceEach.

Prototype

public static String replaceEach(final String text, final String[] searchList, final String[] replacementList) 

Source Link

Document

Replaces all occurrences of Strings within another String.

Usage

From source file:org.eclipse.ebr.maven.AboutFilesUtil.java

public void generateAboutHtmlFile(final SortedMap<Artifact, Model> dependencies, final File outputDirectory)
        throws MojoExecutionException {
    final File aboutHtmlFile = new File(outputDirectory, ABOUT_HTML);
    if (aboutHtmlFile.isFile() && !isForce()) {
        getLog().warn(format("Found existing about.html file at '%s'. %s", aboutHtmlFile,
                REQUIRES_FORCE_TO_OVERRIDE_MESSAGE));
        return;/*  w  w  w .ja v a2s  .c om*/
    }

    String aboutHtmlText = readAboutHtmlTemplate();
    aboutHtmlText = StringUtils.replaceEach(aboutHtmlText, new String[] { // @formatter:off
            "@DATE@", "@THIRD_PARTY_INFO@" },
            new String[] { DateFormat.getDateInstance(DateFormat.LONG, Locale.US).format(new Date()),
                    getThirdPartyInfo(dependencies, outputDirectory) });
    // @formatter:on

    try {
        FileUtils.writeStringToFile(aboutHtmlFile, aboutHtmlText, UTF_8);
    } catch (final IOException e) {
        getLog().debug(e);
        throw new MojoExecutionException(
                format("Unable to write about.html file '%s'. %s", aboutHtmlFile, e.getMessage()));
    }
}

From source file:org.eclipse.ebr.maven.AboutFilesUtil.java

private String getThirdPartyInfo(final SortedMap<Artifact, Model> dependencies, final File outputDirectory)
        throws MojoExecutionException {
    final StrBuilder thirdPartyInfoText = new StrBuilder();

    for (final Entry<Artifact, Model> entry : dependencies.entrySet()) {
        String thirdPartyInfo = readThirdPartyHtmlTemplate();
        final Artifact artifact = entry.getKey();
        final Model artifactPom = entry.getValue();
        thirdPartyInfo = StringUtils.replaceEach(thirdPartyInfo, new String[] { // @formatter:off
                "@DEPENDENCY_HEADLINE@", "@DEPENDENCY_BY@", "@DEPENDENCY_NAME@", "@DEPENDENCY_LICENSING@",
                "@DEPENDENCY_ORIGIN@" },
                new String[] { escapeHtml4(artifactPom.getName()), getDevelopedByInfo(artifact, artifactPom),
                        escapeHtml4(artifactPom.getName()),
                        getLicenseInfo(artifact, artifactPom, outputDirectory),
                        getOriginInfo(artifact, artifactPom) });
        // @formatter:on

        thirdPartyInfoText.append(thirdPartyInfo);
    }// w w w .  ja v  a2  s  .c om

    return thirdPartyInfoText.toString();
}

From source file:org.eclipse.ebr.maven.CreateRecipeMojo.java

private void generateEclipseProjectFile(final File projectDir) throws MojoExecutionException {
    final File eclipseProjectFile = new File(projectDir, DOT_PROJECT);
    if (eclipseProjectFile.isFile() && !force) {
        getLog().warn(format("Found existing .project file at '%s'. %s", eclipseProjectFile,
                REQUIRES_FORCE_TO_OVERRIDE_MESSAGE));
        return;/*from   ww w. j a v  a2s. com*/
    }
    String eclipseProjectFileText = readEclipseProjectFileTemplate();
    eclipseProjectFileText = StringUtils.replaceEach(eclipseProjectFileText, new String[] { // @formatter:off
            "@RECIPE_PROJECT_NAME@" }, new String[] { projectDir.getName() });
    // @formatter:on

    try {
        FileUtils.writeStringToFile(eclipseProjectFile, eclipseProjectFileText, UTF_8);
    } catch (final IOException e) {
        getLog().debug(e);
        throw new MojoExecutionException(
                format("Unable to write .project file '%s'. %s", eclipseProjectFile, e.getMessage()));
    }
}

From source file:org.eclipse.ebr.maven.OsgiBndUtil.java

public void generateOsgiBndFile(final File outputDirectory,
        final Collection<Dependency> compileTimeDependencies) throws MojoExecutionException {
    final File osgiBndFile = new File(outputDirectory, OSGI_BND);
    if (osgiBndFile.isFile() && !isForce()) {
        getLog().warn(format("Found existing osgi.bnd file at '%s'. %s", osgiBndFile,
                REQUIRES_FORCE_TO_OVERRIDE_MESSAGE));
        return;// w  w w .j  a v  a  2 s  . c  om
    }

    String osgiBndText = readOsgiBndTemplate();
    osgiBndText = StringUtils.replaceEach(osgiBndText, new String[] { // @formatter:off
            "@VERSION_VARIABLES@" }, new String[] { getVersionDeclarations(compileTimeDependencies) });
    // @formatter:on

    try {
        FileUtils.writeStringToFile(osgiBndFile, osgiBndText, UTF_8);
    } catch (final IOException e) {
        getLog().debug(e);
        throw new MojoExecutionException(
                format("Unable to write osgi.bnd file '%s'. %s", osgiBndFile, e.getMessage()));
    }
}

From source file:org.fuin.srcgen4j.commons.VariableResolver.java

/**
 * Replaces all variables inside a string with values from a map.
 * //from w w  w  .ja  v  a  2  s.  c  o m
 * @param str
 *            Text with variables (Format: ${key} ) - May be
 *            <code>null</code> or empty.
 * @param vars
 *            Map with key/values (both of type <code>String</code>.
 * 
 * @return String with replaced variables. Unknown variables will remain
 *         unchanged.
 */
@Nullable
public static String replaceVars(@Nullable final String str, @Nullable final Map<String, String> vars) {

    if ((str == null) || (str.length() == 0) || (vars == null) || (vars.size() == 0)) {
        return str;
    }

    final StringBuffer sb = new StringBuffer();

    int end = -1;
    int from = 0;
    int start = -1;
    while ((start = str.indexOf("${", from)) > -1) {
        sb.append(str.substring(end + 1, start));
        end = str.indexOf('}', start + 1);
        if (end == -1) {
            // No closing bracket found...
            sb.append(str.substring(start));
            from = str.length();
        } else {
            final String key = str.substring(start + 2, end);
            final String value = (String) vars.get(key);
            if (value == null) {
                sb.append("${");
                sb.append(key);
                sb.append("}");
            } else {
                sb.append(value);
            }
            from = end + 1;
        }
    }

    sb.append(str.substring(from));

    return StringUtils.replaceEach(sb.toString(), new String[] { "\\n", "\\r", "\\t" },
            new String[] { "\n", "\r", "\t" });

}

From source file:org.guess.generate.Generate.java

public static void main(String[] args) {

    // ==========  ?? ====================

    // ??????//from  w  w  w . j av a 2  s  .  co m
    // ?{packageName}/{moduleName}/{dao,entity,service,web}/{subModuleName}/{className}

    // packageName
    // ????applicationContext.xmlsrping-mvc.xml?base-package?packagesToScan?4?
    String packageName = "net.iharding.modulesmeta";

    String moduleName = "meta"; // ???sys
    String className = "project"; // ??user
    String classAuthor = "Joe.zhang"; // 
    String functionName = "??"; // ??

    List<Field> fields = new ArrayList<Field>();
    fields.add(new Field("projectCode", "?", "String"));
    fields.add(new Field("projectName", "??", "String"));
    fields.add(new Field("remark", "", "String"));
    fields.add(new Field("createDate", "", "Date"));
    fields.add(new Field("updateDate", "", "Date"));
    fields.add(new Field("createId", "", "createId"));
    fields.add(new Field("updateId", "", "updateId"));

    // ???
    Boolean isEnable = true;

    // ==========  ?? ====================

    if (!isEnable) {
        logger.error("????isEnable = true");
        return;
    }

    if (StringUtils.isBlank(moduleName) || StringUtils.isBlank(moduleName) || StringUtils.isBlank(className)
            || StringUtils.isBlank(functionName)) {
        logger.error("??????????????");
        return;
    }

    // ?
    String separator = File.separator;

    // ?
    File projectPath = null;
    try {
        projectPath = new DefaultResourceLoader().getResource("").getFile();
        //         File projectPath = new File("D:/template");
        while (!new File(projectPath.getPath() + separator + "src" + separator + "main").exists()) {
            projectPath = projectPath.getParentFile();
        }
        logger.info("Project Path: {}", projectPath);

        // ?
        String tplPath = StringUtils.replace(
                projectPath.getAbsolutePath() + "/src/test/java/org/guess/generate/temp", "/", separator);
        logger.info("Template Path: {}", tplPath);

        // Java
        String javaPath = StringUtils.replaceEach(
                projectPath.getAbsolutePath() + "/src/main/java/" + StringUtils.lowerCase(packageName),
                new String[] { "/", "." }, new String[] { separator, separator });
        //         String javaPath = "D:/template";
        logger.info("Java Path: {}", javaPath);

        String viewPath = StringUtils.replace(
                projectPath + "/src/main/webapp/WEB-INF/content/" + moduleName + "/" + className, "/",
                separator);
        //         String viewPath = "D:/template";

        // ???
        Configuration cfg = new Configuration();
        FileUtils.isFolderExitAndCreate(tplPath);
        cfg.setDirectoryForTemplateLoading(new File(tplPath));

        // ???
        Map<String, Object> model = Maps.newHashMap();
        model.put("packageName", StringUtils.lowerCase(packageName));
        model.put("moduleName", StringUtils.lowerCase(moduleName));
        model.put("className", StringUtils.uncapitalize(className));
        model.put("ClassName", StringUtils.capitalize(className));
        model.put("classAuthor", StringUtils.isNotBlank(classAuthor) ? classAuthor : "Generate Tools");
        model.put("classVersion", DateUtil.getCurrenDate());
        model.put("functionName", functionName);
        model.put("tableName", model.get("moduleName") + "_" + model.get("className"));

        model.put("fields", fields);

        // ? Entity
        Template template = cfg.getTemplate("entity.ftl");
        String content = FreeMarkers.renderTemplate(template, model);
        String filePath = javaPath + separator + model.get("moduleName") + separator + "model" + separator
                + model.get("ClassName") + ".java";
        //         writeFile(content, filePath);
        logger.info("Entity: {}", filePath);

        // ? Dao
        template = cfg.getTemplate("dao.ftl");
        content = FreeMarkers.renderTemplate(template, model);
        filePath = javaPath + separator + model.get("moduleName") + separator + "dao" + separator
                + model.get("ClassName") + "Dao.java";
        writeFile(content, filePath);
        logger.info("Dao: {}", filePath);

        // ? DaoImpl
        template = cfg.getTemplate("daoImpl.ftl");
        content = FreeMarkers.renderTemplate(template, model);
        filePath = javaPath + separator + model.get("moduleName") + separator + "dao" + separator + "impl"
                + separator + model.get("ClassName") + "DaoImpl.java";
        writeFile(content, filePath);
        logger.info("Dao: {}", filePath);

        // ? Service
        template = cfg.getTemplate("service.ftl");
        content = FreeMarkers.renderTemplate(template, model);
        filePath = javaPath + separator + model.get("moduleName") + separator + "service" + separator
                + model.get("ClassName") + "Service.java";
        writeFile(content, filePath);
        logger.info("Service: {}", filePath);

        // ? Service
        template = cfg.getTemplate("serviceImpl.ftl");
        content = FreeMarkers.renderTemplate(template, model);
        filePath = javaPath + separator + model.get("moduleName") + separator + "service" + separator + "impl"
                + separator + model.get("ClassName") + "ServiceImpl.java";
        writeFile(content, filePath);
        logger.info("Service: {}", filePath);

        // ? Controller
        template = cfg.getTemplate("controller.ftl");
        content = FreeMarkers.renderTemplate(template, model);
        filePath = javaPath + separator + model.get("moduleName") + separator + "controller" + separator
                + model.get("ClassName") + "Controller.java";
        writeFile(content, filePath);
        logger.info("Controller: {}", filePath);

        /*   // ? list.jsp
           template = cfg.getTemplate("list.ftl");
           content = FreeMarkers.renderTemplate(template, model);
           filePath = viewPath + separator + "list.jsp";
           writeFile(content, filePath);
           logger.info("Controller: {}", filePath);
                   
           // ? edit.jsp
           template = cfg.getTemplate("edit.ftl");
           content = FreeMarkers.renderTemplate(template, model);
           filePath = viewPath + separator + "edit.jsp";
           writeFile(content, filePath);
           logger.info("Controller: {}", filePath);*/

        logger.info("Generate Success.");
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:org.gvnix.occ.roo.addon.addon.OCCChecksumMetadata.java

/**
 * Generate to-string code for a Many-to-One member property. This method
 * uses the pk of related object. Supports simple pks or embeddedId pks.
 * //from   w  w  w .j  av  a2s. co m
 * @param propAccessor
 * @param field
 * @param aPrefix
 * @return
 */
private Object getToStringManyToOneProperty(MethodMetadata propAccessor, FieldMetadata field, String prefix) {

    // Get related object type
    final JavaType propertyType = field.getFieldType();

    // Get realted object PK accesor
    final MethodMetadata idAccesor = persistenceMemberLocator.getIdentifierAccessor(propertyType);

    // #9561: Avoid NullPointerException in strange cases
    if (idAccesor == null)
        return StringUtils.EMPTY;

    final JavaType reltatedObjecIdType = idAccesor.getReturnType();

    String propAccessExpression = getPropertyAccesorExpression(prefix, propAccessor.getMethodName(),
            field.getFieldName());

    // check related object id type
    if (reltatedObjecIdType.isCoreType() || reltatedObjecIdType.isPrimitive()) {
        // Is a primitive or core java type
        return StringUtils.replaceEach(MANY_TO_ONE_CODE_FORMAT, new String[] { PROPERTY_KEY, GET_ID_KEY },
                new String[] { propAccessExpression, idAccesor.getMethodName().toString() });
    } else {
        // is embededPk
        List<FieldMetadata> embeddedFields = persistenceMemberLocator.getEmbeddedIdentifierFields(propertyType);
        StringBuilder strb = new StringBuilder();
        propAccessExpression = getPropertyAccesorExpression(propAccessExpression, idAccesor.getMethodName(),
                field.getFieldName());
        JavaSymbolName embeddedAccessorName;
        for (FieldMetadata embeddedField : embeddedFields) {
            embeddedAccessorName = BeanInfoUtils.getAccessorMethodName(embeddedField);
            strb.append(getToStringCodeForBaseField(propAccessExpression, embeddedAccessorName, embeddedField));
        }

        return strb.toString();
    }
}

From source file:org.neo4art.sentiment.util.DictionaryUtils.java

public static String escapeWordForLuceneSearch(String word) {
    return StringUtils.replaceEach(word, LUCENE_SPECIAL_CHARACTERS, LUCENE_SPECIAL_CHARACTERS_ESCAPE);
}

From source file:org.phenotips.utilities.updowner.UpDowner.java

private static String turn(String value) {
    return StringUtils.reverse(StringUtils.replaceEach(value,
            "ABCDEFGJKLMPQRTUVWYabcdefghijklmnopqrstuvwxyz123456789'.,!?<>[](){}%".split(""),
            "??W?M?qp??uodbsn?xz??986,'><][)(}{%"
                    .split("")));
}

From source file:org.pircbotx.PircTestRunner.java

/**
 * Replaces "%server",/*from  www . jav  a2  s .co m*/
 * "%usersource",
 * "%userother",
 * "%userbot",
 * "%nickbot",
 */
public PircTestRunner botIn(@NonNull String line) {
    checkInputEmpty();
    checkOutputEmpty();
    checkEventsEmpty();

    in.nextLine = StringUtils.replaceEach(line,
            new String[] { "%server", "%usersource", "%userother", "%userbot", "%nickbot", },
            new String[] { "irc.someserver.net", USER_SOURCE_HOSTMASK, USER_OTHER_HOSTMASK, USER_BOT_HOSTMASK,
                    BOT_NICK, });
    assertTrue(bot.processNextLine(), "Bot was stopped");

    return this;
}