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.panet.imeta.trans.steps.textfileinput.TextFileInput.java

public static final String[] convertLineToStrings(String line, InputFileMetaInterface inf)
        throws KettleException {
    String[] strings = new String[inf.getInputFields().length];
    int fieldnr;//from  ww  w  .j ava 2  s.co m

    String pol; // piece of line

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

        if (inf.getFileType().equalsIgnoreCase("CSV")) {
            // Split string in pieces, only for CSV!

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

            int len_encl = (inf.getEnclosure() == null ? 0 : inf.getEnclosure().length());
            int len_esc = (inf.getEscapeCharacter() == null ? 0 : inf.getEscapeCharacter().length());

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

                boolean encl_found;
                boolean contains_escaped_enclosures = false;
                boolean contains_escaped_separators = false;

                // Is the field beginning with an enclosure?
                // "aa;aa";123;"aaa-aaa";000;...
                if (len_encl > 0
                        && line.substring(from, from + len_encl).equalsIgnoreCase(inf.getEnclosure())) {
                    if (log.isRowLevel())
                        log.logRowlevel(Messages.getString("TextFileInput.Log.ConvertLineToRowTitle"),
                                Messages.getString("TextFileInput.Log.Encloruse",
                                        line.substring(from, from + len_encl)));
                    encl_found = true;
                    int p = from + len_encl;

                    boolean is_enclosure = len_encl > 0 && p + len_encl < length
                            && line.substring(p, p + len_encl).equalsIgnoreCase(inf.getEnclosure());
                    boolean is_escape = len_esc > 0 && p + len_esc < length
                            && line.substring(p, p + len_esc).equalsIgnoreCase(inf.getEscapeCharacter());

                    boolean enclosure_after = false;

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

                            // Remember to replace them later on!
                            if (is_escape)
                                contains_escaped_enclosures = true;
                        }
                    }

                    // Look for a closing enclosure!
                    while ((!is_enclosure || enclosure_after) && p < line.length()) {
                        p++;
                        enclosure_after = false;
                        is_enclosure = len_encl > 0 && p + len_encl < length
                                && line.substring(p, p + len_encl).equals(inf.getEnclosure());
                        is_escape = len_esc > 0 && p + len_esc < length
                                && line.substring(p, p + len_esc).equals(inf.getEscapeCharacter());

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

                                // Remember to replace them later on!
                                if (is_escape)
                                    contains_escaped_enclosures = true; // remember
                            }
                        }
                    }

                    if (p >= length)
                        next = p;
                    else
                        next = p + len_encl;

                    if (log.isRowLevel())
                        log.logRowlevel(Messages.getString("TextFileInput.Log.ConvertLineToRowTitle"),
                                Messages.getString("TextFileInput.Log.EndOfEnclosure", "" + p));
                } else {
                    encl_found = false;
                    boolean found = false;
                    int startpoint = from;
                    int tries = 1;
                    do {
                        next = line.indexOf(inf.getSeparator(), startpoint);

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

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

                if (encl_found && ((from + len_encl) <= (next - len_encl))) {
                    pol = line.substring(from + len_encl, next - len_encl);
                    if (log.isRowLevel())
                        log.logRowlevel(Messages.getString("TextFileInput.Log.ConvertLineToRowTitle"),
                                Messages.getString("TextFileInput.Log.EnclosureFieldFound", "" + pol));
                } else {
                    pol = line.substring(from, next);
                    if (log.isRowLevel())
                        log.logRowlevel(Messages.getString("TextFileInput.Log.ConvertLineToRowTitle"),
                                Messages.getString("TextFileInput.Log.NormalFieldFound", "" + pol));
                }

                if (dencl && Const.isEmpty(inf.getEscapeCharacter())) {
                    StringBuilder sbpol = new StringBuilder(pol);
                    int idx = sbpol.indexOf(inf.getEnclosure() + inf.getEnclosure());
                    while (idx >= 0) {
                        sbpol.delete(idx, idx + inf.getEnclosure().length());
                        idx = sbpol.indexOf(inf.getEnclosure() + inf.getEnclosure());
                    }
                    pol = sbpol.toString();
                }

                //   replace the escaped enclosures with enclosures... 
                if (contains_escaped_enclosures) {
                    String replace = inf.getEscapeCharacter() + inf.getEnclosure();
                    String replaceWith = inf.getEnclosure();

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

                //replace the escaped separators with separators... 
                if (contains_escaped_separators) {
                    String replace = inf.getEscapeCharacter() + inf.getSeparator();
                    String replaceWith = inf.getSeparator();

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

                // Now add pol to the strings found!
                try {
                    strings[fieldnr] = pol;
                } catch (ArrayIndexOutOfBoundsException e) {
                    // In case we didn't allocate enough space.
                    // This happens when you have less header values specified than there are actual values in the rows.
                    // As this is "the exception" we catch and resize here.
                    //
                    String[] newStrings = new String[strings.length];
                    for (int x = 0; x < strings.length; x++)
                        newStrings[x] = strings[x];
                    strings = newStrings;
                }

                pos = next + inf.getSeparator().length();
                fieldnr++;
            }
            if (pos == length) {
                if (log.isRowLevel())
                    log.logRowlevel(Messages.getString("TextFileInput.Log.ConvertLineToRowTitle"),
                            Messages.getString("TextFileInput.Log.EndOfEmptyLineFound"));
                if (fieldnr < strings.length)
                    strings[fieldnr] = Const.EMPTY_STRING;
                fieldnr++;
            }
        } else {
            // Fixed file format: Simply get the strings at the required positions...
            for (int i = 0; i < inf.getInputFields().length; i++) {
                TextFileInputField field = inf.getInputFields()[i];

                int length = line.length();

                int fieldLength = field.getLength();
                if (fieldLength < 0) {
                    fieldLength = Integer.MAX_VALUE;
                }

                if (field.getPosition() + fieldLength <= length) {
                    strings[i] = line.substring(field.getPosition(), field.getPosition() + fieldLength);
                } else {
                    if (field.getPosition() < length) {
                        strings[i] = line.substring(field.getPosition());
                    } else {
                        strings[i] = "";
                    }
                }
            }
        }
    } catch (Exception e) {
        throw new KettleException(
                Messages.getString("TextFileInput.Log.Error.ErrorConvertingLine", e.toString()), e);
    }

    return strings;
}

From source file:org.alfresco.repo.lotus.ws.impl.helper.AlfrescoQuickrPathHelper.java

/**
 * @param nodeRef NodeRef of the document/folder.
 * @param isRelative if true then returned path will be relative
 * @return Path to the document/folder.//from   ww w  .  j a v a  2s. c  om
 */
public String getNodePath(NodeRef nodeRef, boolean isRelative) {
    String urlPath;
    if (nodeRef.equals(rootNodeRef)) {
        urlPath = rootDisplayPath;
    } else {
        StringBuilder builder = new StringBuilder(
                nodeService.getPath(nodeRef).toDisplayPath(nodeService, permissionService));
        builder.append("/");
        if (isRelative) {
            builder.delete(0, rootDisplayPath.length() + 1);
        }

        String nodeName = (String) nodeService.getProperty(nodeRef, ContentModel.PROP_NAME);
        builder.append(nodeName);
        urlPath = builder.toString();
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Convert " + nodeRef + " to url path '" + urlPath + "'");
    }

    return urlPath;
}

From source file:info.magnolia.ui.framework.message.MessageStore.java

protected String buildWhereTypesClause(MessageType[] messageTypes) {
    if (messageTypes == null || messageTypes.length == 0)
        return StringUtils.EMPTY;

    StringBuilder whereClauseStatement = new StringBuilder(" and (");
    for (MessageType messageType : messageTypes) {
        whereClauseStatement.append(String.format(WHERE_TYPE_CLAUSE, messageType.name()));
        whereClauseStatement.append(" or ");
    }/*www  .  j a v  a  2s . c  om*/
    whereClauseStatement.delete(whereClauseStatement.length() - " or ".length(), whereClauseStatement.length());
    whereClauseStatement.append(")");
    return whereClauseStatement.toString();
}

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

@Override
protected void transformStringContent(String reference, StringBuilder content, ImporterMetadata metadata,
        boolean parsed, boolean partialContent) {
    if (stripBeforeRegex == null) {
        LOG.error("No regular expression provided.");
        return;//w w w .  ja  v  a2s  .c  om
    }
    int flags = Pattern.DOTALL | Pattern.UNICODE_CASE;
    if (!caseSensitive) {
        flags = flags | Pattern.CASE_INSENSITIVE;
    }
    Pattern pattern = Pattern.compile(stripBeforeRegex, flags);
    Matcher match = pattern.matcher(content);
    if (match.find()) {
        if (inclusive) {
            content.delete(0, match.end());
        } else {
            content.delete(0, match.start());
        }
    }
}

From source file:com.github.pagehelper.PageHelper.java

/**
 * countMappedStatement//  www  .  ja v a2 s  . c o m
 *
 * @param ms
 * @param newSqlSource
 * @param suffix
 * @return
 */
private MappedStatement newMappedStatement(MappedStatement ms, BoundSqlSqlSource newSqlSource, String suffix) {
    String id = ms.getId() + suffix;
    //?
    if (suffix == SUFFIX_PAGE) {
        //sql
        MetaObject msObject = forObject(newSqlSource);
        msObject.setValue(BOUND_SQL, getPageSql((String) msObject.getValue(BOUND_SQL)));
        //?
        List<ParameterMapping> newParameterMappings = new ArrayList<ParameterMapping>();
        newParameterMappings.addAll(newSqlSource.getBoundSql().getParameterMappings());
        newParameterMappings
                .add(new ParameterMapping.Builder(ms.getConfiguration(), PAGEPARAMETER_FIRST, Integer.class)
                        .build());
        newParameterMappings
                .add(new ParameterMapping.Builder(ms.getConfiguration(), PAGEPARAMETER_SECOND, Integer.class)
                        .build());
        msObject.setValue("boundSql.parameterMappings", newParameterMappings);
    } else {
        //count sql
        MetaObject msObject = forObject(newSqlSource);
        msObject.setValue(BOUND_SQL, getCountSql((String) msObject.getValue(BOUND_SQL)));
    }
    MappedStatement.Builder builder = new MappedStatement.Builder(ms.getConfiguration(), id, newSqlSource,
            ms.getSqlCommandType());
    builder.resource(ms.getResource());
    builder.fetchSize(ms.getFetchSize());
    builder.statementType(ms.getStatementType());
    builder.keyGenerator(ms.getKeyGenerator());
    if (ms.getKeyProperties() != null && ms.getKeyProperties().length != 0) {
        StringBuilder keyProperties = new StringBuilder();
        for (String keyProperty : ms.getKeyProperties()) {
            keyProperties.append(keyProperty).append(",");
        }
        keyProperties.delete(keyProperties.length() - 1, keyProperties.length());
        builder.keyProperty(keyProperties.toString());
    }
    builder.timeout(ms.getTimeout());
    builder.parameterMap(ms.getParameterMap());
    if (suffix == SUFFIX_PAGE) {
        builder.resultMaps(ms.getResultMaps());
    } else {
        //countint
        List<ResultMap> resultMaps = new ArrayList<ResultMap>();
        ResultMap resultMap = new ResultMap.Builder(ms.getConfiguration(), id, int.class, EMPTY_RESULTMAPPING)
                .build();
        resultMaps.add(resultMap);
        builder.resultMaps(resultMaps);
    }
    builder.resultSetType(ms.getResultSetType());
    builder.cache(ms.getCache());
    builder.flushCacheRequired(ms.isFlushCacheRequired());
    builder.useCache(ms.isUseCache());

    return builder.build();
}

From source file:de.unibremen.informatik.tdki.combo.rewriting.FilterRewriterDB2.java

private void atomicPrintOutput(BufferedReader reader, boolean checkForMessage) throws IOException {
    StringBuilder message = new StringBuilder();
    try {//from   w  w  w.j av a  2 s  .  c o  m
        String line;
        while ((line = reader.readLine()) != null) {
            message.append(line).append("\n");
        }
    } finally {
        reader.close();
    }
    if (checkForMessage && message.length() != 0) {
        message.delete(message.length() - 1, message.length());
        throw new RewritingException(message.toString());
    }
}

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

@Override
protected void transformStringContent(String reference, StringBuilder content, ImporterMetadata metadata,
        boolean parsed, boolean partialContent) {
    if (stripAfterRegex == null) {
        LOG.error("No regular expression provided.");
        return;//w  w w  . j a v  a 2 s  . c  o  m
    }
    int flags = Pattern.DOTALL | Pattern.UNICODE_CASE;
    if (!caseSensitive) {
        flags = flags | Pattern.CASE_INSENSITIVE;
    }
    Pattern pattern = Pattern.compile(stripAfterRegex, flags);
    Matcher match = pattern.matcher(content);
    if (match.find()) {
        if (inclusive) {
            content.delete(match.start(), content.length());
        } else {
            content.delete(match.end(), content.length());
        }
    }
}

From source file:com.mobileman.projecth.web.util.PersistentCookieHelper.java

private String createHash(String salt, User user) {
    StringBuilder sb = new StringBuilder();

    sb.append(salt);/*from  www  .j  a  v  a2s.  co m*/
    sb.append(user.getId());
    sb.append(user.getName().getName());
    sb.append(user.getName().getSurname());
    sb.append(user.getUserAccount().getEmail());

    MessageDigest md;
    try {
        md = MessageDigest.getInstance("SHA-1");
        byte[] src = sb.toString().getBytes("utf-8");
        md.update(src, 0, src.length);
        byte[] sha1hash = new byte[40];
        sha1hash = md.digest();

        String sha1 = convertToHex(sha1hash);

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

        sb.append(user.getId());
        sb.append(SEPARATOR);
        sb.append(salt);
        sb.append(SEPARATOR);
        sb.append(sha1);

        return sb.toString();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return "";
}

From source file:com.redhat.lightblue.metadata.rdbms.converter.Translator.java

protected void generateWhere(SelectStmt selectStmt, StringBuilder queryStringBuilder,
        LinkedList<String> whereConditionals) {
    queryStringBuilder.append("WHERE ");
    for (String where : whereConditionals) {
        queryStringBuilder.append(where).append(" AND ");
    }// w ww  .  j  av  a 2s.  co m
    queryStringBuilder.delete(queryStringBuilder.length() - 5, queryStringBuilder.length() - 1);//remove the last 'AND'
}

From source file:org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDaoImpl.java

/**
 * Return SQL string from storage tags, to be placed between SQL Prefix and SQL Suffix when creating storage tags PreparedStatement.
 * @param tags storage tags array/* www  . ja va 2 s . c  o m*/
 * @return SQL string containing storage tag values to be placed between Prefix and Suffix when creating PreparedStatement.
 * @throws NullPointerException if tags is null
 * @throws IndexOutOfBoundsException if tags is not null, but empty
 */
protected String getSqlValuesFromStorageTags(String[] tags)
        throws NullPointerException, IndexOutOfBoundsException {
    StringBuilder sqlValues = new StringBuilder();
    for (String tag : tags) {
        sqlValues.append("(storage_pool_tags.tag='").append(tag).append("') OR ");
    }
    sqlValues.delete(sqlValues.length() - 4, sqlValues.length());
    return sqlValues.toString();
}