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

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

Introduction

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

Prototype

public static String remove(final String str, final char remove) 

Source Link

Document

Removes all occurrences of a character from within the source string.

A null source string will return null .

Usage

From source file:com.nridge.core.base.io.xml.DataBagXML.java

/**
 * Saves the previous assigned bag/table (e.g. via constructor or set method)
 * to the print writer stream wrapped in a tag name specified in the parameter.
 *
 * @param aPW PrintWriter stream instance.
 * @param aTagName Tag name./*from www  .  jav  a  2 s . c o  m*/
 * @param anIndentAmount Indentation count.
 *
 * @throws IOException I/O related exception.
 */
public void save(PrintWriter aPW, String aTagName, int anIndentAmount) throws IOException {
    IOXML.indentLine(aPW, anIndentAmount);
    String tagName = StringUtils.remove(aTagName, StrUtl.CHAR_SPACE);
    aPW.printf("<%s", tagName);
    if (!mIsSimple) {
        IOXML.writeAttrNameValue(aPW, "type", IO.extractType(mBag.getClass().getName()));
        IOXML.writeAttrNameValue(aPW, "name", mBag.getName());
        IOXML.writeAttrNameValue(aPW, "title", mBag.getTitle());
        IOXML.writeAttrNameValue(aPW, "count", mBag.count());
        IOXML.writeAttrNameValue(aPW, "version", IO.DATABAG_XML_FORMAT_VERSION);
    }
    for (Map.Entry<String, String> featureEntry : mBag.getFeatures().entrySet())
        IOXML.writeAttrNameValue(aPW, featureEntry.getKey(), featureEntry.getValue());
    aPW.printf(">%n");

    for (DataField dataField : mBag.getFields()) {
        if (dataField.isAssigned()) {
            mDataFieldXML.saveNode(aPW, anIndentAmount + 1);
            mDataFieldXML.saveAttr(aPW, dataField);
            mDataFieldXML.saveValue(aPW, dataField, anIndentAmount + 1);
        }
    }

    IOXML.indentLine(aPW, anIndentAmount);
    aPW.printf("</%s>%n", tagName);
}

From source file:info.mikaelsvensson.devtools.analysis.localaccesslog.LocalAccessLogReportGenerator.java

@Override
public void generateReport(File outputFile, ReportPrinter reportPrinter) throws FileNotFoundException {
    final PrintStream ps = new PrintStream(outputFile);
    final Collection<LocalAccessLogSample> allSamples = _log.getSamples();
    Map<String, Collection<LocalAccessLogSample>> samplesByTestSession = SampleCollector.COLLECTOR_BY_SESSION_DATE
            .getFilteredAndGrouped(allSamples);
    for (Map.Entry<String, Collection<LocalAccessLogSample>> sessionEntry : samplesByTestSession.entrySet()) {
        final Collection<LocalAccessLogSample> sessionSamples = sessionEntry.getValue();
        Map<String, Collection<LocalAccessLogSample>> samples = SAMPLE_COLLECTOR
                .getFilteredAndGrouped(sessionSamples);
        String[][] data = new String[samples.size() + 1][];
        int i = 0;
        int sumCount = 0;
        final DefaultPieDataset dataset = new DefaultPieDataset();
        final JFreeChart chart = ChartFactory.createPieChart(
                "Status Codes For Session " + sessionEntry.getKey(), dataset, true, false, Locale.ENGLISH);
        final File chartFile = new File(outputFile.getAbsolutePath() + "."
                + StringUtils.remove(sessionEntry.getKey(), ':').replace(' ', '-') + ".png");
        final PiePlot plot = (PiePlot) chart.getPlot();
        for (Map.Entry<String, Collection<LocalAccessLogSample>> entry : samples.entrySet()) {
            final Collection<LocalAccessLogSample> responseCodeSamples = entry.getValue();
            final int count = responseCodeSamples.size();
            data[i++] = new String[] { entry.getKey(), ToStringUtil.toString(count),
                    ToStringUtil.toString(_log.calculateAverage(responseCodeSamples)),
                    ToStringUtil.toString(_log.calculateMin(responseCodeSamples)),
                    ToStringUtil.toString(_log.calculateMax(responseCodeSamples)) };
            sumCount += count;/*  w  w  w. ja v a2  s. c  o  m*/

            final String label = entry.getKey() + " (" + count + " reqs)";
            dataset.setValue(label, count);
            plot.setSectionPaint(label, entry.getKey().equals("200") ? Color.GREEN : Color.RED);
        }
        data[i] = new String[] { "All", ToStringUtil.toString(sumCount),
                ToStringUtil.toString(_log.calculateAverage(sessionSamples)),
                ToStringUtil.toString(_log.calculateMin(sessionSamples)),
                ToStringUtil.toString(_log.calculateMax(sessionSamples)) };

        reportPrinter.printTable(ps, sessionEntry.getKey(), 10,
                new String[] { "Status Code", "# Requests", "Avg [ms]", "Min [ms]", "Max [ms]" }, data, null);

        if (sumCount > NUMBER_OF_REQUESTS_IN_SHORT_TEST) {
            try {
                ChartUtilities.saveChartAsPNG(chartFile, chart, 500, 500);
            } catch (IOException e) {
                e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
            }
        }
    }
    ps.close();
}

From source file:com.nridge.core.base.io.xml.DSCriteriaXML.java

/**
 * Saves the previous assigned criteria (e.g. via constructor or set method)
 * to the print writer stream wrapped in a tag name specified in the parameter.
 *
 * @param aPW            PrintWriter stream instance.
 * @param aTagName       Tag name./*from w  w w .  j av a2s  . com*/
 * @param anIndentAmount Indentation count.
 *
 * @throws java.io.IOException I/O related exception.
 */
@Override
public void save(PrintWriter aPW, String aTagName, int anIndentAmount) throws IOException {
    DataField dataField;
    DSCriterion dsCriterion;

    String tagName = StringUtils.remove(aTagName, StrUtl.CHAR_SPACE);
    ArrayList<DSCriterionEntry> dsCriterionEntries = mDSCriteria.getCriterionEntries();
    int ceCount = dsCriterionEntries.size();

    IOXML.indentLine(aPW, anIndentAmount);
    aPW.printf("<%s", tagName);
    IOXML.writeAttrNameValue(aPW, "type", IO.extractType(mDSCriteria.getClass().getName()));
    IOXML.writeAttrNameValue(aPW, "name", mDSCriteria.getName());
    IOXML.writeAttrNameValue(aPW, "version", IO.CRITERIA_XML_FORMAT_VERSION);
    IOXML.writeAttrNameValue(aPW, "operator", Field.operatorToString(Field.Operator.AND));
    IOXML.writeAttrNameValue(aPW, "count", ceCount);
    for (Map.Entry<String, String> featureEntry : mDSCriteria.getFeatures().entrySet())
        IOXML.writeAttrNameValue(aPW, featureEntry.getKey(), featureEntry.getValue());
    aPW.printf(">%n");

    if (ceCount > 0) {
        for (DSCriterionEntry ce : dsCriterionEntries) {
            dsCriterion = ce.getCriterion();

            dataField = new DataField(dsCriterion.getField());
            dataField.addFeature("operator", Field.operatorToString(ce.getLogicalOperator()));
            mDataFieldXML.saveNode(aPW, anIndentAmount + 1);
            mDataFieldXML.saveAttr(aPW, dataField);
            mDataFieldXML.saveValue(aPW, dataField, anIndentAmount + 1);
        }
    }

    IOXML.indentLine(aPW, anIndentAmount);
    aPW.printf("</%s>%n", tagName);
}

From source file:de.jfachwert.bank.GeldbetragFormatter.java

private Geldbetrag parse(String text) throws MonetaryParseException {
    String trimmed = new NullValidator<String>().validate(text).trim();
    String[] parts = StringUtils.splitByCharacterType(StringUtils.upperCase(trimmed));
    if (parts.length == 0) {
        throw new InvalidValueException(text, "money amount");
    }//from ww w . j a v a 2  s.  c  om
    Currency cry = Waehrung.DEFAULT_CURRENCY;
    String currencyString = findCurrencyString(parts);
    try {
        if (StringUtils.isNotEmpty(currencyString)) {
            cry = Waehrung.toCurrency(currencyString);
            trimmed = StringUtils.remove(trimmed, currencyString).trim();
        }
        BigDecimal n = new BigDecimal(new NumberValidator().validate(trimmed));
        return Geldbetrag.of(n, cry);
    } catch (IllegalArgumentException ex) {
        throw new LocalizedMonetaryParseException(text, ex);
    }
}

From source file:com.nridge.core.base.io.xml.RelationshipXML.java

/**
 * Saves the previous assigned relationship (e.g. via constructor or set method)
 * to the print writer stream wrapped in a tag name specified in the parameter.
 *
 * @param aPW            PrintWriter stream instance.
 * @param aTagName       Tag name./*from   w  w w  . ja v  a 2 s.  c  o m*/
 * @param anIndentAmount Indentation count.
 *
 * @throws java.io.IOException I/O related exception.
 */
@Override
public void save(PrintWriter aPW, String aTagName, int anIndentAmount) throws IOException {
    DocumentXML documentXML;

    IOXML.indentLine(aPW, anIndentAmount);
    String typeName = mRelationship.getType();
    String tagName = StringUtils.remove(aTagName, StrUtl.CHAR_SPACE);
    aPW.printf("<%s", tagName);
    IOXML.writeAttrNameValue(aPW, "type", typeName);
    for (Map.Entry<String, String> featureEntry : mRelationship.getFeatures().entrySet())
        IOXML.writeAttrNameValue(aPW, featureEntry.getKey(), featureEntry.getValue());
    aPW.printf(">%n");
    DataBag dataBag = mRelationship.getBag();
    if (dataBag.assignedCount() > 0) {
        DataBagXML dataBagXML = new DataBagXML(dataBag);
        dataBagXML.setBag(dataBag);
        dataBagXML.save(aPW, IO.XML_PROPERTIES_NODE_NAME, anIndentAmount + 1);
    }
    for (com.nridge.core.base.doc.Document document : mRelationship.getDocuments()) {
        documentXML = new DocumentXML(document);
        documentXML.setSaveFieldsWithoutValues(mSaveFieldsWithoutValues);
        documentXML.save(aPW, IO.XML_DOCUMENT_NODE_NAME, document, anIndentAmount + 1);
    }
    IOXML.indentLine(aPW, anIndentAmount);
    aPW.printf("</%s>%n", tagName);
}

From source file:com.xpn.xwiki.web.CommentAddAction.java

/**
 * {@inheritDoc}//from   w  w w .ja  va 2 s  . c  om
 * 
 * @see XWikiAction#action(com.xpn.xwiki.XWikiContext)
 */
@Override
public boolean action(XWikiContext context) throws XWikiException {
    // CSRF prevention
    if (!csrfTokenCheck(context)) {
        return false;
    }

    XWiki xwiki = context.getWiki();
    XWikiResponse response = context.getResponse();
    XWikiDocument doc = context.getDoc();
    ObjectAddForm oform = (ObjectAddForm) context.getForm();

    // Make sure this class exists
    BaseClass baseclass = xwiki.getCommentsClass(context);
    if (doc.isNew()) {
        return true;
    } else if (context.getUser().equals(XWikiRightService.GUEST_USER_FULLNAME) && !checkCaptcha(context)) {
        ((VelocityContext) context.get("vcontext")).put("captchaAnswerWrong", Boolean.TRUE);
    } else {
        // className = XWiki.XWikiComments
        String className = baseclass.getName();
        BaseObject object = doc.newObject(className, context);
        // TODO The map should be pre-filled with empty strings for all class properties, just like in
        // ObjectAddAction, so that properties missing from the request are still added to the database.
        baseclass.fromMap(oform.getObject(className), object);
        // Comment author checks
        if (XWikiRightService.GUEST_USER_FULLNAME.equals(context.getUser())) {
            // Guests should not be allowed to enter names that look like real XWiki user names.
            String author = ((BaseProperty) object.get(AUTHOR_PROPERTY_NAME)).getValue() + "";
            author = StringUtils.remove(author, ':');
            while (author.startsWith(USER_SPACE_PREFIX)) {
                author = StringUtils.removeStart(author, USER_SPACE_PREFIX);
            }
            object.set(AUTHOR_PROPERTY_NAME, author, context);
        } else {
            // A registered user must always post with his name.
            object.set(AUTHOR_PROPERTY_NAME, context.getUser(), context);
        }
        doc.setAuthor(context.getUser());
        // Consider comments not being content.
        doc.setContentDirty(false);
        // if contentDirty is false, in order for the change to create a new version metaDataDirty must be true.
        doc.setMetaDataDirty(true);
        xwiki.saveDocument(doc, context.getMessageTool().get("core.comment.addComment"), true, context);
    }
    // If xpage is specified then allow the specified template to be parsed.
    if (context.getRequest().get("xpage") != null) {
        return true;
    }
    // forward to edit
    String redirect = Utils.getRedirect("edit", context);
    sendRedirect(response, redirect);
    return false;
}

From source file:info.magnolia.security.app.dialog.action.SaveGroupDialogAction.java

private String[] itemPropertyToArray(JcrNodeAdapter item, String propertyName) {
    String identifiers = item.getItemProperty(propertyName).getValue().toString();
    identifiers = StringUtils.remove(identifiers, '[');
    identifiers = StringUtils.remove(identifiers, ']');
    return StringUtils.split(identifiers, ',');
}

From source file:io.manasobi.license.LicenseController.java

private String convertISODateToDate(Date isoDate) {

    DateTime dateTime = new DateTime(isoDate);

    String simpleDate = DateUtils.convertDateToString(dateTime.minusHours(9).toDate(),
            "yyyy-MM-dd'T'HH:mm:ss.SSS'Z");

    simpleDate = StringUtils.replace(simpleDate, "T", " ");
    simpleDate = StringUtils.remove(simpleDate, "Z");

    return StringUtils.substring(simpleDate, 0, 19);
}

From source file:com.adobe.acs.commons.mcp.impl.GenericReportExcelServlet.java

@SuppressWarnings("squid:S3776")
private Workbook createSpreadsheet(GenericReport report) {
    Workbook wb = new XSSFWorkbook();

    String name = report.getName();
    for (char ch : new char[] { '\\', '/', '*', '[', ']', ':', '?' }) {
        name = StringUtils.remove(name, ch);
    }//from w  ww  . java2 s. co  m
    Sheet sheet = wb.createSheet(name);
    sheet.createFreezePane(0, 1, 0, 1);

    Row headerRow = sheet.createRow(0);
    CellStyle headerStyle = createHeaderStyle(wb);
    for (int c = 0; c < report.getColumnNames().size(); c++) {
        Cell headerCell = headerRow.createCell(c);
        headerCell.setCellValue(report.getColumnNames().get(c));
        headerCell.setCellStyle(headerStyle);
    }

    List<ValueMap> rows = report.getRows();
    //make rows, don't forget the header row
    for (int r = 0; r < rows.size(); r++) {
        Row row = sheet.createRow(r + 1);

        //make columns
        for (int c = 0; c < report.getColumns().size(); c++) {
            String col = report.getColumns().get(c);
            Cell cell = row.createCell(c);

            if (rows.get(r).containsKey(col)) {
                Object val = rows.get(r).get(col);
                if (val instanceof Number) {
                    Number n = (Number) val;
                    cell.setCellValue(n.doubleValue());
                } else {
                    String sval = String.valueOf(val);
                    if (sval.startsWith("=")) {
                        cell.setCellFormula(sval.substring(1));
                    } else {
                        cell.setCellValue(sval);
                    }
                }
            }
        }
    }
    int lastColumnIndex = report.getColumnNames().size();
    autosize(sheet, lastColumnIndex);
    sheet.setAutoFilter(new CellRangeAddress(0, 1 + rows.size(), 0, lastColumnIndex - 1));
    return wb;
}

From source file:com.thruzero.common.jsf.support.beans.dialog.AbstractAboutApplicationBean.java

public String getJarRows() {
    StringBuffer result = new StringBuffer();

    try {// w w  w.j  ava2  s .  c o  m
        File webInfDir = FacesUtils.getWebInfDir();
        if (webInfDir != null) {
            File libDir = new File(webInfDir, "lib");
            String[] extensions = { "jar" };
            @SuppressWarnings("unchecked") // FileUtils isn't generic
            Collection<File> jarFiles = FileUtils.listFiles(libDir, extensions, false);
            StringMap aboutLibs = ConfigLocator.locate()
                    .getSectionAsStringMap(AboutBoxConfigKeys.ABOUT_LIBS_SECTION);

            if (aboutLibs == null) {
                result.append("<br/><span style=\"color:red;\">The " + AboutBoxConfigKeys.ABOUT_LIBS_SECTION
                        + " config section was not found.</span>");
            } else {
                for (File jarFile : jarFiles) {
                    String version = StringUtils.substringAfterLast(jarFile.getName(), "-");
                    version = StringUtils.remove(version, ".jar");
                    String aboutKey = StringUtils.substringBeforeLast(jarFile.getName(), "-");

                    // make sure it's the full version number (e.g., "hibernate-c3p0-3.5.0-Final" at this point will be "Final". Need to back up a segment to get the version number.
                    String versComp = StringUtils.substringBefore(version, ".");
                    if (!StringUtils.isNumeric(versComp)) {
                        String version2 = StringUtils.substringAfterLast(aboutKey, "-");
                        versComp = StringUtils.substringBefore(version2, ".");
                        if (StringUtils.isNumeric(versComp)) {
                            aboutKey = StringUtils.substringBeforeLast(aboutKey, "-");
                            version = version2 + "-" + version;
                        } else {
                            continue; // give up on this one
                        }
                    }

                    // get config value for this jar file
                    if (StringUtils.isNotEmpty(aboutKey) && StringUtils.isNotEmpty(version)
                            && aboutLibs.containsKey(aboutKey)) {
                        String href = aboutLibs.get(aboutKey);
                        aboutKey = StringUtils.remove(aboutKey, "-core");
                        result.append(TableUtils.createSimpleFormRow(aboutKey, href, version));
                    }
                }
            }
        }
    } catch (Exception e) {
        // don't let the about box crash the app
    }

    return result.toString();
}