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:PropsToXML.java

/**
 * <p>This helper method loads the XML properties from a specific
 *   XML element, or set of elements.</p>
 *
 * @param elements <code>List</code> of elements to load from.
 * @param baseName the base name of this property.
 *///from  ww  w. j a  v a 2 s.c  om
private void loadFromElements(List elements, StringBuffer baseName) {
    // Iterate through each element
    for (Iterator i = elements.iterator(); i.hasNext();) {
        Element current = (Element) i.next();
        String name = current.getName();
        String text = current.getTextTrim();
        // String text = current.getAttributeValue("value");            

        // Don't add "." if no baseName
        if (baseName.length() > 0) {
            baseName.append(".");
        }
        baseName.append(name);

        // See if we have an element value
        if ((text == null) || (text.equals(""))) {
            // If no text, recurse on children
            loadFromElements(current.getChildren(), baseName);
        } else {
            // If text, this is a property
            setProperty(baseName.toString(), text);
        }

        // On unwind from recursion, remove last name
        if (baseName.length() == name.length()) {
            baseName.setLength(0);
        } else {
            baseName.setLength(baseName.length() - (name.length() + 1));
        }
    }
}

From source file:com.mindcognition.mindraider.application.model.outline.OutlineCustodian.java

/**
 * Process line when importing from TWiki.
 * //from  w  w w. j  ava2  s .  co  m
 * @param progressDialogJFrame
 * @param notebookUri
 * @param parentConceptUris
 * @param lastConceptName
 * @param annotation
 * @throws Exception
 */
private void twikiImportProcessLine(ProgressDialogJFrame progressDialogJFrame, String notebookUri,
        String[] parentConceptUris, String lastConceptName, StringBuffer annotation) throws Exception {
    if (lastConceptName == null) {
        // this is notebook annotation (typically TOC before the first
        // section of depth 2)
        activeOutlineResource.setAnnotation(annotation.toString());
        activeOutlineResource.save();
        annotation.setLength(0);
    } else {

        // write previous section annotation
        // if(annotation.length()>0) {
        logger.debug("ANNOTATION:\n" + annotation.toString());
        StatusBar.show("Creating concept '" + lastConceptName + "'...");

        int depth = lastConceptName.indexOf(' ');
        lastConceptName = lastConceptName.substring(depth + 1);
        depth -= 4;
        logger.debug("Depth is: " + depth);
        logger.debug("Label is: " + lastConceptName);

        parentConceptUris[depth] = MindRaider.noteCustodian.create(activeOutlineResource,
                parentConceptUris[depth - 1], lastConceptName,
                MindRaiderVocabulary.getConceptUri(Utils.getNcNameFromUri(notebookUri),
                        "tempConcept" + System.currentTimeMillis()),
                annotation.toString(), false, MindRaiderConstants.MR_OWL_CONTENT_TYPE_TWIKI);

        if (progressDialogJFrame != null) {
            progressDialogJFrame.setProgressMessage(lastConceptName);
        }

        annotation.setLength(0);
        // }
    }
}

From source file:org.pouzinsociety.actions.ping.PingCommand.java

public void execute() throws SocketException, InterruptedException {
    int i = 0;/*from w  ww.jav a  2 s.com*/
    while (stackConfiguration.Complete() == false && i < 100) {
        Thread.sleep(1000);
        i++;
        log.info("Waiting for completion");
    }
    StringBuffer cmdOutput = new StringBuffer();
    StringBuffer tmp = new StringBuffer();
    String hostname = "10.0.0.1";
    try {
        this.dst = new IPv4Address(InetAddress.getByName(hostname));
    } catch (UnknownHostException ex) {
        cmdOutput.append("Error: Unknown host: " + ex.getMessage() + "\n");
        log.error(cmdOutput.toString());
        return;
    }

    cmdOutput.append("\nping " + hostname + "\nOutput:\n");

    final IPv4Header netHeader = new IPv4Header(0, this.ttl, IPv4Constants.IPPROTO_ICMP, this.dst, 8);
    netHeader.setDontFragment(this.dontFragment);

    rt = ipv4Service.getRoutingTable();
    log.info("Routing Table:\n" + rt.toString());

    final ICMPProtocol icmpProtocol = (ICMPProtocol) ipv4NetworkLayer
            .getTransportLayer(ICMPProtocol.IPPROTO_ICMP);

    icmpProtocol.addListener(this);
    try {
        int id_count = 0;
        int seq_count = 0;
        while (this.count != 0) {
            tmp.append("Ping " + dst + " attempt " + seq_count + "\n");
            cmdOutput.append(tmp);
            log.info(tmp.toString());
            tmp.setLength(0);

            if (!this.flood) {
                this.wait = true;
            }

            SocketBuffer packet = new SocketBuffer();
            packet.insert(this.size);
            ICMPEchoHeader transportHeader = new ICMPEchoHeader(8, id_count, seq_count);
            transportHeader.prefixTo(packet);

            Request r = new Request(this.stat, this.timeout, System.currentTimeMillis(), id_count, seq_count);
            registerRequest(r);
            ipv4Service.transmit(netHeader, packet);

            while (this.wait) {
                long time = System.currentTimeMillis() - r.getTimestamp();
                if (time > this.interval) {
                    this.wait = false;
                }
                Thread.sleep(500);
                synchronized (this) {
                    if (response) {
                        tmp.append("Reply from " + dst.toString() + ": " + (hdr1.getDataLength() - 8)
                                + "bytes of data " + "ttl=" + hdr1.getTtl() + " " + "seq=" + hdr2.getSeqNumber()
                                + " " + "time=" + (roundt) + "ms\n");
                        log.info(tmp.toString());
                        cmdOutput.append(tmp.toString());
                        tmp.setLength(0);
                        response = false;
                    }
                }
            }
            this.count--;
            seq_count++;
        }

        while (!isEmpty()) {
            Thread.sleep(100);
        }
    } finally {
        icmpProtocol.removeListener(this);
    }

    tmp.append("-> Packet statistics\n" + this.stat.getStatistics() + "\n");
    log.info(tmp.toString());
    cmdOutput.append(tmp);
    tmp.setLength(0);
    log.info(cmdOutput.toString());

}

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

private void many2manyLoadGroups(StringBuffer select, Connection con, User user, int userKey)
        throws SQLException {
    PreparedStatement ps;/*from   ww w . j  a  v  a 2 s.  c o  m*/
    ResultSet rs;
    select.setLength(0);
    select.append("SELECT ");
    getFieldName(this.groupName, select).append(" FROM ").append(this.groupTable).append(" INNER JOIN ")
            .append(this.groupLinkTable).append(" ON ").append(this.groupTable).append(".")
            .append(this.groupPrimaryKey).append("=").append(this.groupLinkTable).append(".")
            .append(this.groupGroupKey).append(" INNER JOIN ").append(this.userTable).append(" ON ")
            .append(this.userTable).append(".").append(this.userPrimaryKey).append("=")
            .append(this.groupLinkTable).append(".").append(this.groupUserKey).append(" WHERE ")
            .append(this.userTable).append(".").append(this.userPrimaryKey).append("=?");

    ps = con.prepareStatement(select.toString());
    ps.setInt(1, userKey);
    rs = ps.executeQuery();
    while (rs.next()) {

        user.getGroups().add(rs.getString(this.groupName));
    }

    rs.close();
    ps.close();
}

From source file:com.softech.tbb.action.BaseAction.java

/**
 * Return an instance of the form-bean associated with the specified name,
 * if any; otherwise return <code>null</code>. May be used to create an
 * bean registered under a known name or a form-bean name passed with the
 * mapping./*ww w  .j  a  v  a 2s . c  o m*/
 * <p>
 * It is not required that the form-bean specified here be an ActionForm
 * subclass. This allows other helper classes to be registered as form-beans
 * and then instantiated by the Action.
 * 
 * @param request
 *            The HTTP request we are processing
 * @param helperName
 *            name of the form-bean helper
 */
protected Object createHelperBean(HttpServletRequest request, String helperName) {

    StringBuffer sb = new StringBuffer();

    if (isDebug()) {
        sb.append(Log.HELPER_CREATING);
        sb.append(Log.NAME);
        sb.append(helperName);
        servlet.log(sb.toString());
    }

    Object bean = null;

    ActionFormBean formBean = null;
    if (formBean != null) {
        String className = null;
        className = formBean.getType();
        try {
            Class clazz = Class.forName(className);
            bean = clazz.newInstance();
        } catch (Throwable t) {
            bean = null;
            // assemble message: {class}: {exception}
            sb.setLength(0);
            sb.append(Log.CREATE_OBJECT_ERROR);
            sb.append(Log.NAME);
            sb.append(helperName);
            sb.append(Log.SPACE);
            sb.append(Log.ACTION_EXCEPTION);
            sb.append(t.toString());
            String message = sb.toString();
            servlet.log(message);
            // echo log message as error
            ActionErrors errors = getErrors(request, true);
            errors.add(ActionErrors.GLOBAL_ERROR, new ActionError(Tokens.HELPER_ACCESS_ERROR, message));
        }
        if (isDebug()) {
            sb.setLength(0);
            sb.append(Log.HELPER_CREATED);
            sb.append(Log.NAME);
            sb.append(helperName);
            servlet.log(sb.toString());
        }
    } else {
        // Not found
        sb.setLength(0);
        sb.append(Log.CREATE_OBJECT_ERROR);
        sb.append(Log.NAME);
        sb.append(helperName);
        sb.append(Log.SPACE);
        sb.append(Log.NOT_FOUND);
        String message = sb.toString();
        servlet.log(message);
        // echo log message as error
        ActionErrors errors = getErrors(request, true);
        errors.add(ActionErrors.GLOBAL_ERROR, new ActionError(Tokens.HELPER_ACCESS_ERROR, message));
    }

    return bean;

}

From source file:architecture.common.util.TextUtils.java

/**
 * Returns a string that has whitespace removed from both ends of the
 * String, as well as duplicate whitespace removed from within the String.
 *///from  www.  j  av  a 2s  . c  o m
public final static String innerTrim(String s) {
    StringBuffer b = new StringBuffer(s);
    int index = 0;

    while ((b.length() != 0) && (b.charAt(0) == ' ')) {
        b.deleteCharAt(0);
    }

    while (index < b.length()) {
        if (Character.isWhitespace(b.charAt(index))) {
            if (((index + 1) < b.length()) && (Character.isWhitespace(b.charAt(index + 1)))) {
                b.deleteCharAt(index + 1);
                index--; // let's restart at this character!
            }
        }

        index++;
    }

    if (b.length() > 0) {
        int l = b.length() - 1;

        if (b.charAt(l) == ' ') {
            b.setLength(l);
        }
    }

    String result = b.toString();

    return result;
}

From source file:net.rim.ejde.internal.packaging.RAPCFile.java

private void addMidletEntries(File projectFile, BlackBerryProperties properties, Vector<String> entries,
        int index) throws CoreException {
    StringBuffer sb = new StringBuffer();

    sb.append("MIDlet-").append(index);
    sb.append(": ");
    sb.append(properties._general.getTitle());
    sb.append(',');
    Icon[] icons = properties._resources.getIconFiles();
    for (int i = 0; i < icons.length; i++) {
        if (!icons[i].isFocus()) {
            // need to remove the source folder segment
            IPath iconFilePath = getSourceFolderRelativePath(icons[i].getCanonicalFileName());
            sb.append(convertToBackSlash(iconFilePath.toOSString()));
        }//from w  w w  .  ja v  a2 s.c  o m
    }
    sb.append(',');
    if (!StringUtils.isBlank(properties._application.getMainMIDletName().trim())) {
        sb.append(properties._application.getMainMIDletName());
    } else {
        sb.append(properties._application.getMainArgs());
    }
    entries.addElement(sb.toString());

    boolean hasFocusIcon = false;
    // set focus icon
    for (int i = 0; i < icons.length; ++i) {
        if (icons[i].isFocus()) {
            sb.setLength(0);
            // we only allow one focus icon
            sb.append("RIM-MIDlet-Icon-").append(index).append('-').append(1);
            sb.append(": ");
            // need to remove the source folder segment
            IPath iconFilePath = getSourceFolderRelativePath(icons[i].getCanonicalFileName());
            sb.append(convertToBackSlash(iconFilePath.toOSString()));
            sb.append(",focused");
            entries.addElement(sb.toString());
            hasFocusIcon = true;
        }
    }
    if (hasFocusIcon) {
        sb.setLength(0);
        sb.append("RIM-MIDlet-Icon-Count-").append(index);
        sb.append(": ");
        sb.append(1);
        entries.addElement(sb.toString());
    }
    sb.setLength(0);
    sb.append("RIM-MIDlet-Flags-").append(index);
    sb.append(": ");
    sb.append(getFlags(properties, false));
    entries.addElement(sb.toString());

    int ribbonPosition = properties._application.getHomeScreenPosition();
    if (ribbonPosition != 0) {
        sb.setLength(0);
        sb.append("RIM-MIDlet-Position-").append(index);
        sb.append(": ");
        sb.append(ribbonPosition);
        entries.addElement(sb.toString());
    }

    // we need to check all resource related properties to make sure the resource is valid
    String titleResourceBundleClassName = properties._resources.getTitleResourceBundleClassName();
    String titleResourceBundleKey = properties._resources.getTitleResourceBundleKey();
    if (properties._resources.hasTitleResource() && !StringUtils.isEmpty(titleResourceBundleClassName)
            && !StringUtils.isEmpty(titleResourceBundleKey)) {
        sb.setLength(0);
        sb.append("RIM-MIDlet-NameResourceBundle-").append(index);
        sb.append(": ");
        sb.append(titleResourceBundleClassName);
        entries.addElement(sb.toString());

        sb.setLength(0);
        sb.append("RIM-MIDlet-NameResourceId-").append(index);
        sb.append(": ");
        sb.append(getTitleResourceId(properties));
        entries.addElement(sb.toString());
    }
    // check kewword resources

    String keywordResourceBundleClassName = properties.getKeywordResources()
            .getKeywordTitleResourceBundleClassName();
    String keywordResourceBundleKey = properties.getKeywordResources().getKeywordResourceBundleKey();
    if (!StringUtils.isEmpty(keywordResourceBundleClassName)
            && !StringUtils.isEmpty(keywordResourceBundleKey)) {
        sb.setLength(0);
        sb.append("RIM-MIDlet-KeywordResourceBundle-").append(index);
        sb.append(": ");
        sb.append(keywordResourceBundleClassName);
        entries.addElement(sb.toString());

        sb.setLength(0);
        sb.append("RIM-MIDlet-KeywordResourceId-").append(index);
        sb.append(": ");
        sb.append(keywordResourceBundleKey);
        entries.addElement(sb.toString());
    }
}

From source file:org.geefive.salesforce.soqleditor.RESTfulQuery.java

public void executeQuery() throws Exception {
    Vector soqlResults = new Vector();

    HttpClient restClient = new HttpClient();
    restClient.getParams().setCookiePolicy(CookiePolicy.RFC_2109);
    restClient.getHttpConnectionManager().getParams().setConnectionTimeout(30000);

    //      String restfulURLTarget = serverDomain + REST_LOGIN;
    String restfulURLTarget = serverDomain + REST_QUERY;
    System.out.println("RESTful URL Target: " + restfulURLTarget);
    GetMethod method = null;//from   w  w  w  . ja  va 2s  .  co  m
    try {
        method = new GetMethod(restfulURLTarget);
        System.out.println("Setting authorization header with SID [" + SID + "]");
        method.setRequestHeader("Authorization", "OAuth " + SID);

        NameValuePair[] params = new NameValuePair[1];
        params[0] = new NameValuePair("q", "SELECT Name, Id, Phone, CreatedById from Account LIMIT 100");
        method.setQueryString(params);

        int httpResponseCode = restClient.executeMethod(method);
        System.out.println("HTTP_RESPONSE_CODE [" + httpResponseCode + "]");
        System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%");
        System.out
                .println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% EXECUTING QUERY %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%");
        if (httpResponseCode == HttpStatus.SC_OK) {
            try {
                JSONObject response = new JSONObject(
                        new JSONTokener(new InputStreamReader(method.getResponseBodyAsStream())));
                System.out.println("_____________________________________");
                System.out.println("RESPONSE [" + response + "]");
                //               Iterator itr = response.keys();
                //               while(itr.hasNext()){
                //                  String key = (String)itr.next();
                //                  System.out.println("KEY: " + (String)itr.next());
                //               }

                JSONArray resultArray = response.getJSONArray("records");
                StringBuffer soqlQueryResults = new StringBuffer();
                String token = "";
                JSONObject inner = null;
                System.out.println(resultArray.getString(0));
                inner = resultArray.getJSONObject(0);

                Iterator keys = inner.keys();
                HashMap columnNames = new HashMap();
                while (keys.hasNext()) {
                    String column = (String) keys.next();
                    System.out.println("KEY>> " + column);
                    columnNames.put(column, "");
                    soqlQueryResults.append(token + column);
                    token = " * ";
                }
                soqlResults.add(soqlQueryResults.toString());

                //System.out.println("******* UNCOMMENT ME FOR RELEASE *******");

                Iterator keyset = null;
                JSONArray results = response.getJSONArray("records");
                for (int i = 0; i < results.length(); i++) {
                    soqlQueryResults.setLength(0);
                    keyset = columnNames.keySet().iterator();
                    token = "";
                    while (keyset.hasNext()) {
                        String columnName = (String) keyset.next();
                        if (!columnName.equalsIgnoreCase("attributes")) {
                            soqlQueryResults.append(token + results.getJSONObject(i).getString(columnName));
                            token = " * ";
                        }
                    }

                    //                  System.out.println("=====>>>>>>> " + soqlQueryResults.toString());
                    soqlResults.add(soqlQueryResults.toString());

                    //                  System.out.println(results.getJSONObject(i).getString("Id") + ", "
                    //                        + results.getJSONObject(i).getString("Name") + ", "
                    //                        + results.getJSONObject(i).getString("Phone")
                    //                        + ", " + results.getJSONObject(i).getString("CreatedById"));
                } //end for
            } catch (JSONException jsonex) {
                throw jsonex;
            }
        }
    } finally {
        method.releaseConnection();
    }

    Iterator finalData = soqlResults.iterator();
    while (finalData.hasNext()) {
        System.out.println("-||=========>> " + (String) finalData.next());
    }

    System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% EXIT %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%");
}

From source file:org.apache.hadoop.mapreduce.jobhistory.HistoryViewer.java

private void printAllTaskAttempts(TaskType taskType) {
    Map<TaskID, TaskInfo> tasks = job.getAllTasks();
    StringBuffer taskList = new StringBuffer();
    taskList.append("\n").append(taskType);
    taskList.append(" task list for ").append(job.getJobId());
    taskList.append("\nTaskId\t\tStartTime");
    if (TaskType.REDUCE.equals(taskType)) {
        taskList.append("\tShuffleFinished\tSortFinished");
    }/*from  w ww.j  a va  2  s. co  m*/
    taskList.append("\tFinishTime\tHostName\tError\tTaskLogs");
    taskList.append("\n====================================================");
    System.out.println(taskList.toString());
    for (JobHistoryParser.TaskInfo task : tasks.values()) {
        for (JobHistoryParser.TaskAttemptInfo attempt : task.getAllTaskAttempts().values()) {
            if (taskType.equals(task.getTaskType())) {
                taskList.setLength(0);
                taskList.append(attempt.getAttemptId()).append("\t");
                taskList.append(StringUtils.getFormattedTimeWithDiff(dateFormat, attempt.getStartTime(), 0))
                        .append("\t");
                if (TaskType.REDUCE.equals(taskType)) {
                    taskList.append(StringUtils.getFormattedTimeWithDiff(dateFormat,
                            attempt.getShuffleFinishTime(), attempt.getStartTime()));
                    taskList.append("\t");
                    taskList.append(StringUtils.getFormattedTimeWithDiff(dateFormat,
                            attempt.getSortFinishTime(), attempt.getShuffleFinishTime()));
                }
                taskList.append(StringUtils.getFormattedTimeWithDiff(dateFormat, attempt.getFinishTime(),
                        attempt.getStartTime()));
                taskList.append("\t");
                taskList.append(attempt.getHostname()).append("\t");
                taskList.append(attempt.getError());
                String taskLogsUrl = getTaskLogsUrl(WebAppUtils.getHttpSchemePrefix(fs.getConf()), attempt);
                taskList.append(taskLogsUrl != null ? taskLogsUrl : "n/a");
                System.out.println(taskList.toString());
            }
        }
    }
}

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

/**
 * There are rare cases when we want to create sub-class of broadcast implementation.
 *//*from   w  w  w .ja  va 2s . c om*/
public void test_broadcast_deepHierarchy() throws Exception {
    TestObjectInfo object = new TestObjectInfo("object");
    // add listener
    final StringBuffer buffer = new StringBuffer();
    class Listener_1 extends ObjectEventListener {
    }
    class Listener_2 extends Listener_1 {
        public void dispose() throws Exception {
            buffer.append("invoke");
        }
    }
    Object listener = new Listener_2();
    object.addBroadcastListener(listener);
    // send broadcast
    object.getBroadcast(ObjectEventListener.class).dispose();
    assertEquals("invoke", buffer.toString());
    // remove listener and check again
    {
        buffer.setLength(0);
        object.removeBroadcastListener(listener);
        // send broadcast
        object.getBroadcast(ObjectEventListener.class).dispose();
        assertEquals("", buffer.toString());
    }
}