Example usage for java.lang StringBuilder replace

List of usage examples for java.lang StringBuilder replace

Introduction

In this page you can find the example usage for java.lang StringBuilder replace.

Prototype

@Override
public StringBuilder replace(int start, int end, String str) 

Source Link

Usage

From source file:fr.landel.utils.scripts.ScriptsReplacer.java

private void clearUnknownSimples(final StringBuilder sb) {
    String simple;/*from   w  ww. j a v a2 s .c  om*/
    int indexValid;
    int indexDefault;

    final int startLen = this.template.getVariableOpen().length();
    final int stopLen = this.template.getVariableClose().length();

    // get first
    int index = sb.indexOf(this.template.getVariableOpen());
    int indexStop = sb.indexOf(this.template.getVariableClose(), index + startLen);

    for (; index > -1 && indexStop > -1;) {
        simple = sb.substring(index + startLen, indexStop);

        indexValid = simple.indexOf(this.template.getOperatorThen());
        indexDefault = simple.indexOf(this.template.getOperatorElse());

        if (indexValid == -1 && indexDefault == -1) {
            sb.replace(index, indexStop + stopLen, "");
        }

        // get next
        index = sb.indexOf(this.template.getVariableOpen(), index + 1);
        if (index > -1) {
            indexStop = sb.indexOf(this.template.getVariableClose(), index + startLen);
        }
    }
}

From source file:de.bps.course.nodes.vc.provider.wimba.WimbaClassroomProvider.java

private URL createRequestUrl(Map<String, String> parameters) {
    UriBuilder ubu = UriBuilder.fromUri(protocol + "://" + baseUrl).port(port).path("admin").path("api")
            .path("api.pl");

    for (String key : parameters.keySet()) {
        ubu.queryParam(key, parameters.get(key));
    }//from   w  w  w  .  j  a va  2 s .co m

    URL url = null;
    try {
        url = ubu.build().toURL();
    } catch (Exception e) {
        logWarn("Error while creating URL for Wimba Classroom request.", e);
        // try to build the URL in a naiv way below
    }
    if (url == null) {
        // error case, try the naiv way
        try {
            StringBuilder sb = new StringBuilder(protocol + "://" + baseUrl + ":" + port + "/admin/api/api.pl");
            if (!parameters.isEmpty())
                sb.append("?");
            for (String key : parameters.keySet()) {
                sb.append(key + "=" + parameters.get(key) + "&");
            }
            sb.replace(sb.length(), sb.length(), "");
            url = new URL(sb.toString());
        } catch (MalformedURLException e) {
            logError("Error while creating URL for Wimba Classroom request. Please check the configuration!",
                    e);
        }
    }

    if (isLogDebugEnabled())
        logDebug("Request: " + url);

    return url;
}

From source file:org.apache.oozie.tools.OozieDBCLI.java

private void convertClobToBlobInMysql(String sqlFile, Connection conn) throws Exception {
    System.out.println("Converting mediumtext/text columns to mediumblob for all tables");
    PrintWriter writer = new PrintWriter(new FileWriter(sqlFile, true));
    writer.println();//  w  w w  . j  av  a2s.c  om
    Statement statement = conn != null ? conn.createStatement() : null;
    for (Map.Entry<String, List<String>> tableClobColumnMap : getTableClobColumnMap().entrySet()) {
        String tableName = tableClobColumnMap.getKey();
        List<String> columnNames = tableClobColumnMap.getValue();
        StringBuilder modifyColumn = new StringBuilder();
        modifyColumn.append(" ALTER TABLE " + tableName);
        for (String column : columnNames) {
            modifyColumn.append(" MODIFY " + column + " mediumblob,");
        }
        modifyColumn.replace(modifyColumn.length() - 1, modifyColumn.length(), "");
        writer.println(modifyColumn.toString() + ";");
        if (statement != null) {
            statement.executeUpdate(modifyColumn.toString());
        }
    }
    writer.close();
    if (statement != null) {
        statement.close();
    }
    System.out.println("Done");
}

From source file:org.jivesoftware.community.util.StringUtils.java

public static StringBuilder replaceAll(StringBuilder text, String token, String repl) {
    int tokSize = token.length();
    int i = 0;//w  w  w .  j av  a 2  s .c om
    do {
        if (i == -1)
            break;
        i = text.indexOf(token, i);
        if (i != -1) {
            text.replace(i, i + tokSize, repl);
            i += repl.length();
        }
    } while (true);
    return text;
}

From source file:org.eclipse.jubula.client.ui.rcp.dialogs.AbstractEditParametersDialog.java

/**
 * Creates the {@link CellEditor}s of the given Table.
 * @param table a Table/*  w w w.  j a  v a  2s .  c o  m*/
 */
@SuppressWarnings("unchecked")
private void createTableCellEditors(final Table table) {

    final TextCellEditor paramNameTextCellEditor = new TextCellEditor(table);
    ((Text) paramNameTextCellEditor.getControl()).addVerifyListener(new VerifyListener() {

        public void verifyText(VerifyEvent e) {
            Text txt = (Text) e.widget;
            final String oldValue = txt.getText();
            StringBuilder workValue = new StringBuilder(oldValue);
            workValue.replace(e.start, e.end, e.text);
            String newValue = workValue.toString();

            e.doit = Pattern.matches(PARAM_NAME_REGEX, newValue);
        }

    });
    final Set<String> paramTypes = ComponentBuilder.getInstance().getCompSystem().getDataTypes();

    final I18nComboBoxCellEditor i18nParamTypesComboBoxEditor = new I18nComboBoxCellEditor(table,
            paramTypes.toArray(new String[paramTypes.size()]), SWT.READ_ONLY);

    getParamTableViewer()
            .setCellEditors(new CellEditor[] { paramNameTextCellEditor, i18nParamTypesComboBoxEditor });
}

From source file:org.n52.ifgicopter.spf.output.FileWriterPlugin.java

@Override
public int processSingleData(Map<String, Object> data, Long timestamp, Plugin plugin) {
    Long time;//from w w w .  java 2s . c om
    if (timestamp == null) {
        time = (Long) data.get(plugin.getTime().getProperty());
    } else {
        time = timestamp;
    }

    /*
     * check if we have to write the headings
     */
    synchronized (this) {
        if (this.firstRun) {
            StringBuilder firstLine = new StringBuilder();
            firstLine.append("time");
            firstLine.append(this.delimiter);

            List<String> allNeededOutputs = plugin.getOutputProperties();
            for (String item : allNeededOutputs) {
                this.outputFields.add(item);
                firstLine.append(item);
                firstLine.append(this.delimiter);
            }

            for (String item : data.keySet()) {
                /*
                 * if its in the output, we already have it
                 */
                if (allNeededOutputs.contains(item))
                    continue;

                this.outputFields.add(item);
                firstLine.append(item);
                firstLine.append(this.delimiter);
            }

            // firstLine = firstLine.substring(0, firstLine.length() - this.delimiter.length());
            firstLine.replace(firstLine.length() - this.delimiter.length(), firstLine.length(), "");

            firstLine.append(System.getProperty("line.separator"));

            writeToOutputs(firstLine.toString());

            this.firstRun = false;
        }
    }

    /*
     * create the new line
     */
    String str = new DateTime(time).toString() + this.delimiter;

    for (String key : this.outputFields) {
        Object value = data.get(key);

        if (key.equals(plugin.getTime().getProperty())) {
            value = new DateTime(value);
        }

        str += value + this.delimiter;
    }

    str = str.substring(0, str.length() - this.delimiter.length());
    str += System.getProperty("line.separator");

    writeToOutputs(str);

    return STATUS_RUNNING;
}

From source file:de.blizzy.documentr.search.PageFinder.java

private SearchTextSuggestion getSearchTextSuggestion(String searchText, Authentication authentication,
        IndexSearcher searcher) throws IOException, ParseException, TimeoutException {

    List<WordPosition> words = Lists.newArrayList();

    TokenStream tokenStream = null;/*from   ww w.j av  a2 s  . c om*/
    try {
        tokenStream = analyzer.tokenStream(PageIndex.ALL_TEXT_SUGGESTIONS, new StringReader(searchText));
        tokenStream.addAttribute(CharTermAttribute.class);
        tokenStream.addAttribute(OffsetAttribute.class);
        tokenStream.reset();
        while (tokenStream.incrementToken()) {
            CharTermAttribute charTerm = tokenStream.getAttribute(CharTermAttribute.class);
            String text = charTerm.toString();
            if (StringUtils.isNotBlank(text)) {
                OffsetAttribute offset = tokenStream.getAttribute(OffsetAttribute.class);
                WordPosition word = new WordPosition(text, offset.startOffset(), offset.endOffset());
                words.add(word);
            }
        }
        tokenStream.end();
    } finally {
        Util.closeQuietly(tokenStream);
    }

    Collections.reverse(words);

    StringBuilder suggestedSearchText = new StringBuilder(searchText);
    StringBuilder suggestedSearchTextHtml = new StringBuilder(searchText);
    boolean foundSuggestions = false;
    String now = String.valueOf(System.currentTimeMillis());
    String startMarker = "__SUGGESTION-" + now + "__"; //$NON-NLS-1$ //$NON-NLS-2$
    String endMarker = "__/SUGGESTION-" + now + "__"; //$NON-NLS-1$ //$NON-NLS-2$
    DirectSpellChecker spellChecker = new DirectSpellChecker();
    IndexReader reader = searcher.getIndexReader();
    for (WordPosition word : words) {
        Term term = new Term(PageIndex.ALL_TEXT_SUGGESTIONS, word.getWord());
        SuggestWord[] suggestions = spellChecker.suggestSimilar(term, 1, reader,
                SuggestMode.SUGGEST_MORE_POPULAR);
        if (suggestions.length > 0) {
            String suggestedWord = suggestions[0].string;
            int start = word.getStart();
            int end = word.getEnd();
            suggestedSearchText.replace(start, end, suggestedWord);
            suggestedSearchTextHtml.replace(start, end,
                    startMarker + StringEscapeUtils.escapeHtml4(suggestedWord) + endMarker);

            foundSuggestions = true;
        }
    }

    if (foundSuggestions) {
        String suggestion = suggestedSearchText.toString();
        SearchResult suggestionResult = findPages(suggestion, 1, authentication, searcher);
        int suggestionTotalHits = suggestionResult.getTotalHits();
        if (suggestionTotalHits > 0) {
            String html = StringEscapeUtils.escapeHtml4(suggestedSearchTextHtml.toString())
                    .replaceAll(startMarker + "(.*?)" + endMarker, "<strong><em>$1</em></strong>"); //$NON-NLS-1$ //$NON-NLS-2$
            return new SearchTextSuggestion(suggestedSearchText.toString(), html, suggestionTotalHits);
        }
    }

    return null;
}

From source file:org.chililog.server.pubsub.jsonhttp.SubscriptionWorker.java

/**
 * Process a publishing request//from ww w.  j  av a2s . co  m
 * 
 * @param request
 *            Publishing request in JSON format
 * @param response
 *            Publishing response in JSON format
 * @return true if successful; false if error
 */
public boolean process(String request, StringBuilder response) {
    String messageID = null;
    try {
        if (StringUtils.isBlank(request)) {
            throw new IllegalArgumentException("Request content is blank.");
        }

        // Parse JSON
        SubscriptionRequestAO requestAO = JsonTranslator.getInstance().fromJson(request,
                SubscriptionRequestAO.class);
        messageID = requestAO.getMessageID();

        // Authenticate
        authenticate(requestAO);

        // Subscribe using system user because sometimes a token is supplied from the workbench
        String queueAddress = RepositoryConfigBO.buildPubSubAddress(requestAO.getRepositoryName());
        String queueName = queueAddress + ".json-http-" + _channel.getId() + "." + UUID.randomUUID().toString();
        _session = MqService.getInstance().getNonTransactionalSystemClientSession();

        // Filter messages
        StringBuilder filter = new StringBuilder();
        if (!StringUtils.isBlank(requestAO.getHost())) {
            filter.append(String.format("%s = '%s'", RepositoryEntryMqMessage.HOST, requestAO.getHost()));
        }
        if (!StringUtils.isBlank(requestAO.getSource())) {
            if (filter.length() > 0) {
                filter.append(" AND ");
            }
            filter.append(String.format("%s = '%s'", RepositoryEntryMqMessage.SOURCE, requestAO.getSource()));
        }
        if (!StringUtils.isBlank(requestAO.getSeverity())) {
            if (filter.length() > 0) {
                filter.append(" AND ");
            }

            filter.append(String.format("%s IN (", RepositoryEntryMqMessage.SEVERITY));
            int sev = Integer.parseInt(requestAO.getSeverity());
            for (int i = 0; i <= sev; i++) {
                filter.append(String.format("'%s', ", i));
            }
            filter.replace(filter.length() - 1, filter.length(), ")"); // replace last comma with end )
        }

        if (filter.length() == 0) {
            _session.createTemporaryQueue(queueAddress, queueName);
        } else {
            _logger.debug("Subscription filter %s", filter);
            _session.createTemporaryQueue(queueAddress, queueName, filter.toString());
        }

        _consumer = _session.createConsumer(queueName);

        MqMessageHandler handler = new MqMessageHandler(_channel, messageID);
        _consumer.setMessageHandler(handler);

        _session.start();

        // Prepare response
        SubscriptionResponseAO responseAO = new SubscriptionResponseAO(messageID);
        JsonTranslator.getInstance().toJson(responseAO, response);

        // Finish
        return true;
    } catch (Exception ex) {
        _logger.error(ex, "Error processing message: %s", request);

        SubscriptionResponseAO responseAO = new SubscriptionResponseAO(messageID, ex);
        JsonTranslator.getInstance().toJson(responseAO, response);
        return false;
    }
}

From source file:org.wso2.carbon.governance.registry.extensions.executors.ServiceVersionExecutor.java

private void updateWSDLRelativePaths(String targetEnvironment, String currentEnvironment,
        StringBuilder resourceContent, Map.Entry<String, String> newPathMappingsEntry) {
    try {/*from  ww w  .j av  a  2s .c  om*/
        OMElement contentElement = AXIOMUtil.stringToOM(resourceContent.toString());
        updateRelativePath(targetEnvironment, currentEnvironment, contentElement, newPathMappingsEntry);
        List SchemaNodes = evaluateXpath(contentElement, XSD_XPATH_STRING);

        for (Object schemaNode : SchemaNodes) {
            OMElement schema = (OMElement) schemaNode;
            updateRelativePath(targetEnvironment, currentEnvironment, schema, newPathMappingsEntry);
        }
        resourceContent.replace(0, resourceContent.length(), contentElement.toString());
    } catch (XMLStreamException e) {
        log.error(e);
    }
}

From source file:cn.com.ebmp.freesql.io.ResolverUtil.java

/**
 * Attempts to deconstruct the given URL to find a JAR file containing the
 * resource referenced by the URL. That is, assuming the URL references a
 * JAR entry, this method will return a URL that references the JAR file
 * containing the entry. If the JAR cannot be located, then this method
 * returns null.//w  ww  . java 2 s  .c o  m
 * 
 * @param url
 *            The URL of the JAR entry.
 * @param path
 *            The path by which the URL was requested from the class loader.
 * @return The URL of the JAR file, if one is found. Null if not.
 * @throws MalformedURLException
 */
protected URL findJarForResource(URL url, String path) throws MalformedURLException {
    log.debug("Find JAR URL: " + url);

    // If the file part of the URL is itself a URL, then that URL probably
    // points to the JAR
    try {
        for (;;) {
            url = new URL(url.getFile());
            log.debug("Inner URL: " + url);
        }
    } catch (MalformedURLException e) {
        // This will happen at some point and serves a break in the loop
    }

    // Look for the .jar extension and chop off everything after that
    StringBuilder jarUrl = new StringBuilder(url.toExternalForm());
    int index = jarUrl.lastIndexOf(".jar");
    if (index >= 0) {
        jarUrl.setLength(index + 4);
        log.debug("Extracted JAR URL: " + jarUrl);
    } else {
        log.debug("Not a JAR: " + jarUrl);
        return null;
    }

    // Try to open and test it
    try {
        URL testUrl = new URL(jarUrl.toString());
        if (isJar(testUrl)) {
            return testUrl;
        } else {
            // WebLogic fix: check if the URL's file exists in the
            // filesystem.
            log.debug("Not a JAR: " + jarUrl);
            jarUrl.replace(0, jarUrl.length(), testUrl.getFile());
            File file = new File(jarUrl.toString());

            // File name might be URL-encoded
            // if (!file.exists()) {
            // file = new File(StringUtil.urlDecode(jarUrl.toString()));
            // }

            if (file.exists()) {
                log.debug("Trying real file: " + file.getAbsolutePath());
                testUrl = file.toURI().toURL();
                if (isJar(testUrl)) {
                    return testUrl;
                }
            }
        }
    } catch (MalformedURLException e) {
        log.warn("Invalid JAR URL: " + jarUrl);
    }

    log.debug("Not a JAR: " + jarUrl);
    return null;
}