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.dalabs.droop.util.OptionsFileUtil.java

/**
 * Expands any options file that may be present in the given set of arguments.
 *
 * @param args the given arguments/*from  w w  w .  j  a  va  2 s .  com*/
 * @return a new string array that contains the expanded arguments.
 * @throws Exception
 */
public static String[] expandArguments(String[] args) throws Exception {
    List<String> options = new ArrayList<String>();

    for (int i = 0; i < args.length; i++) {
        if (args[i].equals(Droop.DROOP_OPTIONS_FILE_SPECIFIER)) {
            if (i == args.length - 1) {
                throw new Exception("Missing options file");
            }

            String fileName = args[++i];
            File optionsFile = new File(fileName);
            BufferedReader reader = null;
            StringBuilder buffer = new StringBuilder();
            try {
                reader = new BufferedReader(new FileReader(optionsFile));
                String nextLine = null;
                while ((nextLine = reader.readLine()) != null) {
                    nextLine = nextLine.trim();
                    if (nextLine.length() == 0 || nextLine.startsWith("#")) {
                        // empty line or comment
                        continue;
                    }

                    buffer.append(nextLine);
                    if (nextLine.endsWith("\\")) {
                        if (buffer.charAt(0) == '\'' || buffer.charAt(0) == '"') {
                            throw new Exception("Multiline quoted strings not supported in file(" + fileName
                                    + "): " + buffer.toString());
                        }
                        // Remove the trailing back-slash and continue
                        buffer.deleteCharAt(buffer.length() - 1);
                    } else {
                        // The buffer contains a full option
                        options.add(removeQuotesEncolosingOption(fileName, buffer.toString()));
                        buffer.delete(0, buffer.length());
                    }
                }

                // Assert that the buffer is empty
                if (buffer.length() != 0) {
                    throw new Exception(
                            "Malformed option in options file(" + fileName + "): " + buffer.toString());
                }
            } catch (IOException ex) {
                throw new Exception("Unable to read options file: " + fileName, ex);
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException ex) {
                        LOG.info("Exception while closing reader", ex);
                    }
                }
            }
        } else {
            // Regular option. Parse it and put it on the appropriate list
            options.add(args[i]);
        }
    }

    return options.toArray(new String[options.size()]);
}

From source file:com.cloudera.sqoop.util.OptionsFileUtil.java

/**
 * Expands any options file that may be present in the given set of arguments.
 *
 * @param args the given arguments//  w  w w  .j  ava  2  s. c o m
 * @return a new string array that contains the expanded arguments.
 * @throws Exception
 */
public static String[] expandArguments(String[] args) throws Exception {
    List<String> options = new ArrayList<String>();

    for (int i = 0; i < args.length; i++) {
        if (args[i].equals(Sqoop.SQOOP_OPTIONS_FILE_SPECIFIER)) {
            if (i == args.length - 1) {
                throw new Exception("Missing options file");
            }

            String fileName = args[++i];
            File optionsFile = new File(fileName);
            BufferedReader reader = null;
            StringBuilder buffer = new StringBuilder();
            try {
                reader = new BufferedReader(new FileReader(optionsFile));
                String nextLine = null;
                while ((nextLine = reader.readLine()) != null) {
                    nextLine = nextLine.trim();
                    if (nextLine.length() == 0 || nextLine.startsWith("#")) {
                        // empty line or comment
                        continue;
                    }

                    buffer.append(nextLine);
                    if (nextLine.endsWith("\\")) {
                        if (buffer.charAt(0) == '\'' || buffer.charAt(0) == '"') {
                            throw new Exception("Multiline quoted strings not supported in file(" + fileName
                                    + "): " + buffer.toString());
                        }
                        // Remove the trailing back-slash and continue
                        buffer.deleteCharAt(buffer.length() - 1);
                    } else {
                        // The buffer contains a full option
                        options.add(removeQuotesEncolosingOption(fileName, buffer.toString()));
                        buffer.delete(0, buffer.length());
                    }
                }

                // Assert that the buffer is empty
                if (buffer.length() != 0) {
                    throw new Exception(
                            "Malformed option in options file(" + fileName + "): " + buffer.toString());
                }
            } catch (IOException ex) {
                throw new Exception("Unable to read options file: " + fileName, ex);
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException ex) {
                        LOG.info("Exception while closing reader", ex);
                    }
                }
            }
        } else {
            // Regular option. Parse it and put it on the appropriate list
            options.add(args[i]);
        }
    }

    return options.toArray(new String[options.size()]);
}

From source file:com.flexive.shared.ContentLinkFormatter.java

/**
 * <p>Uses the given format string to create an URI for the given tree path items.
 * If more than one path is contained in the given parameter, the paths are joined with
 * a ',' character.//from  ww w  .  ja va  2  s  . com
 * Supported placeholders are:</p>
 * <table>
 * <tr>
 * <th>%{pk}</th>
 * <td>The primary key in "dot" notation. For example, new FxPK(42, 1)
 * results in "42.1" being substituted in the URI.</td>
 * </tr>
 * <tr>
 * <th>%{id}</th>
 * <td>The object ID.</td>
 * </tr>
 * <tr>
 * <th>%{version}</th>
 * <td>The object version.</td>
 * </tr>
 * <tr>
 * <th>%{nodeId}</th>
 * <td>The tree node ID.</td>
 * </tr>
 * <tr>
 * <th>%{caption}</th>
 * <td>The item caption (will be URL-escaped).</td>
 * </tr>
 * <tr>
 * <th>%{caption20}</th>
 * <td>The item caption, abbreviated to max. 20 characters (will be URL-escaped).</td>
 * </tr>
 * </table>
 *
 * @param formatString  the input format string. For example, <code>"/content/%{id}.html"</code>
 * @param paths the tree paths to be formatted
 * @return  the resulting URI string
 */
public String format(String formatString, FxPaths paths) {
    StringBuilder out = new StringBuilder(255);
    for (FxPaths.Path path : paths.getPaths()) {
        out.append(out.length() > 0 ? ", " : "");
        for (FxPaths.Item item : path.getItems()) {
            out.append(format(formatString, item)).append(PATH_DELIM);
        }
        if (!path.getItems().isEmpty()) {
            out.delete(out.length() - PATH_DELIM.length(), out.length());
        }
    }
    return out.toString();
}

From source file:com.huawei.unibi.molap.csvreaderstep.CsvInput.java

/**
 * This method is borrowed from TextFileInput
 * //  ww w.j ava2  s . c o m
 * @param log
 * @param line
 * @param delimiter
 * @param enclosure
 * @param escapeCharacter
 * @return
 * @throws KettleException
 */
public static final String[] guessStringsFromLine(LogChannelInterface log, String line, String delimiter,
        String enclosure, String escapeCharacter) throws KettleException {
    List<String> strings = new ArrayList<String>(MolapCommonConstants.CONSTANT_SIZE_TEN);
    //        int fieldnr;

    String pol; // piece of line

    try {
        if (line == null) {
            return null;
        }

        // Split string in pieces, only for CSV!

        //      fieldnr = 0;
        int pos = 0;
        int length = line.length();
        boolean dencl = false;

        int lenEncl = (enclosure == null ? 0 : enclosure.length());
        int lenEsc = (escapeCharacter == null ? 0 : escapeCharacter.length());

        while (pos < length) {
            int from = pos;
            int next;

            boolean enclFound;
            boolean containsEscapedEnclosures = false;
            boolean containsEscapedSeparators = false;

            // Is the field beginning with an enclosure?
            // "aa;aa";123;"aaa-aaa";000;...
            if (lenEncl > 0 && line.substring(from, from + lenEncl).equalsIgnoreCase(enclosure)) {
                if (log.isRowLevel()) {
                    log.logRowlevel(BaseMessages.getString(PKG, "CsvInput.Log.ConvertLineToRowTitle"), //$NON-NLS-1$
                            BaseMessages.getString(PKG, "CsvInput.Log.ConvertLineToRow", //$NON-NLS-1$
                                    line.substring(from, from + lenEncl)));
                }
                enclFound = true;
                int p = from + lenEncl;

                boolean isEnclosure = lenEncl > 0 && p + lenEncl < length
                        && line.substring(p, p + lenEncl).equalsIgnoreCase(enclosure);
                boolean isEscape = lenEsc > 0 && p + lenEsc < length
                        && line.substring(p, p + lenEsc).equalsIgnoreCase(escapeCharacter);

                boolean enclosureAfter = false;

                // Is it really an enclosure? See if it's not repeated twice or escaped!
                if ((isEnclosure || isEscape) && p < length - 1) {
                    String strnext = line.substring(p + lenEncl, p + 2 * lenEncl);
                    if (strnext.equalsIgnoreCase(enclosure)) {
                        p++;
                        enclosureAfter = true;
                        dencl = true;

                        // Remember to replace them later on!
                        if (isEscape) {
                            containsEscapedEnclosures = true;
                        }
                    }
                }

                // Look for a closing enclosure!
                while ((!isEnclosure || enclosureAfter) && p < line.length()) {
                    p++;
                    enclosureAfter = false;
                    isEnclosure = lenEncl > 0 && p + lenEncl < length
                            && line.substring(p, p + lenEncl).equals(enclosure);
                    isEscape = lenEsc > 0 && p + lenEsc < length
                            && line.substring(p, p + lenEsc).equals(escapeCharacter);

                    // Is it really an enclosure? See if it's not repeated twice or escaped!
                    if ((isEnclosure || isEscape) && p < length - 1) // Is
                    {
                        String strnext = line.substring(p + lenEncl, p + 2 * lenEncl);
                        if (strnext.equals(enclosure)) {
                            p++;
                            enclosureAfter = true;
                            dencl = true;

                            // Remember to replace them later on!
                            if (isEscape) {
                                containsEscapedEnclosures = true; // remember
                            }
                        }
                    }
                }

                if (p >= length) {
                    next = p;
                } else {
                    next = p + lenEncl;
                }

                if (log.isRowLevel()) {
                    log.logRowlevel(BaseMessages.getString(PKG, "CsvInput.Log.ConvertLineToRowTitle"), //$NON-NLS-1$
                            BaseMessages.getString(PKG, "CsvInput.Log.EndOfEnclosure", "" + p)); //$NON-NLS-1$ //$NON-NLS-2$
                }
            } else {
                enclFound = false;
                boolean found = false;
                int startpoint = from;
                int tries = 1;
                do {
                    next = line.indexOf(delimiter, startpoint);

                    // See if this position is preceded by an escape character.
                    if (lenEsc > 0 && next - lenEsc > 0) {
                        String before = line.substring(next - lenEsc, next);

                        if (escapeCharacter != null && escapeCharacter.equals(before)) {
                            // take the next separator, this one is escaped...
                            startpoint = next + 1;
                            tries++;
                            containsEscapedSeparators = true;
                        } else {
                            found = true;
                        }
                    } else {
                        found = true;
                    }
                } while (!found && next >= 0);
            }
            if (next == -1) {
                next = length;
            }

            if (enclFound) {
                pol = line.substring(from + lenEncl, next - lenEncl);
                if (log.isRowLevel()) {
                    log.logRowlevel(BaseMessages.getString(PKG, "CsvInput.Log.ConvertLineToRowTitle"), //$NON-NLS-1$
                            BaseMessages.getString(PKG, "CsvInput.Log.EnclosureFieldFound", "" + pol)); //$NON-NLS-1$ //$NON-NLS-2$
                }
            } else {
                pol = line.substring(from, next);
                if (log.isRowLevel()) {
                    log.logRowlevel(BaseMessages.getString(PKG, "CsvInput.Log.ConvertLineToRowTitle"), //$NON-NLS-1$
                            BaseMessages.getString(PKG, "CsvInput.Log.NormalFieldFound", "" + pol)); //$NON-NLS-1$ //$NON-NLS-2$
                }
            }

            if (dencl) {
                StringBuilder sbpol = new StringBuilder(pol);
                int idx = sbpol.indexOf(enclosure + enclosure);
                while (idx >= 0) {
                    sbpol.delete(idx, idx + (enclosure == null ? 0 : enclosure.length()));
                    idx = sbpol.indexOf(enclosure + enclosure);
                }
                pol = sbpol.toString();
            }

            //  replace the escaped enclosures with enclosures... 
            if (containsEscapedEnclosures) {
                String replace = escapeCharacter + enclosure;
                String replaceWith = enclosure;

                pol = Const.replace(pol, replace, replaceWith);
            }

            //replace the escaped separators with separators...
            if (containsEscapedSeparators) {
                String replace = escapeCharacter + delimiter;
                String replaceWith = delimiter;

                pol = Const.replace(pol, replace, replaceWith);
            }

            // Now add pol to the strings found!
            strings.add(pol);

            pos = next + delimiter.length();
            //        fieldnr++;
        }
        if (pos == length) {
            if (log.isRowLevel()) {
                log.logRowlevel(BaseMessages.getString(PKG, "CsvInput.Log.ConvertLineToRowTitle"), //$NON-NLS-1$
                        BaseMessages.getString(PKG, "CsvInput.Log.EndOfEmptyLineFound")); //$NON-NLS-1$
            }
            strings.add(""); //$NON-NLS-1$
            //                  fieldnr++;
        }
    } catch (Exception e) {
        throw new KettleException(
                BaseMessages.getString(PKG, "CsvInput.Log.Error.ErrorConvertingLine", e.toString()), e); //$NON-NLS-1$
    }

    return strings.toArray(new String[strings.size()]);
}

From source file:de.itsvs.cwtrpc.security.AbstractRpcProcessingFilter.java

protected boolean matchesFilterProcessesUrl(HttpServletRequest request) throws IOException, ServletException {
    final String contextPath;
    final StringBuilder sb;
    final String uri;

    contextPath = request.getContextPath();
    sb = new StringBuilder(request.getRequestURI());
    if ((contextPath.length() > 0) && (sb.indexOf(contextPath) == 0)) {
        sb.delete(0, contextPath.length());
    }/*from  w w  w .j a  va 2 s .com*/
    if ((sb.length() == 0) || (sb.charAt(0) != '/')) {
        sb.insert(0, '/');
    }
    uri = sb.toString();

    if (log.isDebugEnabled()) {
        log.debug(
                "Checking received URI '" + uri + "' against configured URI '" + getFilterProcessesUrl() + "'");
    }
    return getFilterProcessesUrl().equals(uri);
}

From source file:eu.optimis.mi.monitoring_manager.resources.MonitorManagerQueryResourceHome.java

private String array2Str(List<String> coll, String delimiter) {
    if (coll.isEmpty())
        return "";
    StringBuilder sb = new StringBuilder();
    for (String x : coll)
        sb.append(x + delimiter);/*from w  w w  .j  ava 2  s .c o  m*/
    sb.delete(sb.length() - delimiter.length(), sb.length());
    return sb.toString();
}

From source file:com.globalsight.everest.webapp.pagehandler.qachecks.DitaQaReportsHandler.java

private String getJSON(List<ReportFile> p_list) {
    if (p_list == null || p_list.size() == 0) {
        return "[]";
    }//w  w w.  ja  v a 2 s. c  om

    StringBuilder result = new StringBuilder();
    result.append("[");
    for (ReportFile reportFile : p_list) {
        result.append(reportFile.toJSON()).append(", ");
    }
    result.delete(result.length() - 2, result.length());
    result.append("]");
    return result.toString();
}

From source file:org.jasig.ssp.util.importer.job.listener.StagingAndUpsertSkipListener.java

@SuppressWarnings("unchecked")
private void reportOnError(RawItem item, Throwable t) {
    logger.error("ERROR on Stage/Upsert Write", t);

    String fileName = item.getResource().getFilename();
    String[] tableName = fileName.split("\\.");
    stepExecution.getExecutionContext().put("currentEntity", tableName[0]);
    List<String> tableKeys = metadataRepository.getRepository().getColumnMetadataRepository()
            .getTableMetadata(new TableReference(tableName[0])).getTableKeys();

    // There are a few external tables that don't (yet) have natural keys,
    // in these cases we've enforced the key on the staging table
    // so in cases where the external table does not have any keys, we look
    // towards the corresponding staging table for them
    if (tableKeys.isEmpty()) {
        tableKeys = metadataRepository.getRepository().getColumnMetadataRepository()
                .getTableMetadata(new TableReference("stg_" + tableName[0])).getTableKeys();
    }/*  w  ww .ja  va 2 s  .c  o  m*/
    StringBuilder keyBuilder = new StringBuilder();
    Integer index = -1;
    keyBuilder.append("Entity Keys: {");
    for (String key : tableKeys) {
        keyBuilder.append(key).append(" : ").append(item.getRecord().get(key)).append(", ");
        index = keyBuilder.lastIndexOf(", ");
    }
    if (index >= 0)
        keyBuilder.delete(index, index + 2);
    keyBuilder.append("}");
    ErrorEntry error = new ErrorEntry(tableName[0], keyBuilder.toString(), t.getCause().toString(),
            StepType.STAGEUPSERT);
    error.setLineNumber(item.getLineNumber().toString());
    List<ErrorEntry> errors = (List<ErrorEntry>) stepExecution.getJobExecution().getExecutionContext()
            .get("errors");
    if (errors == null) {
        errors = new ArrayList<ErrorEntry>();
    }
    errors.add(error);
    stepExecution.getJobExecution().getExecutionContext().put("errors", errors);
}

From source file:org.apache.hcatalog.mapreduce.MultiOutputFormat.java

/**
 * Compare the aliasContext with userJob and add the differing configuration
 * as mapreduce.multiout.alias.<aliasname>.conf to the userJob.
 * <p>//from ww  w  .j a va 2  s.  c  o m
 * Merge config like tmpjars, tmpfile, tmparchives,
 * mapreduce.job.hdfs-servers that are directly handled by JobClient and add
 * them to userJob.
 * <p>
 * Add mapred.output.dir config to userJob.
 *
 * @param alias alias name associated with a OutputFormat
 * @param userJob reference to Job that the user is going to submit
 * @param aliasContext JobContext populated with OutputFormat related
 *            configuration.
 */
private static void setAliasConf(String alias, JobContext userJob, JobContext aliasContext) {
    Configuration userConf = userJob.getConfiguration();
    StringBuilder builder = new StringBuilder();
    for (Entry<String, String> conf : aliasContext.getConfiguration()) {
        String key = conf.getKey();
        String value = conf.getValue();
        String jobValue = userConf.getRaw(key);
        if (jobValue == null || !jobValue.equals(value)) {
            if (configsToMerge.containsKey(key)) {
                String mergedValue = getMergedConfValue(jobValue, value, configsToMerge.get(key));
                userConf.set(key, mergedValue);
            } else {
                if (configsToOverride.contains(key)) {
                    userConf.set(key, value);
                }
                builder.append(key).append(CONF_KEY_DELIM).append(value).append(CONF_VALUE_DELIM);
            }
        }
    }
    if (builder.length() > CONF_VALUE_DELIM.length()) {
        builder.delete(builder.length() - CONF_VALUE_DELIM.length(), builder.length());
        userConf.set(getAliasConfName(alias), builder.toString());
    }
}

From source file:modula.executor.core.ModulaExecutor.java

/**
 * ??State/* w w  w. j ava2s. c o m*/
 */
protected void logState() {
    if (log.isDebugEnabled()) {
        StringBuilder sb = new StringBuilder("Current States: [ ");
        for (EnterableState es : getCurrentStatus().getStates()) {
            sb.append(es.getId()).append(", ");
        }
        int length = sb.length();
        sb.delete(length - 2, length).append(" ]");
        log.debug(sb.toString());
    }
}