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.jboss.test.classloader.test.ScopingUnitTestCase.java

/** Tests for accessing java system classes from scoped
 * repositories that have system class packages.
 * //  w  w  w .jav a 2s  . c o  m
 * @throws Exception
 */
public void testSystemClasses2() throws Exception {
    log.info("+++ Begin testSystemClasses2");
    UnifiedLoaderRepository3 parent = new UnifiedLoaderRepository3();
    HeirarchicalLoaderRepository3 repository0 = new HeirarchicalLoaderRepository3(parent);
    URL j0URL = getDeployURL("java-sql.jar");
    RepositoryClassLoader ucl0 = repository0.newClassLoader(j0URL, true);

    Class c0 = ucl0.loadClass("java.sql.SQLException");
    StringBuffer info = new StringBuffer();
    ClassLoaderUtils.displayClassInfo(c0, info);
    log.info("Loaded c0: " + info);

    HeirarchicalLoaderRepository3 repository1 = new HeirarchicalLoaderRepository3(parent);
    repository1.setUseParentFirst(false);
    RepositoryClassLoader ucl1 = repository1.newClassLoader(j0URL, true);
    Class c1 = ucl1.loadClass("java.sql.SQLException");
    info.setLength(0);
    ClassLoaderUtils.displayClassInfo(c1, info);
    log.info("Loaded c1: " + info);

    Class c2 = ucl1.loadClass("java.sql.SQLWarning");
    info.setLength(0);
    ClassLoaderUtils.displayClassInfo(c2, info);
    log.info("Loaded c2: " + info);
}

From source file:Strings.java

/** Process one file */
protected void process(String fileName, InputStream inStream) {
    try {// w ww  .j  a  v  a  2s .  c o  m
        int i;
        char ch;

        // This line alone cuts the runtime by about 66% on large files.
        BufferedInputStream is = new BufferedInputStream(inStream);

        StringBuffer sb = new StringBuffer();

        // Read a byte, cast it to char, check if part of printable string.
        while ((i = is.read()) != -1) {
            ch = (char) i;
            if (isStringChar(ch) || (sb.length() > 0 && ch == ' '))
                // If so, build up string.
                sb.append(ch);
            else {
                // if not, see if anything to output.
                if (sb.length() == 0)
                    continue;
                if (sb.length() >= minLength) {
                    report(fileName, sb);
                }
                sb.setLength(0);
            }
        }
        is.close();
    } catch (IOException e) {
        System.out.println("IOException: " + e);
    }
}

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

private void executeWorkFlow(String wfName, User user, Set<String> attributes, Map<String, Object> request)
        throws ProvisioningException {

    StringBuffer surl = new StringBuffer();
    surl.append(this.wfUrlBase).append("/services/wf/login");

    HttpGet get = new HttpGet(surl.toString());
    try {//from   w  ww  . java2s  .co  m
        try {
            httpclient.execute(get);
        } catch (ClientProtocolException e1) {

        } catch (IOException e1) {

        }
    } finally {
        get.releaseConnection();
    }

    surl.setLength(0);
    surl.append(this.wfUrlBase).append("/services/wf/execute");

    HttpPost post = new HttpPost(surl.toString());

    try {

        TremoloUser tu = new TremoloUser();
        tu.setAttributes(new ArrayList<Attribute>());

        tu.setUid(user.getUserID());
        tu.setUserPassword(user.getPassword());

        for (String attrName : user.getAttribs().keySet()) {
            Attribute attr = user.getAttribs().get(attrName);
            if (attributes.size() == 0 || attributes.contains(attrName)) {
                tu.getAttributes().add(attr);
            }
        }

        WFCall wfcall = new WFCall();
        wfcall.setName(wfName);
        wfcall.setUidAttributeName(this.uidAttrName);
        wfcall.setUser(tu);
        wfcall.setRequestParams(new HashMap<String, Object>());
        wfcall.getRequestParams().put(ProvisioningParams.UNISON_EXEC_TYPE, ProvisioningParams.UNISON_EXEC_SYNC);
        Gson gson = new Gson();
        String jsonOut = gson.toJson(wfcall);

        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        formparams.add(new BasicNameValuePair("wfcall", jsonOut));

        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");

        post.setEntity(entity);

        HttpResponse response = httpclient.execute(post);

        BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String line = null;
        StringBuffer res = new StringBuffer();
        while ((line = in.readLine()) != null) {
            //System.out.println(line);
            res.append(line).append('\n');
        }

        ProvisioningResult provRes = gson.fromJson(res.toString(), ProvisioningResult.class);

        if (!provRes.isSuccess()) {
            throw new ProvisioningException(provRes.getError().getError());
        }

    } catch (Exception e) {
        throw new ProvisioningException("Could not execute workflow", e);
    } finally {
        post.releaseConnection();
    }

}

From source file:org.apache.bsf.engines.netrexx.NetRexxEngine.java

/**
 * This is shared code for the exec() and eval() operations. It will
 * evaluate a string containing a NetRexx method body -- which may be
 * as simple as a single return statement.
 * It should store the "bsf" handle where the
 * script can get to it, for callback purposes.
 * <p>/*w ww.j  av  a 2 s .  c o  m*/
 * Note that NetRexx compilation imposes serious overhead -- 11 seconds for
 * the first compile, about 3 thereafter -- but in exchange you get
 * Java-like speeds once the classes have been created (minus the cache
 * lookup cost).
 * <p>
 * Nobody knows whether javac is threadsafe.
 * I'm going to serialize access to the compilers to protect it.
 */
public Object execEvalShared(String source, int lineNo, int columnNo, Object oscript, boolean returnsObject)
        throws BSFException {
    Object retval = null;
    String classname = null;
    GeneratedFile gf = null;

    // Moved into the exec process; see comment above.
    Class rexxclass = null;

    String basescript = oscript.toString();
    String script = basescript; // May be altered by $$CLASSNAME$$ expansion

    try {
        // Do we already have a class exactly matching this code?
        rexxclass = (Class) codeToClass.get(basescript);

        if (rexxclass != null)

        {
            logger.debug("NetRexxEngine: Found pre-compiled class" + " for script '" + basescript + "'");
            classname = rexxclass.getName();
        } else {
            gf = openUniqueFile(tempDir, "BSFNetRexx", ".nrx");
            if (gf == null)
                throw new BSFException("couldn't create NetRexx scratchfile");

            // Obtain classname
            classname = gf.className;

            // Decide whether to declare a return type
            String returnsDecl = "";
            if (returnsObject)
                returnsDecl = "returns java.lang.Object";

            // Write the kluge header to the file.
            // ***** By doing so we give up the ability to use Property blocks.
            gf.fos.write(("class " + classname + ";\n").getBytes());
            gf.fos.write(("method BSFNetRexxEngineEntry(bsf=org.apache.bsf.util.BSFFunctions) "
                    + " public static " + returnsDecl + ";\n").getBytes());

            // Edit the script to replace placeholder with the generated
            // classname. Note that this occurs _after_ the cache was
            // checked!
            int startpoint, endpoint;
            if ((startpoint = script.indexOf(placeholder)) >= 0) {
                StringBuffer changed = new StringBuffer();
                for (; startpoint >= 0; startpoint = script.indexOf(placeholder, startpoint)) {
                    changed.setLength(0); // Reset for 2nd pass or later
                    if (startpoint > 0)
                        changed.append(script.substring(0, startpoint));
                    changed.append(classname);
                    endpoint = startpoint + placeholder.length();
                    if (endpoint < script.length())
                        changed.append(script.substring(endpoint));
                    script = changed.toString();
                }
            }

            BSFDeclaredBean tempBean;
            String className;

            for (int i = 0; i < declaredBeans.size(); i++) {
                tempBean = (BSFDeclaredBean) declaredBeans.elementAt(i);
                className = StringUtils.getClassName(tempBean.type);

                gf.fos.write(
                        (tempBean.name + " =" + className + "   bsf.lookupBean(\"" + tempBean.name + "\");")
                                .getBytes());
            }

            if (returnsObject)
                gf.fos.write("return ".getBytes());

            // Copy the input to the file.
            // Assumes all available -- probably mistake, but same as
            // other engines.
            gf.fos.write(script.getBytes());
            gf.fos.close();

            logger.debug("NetRexxEngine: wrote temp file " + gf.file.getPath() + ", now compiling");

            // Compile through Java to .class file
            String command = gf.file.getPath(); //classname;
            if (logger.isDebugEnabled()) {
                command += " -verbose4";
            } else {
                command += " -noverbose";
                command += " -noconsole";
            }

            netrexx.lang.Rexx cmdline = new netrexx.lang.Rexx(command);
            int retValue;

            // May not be threadsafe. Serialize access on static object:
            synchronized (serializeCompilation) {
                // compile to a .java file
                retValue = COM.ibm.netrexx.process.NetRexxC.main(cmdline, new PrintWriter(System.err));
            }

            // Check if there were errors while compiling the Rexx code.
            if (retValue == 2) {
                throw new BSFException(BSFException.REASON_EXECUTION_ERROR, "There were NetRexx errors.");
            }

            // Load class.
            logger.debug("NetRexxEngine: loading class " + classname);
            rexxclass = EngineUtils.loadClass(mgr, classname);

            // Stash class for reuse
            codeToClass.put(basescript, rexxclass);
        }

        Object[] args = { mgrfuncs };
        retval = callStatic(rexxclass, "BSFNetRexxEngineEntry", args);
    } catch (BSFException e) {
        // Just forward the exception on.
        throw e;
    } catch (Exception e) {
        e.printStackTrace();
        if (e instanceof InvocationTargetException) {
            Throwable t = ((InvocationTargetException) e).getTargetException();
            t.printStackTrace();
        }
        throw new BSFException(BSFException.REASON_IO_ERROR, e.getMessage(), e);
    } finally {
        // Cleanup: delete the .nrx and .class files
        // (if any) generated by NetRexx Trace requests.

        if (gf != null && gf.file != null && gf.file.exists())
            gf.file.delete(); // .nrx file

        if (classname != null) {
            // Generated src
            File file = new File(tempDir + File.separatorChar + classname + ".java");
            if (file.exists())
                file.delete();

            // Generated class
            file = new File(classname + ".class");
            if (file.exists())
                file.delete();

            // Can this be done without disrupting trace?
            file = new File(tempDir + File.separatorChar + classname + ".crossref");
            if (file.exists())
                file.delete();

            // Search for and clean up minor classes, classname$xxx.class
            file = new File(tempDir);
            minorPrefix = classname + "$"; // Indirect arg to filter
            String[] minor_classfiles = file.list(
                    // ANONYMOUS CLASS for filter:
                    new FilenameFilter() {
                        // Starts with classname$ and ends with .class
                        public boolean accept(File dir, String name) {
                            return (0 == name.indexOf(minorPrefix))
                                    && (name.lastIndexOf(".class") == name.length() - 6);
                        }
                    });
            if (minor_classfiles != null)
                for (int i = minor_classfiles.length; i > 0;) {
                    file = new File(minor_classfiles[--i]);
                    file.delete();
                }
        }
    }

    return retval;
}

From source file:FilenameUtils.java

/**
 * Splits a string into a number of tokens.
 * /*from   w ww.ja  va  2s . c  om*/
 * @param text  the text to split
 * @return the tokens, never null
 */
static String[] splitOnTokens(String text) {
    // used by wildcardMatch
    // package level so a unit test may run on this

    if (text.indexOf("?") == -1 && text.indexOf("*") == -1) {
        return new String[] { text };
    }

    char[] array = text.toCharArray();
    ArrayList list = new ArrayList();
    StringBuffer buffer = new StringBuffer();
    for (int i = 0; i < array.length; i++) {
        if (array[i] == '?' || array[i] == '*') {
            if (buffer.length() != 0) {
                list.add(buffer.toString());
                buffer.setLength(0);
            }
            if (array[i] == '?') {
                list.add("?");
            } else if (list.size() == 0 || (i > 0 && list.get(list.size() - 1).equals("*") == false)) {
                list.add("*");
            }
        } else {
            buffer.append(array[i]);
        }
    }
    if (buffer.length() != 0) {
        list.add(buffer.toString());
    }

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

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

private void csarBasicValidation(Component mainComponent, byte[] downloadCSAR) {
    try (ByteArrayInputStream ins = new ByteArrayInputStream(downloadCSAR);
            ZipInputStream zip = new ZipInputStream(ins);) {

        String resourceYaml = null;
        byte[] buffer = new byte[1024];
        ZipEntry nextEntry = zip.getNextEntry();
        StringBuffer sb = new StringBuffer();
        int len;//from ww w  .  j a  va 2 s  .  c  o m

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

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

        sb.setLength(0);
        nextEntry = zip.getNextEntry();

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

        resourceYaml = sb.toString();

        YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
        ArtifactDefinition artifactDefinition = mainComponent.getToscaArtifacts().get(ASSET_TOSCA_TEMPLATE);
        String fileName = artifactDefinition.getArtifactName();
        assertEquals("Tosca-Template file name: ", "Definitions/" + fileName, nextEntry.getName());
        assertTrue("Tosca template Yaml validation: ",
                yamlToObjectConverter.isValidYaml(resourceYaml.getBytes()));

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

From source file:ORG.oclc.oai.server.catalog.AbstractCatalog.java

/**
 * Convert the requested 'from' parameter to the finest granularity supported by this
 * repository.//w w  w .ja v a  2s  . c om
 * 
 * @exception BadArgumentException one or more of the arguments are bad.
 */
public String toFinestFrom(String from) throws BadArgumentException {
    if (debug) {
        System.out.println("AbstractCatalog.toFinestFrom: from=" + from);
        System.out.println(
                "                            target=" + VALID_GRANULARITIES[supportedGranularityOffset]);
    }
    if (StringUtils.isEmpty(from)) {
        return "";
    }
    if (from.length() > VALID_GRANULARITIES[supportedGranularityOffset].length()) {
        throw new BadArgumentException();
    }
    if (from.length() != VALID_GRANULARITIES[supportedGranularityOffset].length()) {
        StringBuffer sb = new StringBuffer(from);
        if (sb.charAt(sb.length() - 1) == 'Z') {
            sb.setLength(sb.length() - 1);
        }

        sb.append(FROM_GRANULARITIES[supportedGranularityOffset].substring(sb.length()));
        from = sb.toString();
    }

    if (!isValidGranularity(from)) {
        throw new BadArgumentException();
    }

    return from;
}

From source file:com.pureinfo.srm.view.function.MakeSelectOptions.java

/**
 * @see com.pureinfo.dolphin.script.function.handler.IFunctionHandler#perform(java.lang.Object[],
 *      com.pureinfo.dolphin.script.execute.IContext)
 *//*from ww  w  .  ja v  a  2 s.c om*/
public Object perform(Object[] _args, IContext _context) throws PureException {
    FunctionHandlerUtil.validateArgsNum(_args, 1);

    String[] sDefault = new String[0];
    if (_args.length > IDX_DEFAULTS && _args[IDX_DEFAULTS] != null) {
        Object def = _args[IDX_DEFAULTS];
        if (def.getClass().isArray()) {
            Object[] objs = (Object[]) def;
            sDefault = new String[objs.length];
            for (int i = 0; i < objs.length; i++) {
                sDefault[i] = objs[i].toString();
            }
        } else {
            sDefault = new String[] { def.toString() };
        }

    }
    String[] sExcludes = new String[0];
    if (_args.length > IDX_EXCLUDES && _args[IDX_EXCLUDES] != null) {
        String str = (String) _args[IDX_EXCLUDES];
        if (str.length() > 0) {
            sExcludes = str.split(",");
        }
    }

    String[][] datas = (String[][]) _args[IDX_DATAS];
    StringBuffer sbuff = null;
    try {
        sbuff = new StringBuffer();
        for (int i = 0; i < datas.length; i++) {
            if (ArrayUtils.contains(sExcludes, datas[i][0])) {
                continue;
            }
            sbuff.append("<option value=\"").append(HtmlUtil.encode(datas[i][0])).append('"');
            sbuff.append(ArrayUtils.contains(sDefault, datas[i][0]) ? " selected" : "");
            sbuff.append('>');
            sbuff.append(HtmlUtil.encode(datas[i][1]));
        }
        return sbuff.toString();
    } finally {
        if (sbuff != null)
            sbuff.setLength(0);
    }
}

From source file:com.tremolosecurity.provisioning.sharepoint.SharePointGroups.java

private void addUserGroups(String userID, User fromsp) throws ProvisioningException {

    if (!this.multiSite) {
        GetGroupCollectionFromUserResult gres = null;
        try {//from w  w w  .j  av  a2  s . c  o  m
            gres = this.getConnection()
                    .getGroupCollectionFromUser(fromsp.getAttribs().get("Login").getValues().get(0));

            for (Group g : gres.getGetGroupCollectionFromUser().getGroups().getGroup()) {
                fromsp.getGroups().add(g.getName());
            }
        } catch (Exception e) {

            if (logger.isDebugEnabled()) {
                logger.debug("Error retrieving groups for '" + userID + "'");
            }

        }

    } else {
        for (String uri : this.uris.keySet()) {
            URL url = this.uris.get(uri);

            GetGroupCollectionFromUserResult gres = null;
            try {
                gres = this.getConnection(url)
                        .getGroupCollectionFromUser(fromsp.getAttribs().get("Login").getValues().get(0));
                StringBuffer b = new StringBuffer();

                for (Group g : gres.getGetGroupCollectionFromUser().getGroups().getGroup()) {
                    b.setLength(0);
                    b.append(uri).append('^').append(g.getName());
                    fromsp.getGroups().add(b.toString());
                }
            } catch (Exception e) {

                if (logger.isDebugEnabled()) {
                    logger.debug("Error retrieving groups for '" + userID + "'");
                }
            }

        }
    }
}

From source file:biz.wolschon.finance.jgnucash.HBCIImporter.PropertiesHBCICallback.java

/**
 * {@inheritDoc}/*from w w  w.j a  v  a2 s .co m*/
 */
public void callback(final HBCIPassport passport, final int reason, final String msg, final int datatype,
        final StringBuffer retData) {
    LOGGER.info("callback: reason=" + reason + " msg=\"" + msg + "\" " + "datatype=" + datatype + " "
            + "retData=\"" + retData + "\"");

    switch (reason) {

    case NEED_COUNTRY:
        //if (msg.equals("Lnderkennzeichen (DE fr Deutschland)")) {
        String country = getProperties().getProperty(HBCIImporter.SETTINGS_COUNTRY, "DE");
        retData.setLength(0); // empty the buffer first
        retData.append(country);
        return;
    //}
    case NEED_PT_PIN:
        //if (msg.equals("Bitte geben Sie die PIN fr das PIN/TAN-Verfahren ein")
        //      || msg.equals("Bitte geben Sie die PIN fr das PIN/TAN-Verfahren ein")) {
        String pin = getProperties().getProperty(HBCIImporter.SETTINGS_PIN);
        if (pin == null || pin.trim().length() == 0 || pin.equalsIgnoreCase("(optional)")) {
            pin = JOptionPane.showInputDialog("Your HBCI-PIN:");
        }
        retData.setLength(0); // empty the buffer first
        retData.append(pin);
        return;
    //}
    case NEED_PASSPHRASE_LOAD:
        //  Bitte geben Sie das neue Passwort fr die Sicherung der Passport-Datei ein
        //if (msg.equals("Bitte geben Sie das Passwort fr den Zugriff auf die Passport-Datei ein")
        //      || msg.equals("Bitte geben Sie das Passwort fr den Zugriff auf die Passport-Datei ein")) {
        retData.setLength(0); // empty the buffer first
        retData.append("0000");
        return;
    //}
    case NEED_PASSPHRASE_SAVE:
        //if (msg.equals("Bitte geben Sie das neue Passwort fr die Sicherung der Passport-Datei ein")
        //      || msg.equals("Bitte geben Sie das neue Passwort fr die Sicherung der Passport-Datei ein")) {
        retData.setLength(0); // empty the buffer first
        retData.append("0000");
        return;
    //}
    case NEED_BLZ:
        //if (msg.equals("Bankleitzahl")) {
        retData.setLength(0); // empty the buffer first
        retData.append(getProperties().getProperty(HBCIImporter.SETTINGS_BANKCODE));
        return;
    //}
    case NEED_HOST:
        //if (msg.equals("Hostname/IP-Adresse")) {
        retData.setLength(0); // empty the buffer first
        String property = getProperties().getProperty(HBCIImporter.SETTINGS_SERVER);
        if (property.startsWith("https://")) {
            property = property.substring("https://".length());
        }
        retData.append(property);
        return;
    //}
    case NEED_USERID:
        if (msg.equals("Nutzerkennung")) {
            retData.setLength(0); // empty the buffer first
            retData.append(getProperties().getProperty(HBCIImporter.SETTINGS_ACCOUNT));
            return;
        }
    case NEED_CUSTOMERID:
        if (msg.equals("Kunden-ID")) {
            //retData.setLength(0); // empty the buffer first
            //Feld soll freigelassen werden retData.replace(0, retData.length(), "90246243");
            return;
        }
    case NEED_CONNECTION: // Bitte stellen Sie jetzt die Verbindung zum Internet her
        return;
    case CLOSE_CONNECTION: // Sie knnen die Internetverbindung jetzt beenden
        return;
    case NEED_PT_SECMECH:
        // we don't really care about this but prefer iTan and Einschritt if possible
        // the fallback-case is enough to handle everything anyway.
        if (retData.toString().contains("900:iTAN")) {
            retData.setLength(0); // empty the buffer first
            retData.append("900");
            return;
        }
        if (retData.toString().contains("999:Einschritt")) {
            retData.setLength(0); // empty the buffer first
            retData.append("999");
            return;
        }
        retData.setLength("999".length()); // select whatever method comes first

    default:
        LOGGER.warn("callback: (unhandled) reason=" + reason + " msg=" + msg);

    }

}