Example usage for java.lang StringBuilder deleteCharAt

List of usage examples for java.lang StringBuilder deleteCharAt

Introduction

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

Prototype

@Override
public StringBuilder deleteCharAt(int index) 

Source Link

Usage

From source file:com.taobao.diamond.client.impl.DefaultDiamondPublisher.java

private String getPushitServers() {
    StringBuilder result = new StringBuilder();
    List<String> serverList = this.diamondConfigure.getPushitDomainNameList();
    for (String server : serverList) {
        result.append(server).append(",");
    }//from   www  .ja  v a 2  s.  com
    result.deleteCharAt(result.length() - 1);

    return result.toString();
}

From source file:hr.fer.zemris.vhdllab.service.extractor.testbench.TestbenchMetadataExtractor.java

/**
 * Populate a component in testbench VHDL.
 * /*from  ww  w.j ava  2  s .c o m*/
 * @param ci
 *            a circuit interface from where to draw information.
 * @param vhdl
 *            a string builder where to store testbench VHDL.
 */
private void populateComponent(CircuitInterface ci, StringBuilder vhdl) {
    vhdl.append("component ").append(ci.getName()).append(" is port (\n");
    for (Port p : ci.getPorts()) {
        vhdl.append("\t").append(p.getName()).append(" : ").append(p.getDirection().toString()).append(" ")
                .append(p.getTypeName());
        if (p.isVector())
            vhdl.append("(").append(p.getFrom()).append(" ").append(p.getDirectionName()).append(" ")
                    .append(p.getTo()).append(")");
        vhdl.append(";\n");
    }
    vhdl.deleteCharAt(vhdl.length() - 2) // deleting last ';'
            .append(");\n");
}

From source file:io.gravitee.gateway.http.core.invoker.DefaultHttpInvoker.java

private URI encodeQueryParameters(Request request, String endpointUri) {
    final StringBuilder requestURI = new StringBuilder(endpointUri);

    if (request.parameters() != null && !request.parameters().isEmpty()) {
        StringBuilder query = new StringBuilder();
        query.append('?');

        for (Map.Entry<String, String> queryParam : request.parameters().entrySet()) {
            query.append(queryParam.getKey());
            if (queryParam.getValue() != null && !queryParam.getValue().isEmpty()) {
                try {
                    query.append('=')
                            .append(URLEncoder.encode(queryParam.getValue(), StandardCharsets.UTF_8.name()));
                } catch (UnsupportedEncodingException e) {
                    logger.error("Unexpected error while encoding query parameters");
                }/*from  w  ww  . j  a v  a2  s  .c o m*/
            }

            query.append('&');
        }

        // Removing latest & separator and encode query parameters
        requestURI.append(query.deleteCharAt(query.length() - 1).toString());
    }

    return URI.create(requestURI.toString());
}

From source file:kmi.taa.core.PredicateObjectRetriever.java

public String csvClean(String origin) {
    if (origin.equals(""))
        return "";
    StringBuilder builder = new StringBuilder();
    String[] str = origin.split(System.getProperty("line.separator"));
    String[] line = new String[2];
    int i = 0;//from ww  w . j  av a 2 s  .c  om

    while (i < str.length) {
        line = str[i].split(",");
        try {
            // if this line is a remaining part of the previous line because of
            // a new line symbol, it will be added to the end of the previous line
            // without line break
            if (line.length == 1) {
                builder.deleteCharAt(builder.length() - 1);
                if (line[0].charAt(0) == '"' && line[0].charAt(line[0].length() - 1) == '"') {
                    builder.append(line[0].substring(1, line[0].length() - 1));
                } else if (line[0].charAt(0) == '"' && line[0].charAt(line[0].length() - 1) != '"') {
                    builder.append(line[0].substring(1, line[0].length()));
                } else if (line[0].charAt(line[0].length() - 1) == '"' && line[0].charAt(0) != '"') {
                    builder.append(line[0].substring(0, line[0].length() - 1));
                } else {
                    builder.append(line[0]);
                }
            } else {
                if (line[0].charAt(0) != '"' && line[0].charAt(line[0].length() - 1) != '"') {
                    builder.deleteCharAt(builder.length() - 1);
                    builder.append(str[i].substring(0, str[i].length() - 1));
                } else if (line[1].charAt(0) == '"' && line[1].charAt(line[1].length() - 1) == '"') {
                    builder.append(line[0].substring(1, line[0].length() - 1) + "\t"
                            + line[1].substring(1, line[1].length() - 1));
                } else if (line[1].charAt(0) == '"' && line[1].charAt(line[1].length() - 1) != '"') {
                    builder.append(line[0].substring(1, line[0].length() - 1) + "\t"
                            + line[1].substring(1, line[1].length()));
                } else if (line[1].charAt(line[1].length() - 1) == '"' && line[1].charAt(0) != '"') {
                    builder.append(line[0].substring(1, line[0].length() - 1) + "\t"
                            + line[1].substring(0, line[1].length() - 1));
                } else {
                    builder.append(line[0].substring(1, line[0].length() - 1) + "\t" + line[1]);
                }

            }
            builder.append(System.lineSeparator());

        } catch (Exception e) {

        }

        i++;
    }

    return builder.toString();
}

From source file:org.apache.solr.cloud.BaseCdcrDistributedZkTest.java

/**
 * Create a new collection through the Collection API. It enforces the use of one max shard per node.
 * It will define the nodes to spread the new collection across by using the mapping {@link #collectionToNodeNames},
 * to ensure that a node will not host more than one core (which will create problem when trying to restart servers).
 *//*from  w  ww  . j  a  v  a 2  s.  c o m*/
private void createCollection(String name) throws Exception {
    CloudSolrClient client = createCloudClient(null);
    try {
        // Create the target collection
        Map<String, List<Integer>> collectionInfos = new HashMap<>();
        int maxShardsPerNode = 1;

        StringBuilder sb = new StringBuilder();
        for (String nodeName : collectionToNodeNames.get(name)) {
            sb.append(nodeName);
            sb.append(',');
        }
        sb.deleteCharAt(sb.length() - 1);

        createCollection(collectionInfos, name, shardCount, replicationFactor, maxShardsPerNode, client,
                sb.toString());
    } finally {
        client.close();
    }
}

From source file:com.ning.http.client.providers.NettyAsyncHttpProvider.java

@SuppressWarnings("deprecation")
HttpRequest construct(Request request, HttpMethod m, Url url) throws IOException {
    String host = url.getHost();//from  w  w  w. ja  va 2  s  . c  o m

    if (request.getVirtualHost() != null) {
        host = request.getVirtualHost();
    }

    HttpRequest nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, m, url.getPath());
    nettyRequest.setHeader(HttpHeaders.Names.HOST, host + ":" + url.getPort());

    Headers h = request.getHeaders();
    if (h != null) {
        Iterator<Pair<String, String>> i = h.iterator();
        Pair<String, String> p;
        while (i.hasNext()) {
            p = i.next();
            if ("host".equalsIgnoreCase(p.getFirst())) {
                continue;
            }
            String key = p.getFirst() == null ? "" : p.getFirst();
            String value = p.getSecond() == null ? "" : p.getSecond();

            nettyRequest.setHeader(key, value);
        }
    }

    String ka = config.getKeepAlive() ? "keep-alive" : "close";
    nettyRequest.setHeader(HttpHeaders.Names.CONNECTION, ka);
    if (config.getProxyServer() != null) {
        nettyRequest.setHeader("Proxy-Connection", ka);
    }

    if (config.getUserAgent() != null) {
        nettyRequest.setHeader("User-Agent", config.getUserAgent());
    }

    if (request.getCookies() != null && !request.getCookies().isEmpty()) {
        CookieEncoder httpCookieEncoder = new CookieEncoder(false);
        Iterator<Cookie> ic = request.getCookies().iterator();
        Cookie c;
        org.jboss.netty.handler.codec.http.Cookie cookie;
        while (ic.hasNext()) {
            c = ic.next();
            cookie = new DefaultCookie(c.getName(), c.getValue());
            cookie.setPath(c.getPath());
            cookie.setMaxAge(c.getMaxAge());
            cookie.setDomain(c.getDomain());
            httpCookieEncoder.addCookie(cookie);
        }
        nettyRequest.setHeader(HttpHeaders.Names.COOKIE, httpCookieEncoder.encode());
    }

    if (config.isCompressionEnabled()) {
        nettyRequest.setHeader(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
    }

    switch (request.getType()) {
    case POST:
        if (request.getByteData() != null) {
            nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH,
                    String.valueOf(request.getByteData().length));
            nettyRequest.setContent(ChannelBuffers.copiedBuffer(request.getByteData()));
        } else if (request.getStringData() != null) {
            // TODO: Not sure we need to reconfigure that one.
            nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH,
                    String.valueOf(request.getStringData().length()));
            nettyRequest.setContent(ChannelBuffers.copiedBuffer(request.getStringData(), "UTF-8"));
        } else if (request.getStreamData() != null) {
            nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH,
                    String.valueOf(request.getStreamData().available()));
            byte[] b = new byte[(int) request.getStreamData().available()];
            request.getStreamData().read(b);
            nettyRequest.setContent(ChannelBuffers.copiedBuffer(b));
        } else if (request.getParams() != null) {
            StringBuilder sb = new StringBuilder();
            for (final Entry<String, String> param : request.getParams().entrySet()) {
                sb.append(param.getKey());
                sb.append("=");
                sb.append(param.getValue());
                sb.append("&");
            }
            sb.deleteCharAt(sb.length() - 1);
            nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(sb.length()));
            nettyRequest.setContent(ChannelBuffers.copiedBuffer(sb.toString().getBytes()));
        } else if (request.getParts() != null) {
            int lenght = computeAndSetContentLength(request, nettyRequest);

            if (lenght == -1) {
                lenght = MAX_BUFFERRED_BYTES;
            }

            /**
             * This is quite ugly to mix and match with Apache Client,
             * but the fastest way for now
             * TODO: Remove this dependency.
             */
            PostMethod post = new PostMethod(request.getUrl());
            MultipartRequestEntity mre = createMultipartRequestEntity(request.getParts(), post.getParams());

            nettyRequest.setHeader(HttpHeaders.Names.CONTENT_TYPE, mre.getContentType());
            nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(mre.getContentLength()));

            ChannelBuffer b = ChannelBuffers.dynamicBuffer((int) lenght);
            mre.writeRequest(new ChannelBufferOutputStream(b));
            nettyRequest.setContent(b);
        } else if (request.getEntityWriter() != null) {
            computeAndSetContentLength(request, nettyRequest);

            ChannelBuffer b = ChannelBuffers.dynamicBuffer((int) request.getLength());
            request.getEntityWriter().writeEntity(new ChannelBufferOutputStream(b));
            nettyRequest.setContent(b);
        }
        break;
    case PUT:
        if (request.getByteData() != null) {
            nettyRequest.setContent(ChannelBuffers.copiedBuffer(request.getByteData()));
        } else if (request.getStringData() != null) {
            nettyRequest.setContent(ChannelBuffers.copiedBuffer(request.getStringData(), "UTF-8"));
        }
        break;
    }

    if (nettyRequest.getHeader(HttpHeaders.Names.CONTENT_TYPE) == null) {
        nettyRequest.setHeader(HttpHeaders.Names.CONTENT_TYPE, "txt/html; charset=utf-8");
    }
    if (log.isDebugEnabled())
        log.debug("Constructed request: " + nettyRequest);
    return nettyRequest;
}

From source file:com.weibo.api.motan.config.RefererConfig.java

private ClusterSupport<T> createClusterSupport(URL refUrl, ConfigHandler configHandler,
        List<URL> registryUrls) {
    List<URL> regUrls = new ArrayList<URL>();

    // directUrls  injvm??local registry
    if (StringUtils.isNotBlank(directUrl) || MotanConstants.PROTOCOL_INJVM.equals(refUrl.getProtocol())) {
        URL regUrl = new URL(MotanConstants.REGISTRY_PROTOCOL_LOCAL, NetUtils.LOCALHOST,
                MotanConstants.DEFAULT_INT_VALUE, RegistryService.class.getName());
        if (StringUtils.isNotBlank(directUrl)) {
            StringBuilder duBuf = new StringBuilder(128);
            String[] dus = MotanConstants.COMMA_SPLIT_PATTERN.split(directUrl);
            for (String du : dus) {
                if (du.contains(":")) {
                    String[] hostPort = du.split(":");
                    URL durl = refUrl.createCopy();
                    durl.setHost(hostPort[0].trim());
                    durl.setPort(Integer.parseInt(hostPort[1].trim()));
                    durl.addParameter(URLParamType.nodeType.getName(), MotanConstants.NODE_TYPE_SERVICE);
                    duBuf.append(StringTools.urlEncode(durl.toFullStr()))
                            .append(MotanConstants.COMMA_SEPARATOR);
                }//from   w  ww.  j  a v  a 2 s .c  o  m
            }
            if (duBuf.length() > 0) {
                duBuf.deleteCharAt(duBuf.length() - 1);
                regUrl.addParameter(URLParamType.directUrl.getName(), duBuf.toString());
            }
        }
        regUrls.add(regUrl);
    } else { // ?URL??
        if (registryUrls == null || registryUrls.isEmpty()) {
            throw new IllegalStateException(String.format(
                    "No registry to reference %s on the consumer %s , please config <motan:registry address=\"...\" /> in your spring config.",
                    interfaceClass, NetUtils.LOCALHOST));
        }
        for (URL url : registryUrls) {
            regUrls.add(url.createCopy());
        }
    }

    for (URL url : regUrls) {
        url.addParameter(URLParamType.embed.getName(), StringTools.urlEncode(refUrl.toFullStr()));
    }
    return configHandler.buildClusterSupport(interfaceClass, regUrls);
}

From source file:info.savestate.saveybot.JSONFileManipulator.java

public String getSlot(String slotString, boolean largeResponse) {
    try {/*from   w  w  w .  j a v  a2s  .  co m*/
        return getSlot(new BigInteger(slotString));
    } catch (Exception e) {
        // going to load all slots made by user.
    }
    JSONArray json = getJSON();
    if (!largeResponse) {
        int entries = 0;
        for (int i = 0; i < json.length(); i++) {
            JSONObject o = json.getJSONObject(i);
            if (o == null)
                continue;
            if (o.getString("name").toLowerCase().equals(slotString.toLowerCase()))
                entries++;
        }
        if (entries > 0)
            return slotString + " owns " + entries + " savestates!!! :D/";
        return slotString + " doesnt own any savestates );";
    }
    StringBuilder slots = new StringBuilder();
    int entries = 0;
    for (int i = 0; i < json.length(); i++) {
        JSONObject o = json.getJSONObject(i);
        if (o == null)
            continue;
        if (o.getString("name").toLowerCase().equals(slotString.toLowerCase())) {
            entries++;
            slots.append(o.getString("slot")).append(", ");
        }
    }
    if (entries > 0) {
        slots.deleteCharAt(slots.length() - 1);
        slots.deleteCharAt(slots.length() - 1);
        return "owha! " + slotString + " owns slot(s) " + slots.toString() + "!!!! :D :D :D/";
    }
    return slotString + " doesn't own any savestates!! (u should fix that !! O:)";
}

From source file:com.linkedin.urls.PathNormalizer.java

License:asdf

/**
 * 1. Replaces "/./" with "/" recursively.
 * 2. "/blah/asdf/.." -> "/blah"/*w  w  w . ja v a  2  s  .  co  m*/
 * 3. "/blah/blah2/blah3/../../blah4" -> "/blah/blah4"
 * 4. "//" -> "/"
 * 5. Adds a slash at the end if there isn't one
 */
private static String sanitizeDotsAndSlashes(String path) {
    StringBuilder stringBuilder = new StringBuilder(path);
    Stack<Integer> slashIndexStack = new Stack<Integer>();
    int index = 0;
    while (index < stringBuilder.length() - 1) {
        if (stringBuilder.charAt(index) == '/') {
            slashIndexStack.add(index);
            if (stringBuilder.charAt(index + 1) == '.') {
                if (index < stringBuilder.length() - 2 && stringBuilder.charAt(index + 2) == '.') {
                    //If it looks like "/../" or ends with "/.."
                    if (index < stringBuilder.length() - 3 && stringBuilder.charAt(index + 3) == '/'
                            || index == stringBuilder.length() - 3) {
                        boolean endOfPath = index == stringBuilder.length() - 3;
                        slashIndexStack.pop();
                        int endIndex = index + 3;
                        // backtrack so we can detect if this / is part of another replacement
                        index = slashIndexStack.empty() ? -1 : slashIndexStack.pop() - 1;
                        int startIndex = endOfPath ? index + 1 : index;
                        stringBuilder.delete(startIndex + 1, endIndex);
                    }
                } else if (index < stringBuilder.length() - 2 && stringBuilder.charAt(index + 2) == '/'
                        || index == stringBuilder.length() - 2) {
                    boolean endOfPath = index == stringBuilder.length() - 2;
                    slashIndexStack.pop();
                    int startIndex = endOfPath ? index + 1 : index;
                    stringBuilder.delete(startIndex, index + 2); // "/./" -> "/"
                    index--; // backtrack so we can detect if this / is part of another replacement
                }
            } else if (stringBuilder.charAt(index + 1) == '/') {
                slashIndexStack.pop();
                stringBuilder.deleteCharAt(index);
                index--;
            }
        }
        index++;
    }

    if (stringBuilder.length() == 0) {
        stringBuilder.append("/"); //Every path has at least a slash
    }

    return stringBuilder.toString();
}

From source file:com.impetus.client.oraclenosql.schemamanager.OracleNoSQLSchemaManager.java

/**
 * Builds the alter ddl query.// w ww  . j  av  a 2s  .c  o m
 * 
 * @param tableInfo
 *            the table info
 * @param newColumns
 *            the new columns
 * @return the string
 */
private String buildAlterDDLQuery(TableInfo tableInfo, Map<String, String> newColumns) {
    String statement;
    StringBuilder builder = new StringBuilder();
    builder.append("ALTER TABLE ");
    builder.append(tableInfo.getTableName());
    builder.append(Constants.OPEN_ROUND_BRACKET);

    for (Map.Entry<String, String> entry : newColumns.entrySet()) {
        builder.append("ADD ");
        builder.append(entry.getKey());
        builder.append(Constants.SPACE);
        String coulmnType = entry.getValue().toLowerCase();
        builder.append(OracleNoSQLValidationClassMapper.getValidType(coulmnType));
        builder.append(Constants.COMMA);
    }

    builder.deleteCharAt(builder.length() - 1);
    builder.append(Constants.CLOSE_ROUND_BRACKET);
    statement = builder.toString();
    return statement;
}