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:com.nway.spring.jdbc.SqlExecutor.java

/**
 *
 * @param sql//from   w w  w . java2 s  .  co  m
 *            SQL
 * @return
 */
private String buildPaginationCountSql(String sql) {

    StringBuilder countSql = new StringBuilder(sql);

    if (SQL_ORDER_BY_PATTERN.matcher(countSql).matches()) {

        countSql.delete(countSql.lastIndexOf(" ORDER "), countSql.length());
    }

    int firstFromIndex = firstFromIndex(sql, 0);

    String selectedColumns = countSql.substring(0, firstFromIndex + 1);

    if (selectedColumns.indexOf(" DISTINCT ") == -1 && !SQL_TOP_PATTERN.matcher(selectedColumns).matches()) {

        countSql = countSql.delete(0, firstFromIndex).insert(0, "SELECT COUNT(1)");
    } else {

        countSql.insert(0, "SELECT COUNT(1) FROM (").append(')');
    }

    return countSql.toString();
}

From source file:com.openteach.diamond.network.waverider.network.Packet.java

public void dump() {
    logger.info(//  w  w w .  ja  v  a 2s  . com
            "==========================================================================dump packet==========================================================================");
    logger.info(new StringBuilder("== magic:").append(magic));
    logger.info(new StringBuilder("== sequence:").append(sequence));
    logger.info(new StringBuilder("== type:").append(type));
    logger.info(new StringBuilder("== length:").append(length));
    logger.info(new StringBuilder("== payLoad Size:").append(payLoad.remaining()));
    logger.info(new StringBuilder("== binary:"));
    byte[] buffer = this.copy().marshall().array();
    StringBuilder sb = new StringBuilder("== ");
    for (int i = 0; i < buffer.length; i++) {
        sb.append(buffer[i]);
        if (i % 80 == 0 && i > 0) {
            logger.info(sb);
            sb.delete(0, sb.length());
        }
    }
    logger.info(
            "========================================================================dump packet end========================================================================");
}

From source file:kilim.tools.DumpClass.java

public void visitFrame(int type, int nLocal, Object[] local, int nStack, Object[] stack) {
    pn("; Frame " + type);

    p(";  Locals - ");
    StringBuilder print = new StringBuilder();
    for (int i = 0; i < nLocal; i++) {
        Object o = local[i];/*  w  w w  .ja  va2s .c  o m*/
        print.append("#" + i + "." + type(o) + "  ");
    }
    log.info(print);
    p(";  Stack - ");
    print.delete(0, print.length());
    for (int i = 0; i < nStack; i++) {
        Object o = stack[i];
        print.append("#" + i + "." + type(o) + "  ");
    }
    log.info(print);
}

From source file:cn.calm.osgi.conter.FelixOsgiHost.java

protected void addExportedPackages(Properties strutsConfigProps, Properties configProps) {
    String[] rootPackages = StringUtils.split(strutsConfigProps.getProperty("scanning.package.includes"), ",");
    List<String> exportedPackages = new ArrayList<String>();
    // build a list of subpackages
    StringBuilder strB = new StringBuilder();
    //      org.osgi.framework;version="[1.4,2)"
    for (String rootPackage : rootPackages) {
        String sp[] = StringUtils.split(rootPackage, ";");
        strB.delete(0, strB.length());
        strB.append(sp[0]);//w  ww  . j a  v a2  s.  c  om
        strB.append(";version=\"");
        try {
            strB.append(sp[1]);
        } catch (Exception e) {
            strB.append("0.0.0");
        }
        strB.append("\"");
        exportedPackages.add(strB.toString());
    }
    //
    //      // make a string with the exported packages and add it to the system
    //      // properties
    if (!exportedPackages.isEmpty()) {
        String systemPackages = (String) configProps.get(Constants.FRAMEWORK_SYSTEMPACKAGES);
        systemPackages = StringUtils.removeEnd(systemPackages, ",") + ","
                + StringUtils.join(exportedPackages, ",");
        configProps.put(Constants.FRAMEWORK_SYSTEMPACKAGES, systemPackages);
    }
    System.out.println(exportedPackages);
}

From source file:inti.ws.spring.resource.template.TemplateResource.java

@Override
public void update() throws Exception {
    ExpressionFactory factory;//from w w w  .  j  a  va2s. c om
    ValueExpression var;
    Object val;
    StringBuilder builder = new StringBuilder(2048);
    MessageDigest digest = DIGESTS.get();

    factory = ExpressionFactory.newInstance();

    for (WebResource file : files) {
        if (file.hasChanged()) {
            file.update();
        }
        builder.append(applyTemplate(factory, file.getName(), file.getContent().replaceAll("\\s+", " ")));
        builder.append(',');
    }
    builder.delete(builder.length() - 1, builder.length());

    super.update();

    content = factory.createValueExpression(context, compressedFile, String.class);

    var = factory.createValueExpression(context, "${files}", String.class);
    var.setValue(context, builder.toString());

    if (parameters != null) {

        for (Map.Entry<String, Object> parameter : parameters.entrySet()) {
            var = factory.createValueExpression(context, "${" + parameter.getKey() + '}', String.class);
            val = parameter.getValue();

            if ("$filename".equals(val)) {
                val = resource.getFile();
            } else if ("$modulename".equals(val)) {
                val = moduleName;
            }

            var.setValue(context, val);
        }

    }
    compressedFile = (String) content.getValue(context);
    builder.delete(0, builder.length());

    digest.reset();
    builder.append(Hex.encodeHexString(digest.digest(compressedFile.getBytes(StandardCharsets.UTF_8))));
    messageDigest = builder.toString();
    builder.delete(0, builder.length());

    DATE_FORMATTER.formatDate(lastModified, builder);
    lastModifiedString = builder.toString();
}

From source file:com.flexive.core.conversion.FxValueConverter.java

/**
 * {@inheritDoc}//from  w  w  w.  jav  a2 s .c om
 */
@Override
@SuppressWarnings("unchecked")
public void marshal(Object o, HierarchicalStreamWriter writer, MarshallingContext ctx) {
    FxValue value = (FxValue) o;
    writer.addAttribute("t", value.getClass().getSimpleName());
    writer.addAttribute("ml", String.valueOf(value.isMultiLanguage()));
    final FxEnvironment env = CacheAdmin.getEnvironment();
    try {
        writer.addAttribute("dl", ConversionEngine.getLang(env, value.getDefaultLanguage()));
        if (!value.isEmpty()) {
            for (long lang : value.getTranslatedLanguages()) {
                writer.startNode("d");
                writer.addAttribute("l", ConversionEngine.getLang(env, lang));
                if (value instanceof FxBinary) {
                    marshalBinary(writer, ctx, (FxBinary) value, lang);
                } else if (value instanceof FxSelectOne) { //format LISTNAME.ITEMNAME
                    final FxSelectOne v = (FxSelectOne) value;
                    writer.setValue(v.getSelectList().getName() + "." + v.getTranslation(lang).getName());
                } else if (value instanceof FxSelectMany) { //format LISTNAME.ITEMNAME, LISTNAME.ITEMNAME
                    final FxSelectMany v = (FxSelectMany) value;
                    StringBuilder sb = new StringBuilder(500);
                    for (FxSelectListItem item : v.getTranslation(lang).getSelected())
                        sb.append(item.getList().getName()).append('.').append(item.getName()).append(", ");
                    if (sb.length() > 0)
                        sb.delete(sb.length() - 2, sb.length());
                    writer.setValue(sb.toString());
                } else
                    writer.setValue(value.getPortableStringValue(value.getTranslation(lang)));
                writer.endNode();
            }
        } else
            writer.addAttribute("empty", "true");
    } catch (FxApplicationException e) {
        throw e.asRuntimeException();
    }
}

From source file:deus.common.AbstractSubsystemAssemblyTest.java

/**
 * Test integration.//from   ww w  .  ja  va 2 s.  com
 */
@Test
public void testIntegration() {
    AbstractSubsystemAssemblyTest.logger
            .info("loaded Spring beans: " + Arrays.toString(this.context.getBeanDefinitionNames()));

    final StringBuilder loadedDomainBeans = new StringBuilder();

    final String[] names = this.context.getBeanDefinitionNames();
    for (final String name : names) {
        final Object bean = this.context.getBean(name);
        if ((bean.getClass().getPackage() != null)
                && bean.getClass().getPackage().getName().startsWith(this.subsystemBasePackage)) {
            loadedDomainBeans.append(name + ", ");
        }
    }

    final int l = loadedDomainBeans.length();
    if (l > 0) {
        loadedDomainBeans.delete(l - 2, l);
    }
    AbstractSubsystemAssemblyTest.logger.info("loaded domain beans: [" + loadedDomainBeans.toString() + "]");
}

From source file:fr.paris.lutece.plugins.workflow.modules.fillingdirectory.service.TaskFillingDirectory.java

/**
 * {@inheritDoc}//from   w  w w.  ja  v a2 s .co m
 */
@Override
public void processTask(int nIdResourceHistory, HttpServletRequest request, Locale locale) {
    Plugin plugin = PluginService.getPlugin(FillingDirectoryPlugin.PLUGIN_NAME);
    TaskFillingDirectoryConfig config = _taskFillingDirectoryConfigService.findByPrimaryKey(this.getId());
    String strIdEntryTypeFile = AppPropertiesService.getProperty(PROPERTY_ID_ENTRY_TYPE_FILE);
    String strIdEntryTypeImg = AppPropertiesService.getProperty(PROPERTY_ID_ENTRY_TYPE_IMG);
    String strIdEntryTypeCheckBox = AppPropertiesService.getProperty(PROPERTY_ID_ENTRY_TYPE_CHECKBOX);
    ResourceHistory resourceHistory = _resourceHistoryService.findByPrimaryKey(nIdResourceHistory);
    Plugin pluginDirectory = PluginService.getPlugin(DirectoryPlugin.PLUGIN_NAME);

    if ((config != null) && (resourceHistory != null)
            && resourceHistory.getResourceType().equals(Record.WORKFLOW_RESOURCE_TYPE)) {
        Record record = RecordHome.findByPrimaryKey(resourceHistory.getIdResource(), pluginDirectory);

        IEntry entry = null;
        EntryFilter entryFilter = new EntryFilter();
        entryFilter.setPosition(config.getPositionEntryDirectory());
        entryFilter.setIdDirectory(record.getDirectory().getIdDirectory());

        List<IEntry> entryList = EntryHome.getEntryList(entryFilter, pluginDirectory);

        if ((entryList != null) && !entryList.isEmpty()) {
            entry = EntryHome.findByPrimaryKey(entryList.get(0).getIdEntry(), pluginDirectory);
        }

        if (entry != null) {
            List<RecordField> listRecordFieldResult = new ArrayList<RecordField>();

            try {
                if (config.isUsedUser()) {
                    List<String> listString = new ArrayList<String>();
                    listString.add(AdminUserService.getAdminUser(request).getAccessCode());
                    entry.getRecordFieldData(record, listString, true, config.isAddNewValue(),
                            listRecordFieldResult, locale);
                } else if (!config.isUsedTaskEntry()) {
                    entry.getRecordFieldData(record, request, true, config.isAddNewValue(),
                            listRecordFieldResult, locale);
                } else {
                    if ((entry.getEntryType().getIdType() == DirectoryUtils
                            .convertStringToInt(strIdEntryTypeFile))
                            || (entry.getEntryType().getIdType() == DirectoryUtils
                                    .convertStringToInt(strIdEntryTypeImg))) {
                        entry.getRecordFieldData(record,
                                TaskFillingDirectoryUtils.getParameterValue(request,
                                        config.getEntryParameter()),
                                true, config.isAddNewValue(), listRecordFieldResult, locale);
                    } else if ((entry.getEntryType().getIdType() == DirectoryUtils
                            .convertStringToInt(strIdEntryTypeCheckBox))) {
                        entry.getRecordFieldData(record,
                                TaskFillingDirectoryUtils.getParameterValuesTypeMultipleChoice(request,
                                        config.getEntryParameter()),
                                true, config.isAddNewValue(), listRecordFieldResult, locale);
                    } else {
                        // If the config has a criteria of the type checkbox/select that provides multiple choices, 
                        // we must display the output in a single line
                        List<String> listParameterValues = TaskFillingDirectoryUtils
                                .getParameterValuesTypeMultipleChoice(request, config.getEntryParameter());

                        if (listParameterValues.size() > 1) {
                            StringBuilder sbParameterValue = new StringBuilder();

                            for (String strParameterValue : listParameterValues) {
                                sbParameterValue.append(strParameterValue + COMMA);
                            }

                            sbParameterValue.delete(sbParameterValue.length() - COMMA.length(),
                                    sbParameterValue.length());

                            List<String> list = new ArrayList<String>();
                            list.add(sbParameterValue.toString());
                            entry.getRecordFieldData(record, list, true, config.isAddNewValue(),
                                    listRecordFieldResult, locale);
                        } else {
                            entry.getRecordFieldData(record,
                                    TaskFillingDirectoryUtils.getParameterValue(request,
                                            config.getEntryParameter()),
                                    true, config.isAddNewValue(), listRecordFieldResult, locale);
                        }
                    }
                }

                //add Indexer action
                DirectorySearchService.getInstance().addIndexerAction(record.getIdRecord(),
                        IndexerAction.TASK_MODIFY, plugin);

                //delete all record field in database associate to the entry and the record
                RecordFieldFilter filter = new RecordFieldFilter();
                filter.setIdRecord(record.getIdRecord());
                filter.setIdEntry(entry.getIdEntry());
                RecordFieldHome.removeByFilter(filter, plugin);

                //insert the new record Field
                for (RecordField recordField : listRecordFieldResult) {
                    recordField.setRecord(record);
                    RecordFieldHome.create(recordField, plugin);
                    //insert new History recordField
                    _recordFieldHistoryService.create(nIdResourceHistory, this.getId(), recordField, plugin);
                }
            } catch (DirectoryErrorException error) {
                throw new RuntimeException(error);
            }
        }
    }
}

From source file:net.kautler.teamcity.sourceforge.SourceForgeIssueFetcher.java

/**
 * Fetches the issues corresponding to the specified IDs that are not cached already as one batch operation
 * from the remote issue tracker.// w  w w  . ja  v  a2s.  c o  m
 *
 * @param dataVehicleJson the {@code JSON} representation of the data vehicle transporting the configuration data
 * @param ids             the IDs to fetch the issues for
 * @param credentials     the credentials to use for authentication
 * @return the fetched issues
 */
@Nullable
@Override
public Collection<IssueData> getIssuesInBatch(@NotNull final String dataVehicleJson,
        @NotNull Collection<String> ids, @Nullable Credentials credentials) {
    return super.defaultGetIssuesInBatch(dataVehicleJson, ids, new BatchFetchFunction() {
        @NotNull
        @Override
        public List<IssueData> batchFetch(@NotNull Collection<String> ids) {
            try {
                StringBuilder queryBuilder = new StringBuilder();
                for (String id : ids) {
                    queryBuilder.append("ticket_num:").append(id).append(" || ");
                }
                if (ids.size() > 0) {
                    queryBuilder.delete(queryBuilder.length() - 4, queryBuilder.length());
                }
                String searchUrl = getSearchUrl(getProject(dataVehicleJson), getTicketTool(dataVehicleJson),
                        queryBuilder.toString());
                InputStream issueStream = fetchHttpFile(searchUrl);
                Collection<Ticket> tickets = GSON
                        .fromJson(new InputStreamReader(issueStream), SearchResult.class).getTickets();
                List<IssueData> result = new ArrayList<IssueData>(tickets.size());
                for (Ticket ticket : tickets) {
                    result.add(getIssueData(ticket, dataVehicleJson));
                }
                return result;
            } catch (IOException e) {
                return emptyList();
            }
        }
    });
}

From source file:com.haulmont.cuba.desktop.gui.components.DesktopTimeField.java

public void setResolution(DateField.Resolution resolution) {
    this.resolution = resolution;
    if (resolution.ordinal() <= DateField.Resolution.SEC.ordinal()) {
        setShowSeconds(true);/*from ww  w  .  j  av  a  2  s  .  c om*/
    } else if (resolution.ordinal() <= DateField.Resolution.MIN.ordinal()) {
        setShowSeconds(false);
    } else if (resolution.ordinal() <= DateField.Resolution.HOUR.ordinal()) {
        StringBuilder builder = new StringBuilder(timeFormat);
        if (timeFormat.contains("mm")) {
            int minutesIndex = builder.indexOf("mm");
            builder.delete(minutesIndex > 0 ? --minutesIndex : minutesIndex, minutesIndex + 3);
            timeFormat = builder.toString();
        }
        setShowSeconds(false);
    }
}