Example usage for java.lang StringBuilder delete

List of usage examples for java.lang StringBuilder delete

Introduction

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

Prototype

@Override
public StringBuilder delete(int start, int end) 

Source Link

Usage

From source file:net.sf.jabref.sql.exporter.DBExporter.java

/**
 * Generates the SQL required to populate the entry_types table with jabref data.
 *
 * @param out The output (PrintSream or Connection) object to which the DML should be written.
 * @param type//from   ww  w  .  j  av a  2  s .c  o m
 */

private void populateEntryTypesTable(Object out, BibDatabaseMode type) throws SQLException {
    List<String> fieldRequirement = new ArrayList<>();

    List<String> existentTypes = new ArrayList<>();
    if (out instanceof Connection) {
        try (Statement sm = (Statement) SQLUtil.processQueryWithResults(out, "SELECT label FROM entry_types");
                ResultSet rs = sm.getResultSet()) {
            while (rs.next()) {
                existentTypes.add(rs.getString(1));
            }
        }
    }
    for (EntryType val : EntryTypes.getAllValues(type)) {
        StringBuilder querySB = new StringBuilder();

        fieldRequirement.clear();
        for (int i = 0; i < SQLUtil.getAllFields().size(); i++) {
            fieldRequirement.add(i, "gen");
        }
        List<String> reqFields = val.getRequiredFieldsFlat();
        List<String> optFields = val.getOptionalFields();
        List<String> utiFields = Collections.singletonList("search");
        fieldRequirement = SQLUtil.setFieldRequirement(SQLUtil.getAllFields(), reqFields, optFields, utiFields,
                fieldRequirement);
        if (existentTypes.contains(val.getName().toLowerCase())) {
            String[] update = fieldStr.split(",");
            querySB.append("UPDATE entry_types SET \n");
            for (int i = 0; i < fieldRequirement.size(); i++) {
                querySB.append(update[i]).append("='").append(fieldRequirement.get(i)).append("',");
            }
            querySB.delete(querySB.lastIndexOf(","), querySB.length());
            querySB.append(" WHERE label='").append(val.getName().toLowerCase()).append("';");
        } else {
            querySB.append("INSERT INTO entry_types (label, ").append(fieldStr).append(") VALUES ('")
                    .append(val.getName().toLowerCase()).append('\'');
            for (String aFieldRequirement : fieldRequirement) {
                querySB.append(", '").append(aFieldRequirement).append('\'');
            }
            querySB.append(");");
        }
        SQLUtil.processQuery(out, querySB.toString());
    }
}

From source file:com.ultramegatech.ey.ElementDetailsFragment.java

/**
 * Get the electron configuration.//from  ww w .j ava  2 s. co  m
 */
private void getElectronConfiguration() {
    final StringBuilder builder = new StringBuilder();
    final StringBuilder descBuilder = new StringBuilder();

    if (mElement.configuration.baseElement != null) {
        builder.append('[').append(mElement.configuration.baseElement).append("] ");
        final Element baseElement = Elements.getElement(mElement.configuration.baseElement);
        if (baseElement != null) {
            descBuilder.append(getString(ElementUtils.getElementName(baseElement.number)));
            descBuilder.append(", ");
        }
    }

    for (Element.Orbital orbital : mElement.configuration.orbitals) {
        builder.append(orbital.shell).append(orbital.orbital);
        builder.append("<sup><small>").append(orbital.electrons).append("</small></sup> ");
        descBuilder.append(orbital.shell).append(' ');
        descBuilder.append(String.valueOf(orbital.orbital).toUpperCase()).append(' ');
        descBuilder.append(orbital.electrons).append(", ");
    }

    descBuilder.delete(descBuilder.length() - 2, descBuilder.length() - 1);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        mTxtConfiguration.setText(Html.fromHtml(builder.toString().trim(), 0));
        mTxtConfiguration.setContentDescription(Html.fromHtml(descBuilder.toString(), 0));
    } else {
        mTxtConfiguration.setText(Html.fromHtml(builder.toString().trim()));
        mTxtConfiguration.setContentDescription(Html.fromHtml(descBuilder.toString()));
    }
}

From source file:org.apache.hadoop.yarn.server.webapp.AppAttemptBlock.java

@Override
protected void render(Block html) {
    String attemptid = $(APPLICATION_ATTEMPT_ID);
    if (attemptid.isEmpty()) {
        puts("Bad request: requires application attempt ID");
        return;//from   w ww . ja v a2  s  .  com
    }

    try {
        appAttemptId = ApplicationAttemptId.fromString(attemptid);
    } catch (IllegalArgumentException e) {
        puts("Invalid application attempt ID: " + attemptid);
        return;
    }

    UserGroupInformation callerUGI = getCallerUGI();
    ApplicationAttemptReport appAttemptReport;
    try {
        final GetApplicationAttemptReportRequest request = GetApplicationAttemptReportRequest
                .newInstance(appAttemptId);
        if (callerUGI == null) {
            appAttemptReport = appBaseProt.getApplicationAttemptReport(request).getApplicationAttemptReport();
        } else {
            appAttemptReport = callerUGI.doAs(new PrivilegedExceptionAction<ApplicationAttemptReport>() {
                @Override
                public ApplicationAttemptReport run() throws Exception {
                    return appBaseProt.getApplicationAttemptReport(request).getApplicationAttemptReport();
                }
            });
        }
    } catch (Exception e) {
        String message = "Failed to read the application attempt " + appAttemptId + ".";
        LOG.error(message, e);
        html.p()._(message)._();
        return;
    }

    if (appAttemptReport == null) {
        puts("Application Attempt not found: " + attemptid);
        return;
    }

    boolean exceptionWhenGetContainerReports = false;
    Collection<ContainerReport> containers = null;
    try {
        final GetContainersRequest request = GetContainersRequest.newInstance(appAttemptId);
        if (callerUGI == null) {
            containers = appBaseProt.getContainers(request).getContainerList();
        } else {
            containers = callerUGI.doAs(new PrivilegedExceptionAction<Collection<ContainerReport>>() {
                @Override
                public Collection<ContainerReport> run() throws Exception {
                    return appBaseProt.getContainers(request).getContainerList();
                }
            });
        }
    } catch (RuntimeException e) {
        // have this block to suppress the findbugs warning
        exceptionWhenGetContainerReports = true;
    } catch (Exception e) {
        exceptionWhenGetContainerReports = true;
    }

    AppAttemptInfo appAttempt = new AppAttemptInfo(appAttemptReport);

    setTitle(join("Application Attempt ", attemptid));

    String node = "N/A";
    if (appAttempt.getHost() != null && appAttempt.getRpcPort() >= 0 && appAttempt.getRpcPort() < 65536) {
        node = appAttempt.getHost() + ":" + appAttempt.getRpcPort();
    }
    generateOverview(appAttemptReport, containers, appAttempt, node);

    if (exceptionWhenGetContainerReports) {
        html.p()._("Sorry, Failed to get containers for application attempt" + attemptid + ".")._();
        return;
    }

    createAttemptHeadRoomTable(html);
    html._(InfoBlock.class);

    createTablesForAttemptMetrics(html);

    // Container Table
    TBODY<TABLE<Hamlet>> tbody = html.table("#containers").thead().tr().th(".id", "Container ID")
            .th(".node", "Node").th(".exitstatus", "Container Exit Status").th(".logs", "Logs")._()._().tbody();

    StringBuilder containersTableData = new StringBuilder("[\n");
    for (ContainerReport containerReport : containers) {
        ContainerInfo container = new ContainerInfo(containerReport);
        containersTableData.append("[\"<a href='").append(url("container", container.getContainerId()))
                .append("'>").append(container.getContainerId()).append("</a>\",\"<a ")
                .append(container.getNodeHttpAddress() == null ? "#"
                        : "href='" + container.getNodeHttpAddress())
                .append("'>")
                .append(container.getNodeHttpAddress() == null ? "N/A"
                        : StringEscapeUtils
                                .escapeJavaScript(StringEscapeUtils.escapeHtml(container.getNodeHttpAddress())))
                .append("</a>\",\"").append(container.getContainerExitStatus()).append("\",\"<a href='")
                .append(container.getLogUrl() == null ? "#" : container.getLogUrl()).append("'>")
                .append(container.getLogUrl() == null ? "N/A" : "Logs").append("</a>\"],\n");
    }
    if (containersTableData.charAt(containersTableData.length() - 2) == ',') {
        containersTableData.delete(containersTableData.length() - 2, containersTableData.length() - 1);
    }
    containersTableData.append("]");
    html.script().$type("text/javascript")._("var containersTableData=" + containersTableData)._();

    tbody._()._();
}

From source file:com.norconex.importer.handler.transformer.impl.StripBetweenTransformer.java

@Override
protected void transformStringContent(String reference, StringBuilder content, ImporterMetadata metadata,
        boolean parsed, boolean partialContent) {
    int flags = Pattern.DOTALL | Pattern.UNICODE_CASE;
    if (!caseSensitive) {
        flags = flags | Pattern.CASE_INSENSITIVE;
    }/*from   w w w  .ja  v a2  s . c o m*/
    for (Pair<String, String> pair : stripPairs) {
        List<Pair<Integer, Integer>> matches = new ArrayList<Pair<Integer, Integer>>();
        Pattern leftPattern = Pattern.compile(pair.getLeft(), flags);
        Matcher leftMatch = leftPattern.matcher(content);
        while (leftMatch.find()) {
            Pattern rightPattern = Pattern.compile(pair.getRight(), flags);
            Matcher rightMatch = rightPattern.matcher(content);
            if (rightMatch.find(leftMatch.end())) {
                if (inclusive) {
                    matches.add(new ImmutablePair<Integer, Integer>(leftMatch.start(), rightMatch.end()));
                } else {
                    matches.add(new ImmutablePair<Integer, Integer>(leftMatch.end(), rightMatch.start()));
                }
            } else {
                break;
            }
        }
        for (int i = matches.size() - 1; i >= 0; i--) {
            Pair<Integer, Integer> matchPair = matches.get(i);
            content.delete(matchPair.getLeft(), matchPair.getRight());
        }
    }
}

From source file:nl.strohalm.cyclos.utils.logging.LoggingHandler.java

private LoggingHandler append(final StringBuilder builder, final ServiceClient serviceClient) {
    builder.append("Web Service Client: ");
    if (serviceClient != null) {
        builder.append(serviceClient.getName()).append(", Host Name: ").append(serviceClient.getHostname());
        builder.append(", Channel: ");
        builder.append(//from   w  w  w  . j  av a  2  s .c  om
                serviceClient.getChannel() == null ? " null " : serviceClient.getChannel().getInternalName());
        builder.append(", Permissions [");
        final Iterator<ServiceOperation> it = serviceClient.getPermissions().iterator();
        while (it.hasNext()) {
            builder.append(it.next().name()).append(", ");
        }
        if (!serviceClient.getPermissions().isEmpty()) {
            builder.delete(builder.length() - 2, builder.length()); // removes the last ', '
        }
        builder.append("], Restricted User: ");
        builder.append(serviceClient.getMember() == null ? " null " : serviceClient.getMember().getUsername());
    } else {
        builder.append(" null ");
    }

    return this;
}

From source file:com.spd.ukraine.lucenewebsearch1.web.IndexingController.java

private String truncateText(String text, String phrase) {
    StringBuilder inputPhrase = new StringBuilder();
    //        try {
    //            URL url = new URL(text);
    //            BufferedReader in = new BufferedReader(new InputStreamReader(url
    //                    .openStream()));
    //            String inputLine;
    //            while ((inputLine = in.readLine()) != null) {
    //                inputPhrase.append(inputLine);
    //                if (inputPhrase.toString().contains(phrase)
    //                        && inputPhrase.length() > MAX_WINDOW_SIZE) {
    //                    break;
    //                }
    //            }
    //            in.close();
    //        } catch (IOException ex) {
    //            return "";
    //        }//from  w  w  w.  java  2s  . c o  m
    inputPhrase = new StringBuilder(text);
    String lowerText = text.toLowerCase();
    int pos = lowerText.indexOf(phrase);
    try {
        inputPhrase.delete(0, Math.max(0, pos - MAX_WINDOW_SIZE))
                .delete(Math.min(pos + MAX_WINDOW_SIZE, inputPhrase.length()), inputPhrase.length());
    } catch (StringIndexOutOfBoundsException e) {
        System.out.println("pos - MAX_WINDOW_SIZE " + (pos - MAX_WINDOW_SIZE));
        System.out.println("pos + MAX_WINDOW_SIZE " + (pos + MAX_WINDOW_SIZE) + " < " + inputPhrase.length());
        System.out.println(e.getMessage() + " text " + text);
    }
    return highLightPhrase(inputPhrase.toString(), phrase);
}

From source file:org.jahia.modules.sociallib.SocialService.java

public void removeSocialConnection(final String fromUuid, final String toUuid, final String connectionType)
        throws RepositoryException {

    execute(new JCRCallback<Boolean>() {
        public Boolean doInJCR(JCRSessionWrapper session) throws RepositoryException {

            QueryManager queryManager = session.getWorkspace().getQueryManager();

            // first we look for the first connection.
            StringBuilder q = new StringBuilder(64);
            q.append("select * from [" + JNT_SOCIAL_CONNECTION + "] where [j:connectedFrom]='").append(fromUuid)
                    .append("' and [j:connectedTo]='").append(toUuid).append("'");
            if (StringUtils.isNotEmpty(connectionType)) {
                q.append(" and [j:type]='").append(connectionType).append("'");
            }/*  w  w w.  j  a  v a2 s .c  o  m*/
            Query connectionQuery = queryManager.createQuery(q.toString(), Query.JCR_SQL2);
            QueryResult connectionResult = connectionQuery.execute();
            NodeIterator connectionIterator = connectionResult.getNodes();
            while (connectionIterator.hasNext()) {
                Node connectionNode = connectionIterator.nextNode();
                session.checkout(connectionNode.getParent());
                connectionNode.remove();
            }

            // now let's remove the reverse connection.
            q.delete(0, q.length());
            q.append("select * from [" + JNT_SOCIAL_CONNECTION + "] where [j:connectedFrom]='").append(toUuid)
                    .append("' and [j:connectedTo]='").append(fromUuid).append("'");
            if (StringUtils.isNotEmpty(connectionType)) {
                q.append(" and [j:type]='").append(connectionType).append("'");
            }
            Query reverseConnectionQuery = queryManager.createQuery(q.toString(), Query.JCR_SQL2);
            QueryResult reverseConnectionResult = reverseConnectionQuery.execute();
            NodeIterator reverseConnectionIterator = reverseConnectionResult.getNodes();
            while (reverseConnectionIterator.hasNext()) {
                Node connectionNode = reverseConnectionIterator.nextNode();
                session.checkout(connectionNode.getParent());
                connectionNode.remove();
            }

            session.save();
            return true;
        }
    });
}

From source file:ca.queensu.cs.sail.mailboxmina2.main.modules.ThreadsModule.java

/**
 * This method stores the root associations of a roots table into the database
 * @param roots a list of roots associations
 * @throws SQLException//from  w  ww.j  a  v a  2 s .  c o m
 */
private void storeRoots(Hashtable<String, String> roots, Connection connection) throws SQLException {
    // Use StringBuilders to create big insertion queries

    StringBuilder rootQueryBuilder = new StringBuilder();

    // Queries use the pgpsql functions
    // merge_parent(int msg_uid, int parent_uid)
    // merge_root(int msg_uid, int root_uid)
    // that take care of insertion / update automatically

    rootQueryBuilder.append("PREPARE rootplan (int, int) AS SELECT merge_root($1, $2);");
    // Genereate the roots query
    int i = 0;
    for (String key : roots.keySet()) {
        rootQueryBuilder.append("EXECUTE rootplan (" + key + ", " + roots.get(key) + ");"
                + System.getProperty("line.separator"));
        i++;
        if ((i % 1000) == 0) {
            i = 0;
            rootQueryBuilder.append("DEALLOCATE rootplan;" + System.getProperty("line.separator"));
            String sqlstr = rootQueryBuilder.toString();
            Statement statement = connection.createStatement();
            statement.execute(sqlstr);
            statement.close();
            rootQueryBuilder.delete(0, rootQueryBuilder.length());
            rootQueryBuilder.append("PREPARE rootplan (int, int) AS SELECT merge_root($1, $2);");
            Main.getLogger().debug(4, "Stored 1000 root relations!");
        }
    }
    if (i > 0) {
        rootQueryBuilder.append("DEALLOCATE rootplan;" + System.getProperty("line.separator"));
        String sqlstr = rootQueryBuilder.toString();
        Statement statement = connection.createStatement();
        statement.execute(sqlstr);
        statement.close();
        Main.getLogger().debug(4, "Stored " + i + " root relations!");
    }
}

From source file:br.com.nordestefomento.jrimum.bopepo.view.ViewerPDF.java

private void setEndereco(Endereco endereco, String campoEndereco1, String campoEndereco2, StringBuilder sb)
        throws IOException, DocumentException {

    if (isNotNull(endereco)) {

        if (isNotNull(endereco.getBairro())) {
            sb.append(endereco.getBairro());
        }//from   w  ww. j  ava2 s  .c  om

        if (isNotNull(endereco.getLocalidade())) {
            sb.append(HIFEN_SEPERADOR);
            sb.append(endereco.getLocalidade());
        }

        if (isNotNull(endereco.getUF())) {
            sb.append(" / ");
            sb.append(endereco.getUF().getNome());
        }

        form.setField(campoEndereco1, sb.toString());

        sb.delete(0, sb.length());

        if (isNotNull(endereco.getLogradouro())) {
            sb.append(endereco.getLogradouro());
        }

        if (isNotNull(endereco.getNumero())) {
            sb.append(", n: ");
            sb.append(endereco.getNumero());
        }

        if (isNotNull(endereco.getCEP())) {
            sb.append(" ");
            sb.append(HIFEN_SEPERADOR);
            sb.append(" CEP: ");
            sb.append(endereco.getCEP().getCep());
        }

        form.setField(campoEndereco2, sb.toString());
    }
}

From source file:ca.queensu.cs.sail.mailboxmina2.main.modules.ThreadsModule.java

/**
 * This method stores associations of parents given as Hash Table
 * in the Database//from   ww w.ja v  a2 s .c  o m
 * 
 * @param parents
 *            a table that maps for every method having a parent this
 *            parent's ID
 * @throws SQLException
 */
private void storeParents(Hashtable<String, String> parents, Connection connection) throws SQLException {
    // Use StringBuilders to create big insertion queries

    StringBuilder parentQueryBuilder = new StringBuilder();

    // Queries use the pgpsql functions
    // merge_parent(int msg_uid, int parent_uid)
    // merge_root(int msg_uid, int root_uid)
    // that take care of insertion / update automatically

    parentQueryBuilder.append("PREPARE parentplan (int, int) AS SELECT merge_parent($1, $2);");
    // Genereate the parents query
    int i = 0;
    for (String key : parents.keySet()) {
        parentQueryBuilder.append("EXECUTE parentplan (" + key + ", " + parents.get(key) + ");"
                + System.getProperty("line.separator"));
        i++;
        if ((i % 1000) == 0) {
            i = 0;
            parentQueryBuilder.append("DEALLOCATE parentplan;" + System.getProperty("line.separator"));
            String sqlstr = parentQueryBuilder.toString();
            Statement statement = connection.createStatement();
            statement.execute(sqlstr);
            statement.close();
            parentQueryBuilder.delete(0, parentQueryBuilder.length());
            parentQueryBuilder.append("PREPARE parentplan (int, int) AS SELECT merge_parent($1, $2);");
            Main.getLogger().debug(4, "Stored 1000 parent relations!");
        }
    }
    if (i > 0) {
        parentQueryBuilder.append("DEALLOCATE parentplan;" + System.getProperty("line.separator"));
        String sqlstr = parentQueryBuilder.toString();
        Statement statement = connection.createStatement();
        statement.execute(sqlstr);
        statement.close();
        Main.getLogger().debug(4, "Stored " + i + " parent relations!");
    }
}