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:net.gtaun.wl.race.dialog.TrackEditDialog.java

@Override
public void show() {
    RacingManagerImpl racingManager = raceService.getRacingManager();

    items.clear();// w w  w . ja  v  a 2 s . c  om
    addItem(stringSet.format("Dialog.TrackEditDialog.Name", track.getName()), (i) -> {
        String caption = stringSet.get("Dialog.TrackEditNameDialog.Caption");
        String message = stringSet.format("Dialog.TrackEditNameDialog.Text", track.getName());
        TrackNamingDialog.create(player, rootEventManager, this, caption, message, raceService, (d, name) -> {
            try {
                TrackManagerImpl trackManager = raceService.getTrackManager();
                trackManager.renameTrack(track, name);
                showParentDialog();
            } catch (AlreadyExistException ex) {
                d.setAppendMessage(
                        stringSet.format("Dialog.TrackEditNameDialog.AlreadyExistAppendMessage", name));
                show();
            } catch (IllegalArgumentException ex) {
                d.setAppendMessage(
                        stringSet.format("Dialog.TrackEditNameDialog.IllegalFormatAppendMessage", name));
                show();
            }
        }).show();
    });

    addItem(() -> {
        String desc = track.getDesc();
        if (StringUtils.isBlank(desc))
            desc = stringSet.get("Common.Empty");
        return stringSet.format("Dialog.TrackEditDialog.Desc", desc);
    }, (i) -> {
        String caption = stringSet.get("Dialog.TrackEditDescDialog.Caption");
        String message = stringSet.format("Dialog.TrackEditDescDialog.Text", track.getName(), track.getDesc());
        WlInputDialog.create(player, rootEventManager).parentDialog(this).caption(caption).message(message)
                .onClickOk((d, text) -> {
                    String desc = StringUtils.trimToEmpty(text);
                    desc = StringUtils.replace(desc, "%", "#");
                    desc = StringUtils.replace(desc, "\t", " ");
                    desc = StringUtils.replace(desc, "\n", " ");

                    track.setDesc(desc);
                    d.showParentDialog();
                }).build().show();
    });

    addItem(() -> stringSet.format("Dialog.TrackEditDialog.Checkpoints", track.getCheckpoints().size()),
            (i) -> show());
    addItem(() -> stringSet.format("Dialog.TrackEditDialog.Length", track.getLength() / 1000.0f),
            (i) -> show());

    addItem(() -> stringSet.get("Dialog.TrackEditDialog.AddCheckpoint"), (i) -> {
        TrackCheckpoint checkpoint = track.createCheckpoint(player.getLocation());
        TrackCheckpointEditDialog.create(player, eventManagerNode, null, raceService, checkpoint, true).show();
    });

    addItem(() -> stringSet.get("Dialog.TrackEditDialog.Setting"), (i) -> {
        TrackSettingDialog.create(player, rootEventManager, this, raceService, track).show();
    });

    addItem(() -> stringSet.get("Dialog.TrackEditDialog.Delete"), (i) -> {
        String caption = stringSet.get("Dialog.TrackDeleteConfirmDialog.Caption");
        String message = stringSet.format("Dialog.TrackDeleteConfirmDialog.Text", track.getName());
        WlInputDialog.create(player, rootEventManager).parentDialog(this).caption(caption).message(message)
                .onClickOk((d, text) -> {
                    if (!track.getName().equals(text)) {
                        d.showParentDialog();
                        return;
                    }

                    raceService.stopEditingTrack(player);

                    TrackManagerImpl trackManager = raceService.getTrackManager();
                    trackManager.deleteTrack(track);

                    String msgboxCaption = stringSet.get("Dialog.TrackDeleteCompleteDialog.Caption");
                    String msgboxMessage = stringSet.format("Dialog.TrackDeleteCompleteDialog.Text",
                            track.getName());
                    WlMsgboxDialog.create(player, rootEventManager).caption(msgboxCaption)
                            .message(msgboxMessage).onClickOk((dialog) -> player.playSound(1083)).build()
                            .show();
                }).build().show();
    });

    addItem(stringSet.get("Dialog.TrackEditDialog.StopEditing"), (i) -> {
        raceService.stopEditingTrack(player);
    });

    addItem(stringSet.get("Dialog.TrackEditDialog.FinishEditing"), () -> {
        if (track.getCheckpoints().size() < 2)
            return false;
        return true;
    }, (i) -> {
        String caption = stringSet.get("Dialog.TrackFinishEditingConfirmDialog.Caption");
        String message = stringSet.format("Dialog.TrackFinishEditingConfirmDialog.Text", track.getName());

        MsgboxDialog.create(player, rootEventManager).caption(caption).message(message).onClickOk((d) -> {
            player.playSound(1083);

            raceService.stopEditingTrack(player);
            track.setStatus(TrackStatus.COMPLETED);

            showParentDialog();
        }).build().show();
        ;
    });

    addItem(stringSet.get("Dialog.TrackEditDialog.Test"), () -> {
        if (track.getCheckpoints().isEmpty())
            return false;
        return true;
    }, (i) -> {
        Runnable startNewRacing = () -> {
            Racing racing = racingManager.createRacing(track, player,
                    RacingUtils.getDefaultName(player, track));
            racing.teleToStartingPoint(player);
            racing.beginCountdown();
        };

        List<TrackCheckpoint> checkpoints = track.getCheckpoints();
        if (checkpoints.isEmpty())
            return;

        if (racingManager.isPlayerInRacing(player)) {
            Racing racing = racingManager.getPlayerRacing(player);
            NewRacingConfirmDialog.create(player, rootEventManager, this, raceService, racing, () -> {
                startNewRacing.run();
            }).show();
        } else
            startNewRacing.run();
    });

    addItem("-", (i) -> show());

    List<TrackCheckpoint> checkpoints = track.getCheckpoints();
    for (int i = 0; i < checkpoints.size(); i++) {
        TrackCheckpoint checkpoint = checkpoints.get(i);
        float distance = player.getLocation().distance(checkpoint.getLocation());
        String item = stringSet.format("Dialog.TrackEditDialog.Checkpoint", i + 1, distance);
        addItem(item, (listItem) -> {
            TrackCheckpointEditDialog.create(player, eventManagerNode, this, raceService, checkpoint, false)
                    .show();
        });
    }

    super.show();
}

From source file:com.adguard.filter.rules.ContentFilterRule.java

/**
 * Creates an instance of the ContentFilterRule from its text format
 *
 * @param ruleText Rule text//www.j  a  v  a 2  s  .com
 */
protected ContentFilterRule(String ruleText) {
    super(ruleText);

    parentSearchLevel = DEFAULT_PARENT_SEARCH_LEVEL;

    int contentRuleMarkIndex = StringUtils.indexOf(ruleText, MASK_CONTENT_RULE);
    int ruleStartIndex = StringUtils.indexOf(ruleText, ATTRIBUTE_START_MARK);

    // Cutting tag name from string
    if (ruleStartIndex == -1) {
        tagName = ruleText.substring(contentRuleMarkIndex + MASK_CONTENT_RULE.length());
    } else {
        tagName = ruleText.substring(contentRuleMarkIndex + MASK_CONTENT_RULE.length(), ruleStartIndex);
    }

    // Loading domains (if any))
    if (contentRuleMarkIndex > 0) {
        String domains = ruleText.substring(0, contentRuleMarkIndex);
        loadDomains(domains);
    }

    // Loading attributes filter
    while (ruleStartIndex != -1) {
        int equalityIndex = ruleText.indexOf(EQUAL, ruleStartIndex + 1);
        int quoteStartIndex = ruleText.indexOf(QUOTES, equalityIndex + 1);
        int quoteEndIndex = getQuoteIndex(ruleText, quoteStartIndex + 1);
        if (quoteStartIndex == -1 || quoteEndIndex == -1) {
            break;
        }
        int ruleEndIndex = ruleText.indexOf(ATTRIBUTE_END_MARK, quoteEndIndex + 1);

        String attributeName = ruleText.substring(ruleStartIndex + 1, equalityIndex);
        String attributeValue = ruleText.substring(quoteStartIndex + 1, quoteEndIndex);
        attributeValue = StringUtils.replace(attributeValue, "\"\"", "\"");

        switch (attributeName) {
        case TAG_CONTENT_MASK:
            tagContentFilter = attributeValue;
            break;
        case WILDCARD_MASK:
            wildcard = new Wildcard(attributeValue, Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
            break;
        case TAG_CONTENT_MAX_LENGTH:
            maxLength = NumberUtils.toInt(attributeValue);
            break;
        case TAG_CONTENT_MIN_LENGTH:
            minLength = NumberUtils.toInt(attributeValue);
            break;
        case PARENT_ELEMENTS:
            parentElements = Arrays.asList(StringUtils.split(attributeValue, ','));
            break;
        case PARENT_SEARCH_LEVEL:
            parentSearchLevel = NumberUtils.toInt(attributeValue);
            break;
        default:
            attributesFilter.put(attributeName, attributeValue);
            break;
        }

        if (ruleEndIndex == -1)
            break;
        ruleStartIndex = ruleText.indexOf(ATTRIBUTE_START_MARK, ruleEndIndex + 1);
    }
}

From source file:com.glaf.core.util.RequestUtils.java

public static String decodeString(String str, String token) {
    try {/*from   w ww . jav  a  2  s  . c o  m*/
        // Base64 base64 = new Base64();
        // byte[] bytes = base64.decode(StringTools.decodeHex(str));
        // String tmp = new String(bytes);
        String tmp = str;
        Encryptor cryptor = EncryptorFactory.getEncryptor();
        tmp = cryptor.decrypt(tmp);
        String salt = DigestUtils.md5Hex(token);
        tmp = StringUtils.replace(tmp, salt, "");
        return tmp;
    } catch (Exception ex) {
        return str;
    }
}

From source file:io.wcm.handler.url.suffix.impl.UrlSuffixUtil.java

/**
 * Decode value/*from w w w  .  j a v a 2  s . c om*/
 * @param suffixPart Suffix part
 * @return Decoded value
 */
public static String decodeValue(String suffixPart) {
    // value is the part *after* KEY_VALUE_DELIMITER
    String value = StringUtils.substringAfter(suffixPart, Character.toString(KEY_VALUE_DELIMITER));

    // un-escape special chars
    for (Map.Entry<String, String> entry : SPECIAL_CHARS_ESCAPEMAP.entrySet()) {
        value = StringUtils.replace(value, entry.getValue(), entry.getKey());
    }

    return value;
}

From source file:de.micromata.genome.tpsb.GroovyExceptionInterceptor.java

public static <T> T wrappTestBuilder(T builder, Class<? extends Throwable> ex) {
    Map<String, Method> collectedMethods = new HashMap<String, Method>();
    collectMethods(builder.getClass(), collectedMethods);
    String methodBlock = renderMethodBlock(collectedMethods);
    String code = StringUtils.replace(codeTemplate, "${METHODBLOCK}", methodBlock);
    code = StringUtils.replace(code, "${PARENTCLASS}", builder.getClass().getName());
    Binding b = new Binding();
    b.setProperty("target", builder);
    b.setProperty("exptectedEx", ex);
    GroovyShell sh = new GroovyShell(b);
    try {/* ww w .  j a  v  a  2  s. co m*/
        Object ret = GroovyUtils.evaluate(sh, code, "wrapper.groovy");
        return (T) ret;
    } catch (CompilationFailedException e) {
        throw new RuntimeException("Invalid expression: " + code + "; " + e.getMessage(), e);
    }
}

From source file:mfi.staticresources.ProcessResources.java

private String deleteBetween(String content, String start, String end, String exclusionContent) {

    try {//from www .ja  v  a  2s  .c om
        String[] subs = StringUtils.substringsBetween(content, start, end);
        if (subs == null || subs.length == 0) {
            // noop
        } else {
            for (String sub : subs) {
                if (StringUtils.isNotBlank(exclusionContent)
                        && StringUtils.containsIgnoreCase(sub, exclusionContent)) {
                    // noop
                } else {
                    sub = start + sub + end;
                    content = StringUtils.replace(content, sub, "");
                }
            }
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    return content;
}

From source file:com.hortonworks.processors.network.GetTcpDumpAttributes.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    FlowFile flowFile = session.get();/*from   w  w w  .  j a va  2s .c om*/
    if (flowFile == null) {
        return;
    }

    flowFile.getAttributes();

    final Map<String, String> attributes = new HashMap<>();
    session.read(flowFile, new InputStreamCallback() {

        @Override
        public void process(InputStream in) throws IOException {
            // Parse the data as string and extract scr/dest host/ports
            String data = IOUtils.toString(in);
            String[] components = StringUtils.split(data);
            attributes.put("src.socket", components[2]);
            attributes.put("dest.socket", StringUtils.replace(components[4], ":", ""));

        }
    });

    //write out attributes to Flow file
    flowFile = session.putAllAttributes(flowFile, attributes);

    session.transfer(flowFile, SUCCESS_RELATIONSHIP);

}

From source file:info.magnolia.about.app.AboutPresenter.java

public AboutView start() {

    // magnolia information
    LicenseFileExtractor licenseProperties = LicenseFileExtractor.getInstance();
    String mgnlEdition = getEditionName();
    String mgnlVersion = licenseProperties.get(LicenseFileExtractor.VERSION_NUMBER);
    String authorInstance = serverConfiguration.isAdmin() ? i18n.translate("about.app.main.instance.author")
            : i18n.translate("about.app.main.instance.public");

    // system information
    String osInfo = String.format("%s %s (%s)", magnoliaProperties.getProperty("os.name"),
            magnoliaProperties.getProperty("os.version"), magnoliaProperties.getProperty("os.arch"));
    String javaInfo = String.format("%s (build %s)", magnoliaProperties.getProperty("java.version"),
            magnoliaProperties.getProperty("java.runtime.version"));
    String serverInfo = MgnlContext.getWebContext().getServletContext().getServerInfo();

    String dbInfo;//from ww w. java2  s .  c  om
    String dbDriverInfo;
    Connection connection = null;
    try {

        String connectionString[] = getConnectionString();

        String repoHome = magnoliaProperties.getProperty("magnolia.repositories.home");
        String repoName = getRepoName();
        connectionString[0] = StringUtils.replace(connectionString[0], "${wsp.home}",
                repoHome + "/" + repoName + "/workspaces/default");
        connection = DriverManager.getConnection(connectionString[0], connectionString[1], connectionString[2]);
        DatabaseMetaData meta = connection.getMetaData();
        dbInfo = meta.getDatabaseProductName() + " " + meta.getDatabaseProductVersion();
        if (dbInfo.toLowerCase().indexOf("mysql") != -1) {
            String engine = getMySQLEngineInfo(connection, connectionString);
            if (engine != null) {
                dbInfo += engine;
            }
        }
        dbDriverInfo = meta.getDriverName() + " " + meta.getDriverVersion();

    } catch (SQLException e) {
        log.debug("Failed to read DB and driver info from connection with {}", e.getMessage(), e);
        dbInfo = i18n.translate("about.app.main.unknown");
        dbDriverInfo = dbInfo;
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                // ignore, nothing we can do
            }
        }
    }

    String jcrInfo;
    try {
        Repository repo = JcrUtils.getRepository();
        jcrInfo = String.format("%s %s", repo.getDescriptor("jcr.repository.name"),
                repo.getDescriptor("jcr.repository.version"));
    } catch (RepositoryException e) {
        log.debug("JCR repository information is not available", e);
        jcrInfo = "-";
    }

    // Prepare information for the view
    viewData.addItemProperty(AboutView.MAGNOLIA_EDITION_KEY, new ObjectProperty<String>(mgnlEdition));
    viewData.addItemProperty(AboutView.MAGNOLIA_VERSION_KEY, new ObjectProperty<String>(mgnlVersion));
    viewData.addItemProperty(AboutView.MAGNOLIA_INSTANCE_KEY, new ObjectProperty<String>(authorInstance));
    viewData.addItemProperty(AboutView.OS_INFO_KEY, new ObjectProperty<String>(osInfo));
    viewData.addItemProperty(AboutView.JAVA_INFO_KEY, new ObjectProperty<String>(javaInfo));
    viewData.addItemProperty(AboutView.SERVER_INFO_KEY, new ObjectProperty<String>(serverInfo));
    viewData.addItemProperty(AboutView.JCR_INFO_KEY, new ObjectProperty<String>(jcrInfo));
    viewData.addItemProperty(AboutView.DB_INFO_KEY, new ObjectProperty<String>(dbInfo));
    viewData.addItemProperty(AboutView.DB_DRIVER_INFO_KEY, new ObjectProperty<String>(dbDriverInfo));
    view.setDataSource(viewData);

    return view;
}

From source file:com.google.dart.engine.internal.index.AbstractDartTest.java

/**
 * Prints given multi-line source in the way ready to paste back into Java test source.
 *///from  w ww . j a  v a2  s  .c om
protected static void printSourceLines(String source) {
    String[] lines = StringUtils.splitByWholeSeparatorPreserveAllTokens(source, EOL);
    for (int i = 0; i < lines.length; i++) {
        String line = lines[i];
        line = StringUtils.replace(line, "\"", "\\\"");
        System.out.print("\"");
        System.out.print(line);
        if (i != lines.length - 1) {
            System.out.println("\",");
        } else {
            System.out.println("\"");
        }
    }
}

From source file:com.brsanthu.dataexporter.DataExporterTestBase.java

protected void compareText(String message, String file, String text) throws IOException {
    InputStream inputStream = this.getClass().getResourceAsStream(file);
    assertNotNull("Couldn't read the reference template", inputStream);

    String expected = IOUtils.toString(inputStream);
    System.out.println("---------------------------------------------------------------------------");
    if (isNotEmpty(message)) {
        System.out.println("\nExpected (" + message + "/" + file + ")\n" + expected);
    } else {/*from   w  ww  . j  a v a 2s.  c  o  m*/
        System.out.println("\nExpected (" + file + ")\n" + expected);
    }
    System.out.println("\nProduced:\n" + text);

    expected = StringUtils.replace(expected, "\r\n", "\n");
    text = StringUtils.replace(text, "\r\n", "\n");
    assertEquals(expected.trim(), text.trim());
}