Example usage for java.lang StringBuffer setLength

List of usage examples for java.lang StringBuffer setLength

Introduction

In this page you can find the example usage for java.lang StringBuffer setLength.

Prototype

@Override
public synchronized void setLength(int newLength) 

Source Link

Usage

From source file:org.openecomp.sdc.ci.tests.execute.imports.CsarUtilsTest.java

private void validateVFCsar(Component certifiedVF, byte[] resultByte, int toscaEntryIndexToPass,
        int ymlDeploymentArtifactIndexToPass, int xmlDeploymentArtifactIndexToPass,
        int heatEnvDeploymentArtifactIndexToPass) {

    // TODO Test to validate everything is right (comment out after testing)
    /*/*w  w  w .j  a v a 2  s.  co m*/
     * try { FileUtils.writeByteArrayToFile(new File("c:/TestCSAR/" + fetchedService.getName() + ".zip"), resultByte); } catch (IOException e) { // Auto-generated catch block e.printStackTrace(); }
     */

    try (ByteArrayInputStream ins = new ByteArrayInputStream(resultByte);
            ZipInputStream zip = new ZipInputStream(ins);) {

        String resourceYaml = null;
        byte[] buffer = new byte[1024];
        ZipEntry nextEntry = zip.getNextEntry();
        StringBuffer sb = new StringBuffer();
        int len;

        while ((len = zip.read(buffer)) > 0) {
            sb.append(new String(buffer, 0, len));
        }

        assertTrue(nextEntry.getName().equals("TOSCA-Metadata/TOSCA.meta"));

        YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();

        int toscaEntryIndex = 0;
        int ymlEntryIndex = 0;
        int xmlArtifactsIndex = 0;
        int heatEnvDeploymentArtifactIndex = 0;
        String fileName = null;
        ArtifactDefinition artifactDefinition;
        Component componentToValidate = null;

        artifactDefinition = certifiedVF.getToscaArtifacts().get(ASSET_TOSCA_TEMPLATE);
        String vfFileName = artifactDefinition.getArtifactName();

        while ((nextEntry = zip.getNextEntry()) != null) {
            sb.setLength(0);

            while ((len = zip.read(buffer)) > 0) {
                sb.append(new String(buffer, 0, len));
            }

            String entryName = nextEntry.getName();

            resourceYaml = sb.toString();
            if (entryName.contains(vfFileName)) {
                componentToValidate = certifiedVF;
                fileName = "Definitions/" + vfFileName;

                assertEquals("Validate entry Name", (fileName), nextEntry.getName());
                assertTrue(yamlToObjectConverter.isValidYaml(resourceYaml.getBytes()));
                validateContent(resourceYaml, componentToValidate);
                ++toscaEntryIndex;
                continue;
            }

            if (entryName.contains(".xml") && entryName.startsWith("Artifacts/")) {
                ++xmlArtifactsIndex;
                continue;
            }

            if (entryName.contains(".sh") && entryName.startsWith("Artifacts/")) {
                ++heatEnvDeploymentArtifactIndex;
                continue;
            }

            if (entryName.contains(".yml") && entryName.startsWith("Artifacts/")) {
                ++ymlEntryIndex;
                continue;
            }

            assertTrue("Unexpected entry: " + entryName, false);
        }
        assertEquals("Validate amount of entries", toscaEntryIndexToPass, toscaEntryIndex);
        assertEquals("Validate amount of YAML artifacts", ymlDeploymentArtifactIndexToPass, ymlEntryIndex);
        assertEquals("Validate amount of generated XML artifacts", xmlDeploymentArtifactIndexToPass,
                xmlArtifactsIndex);
        assertEquals("Validate amount of generated HEAT ENV artifacts", heatEnvDeploymentArtifactIndexToPass,
                heatEnvDeploymentArtifactIndex);

        ins.close();
        zip.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.apache.jasper.JspCompilationContext.java

private static final String canonicalURI(String s) {
    if (s == null)
        return null;
    StringBuffer result = new StringBuffer();
    final int len = s.length();
    int pos = 0;/*from   w  ww  .j a v  a  2 s  . co m*/
    while (pos < len) {
        char c = s.charAt(pos);
        if (isPathSeparator(c)) {
            /*
             * multiple path separators.
             * 'foo///bar' -> 'foo/bar'
             */
            while (pos + 1 < len && isPathSeparator(s.charAt(pos + 1))) {
                ++pos;
            }

            if (pos + 1 < len && s.charAt(pos + 1) == '.') {
                /*
                 * a single dot at the end of the path - we are done.
                 */
                if (pos + 2 >= len)
                    break;

                switch (s.charAt(pos + 2)) {
                /*
                * self directory in path
                * foo/./bar -> foo/bar
                */
                case '/':
                case '\\':
                    pos += 2;
                    continue;

                /*
                * two dots in a path: go back one hierarchy.
                * foo/bar/../baz -> foo/baz
                */
                case '.':
                    // only if we have exactly _two_ dots.
                    if (pos + 3 < len && isPathSeparator(s.charAt(pos + 3))) {
                        pos += 3;
                        int separatorPos = result.length() - 1;
                        while (separatorPos >= 0 && !isPathSeparator(result.charAt(separatorPos))) {
                            --separatorPos;
                        }
                        if (separatorPos >= 0)
                            result.setLength(separatorPos);
                        continue;
                    }
                }
            }
        }
        result.append(c);
        ++pos;
    }
    return result.toString();
}

From source file:com.rsmart.kuali.kfs.cr.batch.CheckReconciliationImportStep.java

/**
 * Process Line//from  w  ww .j a v  a  2s  .  co  m
 * 
 * @param line
 */
public List<String> processDelimitedLine(String line) {
    List<String> fields = new ArrayList<String>();
    StringBuffer sb = new StringBuffer();

    if (line == null) {
        return fields;
    } else if (line.length() == 0) {
        fields.add(line);
    }

    int index = 0;

    do {
        sb.setLength(0);
        if (index < line.length() && line.charAt(index) == QUOTE) {
            index = handleQuotedField(line, sb, ++index);
        } else {
            index = handlePlainField(line, sb, index);
        }

        fields.add(sb.toString());
        index++;
    } while (index < line.length());

    return fields;
}

From source file:com.tremolosecurity.provisioning.core.providers.BasicDB.java

private void many2manyDeleteGroups(Connection con, StringBuffer select, int id) throws SQLException {
    PreparedStatement ps;/*w  ww  . j  a  v  a  2  s  . c om*/
    select.setLength(0);
    select.append("DELETE FROM ").append(this.groupLinkTable).append(" WHERE ");
    this.getFieldName(this.groupUserKey, select).append("=?");
    ps = con.prepareStatement(select.toString());
    ps.setInt(1, id);
    ps.executeUpdate();
}

From source file:org.apache.struts2.jasper.JspCompilationContext.java

protected static final String canonicalURI(String s) {
    if (s == null)
        return null;
    StringBuffer result = new StringBuffer();
    final int len = s.length();
    int pos = 0;//from  w w  w  . j  a v a  2 s.  co m
    while (pos < len) {
        char c = s.charAt(pos);
        if (isPathSeparator(c)) {
            /*
             * multiple path separators.
             * 'foo///bar' -> 'foo/bar'
             */
            while (pos + 1 < len && isPathSeparator(s.charAt(pos + 1))) {
                ++pos;
            }

            if (pos + 1 < len && s.charAt(pos + 1) == '.') {
                /*
                 * a single dot at the end of the path - we are done.
                 */
                if (pos + 2 >= len)
                    break;

                switch (s.charAt(pos + 2)) {
                /*
                * self directory in path
                * foo/./bar -> foo/bar
                */
                case '/':
                case '\\':
                    pos += 2;
                    continue;

                /*
                * two dots in a path: go back one hierarchy.
                * foo/bar/../baz -> foo/baz
                */
                case '.':
                    // only if we have exactly _two_ dots.
                    if (pos + 3 < len && isPathSeparator(s.charAt(pos + 3))) {
                        pos += 3;
                        int separatorPos = result.length() - 1;
                        while (separatorPos >= 0 && !isPathSeparator(result.charAt(separatorPos))) {
                            --separatorPos;
                        }
                        if (separatorPos >= 0)
                            result.setLength(separatorPos);
                        continue;
                    }
                }
            }
        }
        result.append(c);
        ++pos;
    }
    return result.toString();
}

From source file:com.ikanow.infinit.e.application.utils.LogstashConfigUtils.java

public static String validateLogstashInput(String sourceKey, String config, StringBuffer errorMessage,
        boolean isAdmin) {

    if (null == _props) {
        _props = new PropertiesManager();
        String allowedInputs = _props.getProperty("harvest.logstash.allowed_inputs");

        if ((null == allowedInputs) || (allowedInputs.isEmpty())) {
            allowedInputs = "collectd,drupal_dblog,gelf,gemfire,imap,irc,lumberjack,s3,snmptrap,sqs,syslog,twitter,udp,xmpp,zenoss";
            // currently *not* allowed by default: elasticsearch,eventlog,exec,file,ganglia,generator,graphite,heroku,jmx,log4j,pipe,puppet_facter,rabbitmq,redit,relp,sqlite,stdin,stomp,tcp,unix,varnishlog,websocket,wmi,zeromq
        }//w  w  w  . j  a  v  a2  s.c om
        _allowedInputs.addAll(Arrays.asList(allowedInputs.toLowerCase().split("\\s*,\\s*")));

        String allowedFilters = _props.getProperty("harvest.logstash.allowed_filters");
        if ((null == allowedFilters) || (allowedFilters.isEmpty())) {
            allowedFilters = "advisor,alter,anonymize,checksum,cidr,cipher,clone,collate,csv,date,dns,drop,elapsed,extractnumbers,fingerprint,geoip,gelfify,grep,grok,grokdiscovery,l18n,json,json_encode,kv,metaevent,metrics,multiline,mutate,noop,prune,punct,railsparallelrequest,range,sleep,split,sumnumbers,syslog_pri,throttle,translate,unique,urldecode,useragent,uuid,wms,wmts,xml";
            // currently *not* allowed by default: elasticsearch,ruby,zeromq
        }
        _allowedFilters.addAll(Arrays.asList(allowedFilters.toLowerCase().split("\\s*,\\s*")));
    } //TESTED (3_2a)

    // Configuration validation, phase 1

    errorMessage.append("Validation error:");
    BasicDBObject jsonifiedConfig = parseLogstashConfig(config, errorMessage);
    if (null == jsonifiedConfig) {
        return null;
    }
    errorMessage.setLength(0);

    // Configuration validation, phase 2 - very basic checks on the structure of the object

    Object input = jsonifiedConfig.get("input");
    if ((null == input) || !(input instanceof BasicDBObject)) { // Does input exist?
        errorMessage.append(
                "Invalid input format, should be 'input { INPUT_TYPE { ... } }' (only one INPUT_TYPE) and also contain a filter, no \"s around them. (0)");
        return null;
    } //TESTED (3_1d)
    else { // Check there's only one input type and (unless admin) it's one of the allowed types
        BasicDBObject inputDbo = (BasicDBObject) input;
        if (1 != inputDbo.size()) {
            errorMessage.append(
                    "Invalid input format, should be 'input { INPUT_TYPE { ... } }' (only one INPUT_TYPE) and also contain a filter, no \"s around them. (1)");
            return null;
        } //TESTED
        if (!isAdmin) {
            for (String key : inputDbo.keySet()) {
                if (!_allowedInputs.contains(key.toLowerCase())) {
                    errorMessage.append("Security error, non-admin not allowed input type " + key
                            + ", allowed options: " + _allowedInputs.toString());
                    return null;
                } //TESTED
            }
        } //TESTED (3_1abc)
    }
    Object filter = jsonifiedConfig.get("filter");
    if ((null == filter) || !(filter instanceof BasicDBObject)) { // Does filter exist?
        errorMessage.append(
                "Invalid input format, should be 'input { INPUT_TYPE { ... } }' (only one INPUT_TYPE) and also contain a filter, no \"s around them. (2)");
        return null;
    } //TESTED (3_2d)
    else { // Check there's only one input type and (unless admin) it's one of the allowed types
        if (!isAdmin) {
            BasicDBObject filterDbo = (BasicDBObject) filter;
            for (String key : filterDbo.keySet()) {
                if (!_allowedFilters.contains(key.toLowerCase())) {
                    errorMessage.append("Security error, non-admin not allowed filter type " + key
                            + ", allowed options: " + _allowedFilters.toString());
                    return null;
                } //TESTED
            }
        } //TESTED (3_2abc)
    }

    // Configuration validation, phase 3

    Matcher m = null;
    m = _validationRegexInputReplace.matcher(config);
    if (!m.find()) {
        errorMessage.append(
                "Invalid input format, should be 'input { INPUT_TYPE { ... } }' (only one INPUT_TYPE) and also contain a filter, no \"s around them. (3)");
        return null;
    } //TESTED (see above)
    else { // If admin check on allowed types
        String inputType = m.group(2).toLowerCase();

        // If it's a file-based plugin then replace sincedb_path (check that it's not used during the JSON-ification):
        if (inputType.equalsIgnoreCase("file") || inputType.equalsIgnoreCase("s3")) {
            config = _validationRegexInputReplace.matcher(config)
                    .replaceFirst("$1\n      sincedb_path => \"_XXX_DOTSINCEDB_XXX_\"\n");
        } //TESTED

    } //TESTED

    m = _validationRegexNoSourceKey.matcher(config);
    // (this won't help malicious changes to source key, but will let people know they're not supposed to)
    if (m.find()) {
        errorMessage.append(
                "Not allowed to reference sourceKey - this is automatically appended by the logstash harvester");
        return null;
    } //TESTED      

    // OK now need to append the sourceKey at each stage of the pipeline to really really ensure that nobody sets sourceKey to be different 

    m = _validationRegexAppendFields.matcher(config);
    StringBuffer newConfig = new StringBuffer();
    if (m.find()) {
        m.appendReplacement(newConfig, "add_field => [ \"sourceKey\", \"" + sourceKey + "\"] \n\n" + m.group()
                + " \n if [sourceKey] == \"" + sourceKey + "\" { \n\n ");
    } else {
        errorMessage.append(
                "Invalid input format, should be 'input { INPUT_TYPE { ... } }' (only one INPUT_TYPE) and also contain a filter, no \"s around them. (4)");
        return null;
    }
    m.appendTail(newConfig);
    config = newConfig.toString();
    config = config.replaceAll("}[^}]*$", ""); // (remove the last })
    config += "\n\n mutate { update => [ \"sourceKey\", \"" + sourceKey + "\"] } \n}\n}\n"; // double check the sourceKey hasn't been overwritten and close the if from above
    //TESTED (syntactically correct and does overwrite sourceKey everywhere - success_2_2)

    return config;
}

From source file:edu.isi.pfindr.learn.util.PairsFileIO.java

private void getGoldClassForPairs(String inputFilePath) {

    LinkedMap originalTestPairsClassMap = new LinkedMap();
    String originalTestPairsFile = "data/cohort1/bio_nlp/cohort1_s_test_pairs.txt";
    BufferedReader br = null;//from  w  w w . java  2  s  .com
    String[] lineArray;
    String thisLine;
    try {
        br = new BufferedReader(new FileReader(originalTestPairsFile));
        while ((thisLine = br.readLine()) != null) {
            thisLine = thisLine.trim();
            if (thisLine.equals(""))
                continue;

            lineArray = thisLine.split("\t");
            originalTestPairsClassMap.put(lineArray[0] + "\t" + lineArray[1], lineArray[2]);
        }
    } catch (IOException io) {
        try {
            if (br != null)
                br.close();
            io.printStackTrace();
        } catch (IOException e) {
            System.out.println("Problem occured while closing output stream " + br);
            e.printStackTrace();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    List<String> phenotypeList = null;
    StringBuffer resultFileBuffer = new StringBuffer();

    //Read the pairs file, and write the pairs with class from actual test file
    try {
        BufferedWriter resultPairsWriter = new BufferedWriter(
                new FileWriter(inputFilePath.split("\\.")[0] + "_with_gold_class.txt"));
        phenotypeList = FileUtils.readLines(new File(inputFilePath));

        for (int i = 0; i < phenotypeList.size(); i++) {

            lineArray = phenotypeList.get(i).split("\t");
            resultFileBuffer.append(lineArray[0]).append("\t").append(lineArray[1]).append("\t")
                    .append(originalTestPairsClassMap.get(lineArray[0] + "\t" + lineArray[1])).append("\n");
        }

        resultPairsWriter.append(resultFileBuffer.toString());
        resultFileBuffer.setLength(0);
        resultPairsWriter.flush();

    } catch (IOException e) {
        System.out.println("Error while reading/writing file with pairs" + e.getMessage());
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:org.eclipse.wb.tests.designer.core.model.ObjectInfoTest.java

/**
 * Test that listener automatically removed after {@link ObjectInfo#refresh()} when its
 * {@link ObjectInfo} is not linked to its parent.
 *///from  w w w .ja  va2 s. c o m
public void test_broadcast_autoRemove_whenRemoveObject() throws Exception {
    TestObjectInfo parent = new TestObjectInfo("parent");
    TestObjectInfo child = new TestObjectInfo("child");
    // add child and listener (bound to child)
    parent.addChild(child);
    final StringBuffer buffer = new StringBuffer();
    ObjectEventListener listener = new ObjectEventListener() {
        @Override
        public void dispose() throws Exception {
            buffer.append("dispose");
        }
    };
    child.addBroadcastListener(listener);
    // listener works
    {
        child.getBroadcastObject().dispose();
        assertEquals("dispose", buffer.toString());
        buffer.setLength(0);
    }
    // remove "child", do refresh()
    parent.removeChild(child);
    parent.refresh();
    // listener was removed
    {
        child.getBroadcastObject().dispose();
        assertEquals("", buffer.toString());
        buffer.setLength(0);
    }
}

From source file:org.openadaptor.auxil.convertor.delimited.AbstractDelimitedStringConvertor.java

/**
 * Splits a string using a regular expression. Preserves blocks of characters
 * between quoteChars./* w ww .j  a  v a2 s.c om*/
 * 
 * @param delimitedString the delimited string
 * @param regexp a regular expression delimiter
 * @param quoteChar quote character
 * @return an array of strings corresponding to the fields in the string supplied
 * ToDo: add escaping of quote characters
 */
protected String[] extractQuotedValuesRegExp(String delimitedString, String regexp, char quoteChar) {
    char[] chars = delimitedString.toCharArray();
    boolean inQuotes = false;
    StringBuffer buffer = new StringBuffer();
    StringBuffer quoteBuffer = new StringBuffer();
    ArrayList quotes = new ArrayList();
    String escapeSeq = new String(new char[] { 0, 0xff, 0, 0xff });

    /* replace quoted blocks with the escapeSeq */
    for (int i = 0; i < chars.length; i++) {
        if (inQuotes) {
            inQuotes = chars[i] != quoteChar;
            quoteBuffer.append(chars[i]);
            if (!inQuotes) {
                /* finished parsing a quote */
                buffer.append(escapeSeq);
                quotes.add(quoteBuffer.toString());
                quoteBuffer.setLength(0);
            }
        } else if (chars[i] == quoteChar) {
            inQuotes = delimitedString.indexOf(quoteChar, i + 1) != -1;
            if (inQuotes) {
                /* started quote parsing */
                quoteBuffer.append(chars[i]);
            } else {
                buffer.append(chars[i]);
            }
        } else {
            buffer.append(chars[i]);
        }
    }

    /* split the delimitedString and put back the quoted blocks */
    String[] result = buffer.toString().split(regexp, -1);
    java.util.Iterator it = quotes.iterator();
    for (int i = 0; i < result.length; i++) {
        if (result[i].indexOf(escapeSeq) != -1) {
            result[i] = result[i].replaceAll(escapeSeq, (String) it.next());
        }
    }
    return result;
}

From source file:com.tremolosecurity.provisioning.core.providers.BasicDB.java

private PreparedStatement clearField(User user, Connection con, StringBuffer b, String attrName, String userID,
        int userIDnum) throws SQLException {
    b.setLength(0);
    b.append("UPDATE ").append(this.userTable).append(" SET ").append(attrName).append("= NULL WHERE ");
    this.getFieldName(this.userPrimaryKey, b).append("=?");
    PreparedStatement ps = con.prepareStatement(b.toString());

    if (userIDnum != -1) {
        ps.setInt(1, userIDnum);/*from w w  w  . j  a va  2  s  .  com*/
    } else {
        ps.setString(1, userID);
    }
    ps.executeUpdate();
    return ps;
}