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:eu.semlibproject.annotationserver.restapis.APIHelper.java

/**
 * Prepare a SPARQL query to be executed on the internal SPARQL end-point
 * /*from  w  w w .  j  av a  2s .  co m*/
 * @param query             the SPARQL query
 * @param annotationsIDs    the list of all annotations ID in a Notebooks
 * @return                  the prepared query
 */
public String prepareQueryForNotebooksSPARQLEndPoint(String query, List<String> annotationsIDs) {

    String froms = "";
    String fromNameds = "";

    for (String annID : annotationsIDs) {
        String annotationGraph = Annotation.getGraphURIFromID(annID);
        String itemGraph = Annotation.getItemsGraphURIFormID(annID);
        froms += "FROM <" + annotationGraph + "> FROM <" + itemGraph + "> ";
        fromNameds += "FROM NAMED <" + annotationGraph + "> FROM NAMED <" + itemGraph + "> ";
    }

    String finalFroms = " " + froms + fromNameds;

    // Remove any existing FROM and FROM NAMED from the original query
    int startIndex = -1;
    Pattern regExPattern = Pattern.compile("(FROM <.+>\\s*|FROM NAMED <.+>\\s*)+", Pattern.CASE_INSENSITIVE);
    Matcher matcher = regExPattern.matcher(query);

    if (matcher.find()) {
        startIndex = matcher.start();
        String cleanQuery = matcher.replaceAll("");

        StringBuilder finalQuery = new StringBuilder(cleanQuery);
        finalQuery.insert(startIndex, finalFroms);

        return finalQuery.toString();
    } else {
        int indexOfWhere = query.toLowerCase().indexOf("where");
        StringBuilder strBuilder = new StringBuilder(query);
        strBuilder.insert(indexOfWhere, finalFroms);
        return strBuilder.toString();
    }
}

From source file:com.haulmont.cuba.core.sys.remoting.RemotingServlet.java

/**
 * Check correctness of some configuration parameters and log the warning if necessary.
 *//*w w  w  . j ava 2 s  . c  om*/
protected void checkConfiguration(HttpServletRequest request) {
    if (!checkCompleted) {
        GlobalConfig config = AppBeans.get(Configuration.class).getConfig(GlobalConfig.class);
        if (config.getLogIncorrectWebAppPropertiesEnabled()) {
            StringBuilder sb = new StringBuilder();
            if (!request.getServerName().equals(config.getWebHostName())) {
                sb.append("***** cuba.webHostName=").append(config.getWebHostName()).append(", actual=")
                        .append(request.getServerName()).append("\n");
            }
            if (request.getServerPort() != Integer.parseInt(config.getWebPort())) {
                sb.append("***** cuba.webPort=").append(config.getWebPort()).append(", actual=")
                        .append(request.getServerPort()).append("\n");
            }
            String contextPath = request.getContextPath();
            if (contextPath.startsWith("/"))
                contextPath = contextPath.substring(1);
            if (!contextPath.equals(config.getWebContextName())) {
                sb.append("***** cuba.webContextName=").append(config.getWebContextName()).append(", actual=")
                        .append(contextPath).append("\n");
            }
            if (sb.length() > 0) {
                sb.insert(0, "\n*****\n");
                sb.append("*****");
                log.warn(" Invalid configuration parameters that may cause problems:" + sb.toString());
            }
        }
        checkCompleted = true;
    }
}

From source file:com.android.mms.service.http.NetworkAwareHttpClient.java

/**
 * Generates a cURL command equivalent to the given request.
 *//*from w w w  . java2 s .  co  m*/
private static String toCurl(HttpUriRequest request, boolean logAuthToken) throws IOException {
    StringBuilder builder = new StringBuilder();

    builder.append("curl ");

    // add in the method
    builder.append("-X ");
    builder.append(request.getMethod());
    builder.append(" ");

    for (Header header : request.getAllHeaders()) {
        if (!logAuthToken && (header.getName().equals("Authorization") || header.getName().equals("Cookie"))) {
            continue;
        }
        builder.append("--header \"");
        builder.append(header.toString().trim());
        builder.append("\" ");
    }

    URI uri = request.getURI();

    // If this is a wrapped request, use the URI from the original
    // request instead. getURI() on the wrapper seems to return a
    // relative URI. We want an absolute URI.
    if (request instanceof RequestWrapper) {
        HttpRequest original = ((RequestWrapper) request).getOriginal();
        if (original instanceof HttpUriRequest) {
            uri = ((HttpUriRequest) original).getURI();
        }
    }

    builder.append("\"");
    builder.append(uri);
    builder.append("\"");

    if (request instanceof HttpEntityEnclosingRequest) {
        HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request;
        HttpEntity entity = entityRequest.getEntity();
        if (entity != null && entity.isRepeatable()) {
            if (entity.getContentLength() < 1024) {
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                entity.writeTo(stream);

                if (isBinaryContent(request)) {
                    String base64 = Base64.encodeToString(stream.toByteArray(), Base64.NO_WRAP);
                    builder.insert(0, "echo '" + base64 + "' | base64 -d > /tmp/$$.bin; ");
                    builder.append(" --data-binary @/tmp/$$.bin");
                } else {
                    String entityString = stream.toString();
                    builder.append(" --data-ascii \"").append(entityString).append("\"");
                }
            } else {
                builder.append(" [TOO MUCH DATA TO INCLUDE]");
            }
        }
    }

    return builder.toString();
}

From source file:com.haulmont.cuba.gui.data.impl.AbstractCollectionDatasource.java

protected DataLoadContextQuery createDataQuery(DataLoadContext context, Map<String, Object> params) {
    DataLoadContextQuery q = null;//from ww  w.j  ava 2 s .c  o m
    if (query != null && queryParameters != null) {
        Map<String, Object> parameters = getQueryParameters(params);
        for (ParameterInfo info : queryParameters) {
            if (ParameterInfo.Type.DATASOURCE.equals(info.getType())) {
                Object value = parameters.get(info.getFlatName());
                if (value == null) {
                    String[] pathElements = info.getPath().split("\\.");
                    if (pathElements.length == 1) {
                        //nothing selected in 'master' datasource, so return null here to clear the 'detail' datasource
                        return null;
                    } else {
                        //The parameter with null value is the path to the datasource item property,
                        //e.g. :ds$User.group.id.
                        //If the 'master' datasource item is not null then do not clear the 'detail' datasource,
                        //a null query parameter value should be processed
                        String dsName = pathElements[0];
                        final Datasource datasource = dsContext.get(dsName);
                        if (datasource == null) {
                            throw new DevelopmentException("Datasource '" + dsName + "' not found in dsContext",
                                    "datasource", dsName);
                        }
                        if (datasource.getState() != State.VALID || datasource.getItem() == null)
                            return null;
                    }
                }
            }
        }

        String queryString = getJPQLQuery(getTemplateParams(params));
        q = context.setQueryString(queryString);
        // Pass only parameters used in the resulting query
        QueryParser parser = QueryTransformerFactory.createParser(queryString);
        Set<String> paramNames = parser.getParamNames();
        for (Map.Entry<String, Object> entry : parameters.entrySet()) {
            if (paramNames.contains(entry.getKey()))
                q.setParameter(entry.getKey(), entry.getValue());
        }
    } else if (!(context instanceof ValueLoadContext)) {
        Collection<MetaProperty> properties = metadata.getTools().getNamePatternProperties(metaClass);
        if (!properties.isEmpty()) {
            StringBuilder orderBy = new StringBuilder();
            for (MetaProperty metaProperty : properties) {
                if (metaProperty != null && metaProperty.getAnnotatedElement()
                        .getAnnotation(com.haulmont.chile.core.annotations.MetaProperty.class) == null)
                    orderBy.append("e.").append(metaProperty.getName()).append(", ");
            }
            if (orderBy.length() > 0) {
                orderBy.delete(orderBy.length() - 2, orderBy.length());
                orderBy.insert(0, " order by ");
            }
            q = context.setQueryString("select e from " + metaClass.getName() + " e" + orderBy.toString());
        } else
            q = context.setQueryString("select e from " + metaClass.getName() + " e");
    }
    if (q instanceof LoadContext.Query) {
        ((LoadContext.Query) q).setCacheable(isCacheable());
    }
    return q;
}

From source file:com.mediaworx.intellij.opencmsplugin.sync.SyncJob.java

private void doExportPointHandling(ExportEntity entity) {
    StringBuilder confirmation = new StringBuilder();
    StringBuilder notice = new StringBuilder();

    if (!entity.isToBeDeleted()) {
        confirmation.append("Copy of ").append(entity.getVfsPath()).append(" to ")
                .append(entity.getDestination()).append(" - ");
        File file = new File(entity.getSourcePath());
        if (file.exists()) {
            if (file.isFile()) {
                try {
                    FileUtils.copyFile(file, new File(entity.getTargetPath()));
                    confirmation.append("SUCCESS");
                } catch (IOException e) {
                    confirmation.insert(0, ERROR_PREFIX);
                    confirmation.append("FAILED (").append(e.getMessage()).append(")");
                }/*ww  w.  j av a 2s .  com*/
            } else if (file.isDirectory()) {
                try {
                    FileUtils.copyDirectory(file, new File(entity.getTargetPath()));
                    confirmation.append("SUCCESS");
                } catch (IOException e) {
                    confirmation.insert(0, ERROR_PREFIX);
                    confirmation.append("FAILED (").append(e.getMessage()).append(")");
                }
            }
        } else {
            confirmation.append(" - FILE NOT FOUND");
        }
    } else {
        String targetPath = entity.getTargetPath();
        String vfsPath = entity.getVfsPath();

        deleteExportedResource(vfsPath, targetPath, confirmation, notice);
    }
    if (confirmation.indexOf(ERROR_PREFIX) > -1) {
        console.error(confirmation.toString());
    } else {
        console.info(confirmation.toString());
    }
    if (notice.length() > 0) {
        console.notice(notice.toString());
    }
}

From source file:com.pinterest.deployservice.db.DeployQueryFilter.java

public void generateClauseAndValues() {
    this.values = new ArrayList<>();
    StringBuilder sb = new StringBuilder();

    sb = appendSubQuery(sb, "env_id", filter.getEnvIds());
    sb = appendSubQuery(sb, "operator", filter.getOperators());
    sb = appendSubQueryEnum(sb, "deploy_type", filter.getDeployTypes());
    sb = appendSubQueryEnum(sb, "state", filter.getDeployStates());
    sb = appendSubQueryEnum(sb, "acc_status", filter.getAcceptanceStatuss());
    sb = appendSubQuery(sb, "scm_commit", filter.getCommit());
    sb = appendSubQuery(sb, "scm_repo", filter.getRepo());
    sb = appendSubQuery(sb, "scm_branch", filter.getBranch());

    if (filter.getCommitDate() != null) {
        sb.append("commit_date>=? AND ");
        values.add(filter.getCommitDate());
    }/* ww w.  ja  va2s  . co m*/

    if (filter.getBefore() != null) {
        sb.append("start_date<=? AND ");
        values.add(filter.getBefore());
    }

    if (filter.getAfter() != null) {
        sb.append("start_date>=? AND ");
        values.add(filter.getAfter());
    }

    if (sb.length() > 1) {
        // remove the trialing AND and space
        sb.setLength(sb.length() - 4);
        sb.insert(0, "WHERE ");
    }

    if (filter.getOldestFirst() != null && filter.getOldestFirst()) {
        sb.append("ORDER BY start_date ASC LIMIT ?,?");
    } else {
        sb.append("ORDER BY start_date DESC LIMIT ?,?");
    }

    values.add((filter.getPageIndex() - 1) * filter.getPageSize());
    values.add(filter.getPageSize());

    this.whereClause = sb.toString();
}

From source file:net.yacy.search.query.QueryGoal.java

private StringBuilder getGoalQuery() {
    int wc = 0;//from w  w w  .jav a2s.  c  o  m
    StringBuilder w = new StringBuilder(80);
    for (String s : include_strings) {
        if (Segment.catchallString.equals(s))
            continue;
        if (wc > 0)
            w.append(" AND ");
        if (s.indexOf('~') >= 0 || s.indexOf('*') >= 0 || s.indexOf('?') >= 0)
            w.append(s);
        else
            w.append(dq).append(s).append(dq);
        wc++;
    }
    for (String s : exclude_strings) {
        if (wc > 0)
            w.append(" AND -");
        if (s.indexOf('~') >= 0 || s.indexOf('*') >= 0 || s.indexOf('?') >= 0)
            w.append(s);
        else
            w.append(dq).append(s).append(dq);
        wc++;
    }
    if (wc > 1) {
        w.insert(0, '(');
        w.append(')');
    }
    return w;
}

From source file:net.solarnetwork.node.setup.obr.OBRPluginService.java

private OBRPluginProvisionStatus resolveInstall(Collection<String> uids, Locale locale, String provisionID) {
    if (uids == null || uids.size() < 1 || repositoryAdmin == null) {
        return new OBRPluginProvisionStatus(PREVIEW_PROVISION_ID);
    }// ww w  . j ava2s. c om

    // get a list of the Resources we want to install
    SearchFilter filter = filterForPluginUIDs(uids);
    Resource[] resources = repositoryAdmin.discoverResources(filter.asLDAPSearchFilterString());
    if (resources == null || resources.length < 1) {
        return new OBRPluginProvisionStatus(PREVIEW_PROVISION_ID);
    }

    // filter out duplicate, older versions
    resources = getLatestVersions(resources);

    // resolve the complete list of resources we need
    Resolver resolver = repositoryAdmin.resolver();
    for (Resource r : resources) {
        resolver.add(r);
    }
    final boolean success = resolver.resolve();
    if (!success) {
        StringBuilder buf = new StringBuilder();
        Requirement[] failures = resolver.getUnsatisfiedRequirements();
        // TODO: l10n
        if (failures != null && failures.length > 0) {
            for (Requirement r : failures) {
                if (buf.length() > 0) {
                    buf.append(", ");
                }
                buf.append(r.getName());
                if (r.getComment() != null && r.getComment().length() > 0) {
                    buf.append(" (").append(r.getComment()).append(")");
                }
            }
            if (failures.length == 1) {
                buf.insert(0, "The following requirement is not satisfied: ");
            } else {
                buf.insert(0, "The following requirements are not satisfied: ");
            }
        } else {
            buf.append("Unknown error");
        }
        throw new PluginProvisionException(buf.toString());
    }
    Resource[] requiredResources = resolver.getRequiredResources();
    List<Plugin> toInstall = new ArrayList<Plugin>(resources.length + requiredResources.length);
    for (Resource r : resources) {
        toInstall.add(new OBRResourcePlugin(r,
                (StringUtils.matches(coreFeatureSymbolicNamePatterns, r.getSymbolicName()) != null)));
    }
    for (Resource r : requiredResources) {
        toInstall.add(new OBRResourcePlugin(r,
                (StringUtils.matches(coreFeatureSymbolicNamePatterns, r.getSymbolicName()) != null)));
    }
    OBRPluginProvisionStatus result = new OBRPluginProvisionStatus(provisionID);
    result.setPluginsToInstall(toInstall);
    return result;
}

From source file:com.arksoft.epamms.EpammsTest.java

@Test
public void testStringBuilder() {
    StringBuilder sb1 = new StringBuilder();
    int capacity = 50;
    StringBuilder sb2 = new StringBuilder(capacity);
    String myString = "To be or not to be";
    StringBuilder sb3 = new StringBuilder(myString);
    int startIndex = 0;
    int stringLength = myString.length();

    displayProperties("sb1", sb1);
    displayProperties("sb2", sb2);
    displayProperties("sb3", sb3);

    sb3.insert(9, "NOT"); // doesn't do quite what I expected
    displayProperties("sb3", sb3);
}