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:net.sbbi.upnp.messages.ActionMessage.java

private String getResponseBody(InputStream in) throws IOException {
    byte[] buffer = new byte[256];
    int readen = 0;
    StringBuffer content = new StringBuffer(256);
    while ((readen = in.read(buffer)) != -1) {
        content.append(new String(buffer, 0, readen));
    }/*from  www  . j av a2s.c om*/
    // some devices add \0 chars at XML message end
    // which causes XML parsing errors...
    int len = content.length();
    while (content.charAt(len - 1) == '\0') {
        len--;
        content.setLength(len);
    }
    return content.toString().trim();
}

From source file:server.GeneralSPARQLEndpoint.java

/**
 * Executes a SPARQL query on the Endpoint and get the results
 * in the format specified by stSPARQLQueryResultFormat, which is
 * an instance of class (or a subclass) {@link TupleQueryResultFormat}.   
 * // w w  w.  java2  s . c om
 * According to the type of the SPARQL endpoint we add the required parameters
 * in the http request.
 * 
 * @param sparqlQuery
 * @param format
 * @param endpointType
 * @return
 * @throws IOException
 */
public EndpointResult query(String sparqlQuery, stSPARQLQueryResultFormat format, String endpointType)
        throws IOException {
    assert (format != null);

    //System.out.println(URLEncoder.encode(sparqlQuery, "UTF-8"));
    // create a post method to execute
    HttpPost method = new HttpPost(getConnectionURL());

    // set the query parameter
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("query", sparqlQuery));

    //Add required parameters for Vistuoso SPARQL endpoints
    if (!getConnectionURL().contains("openrdf-sesame")) {
        params.add(new BasicNameValuePair("default-graph-uri", "http://" + endpointType));
    }

    UrlEncodedFormEntity encodedEntity = new UrlEncodedFormEntity(params, Charset.forName("UTF-8"));
    method.setEntity(encodedEntity);

    // set the content type
    method.setHeader("Content-Type", "application/x-www-form-urlencoded");

    // set the accept format
    method.addHeader("Accept", format.getDefaultMIMEType());

    try {
        // response that will be filled next
        String responseBody = "";

        // execute the method
        HttpResponse response = hc.execute(method);
        int statusCode = response.getStatusLine().getStatusCode();

        // If the response does not enclose an entity, there is no need
        // to worry about connection release
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream instream = entity.getContent();
            try {

                BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
                StringBuffer strBuf = new StringBuffer();

                // do something useful with the response
                String nextLine;
                while ((nextLine = reader.readLine()) != null) {
                    strBuf.append(nextLine + "\n");
                }

                // remove last newline character
                if (strBuf.length() > 0) {
                    strBuf.setLength(strBuf.length() - 1);
                }

                responseBody = strBuf.toString();
                //System.out.println(responseBody);

            } catch (IOException ex) {
                // In case of an IOException the connection will be released
                // back to the connection manager automatically
                throw ex;

            } catch (RuntimeException ex) {
                // In case of an unexpected exception you may want to abort
                // the HTTP request in order to shut down the underlying
                // connection and release it back to the connection manager.
                method.abort();
                throw ex;

            } finally {
                // Closing the input stream will trigger connection release
                instream.close();
            }
        }

        return new EndpointResult(statusCode, response.getStatusLine().getReasonPhrase(), responseBody);

    } catch (IOException e) {
        throw e;

    } finally {
        // release the connection.
        method.releaseConnection();
    }
}

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

/**
 * Convert the requested 'until' paramter to the finest granularity supported by this repository
 * //from www.  ja v a 2  s .  c om
 * @exception BadArgumentException one or more of the arguments are bad.
 */
public String toFinestUntil(String until) throws BadArgumentException {
    if (StringUtils.isEmpty(until)) {
        return "";
    }
    if (until.length() == VALID_GRANULARITIES[supportedGranularityOffset].length()) {
        if (!isValidGranularity(until)) {
            throw new BadArgumentException();
        }
        return until;
    }
    if (until.length() > VALID_GRANULARITIES[supportedGranularityOffset].length()) {
        throw new BadArgumentException();
    }

    StringBuffer sb = new StringBuffer(until);
    if (sb.charAt(sb.length() - 1) == 'Z') {
        sb.setLength(sb.length() - 1);
    }

    if (sb.length() < VALID_GRANULARITIES[0].length()) {
        while (sb.length() < 4) {
            sb.append("9");
        }
        switch (sb.length()) {
        case 4: // YYYY
            sb.append("-");
        case 5: // YYYY-
            sb.append("12");
        case 7: // YYYY-MM
            sb.append("-");
        case 8: // YYYY-MM-
            sb.append("31");
            break;

        case 6: // YYYY-M
        case 9: // YYYY-MM-D
            throw new BadArgumentException();
        }
    }

    until = sb.toString();
    if (until.length() == VALID_GRANULARITIES[supportedGranularityOffset].length()) {
        if (!isValidGranularity(until)) {
            throw new BadArgumentException();
        }
        return until;
    }

    if (sb.length() < VALID_GRANULARITIES[1].length()) {
        switch (sb.length()) {
        case 10: // YYYY-MM-DD
            sb.append("T");
        case 11: // YYYY-MM-DDT
            sb.append("23");
        case 13: // YYYY-MM-DDThh
            sb.append(":");
        case 14: // YYYY-MM-DDThh:
            sb.append("59");
            // case 16: // YYYY-MM-DDThh:mm
            // sb.append("Z");
            // break;

            // case 12: // YYYY-MM-DDTh
            // case 15: // YYYY-MM-DDThh:m
            // throw new BadGranularityException();
            // }
            // }

            // until = sb.toString();
            // if (until.length() ==
            // VALID_GRANULARITIES[supportedGranularityOffset].length()) {
            // if (!isValidGranularity(until))
            // throw new BadGranularityException();
            // return until;
            // }

            // if (sb.charAt(sb.length()-1) == 'Z')
            // sb.setLength(sb.length()-1); // remove the trailing 'Z'

            // if (sb.length() < VALID_GRANULARITIES[2].length()) {
            // switch (sb.length()) {
        case 16: // YYYY-MM-DDThh:mm
            sb.append(":");
        case 17: // YYYY-MM-DDThh:mm:
            sb.append("59");
        case 19: // YYYY-MM-DDThh:mm:ss
            sb.append("Z");
            break;

        case 18: // YYYY-MM-DDThh:mm:s
            throw new BadArgumentException();
        }
    }

    // until = sb.toString();
    // if (until.length() == VALID_GRANULARITIES[supportedGranularityOffset].length()) {
    // if (!isValidGranularity(until))
    // throw new BadGranularityException();
    // return until;
    // }

    // if (sb.charAt(sb.length()-1) == 'Z')
    // sb.setLength(sb.length()-1); // remove the trailing 'Z'

    // switch (sb.length()) {
    // case 19: // YYYY-MM-DDThh:mm:ss
    // sb.append(".");
    // case 20: // YYYY-MM-DDThh:mm:ss.
    // sb.append("0");
    // case 21: // YYYY-MM-DDThh:mm:ss.s
    // sb.append("Z");
    // break;
    // }

    until = sb.toString();
    if (!isValidGranularity(until)) {
        throw new BadArgumentException();
    }
    return until;
}

From source file:com.qpark.maven.plugin.flowmapper.AbstractMappingTypeGenerator.java

protected String getChildrenImports(final List<ComplexTypeChild> children) {
    StringBuffer sb = new StringBuffer(256);
    TreeSet<String> imports = new TreeSet<String>();
    for (ComplexTypeChild child : children) {
        if (!child.getComplexType().getClassNameFullQualified().startsWith("java.lang.")
                && !"interfaceName".equals(child.getChildName())
                && child.getComplexType().getPackageName() != null
                && child.getComplexType().getPackageName().length() > 0) {
            sb.setLength(0);
            sb.append("import ");
            sb.append(child.getComplexType().getClassNameFullQualified());
            sb.append(";\n");
            imports.add(sb.toString());// w  ww  .  j  a  v  a2s  .  c om
        }
    }
    sb.setLength(0);
    for (String string : imports) {
        sb.append(string);
    }
    return sb.toString();
}

From source file:com.qpark.maven.plugin.flowmapper.AbstractMappingTypeGenerator.java

protected String getChildrenImporxts(final List<ComplexTypeChild> children) {
    StringBuffer sb = new StringBuffer(256);
    TreeSet<String> imports = new TreeSet<String>();
    for (ComplexTypeChild child : children) {
        if (!child.getComplexType().getClassNameFullQualified().startsWith("java.lang.")
                && !"interfaceName".equals(child.getChildName())
                && child.getComplexType().getPackageName() != null
                && child.getComplexType().getPackageName().length() > 0) {
            sb.setLength(0);
            sb.append("import ");
            sb.append(child.getComplexType().getClassNameFullQualified());
            sb.append(";\n");
            imports.add(sb.toString());/*w  w  w . ja  v  a 2  s.  co  m*/
        }
    }
    sb.setLength(0);
    for (String string : imports) {
        sb.append(string);
    }
    return sb.toString();
}

From source file:org.geoserver.platform.GeoServerResourceLoader.java

/**
 * Helper method to build up a file path from components.
 */// w  ww.  java 2 s . c  o m
String concat(String... location) {
    StringBuffer loc = new StringBuffer();
    for (int i = 0; i < location.length; i++) {
        loc.append(location[i]).append(File.separator);
    }
    loc.setLength(loc.length() - 1);
    return loc.toString();
}

From source file:com.pureinfo.srm.project.ProjectToFinishRemindJob.java

private String makeMsg(Project _sPrj, SRMUser _sUser, int _nMonth, String sSectionName) {
    StringBuffer sbuff = new StringBuffer();
    sbuff.append(_sUser.getTrueName()).append(" \n\n");
    sbuff.append("\t ").append(_sPrj.getProjectName()).append(" ").append(_nMonth)
            .append("[").append(DATE_FORMAT.format(_sPrj.getFinishDate())).append("]")
            .append(_nMonth == 1 ? "" : "").append("\n\n");
    sbuff.append(" ").append(sSectionName).append("\n");
    sbuff.append(TODAY);/*  w ww .ja  v a2  s . co m*/
    String sResult_ = sbuff.toString();
    sbuff.setLength(0);
    return sResult_;
}

From source file:org.eclipse.wst.ws.internal.explorer.platform.wsdl.transport.HTTPTransport.java

private String getProxyAuthentication() {
    String proxyUserName = System.getProperty(SYS_PROP_HTTP_PROXY_USER_NAME);
    String proxyPassword = System.getProperty(SYS_PROP_HTTP_PROXY_PASSWORD);
    if (proxyUserName != null && proxyPassword != null) {
        StringBuffer sb = new StringBuffer(proxyUserName);
        sb.append(COLON);/*  w w  w.j  av  a  2 s  . c  o  m*/
        sb.append(proxyPassword);
        Base64 encoder = new Base64();
        String encodedUserNamePassword = new String(encoder.encode(sb.toString().getBytes()));
        sb.setLength(0);
        sb.append(HTTP_HEADER_PROXY_AUTH);
        sb.append(COLON);
        sb.append(SPACE);
        sb.append(BASIC);
        sb.append(SPACE);
        sb.append(stripNewLine(encodedUserNamePassword));
        sb.append(NEW_LINE);
        return sb.toString();
    } else
        return EMPTY_STRING;
}

From source file:org.apache.usergrid.persistence.cassandra.CursorCache.java

/** Turn the cursor cache into a string */
public String asString() {
    /**// w  ww  .  j a  va2 s .c  om
     * No cursors to return
     */
    if (cursors.size() == 0) {
        return null;
    }

    StringBuffer buff = new StringBuffer();

    int nullCount = 0;
    ByteBuffer value = null;

    for (Entry<Integer, ByteBuffer> entry : cursors.entrySet()) {
        value = entry.getValue();

        buff.append(entry.getKey());
        buff.append(":");
        buff.append(encodeBase64URLSafeString(bytes(value)));
        buff.append("|");

        // this range was empty, mark it as a null
        if (value == null || value.remaining() == 0) {
            nullCount++;
        }
    }

    // all cursors are complete, return null
    if (nullCount == cursors.size()) {
        return null;
    }

    // trim off the last pipe
    buff.setLength(buff.length() - 1);

    return encodeBase64URLSafeString(buff.toString().getBytes());
}

From source file:com.newatlanta.appengine.vfs.provider.GaeFileNameParser.java

/**
 * Makes sure <code>filename</code> always specifies a path that is within a
 * sub-directory of the webapp root path.
 *///from   w w  w.  jav a  2s.co m
public FileName parseUri(VfsComponentContext context, FileName baseName, String uri)
        throws FileSystemException {
    StringBuffer name = new StringBuffer();

    // Extract the scheme
    String scheme = UriParser.extractScheme(uri, name);
    if (scheme == null) { // this should never happen
        scheme = "gae";
    }

    // Remove encoding, and adjust the separators
    UriParser.canonicalizePath(name, 0, name.length(), this);
    UriParser.fixSeparators(name);

    // Normalise the path
    FileType fileType = UriParser.normalisePath(name);

    // all GAE files *must* be relative to the root file, which must be the
    // webapp root (though we have no way of enforcing this)
    String rootPath = "";
    if (baseName == null) { // this is the root object
        rootPath = name.toString();
        name.setLength(0);
    } else {
        rootPath = getRootPath(baseName);
        if (name.indexOf(rootPath) == 0) { // if ( name.startsWith( basePath ) )
            name.delete(0, rootPath.length());
        }
    }
    return new GaeFileName(scheme, rootPath, name.toString(), fileType);
}