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:org.ambraproject.service.feed.FeedServiceImpl.java

private String createFilterLimitForArticleType(String[] articleTypes) {
    Arrays.sort(articleTypes); // Consistent order so that each filter will only be cached once.
    StringBuilder fq = new StringBuilder();
    for (String articleType : articleTypes) {
        fq.append("article_type:\"").append(articleType).append("\" OR ");
    }//from   w  w  w  . ja  v a  2s.  co  m
    return fq.replace(fq.length() - 4, fq.length(), "").toString(); // Remove last " OR".
}

From source file:fi.kela.kanta.exceptions.VirheellisetTiedotException.java

@Override
public String getMessage() {

    StringBuilder sb = new StringBuilder();
    if (!StringUtils.isEmpty(getObjektinNimi())) {
        Object[] args = { this.getObjektinNimi() };
        sb.append(String.format(VirheellisetTiedotException.list_start_with_name, args));
    } else {//from  www.  j a v a2s.c om
        sb.append(VirheellisetTiedotException.list_start);
    }
    for (Map.Entry<String, String> entry : virheet.entrySet()) {
        sb.append(entry.getKey()).append(VirheellisetTiedotException.sepr).append(entry.getValue());
        sb.append(", ");
    }
    sb.replace(sb.length() - 2, sb.length(), "");
    sb.append(VirheellisetTiedotException.list_end);
    return sb.toString();
}

From source file:org.executequery.search.TextAreaSearch.java

public static int replaceAll() {

    if (textComponent == null) {
        GUIUtilities.displayWarningMessage("Search text not found.");
        return -1;
    }//from ww w.j  a v  a  2 s . com

    if (findText == null || findText.length() == 0)
        return -1;

    String _text = null;
    String text = textComponent.getText();

    if (text == null || text.length() == 0) {
        GUIUtilities.displayWarningMessage("Search text not found.");
        return -1;
    }

    int caretPosition = textComponent.getCaretPosition();

    if (replacementText == null)
        replacementText = "";

    String regexPattern = null;

    if (!useRegex)
        regexPattern = formatRegularExpression(findText, wholeWords);
    else
        regexPattern = findText;

    Pattern pattern = null;
    Matcher matcher = null;
    StringBuilder resultText = null;

    try {

        if (matchCase)
            pattern = Pattern.compile(regexPattern);
        else
            pattern = Pattern.compile(regexPattern, Pattern.CASE_INSENSITIVE);

        if (wrapSearch)
            matcher = pattern.matcher(text);

        else {

            if (searchDirection == SEARCH_UP)
                matcher = pattern.matcher(text.substring(0, caretPosition));
            else
                matcher = pattern.matcher(text.substring(caretPosition));

        }

        if (matcher.find()) {

            _text = matcher.replaceAll(replacementText);

        } else {

            GUIUtilities.displayWarningMessage("Search text not found.");
            return -1;
        }

        if (wrapSearch) {

            resultText = new StringBuilder(_text);

        } else {

            resultText = new StringBuilder(text);

            if (searchDirection == SEARCH_UP)
                resultText.replace(0, caretPosition, _text);
            else
                resultText.replace(caretPosition, text.length() - 1, _text);

        }

        textComponent.setText(resultText.toString());
        return 0;

    } catch (PatternSyntaxException pExc) {

        if (useRegex)
            GUIUtilities.displayErrorMessage("The regular expression search pattern is invalid.");

        return -1;

    } finally {

        if (resultText != null) {
            int length = resultText.length();
            textComponent.setCaretPosition(length < caretPosition ? length : caretPosition);
        }

        GUIUtilities.scheduleGC();
    }

}

From source file:com.lonepulse.robozombie.response.HeaderProcessor.java

/**
 * <p>Accepts the {@link InvocationContext} along with the {@link HttpResponse} and retrieves all response 
 * headers which are discovered in the {@link HttpResponse}. These are then injected into their matching 
 * {@link StringBuilder} which are identified by @{@link Header} on the endpoint request definition. The 
 * response headers and the in-out parameters are matched using the header name and all parameters with 
 * a runtime value of {@code null} will be ignored.</p> 
 * //from   w ww  .j ava2  s .c  o m
 * @param context
 *          the {@link InvocationContext} which is used to discover any @{@link Header} metadata in its 
 *          <i>request</i> and <i>args</i>
 * <br><br>
 * @param response
 *          the {@link HttpResponse} whose headers are to be retrieved and injected in the in-out 
 *          {@link StringBuilder} parameters found on the request definition
 * <br><br>
 * @return the <i>same</i> deserialized response entity instance which was supplied as a parameter 
 * <br><br>
 * @throws ResponseProcessorException
 *          if the response-header retrieval or injection failed due to an unrecoverable error
 * <br><br>
 * @since 1.3.0
 */
@Override
protected Object process(InvocationContext context, HttpResponse response, Object content) {

    try {

        List<Map.Entry<Header, Object>> headers = Metadata.onParams(Header.class, context);

        String name;
        StringBuilder value;

        for (Map.Entry<Header, Object> header : headers) {

            if (header.getValue() instanceof StringBuilder) {

                name = header.getKey().value();
                value = (StringBuilder) header.getValue();

                org.apache.http.Header[] responseHeaders = response.getHeaders(name);

                if (responseHeaders != null && responseHeaders.length > 0) {

                    String responseHeaderValue = responseHeaders[0].getValue();
                    value.replace(0, value.length(), responseHeaderValue == null ? "" : responseHeaderValue);

                    response.removeHeader(responseHeaders[0]); //remaining headers (equally named) processed if in-out params available
                }
            }
        }

        return content;
    } catch (Exception e) {

        throw new ResponseProcessorException(getClass(), context, e);
    }
}

From source file:com.bizideal.whoami.utils.cloopen.CCPRestSmsSDK.java

/**
 * ???/*from   ww  w . ja  v  a  2 s. c  o  m*/
 * 
 * @param to
 *            ? ??????????100
 * @param templateId
 *            ? ?Id
 * @param datas
 *            ?? ???{??}
 * @return
 */
public HashMap<String, Object> sendTemplateSMS(String to, String templateId, String[] datas) {
    HashMap<String, Object> validate = accountValidate();
    if (validate != null)
        return validate;
    if ((isEmpty(to)) || (isEmpty(App_ID)) || (isEmpty(templateId)))
        throw new IllegalArgumentException("?:" + (isEmpty(to) ? " ?? " : "")
                + (isEmpty(templateId) ? " ?Id " : "") + "");
    CcopHttpClient chc = new CcopHttpClient();
    DefaultHttpClient httpclient = null;
    try {
        httpclient = chc.registerSSL(SERVER_IP, "TLS", Integer.parseInt(SERVER_PORT), "https");
    } catch (Exception e1) {
        e1.printStackTrace();
        throw new RuntimeException("?httpclient" + e1.getMessage());
    }
    String result = "";
    try {
        HttpPost httppost = (HttpPost) getHttpRequestBase(1, TemplateSMS);
        String requsetbody = "";
        if (BODY_TYPE == BodyType.Type_JSON) {
            JsonObject json = new JsonObject();
            json.addProperty("appId", App_ID);
            json.addProperty("to", to);
            json.addProperty("templateId", templateId);
            if (datas != null) {
                StringBuilder sb = new StringBuilder("[");
                for (String s : datas) {
                    sb.append("\"" + s + "\"" + ",");
                }
                sb.replace(sb.length() - 1, sb.length(), "]");
                JsonParser parser = new JsonParser();
                JsonArray Jarray = parser.parse(sb.toString()).getAsJsonArray();
                json.add("datas", Jarray);
            }
            requsetbody = json.toString();
        } else {
            StringBuilder sb = new StringBuilder("<?xml version='1.0' encoding='utf-8'?><TemplateSMS>");
            sb.append("<appId>").append(App_ID).append("</appId>").append("<to>").append(to).append("</to>")
                    .append("<templateId>").append(templateId).append("</templateId>");
            if (datas != null) {
                sb.append("<datas>");
                for (String s : datas) {
                    sb.append("<data>").append(s).append("</data>");
                }
                sb.append("</datas>");
            }
            sb.append("</TemplateSMS>").toString();
            requsetbody = sb.toString();
        }

        LoggerUtil.info("sendTemplateSMS Request body =  " + requsetbody);
        BasicHttpEntity requestBody = new BasicHttpEntity();
        requestBody.setContent(new ByteArrayInputStream(requsetbody.getBytes("UTF-8")));
        requestBody.setContentLength(requsetbody.getBytes("UTF-8").length);
        httppost.setEntity(requestBody);
        HttpResponse response = httpclient.execute(httppost);

        HttpEntity entity = response.getEntity();
        if (entity != null)
            result = EntityUtils.toString(entity, "UTF-8");

        EntityUtils.consume(entity);
    } catch (IOException e) {
        e.printStackTrace();
        LoggerUtil.error(e.getMessage());
        return getMyError("172001", "");
    } catch (Exception e) {
        e.printStackTrace();
        LoggerUtil.error(e.getMessage());
        return getMyError("172002", "");
    } finally {
        if (httpclient != null)
            httpclient.getConnectionManager().shutdown();
    }

    LoggerUtil.info("sendTemplateSMS response body = " + result);

    try {
        if (BODY_TYPE == BodyType.Type_JSON) {
            return jsonToMap(result);
        } else {
            return xmlToMap(result);
        }
    } catch (Exception e) {

        return getMyError("172003", "");
    }
}

From source file:com.jinglingtec.ijiazu.util.CCPRestSmsSDK.java

/**
 * ???/*ww  w . j av a  2s  . c  o  m*/
 *
 * @param to ? ??????????100
 * @param templateId ? ?Id
 * @param datas ?? ???{??}
 *
 * @return
 */
public HashMap<String, Object> sendTemplateSMS(String to, String templateId, String[] datas) {
    HashMap<String, Object> validate = accountValidate();
    if (validate != null) {
        return validate;
    }
    if ((isEmpty(to)) || (isEmpty(App_ID)) || (isEmpty(templateId))) {
        throw new IllegalArgumentException("?:" + (isEmpty(to) ? " ?? " : "")
                + (isEmpty(templateId) ? " ?Id " : "") + "");
    }
    CcopHttpClient chc = new CcopHttpClient();
    DefaultHttpClient httpclient = null;
    try {
        httpclient = chc.registerSSL(SERVER_IP, "TLS", Integer.parseInt(SERVER_PORT), "https");
    } catch (Exception e1) {
        e1.printStackTrace();
        throw new RuntimeException("?httpclient" + e1.getMessage());
    }
    String result = "";
    try {
        HttpPost httppost = (HttpPost) getHttpRequestBase(1, TemplateSMS);
        String requsetbody = "";
        if (BODY_TYPE == BodyType.Type_JSON) {
            JsonObject json = new JsonObject();
            json.addProperty("appId", App_ID);
            json.addProperty("to", to);
            json.addProperty("templateId", templateId);
            if (datas != null) {
                StringBuilder sb = new StringBuilder("[");
                for (String s : datas) {
                    sb.append("\"" + s + "\"" + ",");
                }
                sb.replace(sb.length() - 1, sb.length(), "]");
                JsonParser parser = new JsonParser();
                JsonArray Jarray = parser.parse(sb.toString()).getAsJsonArray();
                json.add("datas", Jarray);
            }
            requsetbody = json.toString();
        } else {
            StringBuilder sb = new StringBuilder("<?xml version='1.0' encoding='utf-8'?><TemplateSMS>");
            sb.append("<appId>").append(App_ID).append("</appId>").append("<to>").append(to).append("</to>")
                    .append("<templateId>").append(templateId).append("</templateId>");
            if (datas != null) {
                sb.append("<datas>");
                for (String s : datas) {
                    sb.append("<data>").append(s).append("</data>");
                }
                sb.append("</datas>");
            }
            sb.append("</TemplateSMS>").toString();
            requsetbody = sb.toString();
        }

        LoggerUtil.info("sendTemplateSMS Request body =  " + requsetbody);
        BasicHttpEntity requestBody = new BasicHttpEntity();
        requestBody.setContent(new ByteArrayInputStream(requsetbody.getBytes("UTF-8")));
        requestBody.setContentLength(requsetbody.getBytes("UTF-8").length);
        httppost.setEntity(requestBody);
        HttpResponse response = httpclient.execute(httppost);

        HttpEntity entity = response.getEntity();
        if (entity != null) {
            result = EntityUtils.toString(entity, "UTF-8");
        }

        EntityUtils.consume(entity);
    } catch (IOException e) {
        e.printStackTrace();
        LoggerUtil.error(e.getMessage());
        return getMyError("172001", "");
    } catch (Exception e) {
        e.printStackTrace();
        LoggerUtil.error(e.getMessage());
        return getMyError("172002", "");
    } finally {
        if (httpclient != null) {
            httpclient.getConnectionManager().shutdown();
        }
    }

    LoggerUtil.info("sendTemplateSMS response body = " + result);

    try {
        if (BODY_TYPE == BodyType.Type_JSON) {
            return jsonToMap(result);
        } else {
            return xmlToMap(result);
        }
    } catch (Exception e) {

        return getMyError("172003", "");
    }
}

From source file:org.wso2.mb.integration.common.clients.operations.queue.QueueMessageSender.java

public void run() {
    try {//from   w  w  w  . j  a v a 2  s.  co  m
        Message message = null;
        String everything = "";
        if (readFromFile) {
            BufferedReader br = new BufferedReader(new FileReader(filePath));
            try {
                StringBuilder sb = new StringBuilder();
                String line = br.readLine();

                while (line != null) {
                    sb.append(line);
                    sb.append('\n');
                    line = br.readLine();
                }

                // Remove the last appended next line since there is no next line.
                sb.replace(sb.length() - 1, sb.length() + 1, "");

                everything = sb.toString();
            } finally {

                br.close();

            }
        }

        long threadID = Thread.currentThread().getId();
        int localMessageCount = 0;
        while (messageCounter.get() < numOfMessagesToSend) {
            if (typeOfMessage.equals("text")) {
                if (!readFromFile) {
                    message = queueSession.createTextMessage(
                            "sending Message:-" + messageCounter.get() + "- " + "ThreadID:" + threadID);
                } else {
                    message = queueSession.createTextMessage(everything);
                }
            } else if (typeOfMessage.equals("byte")) {
                message = queueSession.createBytesMessage();
            } else if (typeOfMessage.equals("map")) {
                message = queueSession.createMapMessage();
            } else if (typeOfMessage.equals("object")) {
                message = queueSession.createObjectMessage();
            } else if (typeOfMessage.equals("stream")) {
                message = queueSession.createStreamMessage();
            }
            message.setStringProperty("msgID", Integer.toString(messageCounter.get()));
            synchronized (messageCounter.getClass()) {
                if (messageCounter.get() >= numOfMessagesToSend) {
                    break;
                }
                queueSender.send(message, DeliveryMode.PERSISTENT, 0, jmsExpiration);
                messageCounter.incrementAndGet();
            }
            localMessageCount++;
            if (messageCounter.get() % printNumberOfMessagesPer == 0) {

                log.info((readFromFile ? "(FROM FILE)" : "(SIMPLE MESSAGE) ") + "[QUEUE SEND] ThreadID:"
                        + threadID + " queueName:" + queueName + " localMessageCount:" + localMessageCount
                        + " totalMessageCount:-" + messageCounter.get() + "- count to send:"
                        + numOfMessagesToSend);
            }
            if (isToPrintEachMessage) {
                log.info("(count:" + messageCounter.get() + "/threadID:" + threadID + ") " + message);
            }
            if (delay != 0) {
                try {
                    Thread.sleep(delay);
                } catch (InterruptedException e) {
                    //silently ignore
                }
            }
        }

        stopSending();

    } catch (JMSException e) {
        log.error("Error while publishing messages", e);
    } catch (IOException e) {
        log.error("Error while reading file", e);
    }
}

From source file:org.drools.workbench.jcr2vfsmigration.jcrExport.ModuleAssetExporter.java

private String setupAssetExportFile(String moduleUuid) {
    StringBuilder fileNameBuilder = new StringBuilder();
    boolean success = false;
    if (StringUtils.isNotBlank(moduleUuid)) {
        fileNameBuilder.insert(0, moduleUuid);
        success = fileManager.createAssetExportFile(fileNameBuilder.toString());
    }/*from   w w  w  . j av  a  2s .c  om*/
    if (!success) {
        fileNameBuilder.replace(0, fileNameBuilder.lastIndexOf("."), Integer.toString(assetFileName++));
        success = fileManager.createAssetExportFile(fileNameBuilder.toString());
        if (!success) {
            logger.error("Module asset file could not be created");
            return null;
        }
    }
    return fileNameBuilder.toString();
}

From source file:gate.tagger.tagme.TaggerTagMeWS.java

protected void annotateText(Document doc, AnnotationSet outputAS, long from, long to) {
    String text = "";
    try {//www. jav a2s .c o  m
        text = doc.getContent().getContent(from, to).toString();
    } catch (InvalidOffsetException ex) {
        throw new GateRuntimeException("Unexpected offset exception, offsets are " + from + "/" + to);
    }
    // send the text to the service and get back the response
    //System.out.println("Annotating text: "+text);
    //System.out.println("Starting offset is "+from);

    // NOTE: there is a bug in the TagMe service which causes offset errors
    // if we use the tweet mode and there are certain patterns in the tweet.
    // The approach recommended by Francesco Piccinno is to replace those 
    // patterns by spaces.    
    if (getIsTweet()) {
        logger.debug("Text before cleaning: >>" + text + "<<");
        // replace 
        text = text.replaceAll(patternStringRT3, "    ");
        text = text.replaceAll(patternStringRT2, "   ");
        text = text.replaceAll(patternHashTag, " $1");
        // now replace the remaining patterns by spaces
        StringBuilder sb = new StringBuilder(text);
        Matcher m = patternUrl.matcher(text);
        while (m.find()) {
            int start = m.start();
            int end = m.end();
            sb.replace(start, end, nSpaces(end - start));
        }
        m = patternUser.matcher(text);
        while (m.find()) {
            int start = m.start();
            int end = m.end();
            sb.replace(start, end, nSpaces(end - start));
        }
        text = sb.toString();
        logger.debug("Text after cleaning:  >>" + text + "<<");
    }
    TagMeAnnotation[] tagmeAnnotations = getTagMeAnnotations(text);
    for (TagMeAnnotation tagmeAnn : tagmeAnnotations) {
        if (tagmeAnn.rho >= minrho) {
            FeatureMap fm = Factory.newFeatureMap();
            fm.put("tagMeId", tagmeAnn.id);
            fm.put("title", tagmeAnn.title);
            fm.put("rho", tagmeAnn.rho);
            fm.put("spot", tagmeAnn.spot);
            fm.put("link_probability", tagmeAnn.link_probability);
            if (tagmeAnn.title == null) {
                throw new GateRuntimeException("Odd: got a null title from the TagMe service" + tagmeAnn);
            } else {
                fm.put("inst", "http://dbpedia.org/resource/" + recodeForDbp38(tagmeAnn.title));
            }
            try {
                gate.Utils.addAnn(outputAS, from + tagmeAnn.start, from + tagmeAnn.end,
                        getOutputAnnotationType(), fm);
            } catch (Exception ex) {
                System.err.println(
                        "Got an exception in document " + doc.getName() + ": " + ex.getLocalizedMessage());
                ex.printStackTrace(System.err);
                System.err.println("from=" + from + ", to=" + to + " TagMeAnn=" + tagmeAnn);
            }
        }
    }
}

From source file:org.apache.oozie.command.coord.CoordPushDependencyCheckXCommand.java

private String resolveCoordConfiguration() throws CommandException {
    try {//from www.  ja va2s.  c  o m
        Configuration actionConf = new XConfiguration(new StringReader(coordAction.getRunConf()));
        StringBuilder actionXml = new StringBuilder(coordAction.getActionXml());
        String newActionXml = CoordActionInputCheckXCommand.resolveCoordConfiguration(actionXml, actionConf,
                actionId, coordAction.getPullInputDependencies(), coordAction.getPushInputDependencies());
        actionXml.replace(0, actionXml.length(), newActionXml);
        return actionXml.toString();
    } catch (Exception e) {
        throw new CommandException(ErrorCode.E1021, e.getMessage(), e);
    }
}