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:edu.ku.brc.specify.toycode.mexconabio.MexConvToSQL.java

/**
 * /*w ww.j a v a 2  s  . c  o  m*/
 */
public void convert(final String databaseName, final String tableName, final String srcFileName,
        final String xmlFileName) {
    String[] months = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", };
    HashMap<String, Integer> monthHash = new HashMap<String, Integer>();
    for (String mn : months) {
        monthHash.put(mn, monthHash.size() + 1);
    }

    Connection conn = null;
    Statement stmt = null;
    try {
        conn = DriverManager.getConnection(
                "jdbc:mysql://localhost/" + databaseName + "?characterEncoding=UTF-8&autoReconnect=true",
                "root", "root");
        stmt = conn.createStatement();

        FMPCreateTable fmpInfo = new FMPCreateTable(tableName, null, true);
        fmpInfo.process(xmlFileName);

        boolean doCreateTable = true;
        if (doCreateTable) {
            processFieldSizes(fmpInfo, srcFileName);

            PrintWriter pw = new PrintWriter(new File("fields.txt"));
            int i = 0;
            for (FieldDef fd : fmpInfo.getFields()) {
                pw.println(i + " " + fd.getName() + "\t" + fd.getType() + "\t" + fd.isDouble());
                i++;
            }
            pw.close();

            BasicSQLUtils.update(conn, fmpInfo.dropTableStr());

            String sqlCreateTable = fmpInfo.createTableStr();

            BasicSQLUtils.update(conn, sqlCreateTable);

            System.out.println(sqlCreateTable);
        }

        String prepSQL = fmpInfo.getPrepareStmtStr(true, true);
        System.out.println(prepSQL);
        pStmt = conn.prepareStatement(prepSQL);

        Vector<FieldDef> fieldDefs = fmpInfo.getFields();

        int rowCnt = 0;
        BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(srcFileName)));
        String str = in.readLine();
        str = in.readLine();
        while (str != null) {
            String line = str;
            char sep = '`';
            String sepStr = "";
            for (char c : seps) {
                if (line.indexOf(c) == -1) {
                    sepStr += c;
                    sep = c;
                    break;
                }
            }
            str = StringUtils.replace(str.substring(1, str.length() - 1), "\",\"", sepStr);
            Vector<String> fields = split(str, sep);

            SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");

            int col = 1;
            int inx = 0;
            for (String fld : fields) {
                String value = fld.trim();
                FieldDef fd = fieldDefs.get(inx);

                switch (fd.getType()) {
                case eText:
                case eMemo: {
                    if (value.length() > 0) {
                        //value = FMPCreateTable.convertFromUTF8(value);
                        if (value.length() <= fd.getMaxSize()) {
                            pStmt.setString(col, value);
                        } else {
                            System.err.println(String.format("The data for `%s` max(%d) is too big %d",
                                    fd.getName(), fd.getMaxSize(), value.length()));
                            pStmt.setString(col, null);
                        }
                    } else {
                        pStmt.setString(col, null);
                    }
                }
                    break;

                case eNumber: {
                    if (StringUtils.isNotEmpty(value)) {
                        String origValue = value;
                        String val = value.charAt(0) == '' ? value.substring(1) : value;
                        val = val.charAt(0) == '-' ? val.substring(1) : val;
                        val = val.indexOf('.') > -1 ? StringUtils.replace(val, ".", "") : val;
                        val = val.indexOf('') > -1 ? StringUtils.replace(val, "", "") : val;

                        if (StringUtils.isNumericSpace(val)) {
                            if (fd.isDouble()) {
                                pStmt.setDouble(col, Double.parseDouble(val));
                            } else {
                                pStmt.setInt(col, Integer.parseInt(val));
                            }
                        } else if (val.startsWith("ca. ")) {
                            pStmt.setInt(col, Integer.parseInt(val.substring(4)));
                        } else if (val.startsWith("ca ")) {
                            pStmt.setInt(col, Integer.parseInt(val.substring(3)));
                        } else {
                            System.err.println(col + " Bad Number val[" + val + "] origValue[" + origValue
                                    + "] " + fieldDefs.get(col - 1).getName());
                            pStmt.setObject(col, null);
                        }
                    } else {
                        pStmt.setDate(col, null);
                    }
                }
                    break;

                case eTime: {
                    Time time = null;
                    try {
                        time = Time.valueOf(value);
                    } catch (Exception ex) {
                    }
                    pStmt.setTime(col, time);
                }
                    break;

                case eDate: {
                    String origValue = value;
                    try {
                        if (StringUtils.isNotEmpty(value) && !value.equals("?") && !value.equals("-")) {
                            int len = value.length();
                            if (len == 8 && value.charAt(1) == '-' && value.charAt(3) == '-') // 0-9-1886
                            {
                                String dayStr = value.substring(0, 1);
                                String monStr = value.substring(2, 3);
                                if (StringUtils.isNumeric(dayStr) && StringUtils.isNumeric(monStr)) {
                                    String year = value.substring(4);
                                    int day = Integer.parseInt(dayStr);
                                    int mon = Integer.parseInt(monStr);
                                    if (day == 0)
                                        day = 1;
                                    if (mon == 0)
                                        mon = 1;

                                    value = String.format("%02d-%02d-%s", day, mon, year);
                                } else {
                                    value = StringUtils.replaceChars(value, '.', ' ');
                                    String[] toks = StringUtils.split(value, ' ');
                                    if (toks.length == 3) {
                                        String dyStr = toks[0];
                                        String mnStr = toks[1];
                                        String yrStr = toks[2];
                                        if (StringUtils.isNumeric(mnStr) && StringUtils.isNumeric(dyStr)
                                                && StringUtils.isNumeric(yrStr)) {
                                            int day = Integer.parseInt(dyStr);
                                            int mon = Integer.parseInt(mnStr);
                                            int year = Integer.parseInt(yrStr);
                                            if (day == 0)
                                                day = 1;
                                            if (mon == 0)
                                                mon = 1;

                                            value = String.format("%02d-%02d-%04d", day, mon, year);
                                        } else {
                                            System.err.println(
                                                    col + " Bad Date#[" + value + "]  [" + origValue + "]\n");
                                        }
                                    } else {
                                        System.err.println(
                                                col + " Bad Date#[" + value + "]  [" + origValue + "]\n");
                                    }
                                }

                            } else if (len == 8 && (value.charAt(3) == '-' || value.charAt(3) == ' ')) // Apr-1886
                            {
                                String monStr = value.substring(0, 3);
                                Integer month = monthHash.get(monStr);
                                String year = value.substring(4);
                                if (month != null && StringUtils.isNumeric(year)) {
                                    value = String.format("01-%02d-%s", month, year);
                                } else {
                                    value = StringUtils.replaceChars(value, '.', ' ');
                                    String[] toks = StringUtils.split(value, ' ');
                                    if (toks.length == 3) {
                                        String dyStr = toks[0];
                                        String mnStr = toks[1];
                                        String yrStr = toks[2];
                                        if (StringUtils.isNumeric(mnStr) && StringUtils.isNumeric(dyStr)
                                                && StringUtils.isNumeric(yrStr)) {
                                            int day = Integer.parseInt(dyStr);
                                            int mon = Integer.parseInt(mnStr);
                                            int yr = Integer.parseInt(yrStr);
                                            if (day == 0)
                                                day = 1;
                                            if (mon == 0)
                                                mon = 1;

                                            value = String.format("%02d-%02d-%04d", day, mon, yr);
                                        } else {
                                            System.err.println(
                                                    col + " Bad Date#[" + value + "]  [" + origValue + "]\n");
                                        }
                                    } else {
                                        System.err.println(
                                                col + " Bad Date#[" + value + "]  [" + origValue + "]\n");
                                    }
                                }

                            } else if ((len == 11 && value.charAt(2) == '-' && value.charAt(6) == '-') || // 10-May-1898
                                    (len == 10 && value.charAt(1) == '-' && value.charAt(5) == '-')) //  7-May-1898
                            {
                                boolean do11 = len == 11;
                                String dayStr = value.substring(0, do11 ? 2 : 1);
                                String monStr = value.substring(do11 ? 3 : 2, do11 ? 6 : 5);

                                Integer month = monthHash.get(monStr);
                                String year = value.substring(do11 ? 7 : 6);
                                if (month != null && StringUtils.isNumeric(dayStr)
                                        && StringUtils.isNumeric(year)) {
                                    int day = Integer.parseInt(dayStr);
                                    if (day == 0)
                                        day = 1;
                                    value = String.format("%02d-%02d-%s", day, month, year);

                                } else {
                                    System.err
                                            .println(col + " Bad Date^[" + value + "]  [" + origValue + "]\n");
                                }
                            } else if (len == 4) {
                                if (StringUtils.isNumeric(value)) {
                                    value = "01-01-" + value;

                                } else if (value.equalsIgnoreCase("s.d.") || value.equalsIgnoreCase("n.d.")
                                        || value.equalsIgnoreCase("s.n.")) {
                                    value = null;
                                }
                            } else if (StringUtils.contains(value, "/")) {
                                value = StringUtils.replace(value, "/", "-");

                            } else if (StringUtils.contains(value, " ")) {
                                value = StringUtils.replace(value, " ", "-");
                            }
                            pStmt.setDate(col,
                                    StringUtils.isNotEmpty(value)
                                            ? new java.sql.Date(sdf.parse(value).getTime())
                                            : null);
                        } else {
                            pStmt.setDate(col, null);
                        }
                    } catch (Exception ex) {
                        System.err.println(col + " Bad Date[" + value + "]  [" + origValue + "]\n" + str);
                        pStmt.setDate(col, null);
                    }
                }
                    break;

                default: {
                    System.err.println("Col: " + col + "  Error - " + fd.getType());
                }
                }
                inx++;
                col++;
            }
            pStmt.execute();
            str = in.readLine();
            rowCnt++;
            if (rowCnt % 1000 == 0) {
                System.out.println(rowCnt);
            }
        }
        in.close();

    } catch (Exception ex) {
        ex.printStackTrace();

    } finally {
        try {
            stmt.close();
            conn.close();
            pStmt.close();

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

From source file:de.tudarmstadt.ukp.clarin.webanno.project.page.ProjectLayersPanel.java

private HelpDataModel getHelpContent() {
    HelpDataModel helpContent = new HelpDataModel();
    BeanWrapper wrapper = new BeanWrapperImpl(helpContent);
    // get annotation preference from file system
    try {/*from w ww  .  j av a 2  s. c  o m*/
        for (Entry<Object, Object> entry : repository.loadHelpContents().entrySet()) {
            String property = entry.getKey().toString();
            if (wrapper.isWritableProperty(property)) {

                if (HelpDataModel.class.getDeclaredField(property)
                        .getGenericType() instanceof ParameterizedType) {
                    List<String> value = Arrays
                            .asList(StringUtils.replaceChars(entry.getValue().toString(), "[]", "").split(","));
                    if (!value.get(0).equals("")) {
                        wrapper.setPropertyValue(property, value);
                    }
                } else {
                    wrapper.setPropertyValue(property, entry.getValue());
                }
            }
        }
    }
    // no preference found
    catch (Exception e) {
    }
    return helpContent;
}

From source file:de.tudarmstadt.ukp.clarin.webanno.project.page.ProjectLayersPanel.java

private String getHelpContent(String aField) {
    String helpFieldContent = "";
    HelpDataModel helpContent = new HelpDataModel();
    BeanWrapper wrapper = new BeanWrapperImpl(helpContent);
    // get annotation preference from file system
    try {//from   w  w w.j a  va 2s . c  om
        for (Entry<Object, Object> entry : repository.loadHelpContents().entrySet()) {
            String property = entry.getKey().toString();
            if (wrapper.isWritableProperty(property)) {
                if (HelpDataModel.class.getDeclaredField(property)
                        .getGenericType() instanceof ParameterizedType) {
                    List<String> value = Arrays
                            .asList(StringUtils.replaceChars(entry.getValue().toString(), "[]", "").split(","));
                    if (!value.get(0).equals("")) {
                        wrapper.setPropertyValue(property, value);
                    }
                } else {
                    if (property.equals(aField)) {
                        helpFieldContent = entry.getValue().toString();
                    }
                    wrapper.setPropertyValue(property, entry.getValue());
                }
            }
        }
    }
    // no preference found
    catch (Exception e) {
    }
    return helpFieldContent;
}

From source file:no.sesat.search.mode.command.NewsAggregatorSearchCommand.java

private String formatToConvention(String replaceString) {
    String newString = StringUtils.replaceChars(replaceString.toLowerCase(), "\u00E6", "ae");
    newString = StringUtils.replaceChars(newString, '\u00F8', 'o');
    newString = StringUtils.replaceChars(newString, '\u00E5', 'a');
    newString = StringUtils.replaceChars(newString, "\u00E4", "ae");
    newString = StringUtils.replaceChars(newString, '\u00F6', 'o');
    newString = StringUtils.replaceChars(newString, ' ', '_');
    return newString;
}

From source file:org.andromda.cartridges.webservice.metafacades.WebServicePackageLogicImpl.java

/**
 * @return findTaggedValue(WebServiceGlobals.XML_XMLNS) or WebServiceUtils.getPkgAbbr(this)
 * @see org.andromda.cartridges.webservice.WebServiceUtils#getPkgAbbr(PackageFacade)
 *//*from  w  ww  .j  ava2s.  com*/
protected String handleGetSchemaLocation() {
    String packageNamespace = this.getNamespace().substring(7) + ".xsd";
    packageNamespace = StringUtils.replaceChars(packageNamespace, "/\\", ".");
    packageNamespace = "xsd/" + StringUtils.replace(packageNamespace, "..", ".");
    return packageNamespace;
}

From source file:org.apache.archiva.common.utils.PathUtil.java

public static String toUrl(File file) {
    try {/*from  w w w  . ja v  a2s.c  om*/
        return file.toURI().toURL().toExternalForm();
    } catch (MalformedURLException e) {
        String pathCorrected = StringUtils.replaceChars(file.getAbsolutePath(), '\\', '/');
        if (pathCorrected.startsWith("file:/")) {
            return pathCorrected;
        }

        return "file://" + pathCorrected;
    }
}

From source file:org.apache.archiva.common.utils.PathUtilTest.java

public void testToUrlRelativePath() {
    File workingDir = new File(".");

    String workingDirname = StringUtils.replaceChars(workingDir.getAbsolutePath(), '\\', '/');

    // Some JVM's retain the "." at the end of the path.  Drop it.
    if (workingDirname.endsWith("/.")) {
        workingDirname = workingDirname.substring(0, workingDirname.length() - 2);
    }//from  w ww. j  av  a2 s.c o m

    if (!workingDirname.startsWith("/")) {
        workingDirname = "/" + workingDirname;
    }

    String path = "path/to/resource.xml";
    String expectedPath = "file:" + workingDirname + "/" + path;

    assertEquals(expectedPath, PathUtil.toUrl(path));
}

From source file:org.apache.archiva.common.utils.PathUtilTest.java

public void testToUrlUsingFileUrl() {
    File workingDir = new File(".");

    String workingDirname = StringUtils.replaceChars(workingDir.getAbsolutePath(), '\\', '/');

    // Some JVM's retain the "." at the end of the path.  Drop it.
    if (workingDirname.endsWith("/.")) {
        workingDirname = workingDirname.substring(0, workingDirname.length() - 2);
    }/*w  w  w .  ja va2 s .co m*/

    if (!workingDirname.startsWith("/")) {
        workingDirname = "/" + workingDirname;
    }

    String path = "path/to/resource.xml";
    String expectedPath = "file:" + workingDirname + "/" + path;

    assertEquals(expectedPath, PathUtil.toUrl(expectedPath));
}

From source file:org.apache.archiva.indexer.maven.search.MavenRepositorySearch.java

/**
 * calculate baseUrl without the context and base Archiva Url
 *
 * @param artifactInfo/*from   www.  jav a 2s  .  c  o  m*/
 * @return
 */
protected String getBaseUrl(ArtifactInfo artifactInfo, List<String> selectedRepos)
        throws RepositoryAdminException {
    StringBuilder sb = new StringBuilder();
    if (StringUtils.startsWith(artifactInfo.getContext(), "remote-")) {
        // it's a remote index result we search a managed which proxying this remote and on which
        // current user has read karma
        String managedRepoId = getManagedRepoId(
                StringUtils.substringAfter(artifactInfo.getContext(), "remote-"), selectedRepos);
        if (managedRepoId != null) {
            sb.append('/').append(managedRepoId);
            artifactInfo.setContext(managedRepoId);
        }
    } else {
        sb.append('/').append(artifactInfo.getContext());
    }

    sb.append('/').append(StringUtils.replaceChars(artifactInfo.getGroupId(), '.', '/'));
    sb.append('/').append(artifactInfo.getArtifactId());
    sb.append('/').append(artifactInfo.getVersion());
    sb.append('/').append(artifactInfo.getArtifactId());
    sb.append('-').append(artifactInfo.getVersion());
    if (StringUtils.isNotBlank(artifactInfo.getClassifier())) {
        sb.append('-').append(artifactInfo.getClassifier());
    }
    // maven-plugin packaging is a jar
    if (StringUtils.equals("maven-plugin", artifactInfo.getPackaging())) {
        sb.append("jar");
    } else {
        sb.append('.').append(artifactInfo.getPackaging());
    }

    return sb.toString();
}

From source file:org.apache.archiva.indexer.search.MavenRepositorySearch.java

/**
 * calculate baseUrl without the context and base Archiva Url
 *
 * @param artifactInfo/*from  ww w  .  j av  a  2s .  c  om*/
 * @return
 */
protected String getBaseUrl(ArtifactInfo artifactInfo, List<String> selectedRepos)
        throws RepositoryAdminException {
    StringBuilder sb = new StringBuilder();
    if (StringUtils.startsWith(artifactInfo.context, "remote-")) {
        // it's a remote index result we search a managed which proxying this remote and on which
        // current user has read karma
        String managedRepoId = getManagedRepoId(StringUtils.substringAfter(artifactInfo.context, "remote-"),
                selectedRepos);
        if (managedRepoId != null) {
            sb.append('/').append(managedRepoId);
            artifactInfo.context = managedRepoId;
        }
    } else {
        sb.append('/').append(artifactInfo.context);
    }

    sb.append('/').append(StringUtils.replaceChars(artifactInfo.groupId, '.', '/'));
    sb.append('/').append(artifactInfo.artifactId);
    sb.append('/').append(artifactInfo.version);
    sb.append('/').append(artifactInfo.artifactId);
    sb.append('-').append(artifactInfo.version);
    if (StringUtils.isNotBlank(artifactInfo.classifier)) {
        sb.append('-').append(artifactInfo.classifier);
    }
    // maven-plugin packaging is a jar
    if (StringUtils.equals("maven-plugin", artifactInfo.packaging)) {
        sb.append("jar");
    } else {
        sb.append('.').append(artifactInfo.packaging);
    }

    return sb.toString();
}