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

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

Introduction

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

Prototype

public static String replace(String text, String searchString, String replacement) 

Source Link

Document

Replaces all occurrences of a String within another String.

Usage

From source file:edu.ku.brc.specify.tasks.subpane.security.UserAgentVSQBldr.java

/**
 * @param dataMap//from   w  w w . j  a  v a2  s . com
 * @param fieldNames
 * @param sqlTemplate
 * @return
 */
protected String buildSearchString(final Map<String, Object> dataMap, final List<String> fieldNames,
        final String sqlTemplate) {
    StringBuilder orderBy = new StringBuilder();
    StringBuilder criteria = new StringBuilder("agent.SpecifyUserID IS NULL AND (");
    int criCnt = 0;
    for (String colName : dataMap.keySet()) {
        String data = (String) dataMap.get(colName);
        if (ESTermParser.getInstance().parse(data.toLowerCase(), true)) {
            if (StringUtils.isNotEmpty(data)) {
                List<SearchTermField> fields = ESTermParser.getInstance().getFields();
                SearchTermField firstTerm = fields.get(0);

                if (criCnt > 0)
                    criteria.append(" OR ");

                String clause = ESTermParser.getInstance().createWhereClause(firstTerm, null, colName);
                criteria.append(clause);

                if (criCnt > 0)
                    orderBy.append(',');

                orderBy.append(colName);

                criCnt++;
            }
        }
    }

    criteria.append(")");

    String sqlStr = null;

    StringBuffer sb = new StringBuffer();
    sb.append(criteria);

    int inxGrpBy = sqlTemplate.toLowerCase().indexOf("group by");
    if (inxGrpBy == -1) {
        sb.append(" ORDER BY ");
        sb.append(orderBy);
        sqlStr = StringUtils.replace(sqlTemplate, "(%s)", sb.toString());
    } else {
        sqlStr = StringUtils.replace(sqlTemplate, "(%s)", sb.toString());
        sqlStr += " ORDER BY " + orderBy;
    }

    log.debug(sqlStr);

    return sqlStr;
}

From source file:info.magnolia.module.workflow.jcr.JCRWorkItemAPI.java

/**
 * convert the name to valid path/*from  ww w . j  av a 2s. c  om*/
 * @param id
 */
public final String convertPath(String id) {
    return StringUtils.replace(StringUtils.replace(id, WorkflowConstants.BAR, StringUtils.EMPTY),
            WorkflowConstants.COLON, WorkflowConstants.DOT);
}

From source file:de.tudarmstadt.ukp.csniper.webapp.search.tgrep.TgrepQuery.java

private List<EvaluationItem> parseOutput(List<String> aOutput) {
    List<EvaluationItem> items = new ArrayList<EvaluationItem>();

    if (aOutput.size() % LINES_PER_MATCH > 0) {
        throw new DataAccessResourceFailureException("Tgrep2 produced [" + aOutput.size()
                + "] output lines, but should have produced a multiple of [" + LINES_PER_MATCH + "].");
    } else {/*from   w w  w  . j a v a  2s.co  m*/
        String[] comment;
        String text;
        int tokenBeginIndex;
        int tokenEndIndex;

        for (Iterator<String> it = aOutput.iterator(); it.hasNext();) {
            // comment - split into documentId, beginOffset, endOffset
            comment = it.next().substring(2).split(TgrepEngine.COMMENT_SEPARATOR);
            if (comment.length < 3) {
                throw new DataAccessResourceFailureException("The corpus contains a malformed comment line ["
                        + StringUtils.join(comment, " ,") + "].");
            }
            String documentId = comment[META_DOCUMENT_ID];
            int beginOffset = Integer.parseInt(comment[META_BEGIN_OFFSET]);
            int endOffset = Integer.parseInt(comment[META_END_OFFSET]);

            // text string - trim and replace bracket placeholders
            text = it.next().trim();
            text = StringUtils.replace(text, LEFT_BRACKET, "(");
            text = StringUtils.replace(text, RIGHT_BRACKET, ")");

            // token index of first token in match (tgrep indices are 1-based, make them
            // 0-based)
            tokenBeginIndex = Integer.parseInt(it.next()) - 1;

            // token index of last token in match (tgrep indices are 1-based, make them 0-based)
            tokenEndIndex = Integer.parseInt(it.next()) - 1;

            // set corpus position to -1; this is cqp specific and we don't use it atm
            EvaluationItem item = new EvaluationItem(corpus, documentId, type, beginOffset, endOffset, text);

            // text-based (i.e. sentence-based) offsets (+1 to skip the whitespace itself)
            int matchBegin = StringUtils.ordinalIndexOf(text, " ", tokenBeginIndex) + 1;
            int matchEnd = StringUtils.ordinalIndexOf(text, " ", tokenEndIndex + 1);

            item.setMatchOnItemText(matchBegin, matchEnd);
            item.setMatchOnOriginalTextViaTokenIndicesAndLookGoodWhileDoingSo(tokenBeginIndex, tokenEndIndex);
            items.add(item);
        }
    }
    return items;
}

From source file:com.bluexml.xforms.controller.mapping.MappingToolFormsToAlfresco.java

/**
 * Returns a JSON string reflecting the content of the GenericClass object built from the
 * instance. The example used as a specification is:
 * <p>//ww  w .j av a  2s.c o m
 * 
 * <pre>
 * {type:"{http://www.bluexml.com/model/content/com/1.0}bluexml_demo_rh_Personne",
 *  properties:{"{http://www.bluexml.com/model/content/com/1.0}bluexml_demo_rh_Personne_nom":"abad", 
 *              "{http://www.bluexml.com/model/content/com/1.0}bluexml_demo_rh_Personne_prenom":"david"
 *             }
 * }
 * 
 * <pre>
 * @param transaction
 * @param formName
 * @param shortPropertyNames
 * @param instance
 * @return
 * @throws ServletException
 */
public String transformsToJSON(AlfrescoTransaction transaction, String formName, Node formNode,
        boolean shortPropertyNames, Map<String, String> initParams) throws ServletException {

    Element root = getRootElement(formName, formNode);

    FormType formType = getFormType(formName);
    GenericClass alfClass = persistFormElement(transaction, formName, root, initParams, false);

    StringBuffer buf = new StringBuffer(256);
    String propName = "";
    String typeName = "";

    ClassType classType = formType.getRealClass();
    String packageName = classType.getPackage();
    String rootPackage = packageName;
    int pos = packageName.indexOf('.');
    if (pos != -1) {
        rootPackage = packageName.substring(0, pos);
    }
    String namespace = MsgId.INT_NAMESPACE_BLUEXML_CLASS + "/" + rootPackage + "/1.0";

    buf.append("{"); // open JSON string

    // the title
    buf.append("type:\"");
    typeName = "{" + namespace + "}" + classType.getAlfrescoName();
    buf.append(typeName);
    buf.append("\"");

    // the properties
    buf.append(",properties:{");
    boolean first = true;
    for (GenericAttribute attribute : alfClass.getAttributes().getAttribute()) {
        if (first == false) {
            buf.append(",");
        }
        first = false;
        propName = "{";
        propName += namespace;
        propName += "}";
        propName += attribute.getQualifiedName();
        if (shortPropertyNames) {
            propName = StringUtils.replace(propName, typeName, "");
        }
        buf.append("\"");
        buf.append(propName);
        buf.append("\":\"");
        buf.append(attribute.getValue().get(0).getValue());
        buf.append("\"");
    }
    buf.append("}"); // close properties

    buf.append("}"); // close the JSON string

    return buf.toString();
}

From source file:com.google.gdt.eclipse.designer.actions.AbstractModuleAction.java

/**
 * Shows the {@link Throwable} to user./*www. j a v a  2  s  . co  m*/
 */
public static void showException(final Throwable exception) {
    // log
    DesignerPlugin.log(exception);
    // show
    {
        final Throwable rootCause = DesignerExceptionUtils.getDesignerCause(exception);
        final Status status = new Status(IStatus.ERROR, DesignerPlugin.getDefault().toString(), IStatus.ERROR,
                "Parse error or internal Designer error.", rootCause);
        ErrorDialog dialog = new ErrorDialog(DesignerPlugin.getShell(), "Exception happened",
                "Designer error occurred.\nSelect Details>> for more information.\nSee the Error Log for more information.",
                status, IStatus.ERROR) {
            private Clipboard clipboard;

            @Override
            protected org.eclipse.swt.widgets.List createDropDownList(Composite parent) {
                final org.eclipse.swt.widgets.List list = super.createDropDownList(parent);
                list.removeAll();
                // populate list using custom PrintWriter
                list.add("Plug-in Provider: Google");
                list.add("Plug-in Name: " + BrandingUtils.getBranding().getProductName());
                list.add("Plug-in ID: org.eclipse");
                //list.add("Plug-in Version: " + String.valueOf(product.getVersion()));
                list.add("");
                final PrintWriter printWriter = new PrintWriter(new Writer() {
                    @Override
                    public void write(char[] cbuf, int off, int len) throws IOException {
                        if (len != 2 && !(cbuf[0] == '\r' || cbuf[0] == '\n')) {
                            list.add(StringUtils.replace(new String(cbuf, off, len), "\t", "    "));
                        }
                    }

                    @Override
                    public void flush() throws IOException {
                    }

                    @Override
                    public void close() throws IOException {
                    }
                });
                if (rootCause != null) {
                    rootCause.printStackTrace(printWriter);
                    list.add("");
                    list.add("Full stack trace (to see full context):");
                }
                exception.printStackTrace(printWriter);
                // print config
                list.add("");
                // install own context menu
                Menu menu = list.getMenu();
                menu.dispose();
                Menu copyMenu = new Menu(list);
                MenuItem copyItem = new MenuItem(copyMenu, SWT.NONE);
                copyItem.setText(JFaceResources.getString("copy")); //$NON-NLS-1$
                copyItem.addSelectionListener(new SelectionListener() {
                    public void widgetSelected(SelectionEvent e) {
                        copyList(list);
                    }

                    public void widgetDefaultSelected(SelectionEvent e) {
                        copyList(list);
                    }
                });
                list.setMenu(copyMenu);
                return list;
            }

            private void copyList(org.eclipse.swt.widgets.List list) {
                if (clipboard != null) {
                    clipboard.dispose();
                }
                StringBuffer statusBuffer = new StringBuffer();
                for (int i = 0; i < list.getItemCount(); ++i) {
                    statusBuffer.append(list.getItem(i));
                    statusBuffer.append("\r\n");
                }
                clipboard = new Clipboard(list.getDisplay());
                clipboard.setContents(new Object[] { statusBuffer.toString() },
                        new Transfer[] { TextTransfer.getInstance() });
            }

            @Override
            public boolean close() {
                if (clipboard != null) {
                    clipboard.dispose();
                }
                return super.close();
            }
        };
        dialog.open();
    }
}

From source file:com.google.gdt.eclipse.designer.core.model.module.ModuleModelTest.java

/**
 * Parse GWT module with "entry-point" element.
 *//*from ww  w.  java2  s  .  c o  m*/
public void test_parseEntryPoint() throws Exception {
    parse(new String[] { "<!-- -------------------------------- -->", "<module>",
            "  <entry-point class='some.class'/>", "</module>" });
    assertThat(m_module.getChildren()).hasSize(1);
    // prepare single "<entry-point>" element
    EntryPointElement entryPointElement;
    {
        List<EntryPointElement> entryPointElements = m_module.getEntryPointElements();
        assertThat(entryPointElements).hasSize(1);
        entryPointElement = entryPointElements.get(0);
    }
    // current "class" value
    assertEquals("some.class", entryPointElement.getClassName());
    // set new "class" value
    {
        entryPointElement.setClassName("new.class");
        assertUpdatedModuleFile(StringUtils.replace(m_moduleContent, "some.class", "new.class"));
    }
    // toString()
    assertEquals(getSourceDQ("<module>", "  <entry-point class='new.class'/>", "</module>"),
            m_module.toString());
}

From source file:com.alibaba.otter.manager.web.common.NumberFormatUtil.java

public String getHtmlOriginalContent(String originalContent) {
    originalContent = StringUtils.replace(originalContent, "\n", "<br>");
    originalContent = StringUtils.replace(originalContent, "\t", "&nbsp;&nbsp;&nbsp;&nbsp;");
    return StringEscapeUtils.escapeJavaScript(originalContent);
}

From source file:edu.ku.brc.specify.toycode.mexconabio.MexConvToSQLNew.java

public void convert(final String tableName, final String fileName) {
    String str = "";
    int fldLen = 0;
    int inx = 0;//from   w ww .j  a  v a2 s  .  c o m

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

        int[] fieldLengths = null;

        BasicSQLUtils.deleteAllRecordsFromTable(conn, tableName, SERVERTYPE.MySQL);
        Vector<Integer> types = new Vector<Integer>();
        Vector<String> names = new Vector<String>();

        String selectStr = null;
        String prepareStr = null;
        try {
            prepareStr = FileUtils.readFileToString(new File("prepare_stmt.txt"));
            selectStr = FileUtils.readFileToString(new File("select.txt"));

        } catch (IOException e) {
            e.printStackTrace();
        }

        int idInx = selectStr.indexOf("ID,");
        if (idInx == 0) {
            selectStr = selectStr.substring(3);
        }

        File file = new File("/Users/rods/Documents/" + fileName);
        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
        //SimpleDateFormat stf = new SimpleDateFormat("k:mm:ss");

        int rowCnt = 0;
        try {
            System.out.println(prepareStr);

            PreparedStatement pStmt = conn.prepareStatement(prepareStr);
            BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF8"));
            str = in.readLine();

            String[] fieldNames = StringUtils.split(str, ",");
            //String[] fieldNamesDB = StringUtils.split(selectStr, ",");

            String sql = "SELECT " + selectStr + " FROM " + tableName;
            System.out.println(sql);

            ResultSet rs = stmt.executeQuery(sql);
            ResultSetMetaData rsmd = rs.getMetaData();

            fieldLengths = new int[rsmd.getColumnCount()];
            for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                fieldLengths[i - 1] = rsmd.getPrecision(i);
                types.add(rsmd.getColumnType(i));
                names.add(rsmd.getColumnName(i));
                System.out.println((i > 1 ? fieldNames[i - 2] : "ID") + " / " + rsmd.getColumnName(i) + " - "
                        + rsmd.getPrecision(i));
            }

            int numCols = rsmd.getColumnCount();
            rs.close();

            System.out.println("Number of Fields: " + numCols);

            str = in.readLine();
            while (str != null) {
                //System.err.println(str);

                str = StringUtils.replace(str.substring(1, str.length() - 1), "\",\"", "|");

                Vector<String> fields = split(str);
                if (fields.size() != numCols) {
                    System.out.println("numCols: " + numCols + " != " + fields.size() + "fields.size()");
                    continue;
                }

                int col = 1;
                inx = 0;
                for (String fld : fields) {
                    String field = fld.trim();
                    //if (field.length() > 1)
                    //{
                    //    field = field.substring(1, field.length()-1);
                    //}
                    //if (inx > 204) break;

                    fldLen = field.length();

                    pStmt.setObject(col, null);

                    switch (types.get(inx)) {
                    case java.sql.Types.LONGVARCHAR:
                    case java.sql.Types.VARCHAR:
                    case java.sql.Types.LONGNVARCHAR: {
                        if (field.length() > 0) {
                            if (field.length() <= fieldLengths[inx]) {
                                pStmt.setString(col, field);
                            } else {
                                System.err.println(String.format("The data for `%s` (%d) is too big %d f[%s]",
                                        names.get(inx), fieldLengths[inx], field.length(), field));
                                pStmt.setString(col, null);
                            }
                        } else {
                            pStmt.setString(col, null);
                        }
                    }
                        break;

                    case java.sql.Types.DOUBLE:
                    case java.sql.Types.FLOAT: {
                        if (StringUtils.isNotEmpty(field)) {
                            if (StringUtils.isNumeric(field)) {
                                pStmt.setDouble(col, field.length() > 0 ? Double.parseDouble(field) : null);
                            } else {
                                System.err.println(col + " Bad Number[" + field + "] ");
                                pStmt.setDate(col, null);
                            }
                        } else {
                            pStmt.setDate(col, null);
                        }
                    }
                        break;

                    case java.sql.Types.INTEGER: {
                        if (StringUtils.isNotEmpty(field)) {
                            if (StringUtils.isNumeric(field)) {
                                pStmt.setInt(col, field.length() > 0 ? Integer.parseInt(field) : null);
                            } else {
                                System.err.println(col + " Bad Number[" + field + "] ");
                                pStmt.setDate(col, null);
                            }
                        } else {
                            pStmt.setDate(col, null);
                        }
                    }
                        break;

                    case java.sql.Types.TIME: {
                        Time time = null;
                        try {
                            time = Time.valueOf(field);
                        } catch (Exception ex) {
                        }
                        pStmt.setTime(col, time);
                    }
                        break;

                    case java.sql.Types.DATE: {
                        try {
                            if (StringUtils.isNotEmpty(field)) {
                                if (StringUtils.contains(field, "/")) {
                                    field = StringUtils.replace(field, "/", "-");
                                } else if (StringUtils.contains(field, " ")) {
                                    field = StringUtils.replace(field, " ", "-");
                                }
                                pStmt.setDate(col,
                                        field.length() > 0 ? new java.sql.Date(sdf.parse(field).getTime())
                                                : null);
                            } else {
                                pStmt.setDate(col, null);
                            }
                        } catch (Exception ex) {
                            System.err.println(col + " Bad Date[" + field + "]\n" + str);
                            pStmt.setDate(col, null);
                        }
                    }
                        break;

                    default: {
                        System.err.println("Error - " + types.get(inx));
                    }
                    }
                    inx++;
                    col++;
                }
                pStmt.execute();
                str = in.readLine();
                rowCnt++;
            }
            in.close();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();

        } catch (Exception e) {
            System.err.println("Row: " + rowCnt);
            System.err.println(str);
            System.err.println(inx + "  " + fieldLengths[inx] + " - Field Len: " + fldLen);
            e.printStackTrace();
        }

        /*BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
        while (bis.available() > 0)
        {
        int bytesRead = bis.read(bytes);
        if (bytesRead > 0)
        {
            System.arraycopy(bytes, bytesRead, buffer, bufEndInx, bytesRead);
            bufEndInx += bytesRead;
            int inx = 0;
            while (inx < bufEndInx)
            {
                if (buffer[inx] != '\n')
                {
                    String line = 
                }
                inx++;
            }
        }
        }*/

    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        try {
            stmt.close();
            conn.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

From source file:com.sfs.whichdoctor.isb.publisher.PersonIsbXmlWriter.java

/**
 * Isb envelope./*  w  w  w.  j a  v a2 s  . co  m*/
 *
 * @param payload the payload
 * @param source the source
 * @param target the target
 *
 * @return the string
 *
 * @throws IOException Signals that an I/O exception has occurred.
 */
public final String isbEnvelope(final String payload, final String source, final String target)
        throws IOException {

    String xmlPayload = "";
    if (payload != null) {
        if (payload.startsWith("<?xml ")) {
            xmlPayload = StringUtils.replace(payload, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "");
        } else {
            xmlPayload = payload;
        }
    }

    xmlwriter = new XmlWriter();

    xmlwriter.writeEntity("isb");
    xmlwriter.writeAttribute("version", "1.0");
    xmlwriter.writeAttribute("target", target);
    xmlwriter.writeAttribute("source", source);

    xmlwriter.writeXml(xmlPayload);

    xmlwriter.endEntity();

    return xmlwriter.getXml();
}

From source file:info.magnolia.link.LinkUtilTest.java

@Test
public void testUUIDToRelativeLinks() throws LinkException {
    String res = LinkUtil.convertLinksFromUUIDPattern(HTML_WITH_UUIDS,
            LinkTransformerManager.getInstance().getRelative("/parent/sub2"));
    assertEquals(StringUtils.replace(HTML_WITH_ABSOLUTE_LINK, "/parent/sub.html", "sub.html"), res);
}