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:com.gargoylesoftware.htmlunit.javascript.host.css.CSSStyleDeclaration2Test.java

/**
 * Test types of properties./*from  w ww.j a  v a 2s. co  m*/
 * @throws Exception if the test fails
 */
@Test
public void properties2() throws Exception {
    final String expected = loadExpectation("CSSStyleDeclaration2Test.properties2", ".txt");

    final String html = "<html>\n" + "<head><title>Tester</title>\n" + "<script>\n" + "function test() {\n"
            + "  var style = document.getElementById('myDiv').style;\n" + "  var array = [];\n"
            + "  for (var i in style) {\n" + "    try {\n"
            + "      if (eval('style.' + i) === '') { array.push(i); }\n" + "    } catch(e) {}\n" // ignore strange properties like '@@iterator'
            + "  }\n" + "  array.sort();\n"
            + "  document.getElementById('myTextarea').value = array.join('\\n');\n" + "}\n"
            + "</script></head>\n" + "<body onload='test()'>\n" + "  <div id='myDiv'><br></div>\n"
            + "  <textarea id='myTextarea' cols='120' rows='20'></textarea>\n" + "</body></html>";

    final WebDriver driver = loadPage2(html);

    String actual = driver.findElement(By.id("myTextarea")).getAttribute("value");
    actual = StringUtils.replace(actual, "\r\n", "\n");
    assertEquals(expected, actual);
}

From source file:com.dominion.salud.mpr.negocio.service.acuerdos.impl.AcuCentrosServiceImpl.java

/**
 * Inserta AcuCentros en BuzonOut para procesos de integracion
 *
 * @param acuCentros/*from  w w w .  ja  va  2 s.com*/
 */
@Override
@Transactional
public void toBuzonOut(AcuCentros acuCentros) {
    if (acuCentros != null) {
        logger.debug("INSERTANDO ACUERDO EN BUZON_OUT: [" + acuCentros.getAcuerdos().toString() + "]");

        BuzonOut buzonOut = new BuzonOut();
        buzonOut.setCentros(acuCentros.getCentros());
        buzonOut.setFechaOut(new Date());
        buzonOut.setTipo("ZFN_O13");

        try {
            ZFN_M13 zfn_m13 = toHL7(acuCentros);
            buzonOut.setIdMensaje(zfn_m13.getMSH().getMessageControlID().getValue()); //MSH.10
            logger.debug("     MessageControlID: " + buzonOut.getIdMensaje());
            buzonOut.setMensaje(zfn_m13.encode());
            buzonOut.setEstado(BuzonOut.MENSAJE_NO_PROCESADO);
            buzonOutService.save(buzonOut);
        } catch (HL7Exception | IOException e) {
            logger.error("Se han producido errores al generar el mensaje del ACUERDO:\n "
                    + (StringUtils.isNotBlank(e.getMessage()) ? e.getMessage() : e.toString()));

            buzonOut.setIdMensaje("NO GENERADO (" + new Date().getTime() + ")");
            buzonOut.setEstado(BuzonOut.MENSAJE_ERRONEO);
            buzonOut.setMensaje("El mensaje ZFN_M13 no ha podido ser generado");
            buzonOutService.save(buzonOut);

            BuzonErrores buzonErrores = new BuzonErrores();
            buzonErrores.setBuzonOut(buzonOut);
            buzonErrores.setParametros(acuCentros.getIdAcuCentro().toString());
            buzonErrores.setFechaError(new Date());
            buzonErrores.setEstado(BuzonErrores.MENSAJE_NO_PROCESADO);
            buzonErrores.setMensaje("<b>Se han producido errores al generar el mensaje del ACUERDO:</b><br> "
                    + (StringUtils.isNotBlank(e.getMessage())
                            ? StringUtils.replace(e.getMessage(), "\n", "<br>")
                            : e.toString()));
            buzonErroresService.save(buzonErrores);
        }
        logger.debug("FINALIZANDO LA INSERCION DEL ACUERDO: [" + acuCentros.getAcuerdos().toString()
                + "] EN BUZON_OUT: [" + buzonOut.toString() + "]");
    }
}

From source file:mx.itesm.web2mexadl.mvc.MvcAnalyzer.java

/**
 * Export the given data into a MexADL architecture document.
 * //from   w ww. j av  a  2  s  .c  o  m
 * @param modelPackages
 * @param controllerPackages
 * @param viewPackages
 * @throws IOException
 */
public static void exportToMexADL(final File outputDir, final String modelPackages,
        final String controllerPackages, final String viewPackages) throws IOException {
    File outputFile;
    String outputContents;

    // Initial template
    outputFile = new File(outputDir, "mvcArchitecture.xml");
    FileUtils.deleteQuietly(outputFile);
    FileUtils.copyInputStreamToFile(
            MvcAnalyzer.class.getResourceAsStream("/mx/itesm/web2mexadl/templates/MvcTemplate.xml"),
            outputFile);

    // Update template with implementation packages
    outputContents = FileUtils.readFileToString(outputFile, "UTF-8");
    outputContents = StringUtils.replace(outputContents, "<!-- Model implementation -->", modelPackages);
    outputContents = StringUtils.replace(outputContents, "<!-- View implementation -->", viewPackages);
    outputContents = StringUtils.replace(outputContents, "<!-- Controller implementation -->",
            controllerPackages);

    // Final architecture
    FileUtils.write(outputFile, outputContents);
}

From source file:com.taobao.android.utils.ZipUtils.java

private static String getFileName(File folder, File file) {
    String name = StringUtils.replace(file.getAbsolutePath(), folder.getAbsolutePath() + "/", "");
    return name;//  w w w . j  a  va 2s  .co m
}

From source file:com.gargoylesoftware.htmlunit.html.HtmlSerializer.java

private void appendHtmlPreformattedText(final HtmlPreformattedText htmlPreformattedText) {
    if (isVisible(htmlPreformattedText)) {
        doAppendBlockSeparator();/*from w w  w  . j a v a2s .c o m*/
        String text = htmlPreformattedText.getTextContent();
        text = StringUtils.replace(text, "\t", AS_TEXT_TAB);
        text = StringUtils.replace(text, " ", AS_TEXT_BLANK);
        text = TEXT_AREA_PATTERN.matcher(text).replaceAll(AS_TEXT_NEW_LINE);
        text = StringUtils.replace(text, "\r", AS_TEXT_NEW_LINE);
        doAppend(text);
        doAppendBlockSeparator();
    }
}

From source file:alfio.util.TemplateResource.java

public static Map<String, Object> prepareModelForConfirmationEmail(Organization organization, Event event,
        TicketReservation reservation, Optional<String> vat, List<Ticket> tickets, OrderSummary orderSummary,
        String reservationUrl, String reservationShortID, Optional<String> invoiceAddress,
        Optional<String> bankAccountNr, Optional<String> bankAccountOwner) {
    Map<String, Object> model = new HashMap<>();
    model.put("organization", organization);
    model.put("event", event);
    model.put("ticketReservation", reservation);
    model.put("hasVat", vat.isPresent());
    model.put("vatNr", vat.orElse(""));
    model.put("tickets", tickets);
    model.put("orderSummary", orderSummary);
    model.put("reservationUrl", reservationUrl);
    model.put("locale", reservation.getUserLanguage());

    ZonedDateTime confirmationTimestamp = Optional.ofNullable(reservation.getConfirmationTimestamp())
            .orElseGet(ZonedDateTime::now);
    model.put("confirmationDate", confirmationTimestamp.withZoneSameInstant(event.getZoneId()));

    if (reservation.getValidity() != null) {
        model.put("expirationDate",
                ZonedDateTime.ofInstant(reservation.getValidity().toInstant(), event.getZoneId()));
    }//ww w  .  ja  v  a  2  s.  com

    model.put("reservationShortID", reservationShortID);

    model.put("hasInvoiceAddress", invoiceAddress.isPresent());
    invoiceAddress.ifPresent(addr -> {
        model.put("invoiceAddress", StringUtils.replace(addr, "\n", ", "));
        model.put("invoiceAddressAsList", Arrays.asList(StringUtils.split(addr, '\n')));
    });

    model.put("hasBankAccountNr", bankAccountNr.isPresent());
    bankAccountNr.ifPresent(nr -> {
        model.put("bankAccountNr", nr);
    });

    model.put("isOfflinePayment",
            reservation.getStatus() == TicketReservation.TicketReservationStatus.OFFLINE_PAYMENT);
    model.put("paymentReason", event.getShortName() + " " + reservationShortID);
    model.put("hasBankAccountOnwer", bankAccountOwner.isPresent());
    bankAccountOwner.ifPresent(owner -> {
        model.put("bankAccountOnwer", StringUtils.replace(owner, "\n", ", "));
        model.put("bankAccountOnwerAsList", Arrays.asList(StringUtils.split(owner, '\n')));
    });

    return model;
}

From source file:com.iksgmbh.sql.pojomemodb.utils.FileUtil.java

/**
 * Searches each line for "toReplace" and replaces in each line all occurrences
 * by the replavement.//from  w  ww.j a v a2 s.co  m
 * @param textFile
 * @param toReplace
 * @param replacement
 */
public static void replaceLinesInTextFile(final File textFile, final String toReplace,
        final String replacement) {
    try {
        final List<String> oldFileContent = getFileContentAsList(textFile);
        final List<String> newFileContent = new ArrayList<String>();

        for (final String line : oldFileContent) {
            newFileContent.add(StringUtils.replace(line, toReplace, replacement));
        }

        createNewFileWithContent(textFile, newFileContent);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

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

/**
 * Creates regexp from url rule text/*from w ww. j  a  v a 2 s. co m*/
 *
 * @param urlRuleText Url rule text
 * @return Regexp
 */
private String createRegexFromRule(String urlRuleText) {
    // Replacing regex special symbols
    String regexText = StringUtils.replaceEach(urlRuleText,
            new String[] { "?", ".", "+", "[", "]", "(", ")", "{", "}", "#", " ", "\\", "$" },
            new String[] { "\\?", "\\.", "\\+", "\\[", "\\]", "\\(", "\\)", "\\{", "\\}", "\\#", "\\ ", "\\\\",
                    "\\$" });

    regexText = regexText.substring(0, MASK_START_URL.length()) + StringUtils
            .replace(regexText.substring(MASK_START_URL.length(), regexText.length() - 1), "|", "\\|")
            + regexText.substring(regexText.length() - 1);
    // Replacing special url masks
    regexText = StringUtils.replace(regexText, MASK_ANY_SYMBOL, REGEXP_ANY_SYMBOL);
    regexText = StringUtils.replace(regexText, MASK_SEPARATOR, REGEXP_SEPARATOR);
    if (regexText.startsWith(MASK_START_URL)) {
        regexText = REGEXP_START_URL + regexText.substring(MASK_START_URL.length());
    } else if (regexText.startsWith(MASK_PIPE)) {
        regexText = REGEXP_START_STRING + regexText.substring(MASK_PIPE.length());
    }
    if (regexText.endsWith(MASK_PIPE)) {
        regexText = regexText.substring(0, regexText.length() - 1) + REGEXP_END_STRING;
    }

    return regexText;
}

From source file:de.micromata.genome.util.text.TextSplitterUtils.java

/**
 * Parse tokens, but also ignore tokenizing inside quotes. The quote sign itself can be quoted with \\.
 * /*from w ww. jav  a  2s. co m*/
 * Inside the quoted only the quote sign will be unescaped, all other \\ will be remain.
 *
 * @param text the text
 * @param tokens the tokens
 * @param returnDelimiter the return delimiter
 * @param quoteChar the quote char
 * @return list of tokens
 * @since 1.2.1
 */
public static List<String> parseQuotedStringTokens(String text, String[] tokens, boolean returnDelimiter,
        char quoteChar) {
    Token[] tks = new Token[tokens.length + 1];
    int i = 0;
    int quoteTk = -5;

    for (; i < tokens.length; ++i) {
        String p = tokens[i];
        if (p.length() == 1) {
            tks[i] = new CharToken(i + 1, p.charAt(0));
        } else {
            tks[i] = new StringToken(i + 1, p);
        }
    }
    char escapeChar = '\\';
    tks[tks.length - 1] = new CharToken(quoteTk, quoteChar);
    List<TokenResult> tksr = TextSplitterUtils.parseStringTokens(text, tks, escapeChar, true, true);
    List<String> ret = new ArrayList<String>();
    TokenResult tk;
    String ecapeQuote = "" + escapeChar + quoteChar;
    boolean previousWasSplitter = true;
    nextMainLoop: for (i = 0; i < tksr.size(); ++i) {
        tk = tksr.get(i);
        if (tk.getTokenType() == quoteTk) {
            StringBuilder sb = new StringBuilder();
            ++i;
            for (; i < tksr.size(); ++i) {
                tk = tksr.get(i);
                if (tk.getTokenType() == quoteTk) {
                    if (previousWasSplitter == true) {
                        ret.add(sb.toString());
                    } else {
                        ret.set(ret.size() - 1, ret.get(ret.size() - 1) + sb.toString());
                    }
                    previousWasSplitter = false;
                    continue nextMainLoop;
                }
                String s = tk.getConsumed();
                s = StringUtils.replace(s, ecapeQuote, "" + quoteChar);
                sb.append(s);
            }
            throw new IllegalArgumentException("Missing end Quote in " + text);
        }
        if (tk.getTokenType() == 0) {
            if (previousWasSplitter == false) {
                ret.set(ret.size() - 1, ret.get(ret.size() - 1) + unescape(tk.getConsumed(), escapeChar));
            } else {
                ret.add(unescape(tk.getConsumed(), escapeChar));
            }

            previousWasSplitter = false;
        } else {
            previousWasSplitter = true;
            if (returnDelimiter == true) {
                ret.add(tk.getConsumed());
            }
        }
    }
    return ret;
}

From source file:net.canadensys.dataportal.occurrence.controller.OccurrenceController.java

/**
 * Build and fill A OccurrenceViewModel based on a OccurrenceModel.
 * //from   w  w  w .j  a  va2s . c  o m
 * @param occModel
 * @return OccurrenceViewModel instance, never null
 */
public OccurrenceViewModel buildOccurrenceViewModel(OccurrenceModel occModel, DwcaResourceModel resourceModel,
        List<OccurrenceExtensionModel> occMultimediaExtModelList, Locale locale) {
    OccurrenceViewModel occViewModel = new OccurrenceViewModel();
    ResourceBundle bundle = appConfig.getResourceBundle(locale);
    // handle multimedia first (priority over associatedmedia)
    if (occMultimediaExtModelList != null) {
        String multimediaFormat, multimediaLicense, multimediaReference, multimediaIdentifier, licenseShortname;
        boolean isImage;
        MultimediaViewModel multimediaViewModel;
        Map<String, String> extData;

        for (OccurrenceExtensionModel currMultimediaExt : occMultimediaExtModelList) {
            extData = currMultimediaExt.getExt_data();

            multimediaFormat = StringUtils.defaultString(extData.get("format"));
            multimediaLicense = StringUtils.defaultString(extData.get("license"));
            multimediaIdentifier = extData.get("identifier");
            // if reference is blank, use the identifier
            multimediaReference = StringUtils.defaultIfBlank(extData.get("references"), multimediaIdentifier);

            // check if it's an image
            isImage = multimediaFormat.startsWith("image");
            licenseShortname = appConfig.getLicenseShortName(multimediaLicense);

            multimediaViewModel = new MultimediaViewModel(multimediaIdentifier, multimediaReference,
                    extData.get("title"), multimediaLicense, extData.get("creator"), isImage, licenseShortname);
            occViewModel.addMultimediaViewModel(multimediaViewModel);
        }
    }

    // handle media (only if occMultimediaExtModelList was not provided)
    if ((occMultimediaExtModelList == null || occMultimediaExtModelList.isEmpty())
            && StringUtils.isNotEmpty(occModel.getAssociatedmedia())) {
        // assumes that data are coming from harvester
        String[] media = occModel.getAssociatedmedia().split("; ");

        MultimediaViewModel multimediaViewModel;
        boolean isImage;
        String title;
        int imageNumber = 1, otherMediaNumber = 1;
        for (String currentMedia : media) {
            isImage = MIME_TYPE_MAP.getContentType(currentMedia).startsWith("image");
            String image = bundle.getString("occ.image");
            if (isImage) {
                title = image + " " + imageNumber;
                imageNumber++;
            } else {
                title = bundle.getString("occ.associatedmedia") + " " + otherMediaNumber;
                otherMediaNumber++;
            }

            multimediaViewModel = new MultimediaViewModel(currentMedia, currentMedia, title, null, null,
                    isImage, null);
            occViewModel.addMultimediaViewModel(multimediaViewModel);
        }
    }

    // handle associated sequences
    handleAssociatedSequence(occModel, occViewModel);

    // handle data source page URL (url to the resource page)
    if (resourceModel != null) {
        if (StringUtils.contains(resourceModel.getArchive_url(), IPT_ARCHIVE_PATTERN)) {
            occViewModel.setDataSourcePageURL(StringUtils.replace(resourceModel.getArchive_url(),
                    IPT_ARCHIVE_PATTERN, IPT_RESOURCE_PATTERN));
        }
    }

    // handle Recommended Citation
    String datasourcePageUrl = occViewModel.getDataSourcePageURL();
    if (datasourcePageUrl != null)
        occViewModel.setRecommendedCitation(
                Formatter.buildRecommendedCitation(occModel, datasourcePageUrl, bundle));
    return occViewModel;
}