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

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

Introduction

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

Prototype

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

Source Link

Document

Replaces all occurrences of a String within another String.

A null reference passed to this method is a no-op.

 StringUtils.replace(null, *, *)        = null StringUtils.replace("", *, *)          = "" StringUtils.replace("any", null, *)    = "any" StringUtils.replace("any", *, null)    = "any" StringUtils.replace("any", "", *)      = "any" StringUtils.replace("aba", "a", null)  = "aba" StringUtils.replace("aba", "a", "")    = "b" StringUtils.replace("aba", "a", "z")   = "zbz" 

Usage

From source file:org.dashbuilder.dataprovider.sql.JDBCUtils.java

public static String changeCaseExcludeQuotes(String s, boolean upper) {
    List<String> keepList = getWordsBetweenQuotes(s);
    String tmpStr = upper ? s.toUpperCase() : s.toLowerCase();
    for (String word : keepList) {
        String tmpWord = upper ? word.toUpperCase() : word.toLowerCase();
        for (int i = 0; i < QUOTES.length; i++) {
            String quote = QUOTES[i];
            tmpStr = StringUtils.replace(tmpStr, quote + tmpWord + quote, quote + word + quote);
        }//from   w  ww  .j av a 2  s .  c  om
    }
    return tmpStr;
}

From source file:org.dbgl.util.DFendReloadedImportThread.java

private String fixCRLF(final String s) {
    return StringUtils.replace(StringUtils.replace(s, "[13][10]", "\n"), "[13]", "").trim();
}

From source file:org.dbgl.util.ImportThread.java

public void doFancyStuff(Object obj, StringBuffer messageLog) throws IOException, SQLException {
    ExpProfile prof = (ExpProfile) obj;//from w  w  w . j  a va2  s . c o m
    displayTitle(settings.msg("dialog.import.importing", new Object[] { prof.getTitle() }));

    int devId = KeyValuePair.findIdByValue(dbase.readDevelopersList(), prof.getDeveloperName());
    int publId = KeyValuePair.findIdByValue(dbase.readPublishersList(), prof.getPublisherName());
    int genId = KeyValuePair.findIdByValue(dbase.readGenresList(), prof.getGenre());
    int yrId = KeyValuePair.findIdByValue(dbase.readYearsList(), prof.getYear());
    int statId = KeyValuePair.findIdByValue(dbase.readStatusList(), prof.getStatus());
    String[] customStrings = DFendImportThread.CUST_STRINGS;
    int[] customInts = DFendImportThread.CUST_INTS;
    int[] custIDs = DFendImportThread.CUST_IDS;
    if (customValues) {
        customStrings = prof.getCustomStrings();
        customInts = prof.getCustomInts();
        for (int i = 0; i < 4; i++) {
            custIDs[i] = KeyValuePair.findIdByValue(dbase.readCustomList(i), prof.getCustomString(i));
        }
    }

    Profile addedProfile = dbase.addOrEditProfile(prof.getTitle(), prof.getDeveloperName(),
            prof.getPublisherName(), prof.getGenre(), prof.getYear(), prof.getStatus(), prof.getNotes(),
            prof.isDefault(), prof.getSetup(), prof.getSetupParameters(), devId, publId, genId, yrId, statId,
            prof.getDbversionId(), prof.getLinks(), prof.getLinkTitles(), customStrings, customInts, custIDs,
            -1);

    String newCapturesString = FileUtils.constructCapturesDir(addedProfile.getId());
    File relativeCapturesDirInZip = new File(prof.getCaptures());
    File canonicalCapturesDir = FileUtils.canonicalToData(newCapturesString);
    if (!canonicalCapturesDir.exists()) {
        FileUtils.createDir(canonicalCapturesDir);
        messageLog.append(PREFIX_OK)
                .append(settings.msg("dialog.import.notice.createddir", new Object[] { canonicalCapturesDir }))
                .append('\n');
        if (importCaptures) {
            if (sevenzip) {
                for (int i : FileUtils.findRelatedEntryIds(zArchive, relativeCapturesDirInZip))
                    sevenzipDstFileMap.put(i, FileUtils.determineDstSevenzipFile(relativeCapturesDirInZip,
                            canonicalCapturesDir, zArchive.getEntry(i).getName()));
            } else {
                try {
                    FileUtils.extractZip(zipfile, relativeCapturesDirInZip, canonicalCapturesDir, this);
                    messageLog.append(PREFIX_OK).append(settings.msg("dialog.import.notice.extractedcaptures",
                            new Object[] { canonicalCapturesDir })).append('\n');
                } catch (IOException e) {
                    messageLog.append(PREFIX_ERR).append(settings.msg("dialog.import.error.capturesextraction",
                            new Object[] { StringRelatedUtils.toString(e) })).append('\n');
                }
            }
        }
    } else {
        messageLog.append(PREFIX_ERR).append(
                settings.msg("dialog.import.error.capturesdirexists", new Object[] { canonicalCapturesDir }))
                .append('\n');
    }

    File relativeGameDir = prof.getGameDir();
    File relativeGameDirInZip = new File(FileUtils.DOSROOT_DIR,
            new File(String.valueOf(prof.getImportedId()), relativeGameDir.getPath()).getPath());
    File canonicalGameDir = FileUtils
            .canonicalToDosroot(new File(prof.getBaseDir(), prof.getGameDir().getPath()).getPath());
    if (importGameData) {
        if (!canonicalGameDir.exists()) {
            FileUtils.createDir(canonicalGameDir);
            messageLog.append(PREFIX_OK)
                    .append(settings.msg("dialog.import.notice.createddir", new Object[] { canonicalGameDir }))
                    .append('\n');
            if (sevenzip) {
                for (int i : FileUtils.findRelatedEntryIds(zArchive, relativeGameDirInZip))
                    sevenzipDstFileMap.put(i, FileUtils.determineDstSevenzipFile(relativeGameDirInZip,
                            canonicalGameDir, zArchive.getEntry(i).getName()));
            } else {
                try {
                    FileUtils.extractZip(zipfile, relativeGameDirInZip, canonicalGameDir, this);
                    messageLog.append(PREFIX_OK).append(settings.msg("dialog.import.notice.extractedgamedata",
                            new Object[] { canonicalGameDir })).append('\n');
                } catch (IOException e) {
                    throw new IOException(settings.msg("dialog.import.error.gamedataextraction",
                            new Object[] { StringRelatedUtils.toString(e) }), e);
                }
            }
        }
    }

    DosboxVersion assocDBVersion = DosboxVersion.findById(dbversions, prof.getDbversionId());
    String newConfString = null;
    if (useExistingConf && FileUtils.areRelated(new File(FileUtils.getDosRoot()), prof.getCanonicalConfFile())
            && FileUtils.isExistingFile(prof.getCanonicalConfFile())) {
        newConfString = prof.getCanonicalConfFile().getPath();
        messageLog.append(PREFIX_OK).append(settings.msg("dialog.import.notice.usingexistingconf",
                new Object[] { prof.getCanonicalConfFile() })).append('\n');
    } else {
        Conf gameConf = new Conf(prof.getImportedFullConfig(), prof.getImportedIncrConfig(), importFullSettings,
                zipfile.getPath(), prof, addedProfile.getId(), assocDBVersion, ps);
        newConfString = FileUtils.makeRelativeToData(gameConf.getConfFile()).getPath();
        Profile newProfile = new Profile(addedProfile.getId(), newConfString, newCapturesString, prof);
        if (!newProfile.getCanonicalConfFile().getParentFile().exists()) {
            FileUtils.createDir(newProfile.getCanonicalConfFile().getParentFile());
            messageLog.append(PREFIX_OK).append(settings.msg("dialog.import.notice.createddir",
                    new Object[] { newProfile.getCanonicalConfFile().getParentFile() })).append('\n');
        }
        String dstCapRelative = FileUtils.constructRelativeCapturesDir(addedProfile.getId(),
                newProfile.getCanonicalConfFile().getParentFile(),
                gameConf.getSettings().detectDosboxVersionGeneration());
        gameConf.getSettings().setValue("dosbox", "captures", dstCapRelative);

        String mapperfileEntry = prof.getMapperfile();
        if (importMapperfiles && (mapperfileEntry != null)) {
            File dstFile = new File(StringUtils.replace(newProfile.getCanonicalConfFile().getPath(),
                    FileUtils.CONF_EXT, FileUtils.MAPPER_EXT));
            gameConf.getSettings().setValue("sdl", "mapperfile", dstFile.getName());
            if (sevenzip) {
                int i = FileUtils.findEntryId(zArchive, PlatformUtils.toArchivePath(mapperfileEntry));
                if (i != -1)
                    sevenzipDstFileMap.put(i, dstFile);
            } else {
                try {
                    FileUtils.extractZip(zipfile, PlatformUtils.toArchivePath(mapperfileEntry), dstFile, this);
                    messageLog.append(PREFIX_OK).append(
                            settings.msg("dialog.import.notice.extractedmapperfile", new Object[] { dstFile }))
                            .append('\n');
                } catch (IOException e) {
                    messageLog.append(PREFIX_ERR)
                            .append(settings.msg("dialog.import.error.mapperfileextraction",
                                    new Object[] { StringRelatedUtils.toString(e) }))
                            .append('\n');
                }
            }
        }

        gameConf.save();
        messageLog.append(PREFIX_OK).append(settings.msg("dialog.import.notice.createdconf",
                new Object[] { newProfile.getCanonicalConfFile() })).append('\n');
    }
    addedProfile = dbase.updateProfileConf(newConfString, newCapturesString, addedProfile.getId());

    String[] setup = prof.getSetup();
    for (int i = 0; i < setup.length; i++) {
        if (setup[i].length() > 0)
            setup[i] = FileUtils.prefixAndSanitizeToDosroot(prof.getBaseDir(), new File(setup[i])).getPath();
    }
    String[] links = prof.getLinks();
    for (int i = 0; i < links.length; i++) {
        if (!links[i].equals("") && !links[i].contains("://")) {
            links[i] = FileUtils.makeRelativeToDosroot(FileUtils.canonicalToData(links[i])).getPath();
            links[i] = FileUtils.prefixAndSanitizeToDosroot(prof.getBaseDir(), new File(links[i])).getPath();
            if (!prof.getBaseDir().isAbsolute()) {
                links[i] = FileUtils.DOSROOT_DIR + links[i];
            }
        }
    }
    addedProfile = dbase.updateProfileSetupAndLinks(setup, links, addedProfile.getId());

    if (importNativecommands) {
        dbase.saveNativeCommands(prof.getNativeCommandsList(), addedProfile.getId(), -1);
    }

    messageLog.append(PREFIX_OK).append(settings.msg("dialog.import.notice.createddbentry",
            new Object[] { addedProfile.getId(), newConfString, newCapturesString, assocDBVersion.getTitle() }))
            .append('\n');
}

From source file:org.dbgl.util.PlatformUtils.java

public static void createShortcut(final Profile profile, final List<DosboxVersion> dbversionsList)
        throws IOException {
    DosboxVersion dbversion = DosboxVersion.findById(dbversionsList, profile.getDbversionId());
    String strictFilename = profile.getTitle().replaceAll("[\\/:*?\"<>|]", " ").trim();
    StringBuffer params = new StringBuffer(128);
    if (dbversion.isMultiConfig()) {
        params.append("-conf \"\"").append(dbversion.getCanonicalConfFile()).append("\"\" ");
    }//  w  w  w  .  j a va  2s.  c o m
    params.append("-conf \"\"").append(profile.getCanonicalConfFile()).append("\"\"");
    if (Settings.getInstance().getSettings().getBooleanValue("dosbox", "hideconsole")) {
        params.append(" -noconsole");
    }

    if (IS_WINDOWS) {

        File desktopDir = FileSystemView.getFileSystemView().getHomeDirectory();
        File lnkFile = new File(desktopDir, strictFilename + ".lnk");
        File vbsFile = FileUtils.canonicalToData("shortcut.vbs");
        BufferedWriter vbsWriter = new BufferedWriter(new FileWriter(vbsFile));
        vbsWriter.write("Set oWS = WScript.CreateObject(\"WScript.Shell\")" + EOLN);
        vbsWriter.write("Set oLink = oWS.CreateShortcut(\"" + lnkFile.getCanonicalPath() + "\")" + EOLN);
        vbsWriter.write("oLink.TargetPath = \"" + dbversion.getCanonicalExecutable().getPath() + "\"" + EOLN);
        vbsWriter.write("oLink.Arguments = \"" + params.toString() + "\"" + EOLN);
        vbsWriter.write("oLink.Description = \""
                + Settings.getInstance().msg("general.shortcut.title", new Object[] { strictFilename }) + "\""
                + EOLN);
        vbsWriter.write("oLink.WorkingDirectory = \"" + FileUtils.getDosRoot() + "\"" + EOLN);
        vbsWriter.write("oLink.Save" + EOLN);
        vbsWriter.close();
        Process proc = Runtime.getRuntime().exec(new String[] { "CSCRIPT", vbsFile.getCanonicalPath() }, null,
                vbsFile.getParentFile());
        StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "CSCRIPT stderr");
        StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "CSCRIPT stdout");
        outputGobbler.start();
        errorGobbler.start();
        try {
            proc.waitFor();
        } catch (InterruptedException e) {
        }
        FileUtils.removeFile(vbsFile);

    } else if (IS_LINUX) {

        File desktopDir = new File(System.getProperty("user.home"), "/Desktop");
        File desktopFile = new File(desktopDir, strictFilename + ".desktop");
        BufferedWriter desktopWriter = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(desktopFile), "UTF-8"));
        desktopWriter.write("[Desktop Entry]" + EOLN);
        desktopWriter.write("Version=1.0" + EOLN);
        desktopWriter.write("Type=Application" + EOLN);
        desktopWriter.write("Name=" + strictFilename + EOLN);
        desktopWriter.write("Comment="
                + Settings.getInstance().msg("general.shortcut.title", new Object[] { strictFilename }) + EOLN);
        desktopWriter.write("Icon="
                + new File(dbversion.getCanonicalExecutable().getParent(), "dosbox.ico").getPath() + EOLN);
        desktopWriter.write("TryExec=" + dbversion.getCanonicalExecutable().getPath() + EOLN);
        desktopWriter.write("Exec=" + dbversion.getCanonicalExecutable().getPath() + " "
                + StringUtils.replace(params.toString(), "\"\"", "\"") + EOLN);
        desktopWriter.write("Path=" + FileUtils.getDosRoot() + EOLN);
        desktopWriter.close();
        desktopFile.setExecutable(true);

    }
}

From source file:org.dbgl.util.StringRelatedUtils.java

public static String textAreaToString(final String contents, final String del, final String eoln) {
    return StringUtils.replace(StringUtils.strip(contents, del), del, eoln);
}

From source file:org.dbgl.util.StringRelatedUtils.java

public static String stringToTextArea(final String string, final String del, final String eoln) {
    return StringUtils.replace(string, eoln, del);
}

From source file:org.diorite.cfg.system.elements.StringTemplateElement.java

@Override
public void appendValue(final Appendable writer, final CfgEntryData field, final Object source,
        final Object elementRaw, final int level, final ElementPlace elementPlace) throws IOException {
    StringStyle style = field.getOption(FieldOptions.STRING_STYLE, StringStyle.DEFAULT);
    if ((style == StringStyle.ALWAYS_MULTI_LINE) && (elementPlace == ElementPlace.SIMPLE_LIST_OR_MAP)) // multi line strings don't works in simple lists/maps.
    {//from w ww . j  a va2 s  .  c  om
        style = StringStyle.DEFAULT;
    }
    final String element = Enum.class.isAssignableFrom(elementRaw.getClass()) ? ((Enum<?>) elementRaw).name()
            : elementRaw.toString();
    switch (style) {
    case ALWAYS_QUOTED: {
        writeQuoted(writer, element);
        break;
    }
    case ALWAYS_SINGLE_QUOTED: {
        writeSingleQuoted(writer, StringUtils.replaceEach(element, REP_PREV_1, REP_PREV_2));
        break;
    }
    case ALWAYS_MULTI_LINE: {
        writeMultiLine(writer, element, level, elementPlace);
        break;
    }
    default: {
        final boolean haveNewLines = StringUtils.contains(element, '\n');
        if ((elementPlace != ElementPlace.SIMPLE_LIST_OR_MAP) && haveNewLines) {
            writeMultiLine(writer, element, level, elementPlace);
            return;
        }
        boolean needQuote = false;
        if (element.isEmpty()) {
            writeSingleQuoted(writer, element);
            return;
        }
        final char f = element.charAt(0);
        if (StringUtils.containsAny(element, ':', '#')) {
            needQuote = true;
        } else {
            for (final char c : CANT_BE_FIRST) {
                if (c == f) {
                    needQuote = true;
                    break;
                }
            }
        }
        if (needQuote) {
            writeQuoted(writer, element);
            return;
        }
        if (StringUtils.isNumeric(element)) {
            writeQuoted(writer, element);
        } else {
            writer.append(StringUtils.replace(element, "\n", "\\n"));
        }
        break;
    }
    }
}

From source file:org.diorite.cfg.system.elements.StringTemplateElement.java

private static void writeSingleQuoted(final Appendable writer, final String element) throws IOException {
    writer.append('\'');
    writer.append(StringUtils.replace(element, "\n", "\\n"));
    writer.append('\'');
}

From source file:org.diorite.chat.placeholder.PlaceholderData.java

/**
 * Uses this placeholder on given string.
 *
 * @param str string to use./*from www .  j  a  v  a 2  s  . c  om*/
 * @param obj object to fetch the data needed for placeholder.
 *
 * @return string with replaced placeholder.
 */
default String replace(final String str, final T obj) {
    final Object result = this.apply(obj);
    if (result instanceof BaseComponent) {
        return StringUtils.replace(str, this.getFullName(), ((BaseComponent) result).toLegacyText());
    } else {
        return StringUtils.replace(str, this.getFullName(), result.toString());
    }
}

From source file:org.diorite.material.Material.java

/**
 * Method will try to find material by given name, converting it to any possible type of id: <br>
 * <ul>/*from ww  w.  j a  v  a  2 s  . c  o m*/
 * <li>{numericId} {@literal ->} like "1" for stone</li>
 * <li>{enumStringId} {@literal ->} like "STONE"</li>
 * <li>{minecraftStringId} {@literal ->} like "minecraft:stone"</li>
 * <li>minecraft:{shortMinecraftStringId} {@literal ->} like "stone"</li>
 * <li>{numericId}:{numericMeta} {@literal ->} like "1:0"</li>
 * <li>{numericId}:{stringMeta} {@literal ->} like "1:diorite"</li>
 * <li>{enumStringId}:{numericMeta} {@literal ->} like "STONE:0"</li>
 * <li>{enumStringId}:{stringMeta} {@literal ->} like "STONE:diorite"</li>
 * <li>{minecraftStringId}:{numericMeta} {@literal ->} like "minecraft:stone:diorite"</li>
 * <li>minecraft:{shortMinecraftStringId}:{numericMeta} {@literal ->} like "stone:diorite"</li>
 * </ul>
 * With extended mode it will also scan all materials and looks for sub-material with name equals to given string
 * multiple types may have this same sub-material name, so may not return valid material for types like that.
 *
 * @param string   material name/id to find.
 * @param extended if it should use extended mode. (slower)
 *
 * @return material or null if it didn't find any.
 */
public static Material matchMaterial(String string, final boolean extended) {
    string = StringUtils.replace(string, " ", "_");

    // using simple id
    final Integer i = DioriteMathUtils.asInt(string);
    if (i != null) {
        return getByID(i);
    }

    // find in enum by whole string
    Material result = getByEnumName(string);
    if ((result != null) || (((result = getByMinecraftId(string))) != null)
            || (((result = getByMinecraftId("minecraft:" + string))) != null)) {
        return result;
    }

    // split to [id, meta], where meta can't contains any ":"
    final int index = string.lastIndexOf(':');
    if (index == -1) {
        if (!extended) {
            return string.equalsIgnoreCase("diorite") ? StoneMat.STONE_DIORITE : null;
        }

        for (final Material m : values()) {
            result = m.getType(string);
            if (result != null) {
                return result;
            }
        }

        // :<
        return null;
    }
    final String idPart = string.substring(0, index);
    final String metaPart = string.substring(index + 1);
    final Integer id = DioriteMathUtils.asInt(idPart);
    final Integer meta = DioriteMathUtils.asInt(metaPart);

    // by numeric id, and numeric or text meta.
    if (id != null) {
        return (meta != null) ? getByID(id, meta) : getByID(id, metaPart);
    }

    if (meta != null) {
        result = getByEnumName(idPart, meta);
        if ((result != null) || (((result = getByMinecraftId(idPart, meta))) != null)
                || (((result = getByMinecraftId("minecraft:" + idPart, meta))) != null)) {
            return result;
        }
    }
    result = getByEnumName(idPart, metaPart);
    if ((result != null) || (((result = getByMinecraftId(idPart, metaPart))) != null)
            || (((result = getByMinecraftId("minecraft:" + idPart, metaPart))) != null)) {
        return result;
    }

    // :<
    return null;
}