Example usage for org.apache.commons.lang StringUtils replaceChars

List of usage examples for org.apache.commons.lang StringUtils replaceChars

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils replaceChars.

Prototype

public static String replaceChars(String str, String searchChars, String replaceChars) 

Source Link

Document

Replaces multiple characters in a String in one go.

Usage

From source file:com.npower.dm.model.TestGenerateModelXMLByCSV.java

/**
 * @param maps//from  ww  w  .j a  v a 2 s  . c  o m
 * @param outputBaseDir
 * @throws DMException
 * @throws Exception
 */
private void outputModelsXML(Map<String, TreeSet<String>> maps, String outputBaseDir)
        throws DMException, Exception {
    // Generate XML
    ManagementBeanFactory factory = AllTests.getManagementBeanFactory();
    ModelBean bean = factory.createModelBean();
    int total = 0;
    int total4New = 0;
    int total4Exists = 0;
    try {
        for (String manufacturerExtID : maps.keySet()) {
            String folderName = manufacturerExtID.trim().toLowerCase();
            folderName = StringUtils.replaceChars(folderName, '-', '_');
            folderName = StringUtils.replaceChars(folderName, ' ', '_');
            File outputDir = new File(outputBaseDir, "models/" + folderName);
            if (!outputDir.exists()) {
                outputDir.mkdirs();
                File iconDir = new File(outputDir, "icons");
                if (!iconDir.exists()) {
                    iconDir.mkdirs();
                }
            }
            File outputFile = new File(outputDir, "models.additional.xml");
            BufferedWriter out = new BufferedWriter(new FileWriter(outputFile));
            out.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
            out.write("<Setup>\n");
            out.write("<!--  Models: " + manufacturerExtID.trim() + " -->\n");
            out.write("<Models>\n");
            out.write("\n");

            for (String modelExtID : maps.get(manufacturerExtID)) {
                total++;
                Manufacturer manufacturer = bean.getManufacturerByExternalID(manufacturerExtID);
                Model model = bean.getModelByManufacturerModelID(manufacturer, modelExtID);
                if (model != null) {
                    // Exists
                    total4Exists++;
                    System.err.println(manufacturerExtID + " " + modelExtID + " exists!");
                } else {
                    total4New++;
                    out.write(this.writeXML(manufacturerExtID, modelExtID, folderName));
                    out.write("\n");

                }
            }

            out.write("\n");
            out.write("</Models>\n");
            out.write("</Setup>\n");

            out.close();
        }

    } catch (Exception e) {
        throw e;
    } finally {
        factory.release();
    }

    System.out.println("*********************************************************************");
    System.out.println(" Total         : " + total);
    System.out.println(" Total (Exists): " + total4Exists);
    System.out.println(" Total (New)   : " + total4New);
    System.out.println("*********************************************************************");
}

From source file:br.com.nordestefomento.jrimum.utilix.Field.java

/**
 * <p>/*  ww  w .j a v  a  2  s  . c  o  m*/
 * Escreve o campo no formato e tamanho especificado.
 * </p>
 * 
 * @see TextStream#write()
 * 
 * @return campo escrito
 * @since 0.2
 */
public String write() {

    String str = null;

    if (value instanceof TextStream) {

        TextStream its = (TextStream) value;

        str = its.write();

    } else if (value instanceof Date) {

        Date campoDate = (Date) value;

        if (campoDate.compareTo(DateUtil.DATE_NULL) == 0) {
            str = StringUtils.EMPTY;

        } else {
            str = format.format(value);
        }

    } else if (value instanceof BigDecimal) {
        str = StringUtils.replaceChars(value.toString(), ".", StringUtils.EMPTY);

    } else {
        str = value.toString();
    }

    str = fill(str);

    if (str.length() != length) {
        throw new IllegalArgumentException(
                "O tamaho do campo [ " + str + " ]  incompatvel com o especificado [" + length + "]!");
    }

    return StringUtil.eliminateAccent(str).toUpperCase();
}

From source file:com.haulmont.cuba.web.gui.components.WebTimeField.java

protected void updateTimeFormat() {
    String mask = StringUtils.replaceChars(timeFormat, "Hhmsa", "####U");
    placeholder = StringUtils.replaceChars(mask, "#U", "__");
    component.setMask(mask);/*from   w  w w  .j  a  v  a  2  s.c om*/
    component.setNullRepresentation(placeholder);
}

From source file:de.forsthaus.webui.customer.CustomerSearchCtrl.java

/**
 * Restore the operator sign in the operator listbox by comparing the <br>
 * value of the filter. <br>/*  ww w  .  java  2s .c o  m*/
 * 
 * @param listbox
 *            Listbox that shows the operator signs.
 * @param filter
 *            Filter that corresponds to the operator listbox.
 */
private void restoreOperator(Listbox listbox, Filter filter) {
    if (filter.getOperator() == Filter.OP_EQUAL) {
        listbox.setSelectedIndex(1);
    } else if (filter.getOperator() == Filter.OP_NOT_EQUAL) {
        listbox.setSelectedIndex(2);
    } else if (filter.getOperator() == Filter.OP_LESS_THAN) {
        listbox.setSelectedIndex(3);
    } else if (filter.getOperator() == Filter.OP_GREATER_THAN) {
        listbox.setSelectedIndex(4);
    } else if (filter.getOperator() == Filter.OP_LESS_OR_EQUAL) {
        listbox.setSelectedIndex(5);
    } else if (filter.getOperator() == Filter.OP_GREATER_OR_EQUAL) {
        listbox.setSelectedIndex(6);
    } else if (filter.getOperator() == Filter.OP_ILIKE) {
        // Delete used '%' signs if the operator is like or iLike
        String str = StringUtils.replaceChars(filter.getValue().toString(), "%", "");
        filter.setValue(str);
        listbox.setSelectedIndex(7);
    }
}

From source file:com.redhat.rhn.frontend.struts.StrutsDelegate.java

/**
 * Use this for every textarea that we use in our UI.  Otherwise you will get ^M
 * in your file showing up./*from   w  w w.ja  v a  2 s. c o  m*/
 * @param form to fetch from
 * @param name of value in form
 * @return String without CR in them.
 */
public String getTextAreaValue(DynaActionForm form, String name) {
    String value = form.getString(name);
    return StringUtils.replaceChars(value, "\r", "");
}

From source file:cn.vlabs.duckling.vwb.ui.servlet.SimpleUploaderServlet.java

protected String executeUpload(HttpServletRequest request, VWBContext context, InputStream data,
        String filename, long contentLength, HashMap<String, String> hashMap, HttpServletResponse response) {
    String pageName = "Main";
    String signature;// w  w w .  ja va2 s  .c  o m

    String created = null;
    String title;
    if (hashMap != null) {
        title = hashMap.get("title");
        pageName = hashMap.get("page");
        if (pageName == null || pageName.equals(""))
            pageName = "Main";
        signature = hashMap.get("signature");
        if (signature == null || signature.equals(""))
            signature = "off";
    } else
        return null;

    if (!isTypeAllowed(filename)) {
        request.setAttribute(RETVAL, "205");
        request.setAttribute(ERRORMESSAGE, rb.getString("uploader.filetype"));
        return null;
    }
    if (filename == null || filename.trim().length() == 0) {
        log.error("Empty file name given.");
        request.setAttribute(RETVAL, "207");
        request.setAttribute(ERRORMESSAGE, rb.getString("uploader.emptyname"));
        return null;
    }
    //
    // Should help with IE 5.22 on OSX
    //
    filename = filename.trim();
    //
    // Remove any characters that might be a problem. Most
    // importantly - characters that might stop processing
    // of the URL.
    //
    filename = StringUtils.replaceChars(filename, "#?\"'", "____");
    if (data == null) {
        log.error("File could not be opened.");
        request.setAttribute(RETVAL, "208");
        request.setAttribute(ERRORMESSAGE, rb.getString("uploader.notopenfile"));

        return null;
    }
    StreamInfo stream = new StreamInfo();
    stream.setFilename(filename);
    stream.setInputStream(data);
    stream.setLength(contentLength);
    SiteMetaInfo site = VWBContainerImpl.findSite(request);
    AttachmentService attachementService = VWBContainerImpl.findContainer().getAttachmentService();
    boolean cachable = "true".equalsIgnoreCase(hashMap.get("cachable"));
    try {
        VWBSession session = VWBSession.findSession(request);
        int docid = attachementService.createDocument(site.getId(), pageName,
                session.getCurrentUser().getName(), true, stream);
        if (docid == 0) {
            log.error("clb?");
            request.setAttribute(RETVAL, "209");
            request.setAttribute(ERRORMESSAGE, rb.getString("error.create"));
            return null;
        }
        AttachmentURL attach;
        if (title.lastIndexOf('.') != -1) {
            String suffix = title.substring(title.lastIndexOf('.') + 1);
            attach = new AttachmentURL(cachable, docid, suffix);
        } else {
            attach = new AttachmentURL(cachable, docid);
        }

        // ?
        log.info("?:id=" + docid + ";title=" + filename + "");

        // ??
        // ??
        if (signature.equals("on")) {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            signature = "   ? " + context.getCurrentUser().getName() + "   "
                    + df.format(Calendar.getInstance().getTime()) + "  ";
            request.setAttribute(FILEURL, signature);
        }

        // ?hash
        created = attach.buildURL(context.getBaseURL());

        request.setAttribute(RETVAL, "0");
        request.setAttribute(ERRORMESSAGE, rb.getString("uploader.success"));
    } catch (Exception e) {
        e.printStackTrace();
        request.setAttribute(RETVAL, "210");
        request.setAttribute(ERRORMESSAGE, rb.getString("uploader.upload"));
        return null;
    }

    return created;

}

From source file:com.openbravo.pos.imports.JPanelCSVImport.java

/**
 * Imports the CVS File using specifications from the form.
 *
 * @param CSVFileName Name of the file (including path) to import.
 * @throws IOException If there are file reading issues.
 *///w w w.j  a  va  2  s.  c o m
private void ImportCsvFile(String CSVFileName) throws IOException {

    File f = new File(CSVFileName);
    if (f.exists()) {
        // Read file
        products = new CsvReader(CSVFileName);
        products.setDelimiter(((String) jComboSeparator.getSelectedItem()).charAt(0));
        products.readHeaders();

        currentRecord = 0;
        while (products.readRecord()) {
            productReference = products.get((String) jComboReference.getSelectedItem());
            productName = products.get((String) jComboName.getSelectedItem());
            productBarcode = products.get((String) jComboBarcode.getSelectedItem());
            String BuyPrice = products.get((String) jComboBuy.getSelectedItem());
            String SellPrice = products.get((String) jComboSell.getSelectedItem());
            Category = products.get((String) jComboCategory.getSelectedItem());
            currentRecord++;

            // Strip Currency Symbols
            BuyPrice = StringUtils.replaceChars(BuyPrice, "$", ""); // Remove currency symbol
            SellPrice = StringUtils.replaceChars(SellPrice, "$", ""); // Remove currency symbol

            dCategory = getCategory();

            // set the csvMessage to a default value
            if ("Bad Category".equals(dCategory)) {
                csvMessage = "Bad category details";
            } else {
                csvMessage = "Missing data or Invalid number";
            }

            // Validate and convert the prices or change them to null
            if (validateNumber(BuyPrice)) {
                productBuyPrice = Double.parseDouble(BuyPrice);
            } else {
                productBuyPrice = null;
            }

            if (validateNumber(SellPrice)) {
                productSellPrice = getSellPrice(SellPrice);
            } else {
                productSellPrice = null;
            }

            /**
             * Check to make sure our entries aren't bad or blank or the
             * category is not bad
             *
             */
            if ("".equals(productReference) | "".equals(productName) | "".equals(productBarcode)
                    | "".equals(BuyPrice) | "".equals(SellPrice) | productBuyPrice == null
                    | productSellPrice == null | "Bad Category".equals(dCategory)) {
                if (productBuyPrice == null | productSellPrice == null) {
                    badPrice++;
                } else {
                    missingData++;
                }
                createCSVEntry(csvMessage, null, null);
            } else {
                // We know that the data passes the basic checks, so get more details about the product
                recordType = getRecord();
                switch (recordType) {
                case "new":
                    createProduct("new");
                    newRecords++;
                    jTextNew.setText(Integer.toString(newRecords));
                    createCSVEntry("New product", null, null);
                    break;
                case "name error":
                case "barcode error":
                case "reference error":
                case "Duplicate Reference found.":
                case "Duplicate Barcode found.":
                case "Duplicate Description found.":
                case "Exception":
                    invalidRecords++;
                    createCSVEntry(recordType, null, null);
                    break;
                default:
                    updateRecord(recordType);
                    break;
                }
            }
        }
    } else {
        JOptionPane.showMessageDialog(null, "Unable to locate " + CSVFileName, "File not found",
                JOptionPane.WARNING_MESSAGE);
    }

    // update the record fields on the form
    jTextNew.setText(Integer.toString(newRecords));
    jTextUpdate.setText(Integer.toString(priceUpdates));
    jTextInvalid.setText(Integer.toString(invalidRecords));
    jTextMissing.setText(Integer.toString(missingData));
    jTextNoChange.setText(Integer.toString(noChanges));
    jTextBadPrice.setText(Integer.toString(badPrice));
    jTextBadCats.setText(Integer.toString(badCategories.size()));

    jImport.setEnabled(true);
}

From source file:com.npower.dm.model.TestGenerateModelXMLByWurfl.java

/**
 * @param maps//from   w  w w .  j a v a  2  s.  c o  m
 * @param outputBaseDir
 * @throws DMException
 * @throws Exception
 */
private void outputManufacturersXML(Map<String, Set<String>> maps, Map<String, String> brandNames,
        String outputBaseDir) throws DMException, Exception {
    // Generate XML
    ManagementBeanFactory factory = AllTests.getManagementBeanFactory();
    ModelBean bean = factory.createModelBean();
    int total = 0;
    int total4New = 0;
    int total4Exists = 0;
    try {
        for (String manufacturerExtID : maps.keySet()) {
            Manufacturer manufacturer = bean.getManufacturerByExternalID(manufacturerExtID);
            String folderName = manufacturerExtID.trim().toLowerCase();
            folderName = StringUtils.replaceChars(folderName, '-', '_');
            folderName = StringUtils.replaceChars(folderName, ' ', '_');
            File outputDir = new File(outputBaseDir, "manufacturers");
            if (!outputDir.exists()) {
                outputDir.mkdirs();
            }
            File outputFile = null;
            if (manufacturer != null) {
                outputFile = new File(outputDir, folderName + ".2nd.xml");

                this.modelNames.add(brandNames.get(manufacturerExtID.trim().toLowerCase()));
                this.modelFiles.add("./manufacturers/" + folderName + ".2nd.xml");
            } else {
                outputFile = new File(outputDir, folderName + ".xml");

                this.manufacturerNames.add(manufacturerExtID);
                this.manufacturerFiles.add(folderName + ".xml");

                this.modelNames.add(brandNames.get(manufacturerExtID.trim().toLowerCase()));
                this.modelFiles.add("./manufacturers/" + folderName + ".xml");
            }
            BufferedWriter out = new BufferedWriter(new FileWriter(outputFile));
            out.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
            out.write("<Setup>\n");
            out.write("<Manufacturers>\n");
            out.write("\n");
            out.write("<Manufacturer>\n");
            out.write("<Name>" + brandNames.get(manufacturerExtID.trim().toLowerCase()) + "</Name>\n");
            out.write("<ExternalID>" + brandNames.get(manufacturerExtID.trim().toLowerCase())
                    + "</ExternalID>\n");
            out.write("<Description>" + brandNames.get(manufacturerExtID.trim().toLowerCase())
                    + "</Description>\n");
            out.write("<Models filename=\"./models/" + folderName.trim() + "/models.2nd.xml\"/>\n");
            out.write("</Manufacturer>\n");
            out.write("\n");
            out.write("</Manufacturers>\n");
            out.write("</Setup>\n");

            out.close();
        }

    } catch (Exception e) {
        throw e;
    } finally {
        factory.release();
    }

    System.out.println("*********************************************************************");
    System.out.println(" Total         : " + total);
    System.out.println(" Total (Exists): " + total4Exists);
    System.out.println(" Total (New)   : " + total4New);
    System.out.println("*********************************************************************");
}

From source file:com.manydesigns.portofino.model.database.DatabaseLogic.java

public static String normalizeName(String name) {
    name = StringUtils.replaceChars(name, ".", "_");
    String firstLetter = name.substring(0, 1);
    String others = name.substring(1);

    StringBuilder result = new StringBuilder();
    result.append(checkFirstLetter(firstLetter));

    for (int i = 0; i < others.length(); i++) {
        String letter = String.valueOf(others.charAt(i));
        result.append(checkOtherLetters(letter));
    }/*from  ww  w.  ja  v  a 2 s . co m*/
    String normalizedName = result.toString();
    if (ArrayUtils.contains(HQL_KEYWORDS, normalizedName.toLowerCase())) {
        normalizedName = "_" + normalizedName;
    }
    if (!name.equals(normalizedName)) {
        logger.info("Name " + name + " normalized to " + normalizedName);
    }
    return normalizedName;
}

From source file:com.iyonger.apm.web.controller.PerfTestController.java

private Map<String, Object> getPerfGraphData(Long id, String[] dataTypes, boolean onlyTotal, int imgWidth) {
    final PerfTest test = perfTestService.getOne(id);
    int interval = perfTestService.getReportDataInterval(id, dataTypes[0], imgWidth);
    Map<String, Object> resultMap = Maps.newHashMap();
    for (String each : dataTypes) {
        Pair<ArrayList<String>, ArrayList<String>> tpsResult = perfTestService.getReportData(id, each,
                onlyTotal, interval);//from   w  w  w .j  a v a 2 s .  co  m
        Map<String, Object> dataMap = Maps.newHashMap();
        dataMap.put("labels", tpsResult.getFirst());
        dataMap.put("data", tpsResult.getSecond());
        resultMap.put(StringUtils.replaceChars(each, "()", ""), dataMap);
    }
    resultMap.put(PARAM_TEST_CHART_INTERVAL, interval * test.getSamplingInterval());
    return resultMap;
}