Example usage for java.lang StringBuilder insert

List of usage examples for java.lang StringBuilder insert

Introduction

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

Prototype

@Override
public StringBuilder insert(int offset, double d) 

Source Link

Usage

From source file:com.qwazr.utils.HtmlUtils.java

public final static String urlHostPathWrapReduce(String url, int maxSize) {
     URL u;// w ww.  j a  v a2s.  c  o m
     try {
         u = new URL(url);
     } catch (MalformedURLException e) {
         return url;
     }
     String path = StringUtils.fastConcat(u.getHost(), '/', u.getPath());
     String[] frags = StringUtils.split(path, '/');
     if (frags.length < 2)
         return path;
     int startPos = 1;
     int endPos = frags.length - 2;
     StringBuilder sbStart = new StringBuilder(frags[0]);
     StringBuilder sbEnd = new StringBuilder(frags[frags.length - 1]);
     int length = sbStart.length() + sbEnd.length();
     for (;;) {
         boolean bHandled = false;
         if (startPos != -1 && startPos < endPos) {
             if (frags[startPos].length() + length < maxSize) {
                 sbStart.append('/');
                 sbStart.append(frags[startPos++]);
                 bHandled = true;
             }
         }
         if (endPos != -1 && endPos > startPos) {
             if (frags[endPos].length() + length < maxSize) {
                 sbEnd.insert(0, '/');
                 sbEnd.insert(0, frags[endPos--]);
                 bHandled = true;
             }
         }
         if (!bHandled)
             break;
     }
     return StringUtils.fastConcat(sbStart, "//", sbEnd);
 }

From source file:net.triptech.metahive.model.Submission.java

/**
 * Builds the where statement./*from   ww  w . ja v a2  s  .co  m*/
 *
 * @param filter the filter
 * @return the string
 */
private static String buildWhere(final SubmissionFilter filter) {
    StringBuilder where = new StringBuilder();

    if (filter.getPersonId() != null && filter.getPersonId() > 0) {
        where.append("s.person = :personId");
    }
    if (filter.getOrganisationId() != null && filter.getOrganisationId() > 0) {
        if (where.length() > 0) {
            where.append(" AND ");
        }
        where.append("s.organisation = :organisationId");
    }

    if (where.length() > 0) {
        where.insert(0, " WHERE ");
    }
    return where.toString();
}

From source file:com.haulmont.cuba.gui.ComponentsHelper.java

public static String getFilterComponentPath(Filter filter) {
    StringBuilder sb = new StringBuilder(filter.getId() != null ? filter.getId() : "filterWithoutId");
    Frame frame = filter.getFrame();
    while (frame != null) {
        sb.insert(0, ".");
        String s = frame.getId() != null ? frame.getId() : "frameWithoutId";
        if (s.contains(".")) {
            s = "[" + s + "]";
        }// w ww .  j  a v  a2  s.c  om
        sb.insert(0, s);
        if (frame instanceof Window) {
            break;
        }
        frame = frame.getFrame();
    }
    return sb.toString();
}

From source file:mx.klozz.xperience.tweaker.helpers.Helpers.java

public static void get_assetsScript(String fn, Context c, String prefix, String postfix) {
    byte[] buffer;
    final AssetManager assetManager = c.getAssets();
    try {// w ww  . j a  va2s  . c o  m
        InputStream f = assetManager.open(fn);
        buffer = new byte[f.available()];
        f.read(buffer);
        f.close();
        final String s = new String(buffer);
        final StringBuilder sb = new StringBuilder(s);
        if (!postfix.equals("")) {
            sb.append("\n\n").append(postfix);
        }
        if (!prefix.equals("")) {
            sb.insert(0, prefix + "\n");
        }
        sb.insert(0, "#!" + Helpers.BinExist("sh") + "\n\n");
        try {
            FileOutputStream fos;
            fos = c.openFileOutput(fn, Context.MODE_PRIVATE);
            fos.write(sb.toString().getBytes());
            fos.close();

        } catch (IOException e) {
            Log.d(TAG, "error write " + fn + " file");
            e.printStackTrace();
        }
    } catch (IOException e) {
        Log.d(TAG, "error read " + fn + " file");
        e.printStackTrace();
    }
}

From source file:com.mirth.connect.client.ui.components.MirthTree.java

/**
 * Construct a path for a specific node.
 * //from   w w w. jav a  2 s .c o  m
 * @param parent
 * @param prefix
 * @param suffix
 * @return
 */
public static StringBuilder constructPath(TreeNode parent, String prefix, String suffix) {
    StringBuilder sb = new StringBuilder();
    sb.insert(0, prefix);

    MirthTreeNode node = (MirthTreeNode) parent;
    SerializationType serializationType = node.getSerializationType();

    // Get the parent if the leaf was actually passed in instead of the parent.
    if (node.isLeaf()) {
        node = (MirthTreeNode) node.getParent();
    }

    /*
     * MIRTH-3196 - We now assign nodes types as we iterate from child to parent to add more
     * versatility to namespace drag and drop. The drag and drop can drag nodes, attribute or
     * namespace attributes so the user should be able to correctly do these now. If a node has
     * a namespace then will wildcard it. If an ancestor of the node has an implicit namespace
     * then we will also append a wildcard. The only exception to this is if the implicit
     * namespace is on the root node, we actually set this to the default namespace in
     * JavaScriptBuilder.
     */

    LinkedList<PathNode> nodeQ = new LinkedList<PathNode>();
    while (node != null && node.getParent() != null) {
        if (serializationType.equals(SerializationType.JSON) && node.isArrayElement()) {
            nodeQ.add(new PathNode(String.valueOf(node.getParent().getIndex(node) - 1),
                    PathNode.NodeType.ARRAY_CHILD));
        } else {

            PathNode.NodeType type = PathNode.NodeType.OTHER;
            if (serializationType.equals(SerializationType.XML)) {
                type = getXmlNodeType(node);
            }

            String nodeValue = node.getValue().replaceAll(" \\(.*\\)", "");
            nodeQ.add(new PathNode(nodeValue, type));

            if (serializationType.equals(SerializationType.XML)) {
                int parentIndexValue = getIndexOfNode(node);
                if (parentIndexValue != -1) {
                    nodeQ.add(nodeQ.size() - 1,
                            new PathNode(String.valueOf(parentIndexValue), PathNode.NodeType.ARRAY_CHILD));
                }
            }
        }
        node = (MirthTreeNode) node.getParent();
    }

    boolean foundImplicitNamespace = false;

    while (!nodeQ.isEmpty()) {
        PathNode nodeValue = nodeQ.removeLast();

        //We start at the parent so if any implicit namespaces are reached then the rest of the nodes should wildcard the namespace
        boolean includeNamespace = false;
        PathNode.NodeType type = nodeValue.getType();

        //We don't want to include a wildcard for attributes, ns definitions or array indices
        if (serializationType.equals(SerializationType.XML) && !Arrays
                .asList(PathNode.NodeType.XML_ATTRIBUTE, PathNode.NodeType.XMLNS_DEFINITION,
                        PathNode.NodeType.XML_PREFIX_DEFINITION, PathNode.NodeType.ARRAY_CHILD)
                .contains(type)) {
            if (foundImplicitNamespace) {
                includeNamespace = true;
            } else if (type == PathNode.NodeType.XML_XMLNS_NODE) {
                foundImplicitNamespace = true;
                includeNamespace = true;
            } else if (type == PathNode.NodeType.XML_PREFIXED_NODE) {
                includeNamespace = true;
            }
        }

        if (includeNamespace) {
            int colonIndex = nodeValue.getValue().indexOf(':') + 1;
            sb.append(".*::['" + StringUtils.substring(nodeValue.getValue(), colonIndex) + "']");
        } else if (serializationType.equals(SerializationType.XML)
                && type == PathNode.NodeType.XMLNS_DEFINITION) {
            sb.append(".namespace('')");
        } else if (serializationType.equals(SerializationType.XML)
                && type == PathNode.NodeType.XML_PREFIX_DEFINITION) {
            sb.append(".namespace('" + StringUtils.substringAfter(nodeValue.getValue(), "@xmlns:") + "')");
        } else if (type == PathNode.NodeType.XML_PREFIXED_ATTRIBUTE) {
            sb.append(".@*::['" + StringUtils.substringAfter(nodeValue.getValue(), ":") + "']");
        } else if (type == PathNode.NodeType.ARRAY_CHILD) {
            sb.append("[" + nodeValue.getValue() + "]");
        } else {
            sb.append("['" + nodeValue.getValue() + "']");
        }
    }

    if (!serializationType.equals(SerializationType.JSON)) {
        sb.append(suffix);
    }

    return sb;
}

From source file:com.android.settings.util.Helpers2.java

public static void get_assetsScript(String fn, Context c, String prefix, String postfix) {
    byte[] buffer;
    final AssetManager assetManager = c.getAssets();
    try {//from  w ww.j av a 2s .  c  o  m
        InputStream f = assetManager.open(fn);
        buffer = new byte[f.available()];
        f.read(buffer);
        f.close();
        final String s = new String(buffer);
        final StringBuilder sb = new StringBuilder(s);
        if (!postfix.equals("")) {
            sb.append("\n\n").append(postfix);
        }
        if (!prefix.equals("")) {
            sb.insert(0, prefix + "\n");
        }
        sb.insert(0, "#!" + Helpers2.binExist("sh") + "\n\n");
        try {
            FileOutputStream fos;
            fos = c.openFileOutput(fn, Context.MODE_PRIVATE);
            fos.write(sb.toString().getBytes());
            fos.close();

        } catch (IOException e) {
            Log.d(TAG, "error write " + fn + " file");
            e.printStackTrace();
        }

    } catch (IOException e) {
        Log.d(TAG, "error read " + fn + " file");
        e.printStackTrace();
    }
}

From source file:newsgroup.ToJSON2D.java

public static void go2json(String path) throws IOException {
    List<String> readLines = FileUtils.readLines(new File(path));
    List<String[]> cat1 = new ArrayList<>();
    List<String[]> cat2 = new ArrayList<>();
    for (String line : readLines) {
        String[] split = line.split(",");
        if (split[2].equals("1")) {
            cat1.add(split);//from  ww w. j a  v  a  2  s . c om
        } else if (split[2].equals("2")) {
            cat2.add(split);
        } else {
            break;
        }
    }
    StringBuilder sb = new StringBuilder();
    sb.append("[[");
    for (String[] li : cat1) {
        sb.append("[").append(li[0]).append(",").append(li[1]).append("],");
    }
    sb.deleteCharAt(sb.length() - 1);
    sb.append("],[");
    for (String[] li : cat2) {
        sb.append("[").append(li[0]).append(",").append(li[1]).append("],");
    }
    sb.deleteCharAt(sb.length() - 1);
    sb.append("]];");
    String name = "";
    if (path.contains("mtrick")) {
        name = "mtrick";
    } else if (path.contains("DTL")) {
        name = "DTL";
    } else if (path.contains("TriTL")) {
        name = "TriTL";
    } else if (path.contains("our")) {
        name = "our";
    }
    sb.insert(0, "var " + name + "=");
    FileUtils.write(new File(path + ".js"), sb.toString());
}

From source file:com.github.gekoh.yagen.util.FieldInfo.java

/**
 * merges given collection of javax.persistence.AttributeOverride elements into an optionally existing
 * javax.persistence.AttributeOverrides annotation with optionally pre-existing javax.persistence.AttributeOverride elements.
 *
 * @param annotation existing javax.persistence.AttributeOverrides annotation, if any, otherwise it will be created
 * @param attributeOverrides collection of javax.persistence.AttributeOverride annotation to be appended
 * @return merged AttributeOverrides annotation
 *///  w w w .j a  v  a  2s  .c  om
private static String concatOverrides(String annotation, Collection<String> attributeOverrides) {
    StringBuilder columnAnnotation = new StringBuilder(annotation != null ? annotation : "");

    for (String addOverride : attributeOverrides) {
        if (columnAnnotation.length() < 1) {
            columnAnnotation.append("@javax.persistence.AttributeOverrides({").append(addOverride).append("})");
            continue;
        }

        columnAnnotation.insert(columnAnnotation.length() - 2, ", ");
        columnAnnotation.insert(columnAnnotation.length() - 2, addOverride);
    }

    return columnAnnotation.toString();
}

From source file:com.wxxr.nirvana.json.JSONUtil.java

public static void writeJSONToResponse(SerializationParams serializationParams) throws IOException {
    StringBuilder stringBuilder = new StringBuilder();
    if (StringUtils.isNotBlank(serializationParams.getSerializedJSON()))
        stringBuilder.append(serializationParams.getSerializedJSON());

    if (StringUtils.isNotBlank(serializationParams.getWrapPrefix()))
        stringBuilder.insert(0, serializationParams.getWrapPrefix());
    else if (serializationParams.isWrapWithComments()) {
        stringBuilder.insert(0, "/* ");
        stringBuilder.append(" */");
    } else if (serializationParams.isPrefix())
        stringBuilder.insert(0, "{}&& ");

    if (StringUtils.isNotBlank(serializationParams.getWrapSuffix()))
        stringBuilder.append(serializationParams.getWrapSuffix());

    String json = stringBuilder.toString();

    if (LOG.isDebugEnabled()) {
        LOG.debug("[JSON]" + json);
    }/*from w w  w  . jav  a 2  s  .co m*/

    HttpServletResponse response = serializationParams.getResponse();

    // status or error code
    if (serializationParams.getStatusCode() > 0)
        response.setStatus(serializationParams.getStatusCode());
    else if (serializationParams.getErrorCode() > 0)
        response.sendError(serializationParams.getErrorCode());

    // content type
    response.setContentType(
            serializationParams.getContentType() + ";charset=" + serializationParams.getEncoding());

    if (serializationParams.isNoCache()) {
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Expires", "0");
        response.setHeader("Pragma", "No-cache");
    }

    if (serializationParams.isGzip()) {
        response.addHeader("Content-Encoding", "gzip");
        GZIPOutputStream out = null;
        InputStream in = null;
        try {
            out = new GZIPOutputStream(response.getOutputStream());
            in = new ByteArrayInputStream(json.getBytes(serializationParams.getEncoding()));
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        } finally {
            if (in != null)
                in.close();
            if (out != null) {
                out.finish();
                out.close();
            }
        }

    } else {
        response.setContentLength(json.getBytes(serializationParams.getEncoding()).length);
        PrintWriter out = response.getWriter();
        out.print(json);
    }
}

From source file:com.struts2ext.json.JSONUtil.java

public static void writeJSONToResponse(SerializationParams serializationParams) throws IOException {
    StringBuilder stringBuilder = new StringBuilder();
    if (StringUtils.isNotBlank(serializationParams.getSerializedJSON()))
        stringBuilder.append(serializationParams.getSerializedJSON());

    if (StringUtils.isNotBlank(serializationParams.getWrapPrefix()))
        stringBuilder.insert(0, serializationParams.getWrapPrefix());
    else if (serializationParams.isWrapWithComments()) {
        stringBuilder.insert(0, "/* ");
        stringBuilder.append(" */");
    } else if (serializationParams.isPrefix())
        stringBuilder.insert(0, "{}&& ");

    if (StringUtils.isNotBlank(serializationParams.getWrapSuffix()))
        stringBuilder.append(serializationParams.getWrapSuffix());

    String json = stringBuilder.toString();

    if (LOG.isDebugEnabled()) {
        LOG.debug("[JSON]" + json);
    }/*from w w w . j a va  2  s.  co  m*/

    HttpServletResponse response = serializationParams.getResponse();

    // status or error code
    if (serializationParams.getStatusCode() > 0)
        response.setStatus(serializationParams.getStatusCode());
    else if (serializationParams.getErrorCode() > 0)
        response.sendError(serializationParams.getErrorCode());

    // content type
    if (serializationParams.isSmd())
        response.setContentType("application/json-rpc;charset=" + serializationParams.getEncoding());
    else
        response.setContentType(
                serializationParams.getContentType() + ";charset=" + serializationParams.getEncoding());

    if (serializationParams.isNoCache()) {
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Expires", "0");
        response.setHeader("Pragma", "No-cache");
    }

    if (serializationParams.isGzip()) {
        response.addHeader("Content-Encoding", "gzip");
        GZIPOutputStream out = null;
        InputStream in = null;
        try {
            out = new GZIPOutputStream(response.getOutputStream());
            in = new ByteArrayInputStream(json.getBytes(serializationParams.getEncoding()));
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        } finally {
            if (in != null)
                in.close();
            if (out != null) {
                out.finish();
                out.close();
            }
        }

    } else {
        response.setContentLength(json.getBytes(serializationParams.getEncoding()).length);
        PrintWriter out = response.getWriter();
        out.print(json);
    }
}