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:com.tremolosecurity.proxy.filters.PreAuthFilter.java

@Override
public void doFilter(HttpFilterRequest request, HttpFilterResponse response, HttpFilterChain chain)
        throws Exception {
    AuthInfo userData = ((AuthController) request.getSession().getAttribute(ProxyConstants.AUTH_CTL))
            .getAuthInfo();//from w  w  w .jav a2s .co  m
    ConfigManager cfg = (ConfigManager) request.getAttribute(ProxyConstants.TREMOLO_CFG_OBJ);

    List<Cookie> cookies = null;

    if (userData.getAuthLevel() > 0 && userData.isAuthComplete()) {
        UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG);
        HttpSession session = request.getSession();
        String uid = (String) session.getAttribute("TREMOLO_PRE_AUTH");
        if (uid == null || !uid.equals(userData.getUserDN())) {
            session.setAttribute("TREMOLO_PRE_AUTH", userData.getUserDN());
            HashMap<String, String> uriParams = new HashMap<String, String>();
            uriParams.put("fullURI", this.uri);

            UrlHolder remHolder = cfg.findURL(this.url);

            org.apache.http.client.methods.HttpRequestBase method = null;

            if (this.postSAML) {
                PrivateKey pk = holder.getConfig().getPrivateKey(this.keyAlias);
                java.security.cert.X509Certificate cert = holder.getConfig().getCertificate(this.keyAlias);

                Saml2Assertion assertion = new Saml2Assertion(
                        userData.getAttribs().get(this.nameIDAttribute).getValues().get(0), pk, cert, null,
                        this.issuer, this.assertionConsumerURL, this.audience, this.signAssertion,
                        this.signResponse, false, this.nameIDType, this.authnCtxClassRef);

                String respXML = "";

                try {
                    respXML = assertion.generateSaml2Response();
                } catch (Exception e) {
                    throw new ServletException("Could not generate SAMLResponse", e);
                }

                List<NameValuePair> formparams = new ArrayList<NameValuePair>();
                String base64 = Base64.encodeBase64String(respXML.getBytes("UTF-8"));

                formparams.add(new BasicNameValuePair("SAMLResponse", base64));
                if (this.relayState != null && !this.relayState.isEmpty()) {
                    formparams.add(new BasicNameValuePair("RelayState", this.relayState));
                }

                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
                HttpPost post = new HttpPost(this.assertionConsumerURL);
                post.setEntity(entity);
                method = post;

            } else {
                HttpGet get = new HttpGet(remHolder.getProxyURL(uriParams));
                method = get;
            }

            LastMileUtil.addLastMile(cfg, userData.getAttribs().get(loginAttribute).getValues().get(0),
                    this.loginAttribute, method, lastMileKeyAlias, true);
            BasicHttpClientConnectionManager bhcm = new BasicHttpClientConnectionManager(
                    cfg.getHttpClientSocketRegistry());
            try {
                CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(bhcm)
                        .setDefaultRequestConfig(cfg.getGlobalHttpClientConfig()).build();

                HttpResponse resp = httpclient.execute(method);

                if (resp.getStatusLine().getStatusCode() == 500) {
                    BufferedReader in = new BufferedReader(
                            new InputStreamReader(resp.getEntity().getContent()));
                    StringBuffer error = new StringBuffer();
                    String line = null;
                    while ((line = in.readLine()) != null) {
                        error.append(line).append('\n');
                    }

                    logger.warn("Pre-Auth Failed : " + error);
                }

                org.apache.http.Header[] headers = resp.getAllHeaders();

                StringBuffer stmp = new StringBuffer();

                cookies = new ArrayList<Cookie>();

                for (org.apache.http.Header header : headers) {
                    if (header.getName().equalsIgnoreCase("set-cookie")
                            || header.getName().equalsIgnoreCase("set-cookie2")) {
                        //System.out.println(header.getValue());
                        String cookieVal = header.getValue();
                        /*if (cookieVal.endsWith("HttpOnly")) {
                           cookieVal = cookieVal.substring(0,cookieVal.indexOf("HttpOnly"));
                        }
                                
                        //System.out.println(cookieVal);*/

                        List<HttpCookie> cookiesx = HttpCookie.parse(cookieVal);
                        for (HttpCookie cookie : cookiesx) {

                            String cookieFinalName = cookie.getName();
                            if (cookieFinalName.equalsIgnoreCase("JSESSIONID")) {
                                stmp.setLength(0);
                                stmp.append("JSESSIONID").append('-')
                                        .append(holder.getApp().getName().replaceAll(" ", "|"));
                                cookieFinalName = stmp.toString();
                            }

                            //logger.info("Adding cookie name '" + cookieFinalName + "'='" + cookie.getValue() + "'");

                            Cookie respcookie = new Cookie(cookieFinalName, cookie.getValue());
                            respcookie.setComment(cookie.getComment());
                            if (cookie.getDomain() != null) {
                                //respcookie.setDomain(cookie.getDomain());
                            }
                            respcookie.setMaxAge((int) cookie.getMaxAge());
                            respcookie.setPath(cookie.getPath());

                            respcookie.setSecure(cookie.getSecure());
                            respcookie.setVersion(cookie.getVersion());
                            cookies.add(respcookie);

                            if (request.getCookieNames().contains(respcookie.getName())) {
                                request.removeCookie(cookieFinalName);
                            }

                            request.addCookie(new Cookie(cookie.getName(), cookie.getValue()));
                        }
                    }
                }

            } finally {
                bhcm.shutdown();
            }
        }
    }

    chain.nextFilter(request, response, chain);
    if (cookies != null) {

        for (Cookie cookie : cookies) {

            response.addCookie(cookie);
        }
    }

}

From source file:com.m2a.struts.M2AActionBase.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.
 * <p>/*ww w  . j  a v a2s .  c o  m*/
 * 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 = servlet.findFormBean(helperName);
    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:org.opencastproject.deliver.itunesu.HTTPHelper.java

/**
 * Sends a multi-part POST HTTP request with file data and returns the response as a string.
 *
 * @param fileName the name of the file to upload
 * @return the HTTP response/*from   ww w .j  a v a 2  s.  c om*/
 * @throws IOException
 */
public String uploadFile(String fileName) throws IOException {
    // boundary string
    boundary = "---------------------------" + randomString();

    // multi-part form data with randomly generated boundary string
    connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
    connection.connect();

    // get the output stream
    outputStream = connection.getOutputStream();

    StringBuffer stringBuffer = new StringBuffer();

    // form data starts
    stringBuffer.append("--");
    stringBuffer.append(boundary);
    stringBuffer.append("\r\n");

    // file name
    stringBuffer.append("Content-Disposition: form-data; name=\"file\"; filename=\"");
    stringBuffer.append(fileName);
    stringBuffer.append("\"\r\n");

    // content type
    stringBuffer.append("Content-Type: ");
    String type = connection.guessContentTypeFromName(fileName);
    if (type == null) {
        // default content type
        type = "application/octet-stream";
    }
    stringBuffer.append(type);
    stringBuffer.append("\r\n");
    stringBuffer.append("\r\n");

    outputStream.write(stringBuffer.toString().getBytes());

    // file data
    File file = new File(fileName);
    InputStream is = new FileInputStream(file);
    byte[] buf = new byte[FILE_BUFFER_SIZE];
    int nread;
    int navailable;
    int total = 0;
    synchronized (is) {
        while ((nread = is.read(buf, 0, buf.length)) >= 0) {
            outputStream.write(buf, 0, nread);
            total += nread;
        }
    }
    outputStream.flush();

    // reset the string buffer
    stringBuffer.setLength(0);
    stringBuffer.append("\r\n");

    // end of form data
    stringBuffer.append("--");
    stringBuffer.append(boundary);
    stringBuffer.append("--");
    stringBuffer.append("\r\n");

    outputStream.write(stringBuffer.toString().getBytes());

    outputStream.close();

    String response = readResponse();

    // exception handling
    checkStatusCode();

    // clean
    connection.disconnect();

    return response;
}

From source file:fi.ni.IFC_ClassModel.java

/**
 * Parse_ if c_ line statement./*from  w ww  .  jav a 2 s.  co  m*/
 * 
 * @param line
 *            the line
 */
private void parse_IFC_LineStatement(String line) {
    IFC_X3_VO ifcvo = new IFC_X3_VO();
    int state = 0;
    StringBuffer sb = new StringBuffer();
    int cl_count = 0;
    LinkedList<Object> current = ifcvo.getList();
    Stack<LinkedList<Object>> list_stack = new Stack<LinkedList<Object>>();
    for (int i = 0; i < line.length(); i++) {
        char ch = line.charAt(i);
        switch (state) {
        case 0:
            if (ch == '=') {
                ifcvo.setLine_num(toLong(sb.toString()));
                sb.setLength(0);
                state++;
                continue;
            } else if (Character.isDigit(ch))
                sb.append(ch);
            break;
        case 1: // (
            if (ch == '(') {
                ifcvo.setName(sb.toString());
                sb.setLength(0);
                state++;
                continue;
            } else if (ch == ';') {
                ifcvo.setName(sb.toString());
                sb.setLength(0);
                state = Integer.MAX_VALUE;
            } else if (!Character.isWhitespace(ch))
                sb.append(ch);
            break;
        case 2: // (... line started and doing (...
            if (ch == '\'') {
                state++;
            }
            if (ch == '(') {
                list_stack.push(current);
                LinkedList<Object> tmp = new LinkedList<Object>();
                if (sb.toString().trim().length() > 0)
                    current.add(sb.toString().trim());
                sb.setLength(0);
                current.add(tmp); // listaan listn lista
                current = tmp;
                cl_count++;
                // sb.append(ch);
            } else if (ch == ')') {
                if (cl_count == 0) {
                    if (sb.toString().trim().length() > 0)
                        current.add(sb.toString().trim());
                    sb.setLength(0);
                    state = Integer.MAX_VALUE; // line is done
                    continue;
                } else {
                    if (sb.toString().trim().length() > 0)
                        current.add(sb.toString().trim());
                    sb.setLength(0);
                    cl_count--;
                    current = list_stack.pop();
                }
            } else if (ch == ',') {
                if (sb.toString().trim().length() > 0)
                    current.add(sb.toString().trim());
                current.add(Character.valueOf(ch));

                sb.setLength(0);
            } else {
                sb.append(ch);

            }
            break;
        case 3: // (...
            if (ch == '\'') {
                state--;
            } else {
                sb.append(ch);

            }
            break;
        default:
            // Do nothing
        }
    }
    linemap.put(ifcvo.line_num, ifcvo);
}

From source file:com.pureinfo.srm.patent.domain.impl.PatentMgrImpl.java

/**
 * /* w  w  w  .  ja  v  a2  s.c o  m*/
 * @see com.pureinfo.srm.patent.domain.IPatentMgr#getNeedRemindYearFeePatentOfUserNo(int,
 *      com.pureinfo.srm.auth.model.SRMUser)
 */
public int getNeedRemindYearFeePatentOfUserNo(int _nNumDays, SRMUser _user) throws PureException {
    IStatement query = null;
    StringBuffer sbuff = new StringBuffer();
    try {
        sbuff.append("SELECT COUNT(*) FROM {this} WHERE {this.patentType}<>" + SRMConstants.PATENT_TYPE_RJDJ);
        sbuff.append(" AND {this.pkType}<>1 AND {this.yearFeeDate}<=? ");
        sbuff.append(" AND {this.status}=" + SRMConstants.PATENT_STATUS_HAS_RIGHT);
        sbuff.append(" AND {this.administrator}=?");

        query = this.createQuery(sbuff.toString(), 1);
        query.setDate(0, PatentHelper.getDateOfNumDays(new Date(), _nNumDays));
        query.setInt(1, _user.getId());
        return ((Number) query.executeStat()).intValue();
    } catch (Exception e) {
        throw new PureException(ArkExceptionTypes.CONTENT_MANAGEMENT,
                "failed to get need remind year fee patent NO Of UserId- " + _user.getId(), e);
    } finally {
        if (query != null)
            query.clear(true);
        sbuff.setLength(0);
    }
}

From source file:com.sec.ose.osi.sdk.protexsdk.discovery.report.DefaultEntityListCreator.java

protected ReportEntityList buildEntityListFromHTML(BufferedReader htmlReportReader,
        ArrayList<String> entityKeyList, ArrayList<String> duplicationCheckingField) {
    ReportEntityList reportEntityList = new ReportEntityList();
    ReportEntity reportEntity = null;/*w w  w .  j  ava 2  s .c  om*/
    String tmpLine = null;

    if (duplicationCheckingField == null) {
        duplicationCheckingField = new ArrayList<String>();
    }

    int insertedCnt = 0;

    try {
        StringBuffer tmpValue = new StringBuffer("");
        while ((tmpLine = htmlReportReader.readLine()) != null) {
            tmpLine = tmpLine.trim();
            if (tmpLine.startsWith("<tr ")) {
                reportEntity = new ReportEntity();
                int index = 0;
                while ((tmpLine = htmlReportReader.readLine()) != null) {
                    tmpLine = tmpLine.trim();
                    if (tmpLine.startsWith("<td ")) {
                        while ((tmpLine = htmlReportReader.readLine()) != null) {
                            tmpLine = tmpLine.trim();
                            if (tmpLine.startsWith("</td>")) {
                                String key = entityKeyList.get(index);
                                String value = "";

                                if (key.equals(ReportInfo.COMPARE_CODE_MATCHES.COMPARE_CODE_MATCHES_LINK)) {
                                    value = extractURL(tmpValue);
                                } else {
                                    value = removeTag(tmpValue);
                                }
                                reportEntity.setValue(key, value);
                                tmpValue.setLength(0);
                                ++index;
                                break;
                            }
                            tmpValue.append(tmpLine);
                        }
                    }
                    if (tmpLine.startsWith("</tr>")) {
                        if (hasNoData(entityKeyList, index)) {
                            break;
                        }
                        reportEntityList.addEntity(reportEntity);
                        insertedCnt++;
                        if (insertedCnt % 10000 == 0) {
                            log.debug("buildEntityList insertedCnt: " + insertedCnt);
                        }
                        break;
                    }
                }
            }
            if (tmpLine.startsWith(HTML_DATA_TABLE_END_TAG)) {
                break;
            }
        }
    } catch (IOException e) {
        log.warn(e);
        String[] buttonOK = { "OK" };
        JOptionPane.showOptionDialog(null, "Out Of Memory Error", "Java heap space", JOptionPane.OK_OPTION,
                JOptionPane.ERROR_MESSAGE, null, buttonOK, "OK");
    }
    log.debug("buildEntityList insertedCnt finally : " + insertedCnt);
    return reportEntityList;
}

From source file:org.apache.fop.fo.FONode.java

/**
 * Returns a String containing as much context information as possible about a node. Call
 * this method only in exceptional conditions because this method may perform quite extensive
 * information gathering inside the FO tree.
 * @return a String containing context information
 *//*from ww  w  .  j ava2  s  .c o m*/
// [GA] remove deprecation - no alternative specified
//  @deprecated Not localized! Should rename getContextInfoAlt() to getContextInfo() when done!
public String getContextInfo() {
    StringBuffer sb = new StringBuffer();
    if (getLocalName() != null) {
        sb.append(getName());
        sb.append(", ");
    }
    if (this.locator != null) {
        sb.append("location: ");
        sb.append(getLocatorString(this.locator));
    } else {
        String s = gatherContextInfo();
        if (s != null) {
            sb.append("\"");
            sb.append(s);
            sb.append("\"");
        } else {
            sb.append("no context info available");
        }
    }
    if (sb.length() > 80) {
        sb.setLength(80);
    }
    return sb.toString();
}

From source file:com.pureinfo.srm.outlay.action.SearchCheckCodeAction.java

public ActionForward executeAction() throws PureException {
    // TODO Auto-generated method stub

    String zy = request.getParameter("dp_abstract");
    String amt1 = request.getParameter("dp_money1");
    String amt2 = request.getParameter("dp_money2");
    String datestr1 = request.getParameter("date1");
    String datestr2 = request.getParameter("date2");
    String fno = request.getParameter("dp_checkcode");

    if (zy != null) {
        try {/*from ww w . jav  a 2 s.  co m*/
            zy = new String(zy.getBytes("ISO-8859-1"), "UTF-8");
        } catch (UnsupportedEncodingException ex) {
            // TODO Auto-generated catch block
            ex.printStackTrace(System.err);
        }
    }
    String urlStr = "http://cwcx.zju.edu.cn/servlet/cwTxtPub?funcno=KYDKINFO";
    StringBuffer url = new StringBuffer();
    url.append(urlStr);

    MD5 md5 = new MD5();

    if (fno != null) {
        url.append("&fno=" + fno);
    } else {
        url.append("&fno=");
    }
    if (zy != null) {
        url.append("&zy=" + zy);
    } else {
        url.append("&zy=");
    }
    if (amt1 != null && !"".equals(amt1.trim())) {
        url.append("&amt1=" + amt1);
    } else {
        url.append("&amt1=-99999999999");

    }
    if (amt2 != null && !"".equals(amt2.trim())) {
        url.append("&amt2=" + amt2);

    } else {
        url.append("&amt2=99999999999");
    }
    if (datestr1 != null && !"".equals(datestr1.trim())) {
        url.append("&date1=" + datestr1);
    } else {
        url.append("&date1=1800-01-01");
    }
    if (datestr2 != null && !"".equals(datestr2.trim())) {
        url.append("&date2=" + datestr2);
    } else {
        url.append("&date2=2099-12-31");
    }

    String test = url.toString();

    String[] arr = test.split("\\?");
    String md5test = "KYDKINFO" + arr[1] + "A3ixoSisQ";
    String md5sign = md5.getMD5Encode(md5test);
    url.append("&sign=" + md5sign);

    String content = getPageContent(url.toString(), "");
    String tableInfo = formTable(content);
    url.setLength(0);
    request.setAttribute("content", tableInfo);
    return mapping.findForward("success");
}

From source file:com.jjoe64.graphview_demos.fragments.CollectData.java

/**
     * <p>Unescapes any Java literals found in the <code>String</code> to a
     * <code>Writer</code>.</p>
     */*from ww  w .  j  a v  a  2  s . c  o m*/
     * <p>For example, it will turn a sequence of <code>'\'</code> and
     * <code>'n'</code> into a newline character, unless the <code>'\'</code>
     * is preceded by another <code>'\'</code>.</p>
     *
     * <p>A <code>null</code> string input has no effect.</p>
     *
     * @param str  the <code>String</code> to unescape, may be null
     * @throws IllegalArgumentException if the Writer is <code>null</code>
     * @throws IOException if error occurs on underlying Writer
     */
    private String unescapeJava(String str) throws IOException {
        if (str == null) {
            return "";
        }
        int sz = str.length();
        StringBuffer unicode = new StringBuffer(4);

        StringBuilder strout = new StringBuilder();
        boolean hadSlash = false;
        boolean inUnicode = false;
        for (int i = 0; i < sz; i++) {
            char ch = str.charAt(i);
            if (inUnicode) {
                // if in unicode, then we're reading unicode
                // values in somehow
                unicode.append(ch);
                if (unicode.length() == 4) {
                    // unicode now contains the four hex digits
                    // which represents our unicode character
                    try {
                        int value = Integer.parseInt(unicode.toString(), 16);
                        strout.append((char) value);
                        unicode.setLength(0);
                        inUnicode = false;
                        hadSlash = false;
                    } catch (NumberFormatException nfe) {
                        // throw new NestableRuntimeException("Unable to parse unicode value: " + unicode, nfe);
                        throw new IOException("Unable to parse unicode value: " + unicode, nfe);
                    }
                }
                continue;
            }
            if (hadSlash) {
                // handle an escaped value
                hadSlash = false;
                switch (ch) {
                case '\\':
                    strout.append('\\');
                    break;
                case '\'':
                    strout.append('\'');
                    break;
                case '\"':
                    strout.append('"');
                    break;
                case 'r':
                    strout.append('\r');
                    break;
                case 'f':
                    strout.append('\f');
                    break;
                case 't':
                    strout.append('\t');
                    break;
                case 'n':
                    strout.append('\n');
                    break;
                case 'b':
                    strout.append('\b');
                    break;
                case 'u': {
                    // uh-oh, we're in unicode country....
                    inUnicode = true;
                    break;
                }
                default:
                    strout.append(ch);
                    break;
                }
                continue;
            } else if (ch == '\\') {
                hadSlash = true;
                continue;
            }
            strout.append(ch);
        }
        if (hadSlash) {
            // then we're in the weird case of a \ at the end of the
            // string, let's output it anyway.
            strout.append('\\');
        }
        return new String(strout.toString());
    }

From source file:edu.utah.further.core.api.text.StringUtil.java

/**
 * Truncates a string to a specified number of characters.
 * /*from   w  ww  . j  av  a2s . c om*/
 * @param str
 *            The string to truncate
 * @param numChars
 *            The number of characters to truncate
 * @param showEllipse
 *            Flag indicating whether or not to show an ellipse if the string is
 *            truncated
 * @param ellipsisSymbol
 *            ellipsis symbol to append at the end of the string if truncated
 * @return The truncated string if string length is more than <code>numChars</code>
 *         otherwise return the full string
 */
public static String truncate(final String str, final int numChars, final boolean showEllipse,
        final String ellipsisSymbol) {
    final StringBuffer truncatedStr = new StringBuffer(str != null ? str : "");
    if (str != null && str.length() >= numChars) {
        truncatedStr.setLength(numChars);
        if (showEllipse) {
            truncatedStr.append(ellipsisSymbol);
        }
    }
    return truncatedStr.toString();
}