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.hangum.tadpole.engine.sql.util.export.SQLExporter.java

public static String makeFileInsertStatment(String tableName, QueryExecuteResultDTO rsDAO, int intLimitCnt,
        int commit) throws Exception {
    String strTmpDir = PublicTadpoleDefine.TEMP_DIR + tableName + System.currentTimeMillis()
            + PublicTadpoleDefine.DIR_SEPARATOR;
    String strFile = tableName + ".sql";
    String strFullPath = strTmpDir + strFile;

    final String INSERT_INTO_STMT = "INSERT INTO " + tableName + " (%s) VALUES (%S);"
            + PublicTadpoleDefine.LINE_SEPARATOR;

    //  ?.//w  ww  .j av a2 s  .  c om
    String strColumns = "";
    Map<Integer, String> mapTable = rsDAO.getColumnLabelName();
    for (int i = 1; i < mapTable.size(); i++) {
        if (i != (mapTable.size() - 1))
            strColumns += mapTable.get(i) + ",";
        else
            strColumns += mapTable.get(i);
    }

    // ?? .
    StringBuffer sbInsertInto = new StringBuffer();
    int DATA_COUNT = 1000;
    List<Map<Integer, Object>> dataList = rsDAO.getDataList().getData();
    Map<Integer, Integer> mapColumnType = rsDAO.getColumnType();
    String strResult = new String();
    for (int i = 0; i < dataList.size(); i++) {
        Map<Integer, Object> mapColumns = dataList.get(i);

        strResult = "";
        for (int j = 1; j < mapColumnType.size(); j++) {
            Object strValue = mapColumns.get(j);
            strValue = strValue == null ? "" : strValue;
            if (!RDBTypeToJavaTypeUtils.isNumberType(mapColumnType.get(j))) {
                strValue = StringEscapeUtils.escapeSql(strValue.toString());
                strValue = StringHelper.escapeSQL(strValue.toString());

                strValue = SQLUtil.makeQuote(strValue.toString());
            }

            if (j != (mapTable.size() - 1))
                strResult += strValue + ",";
            else
                strResult += strValue;
        }
        sbInsertInto.append(String.format(INSERT_INTO_STMT, strColumns, strResult));

        if (intLimitCnt == i) {
            return sbInsertInto.toString();
        }

        if (commit > 0 && (i % commit) == 0) {
            sbInsertInto
                    .append("COMMIT" + PublicTadpoleDefine.SQL_DELIMITER + PublicTadpoleDefine.LINE_SEPARATOR);
        }

        if ((i % DATA_COUNT) == 0) {
            FileUtils.writeStringToFile(new File(strFullPath), sbInsertInto.toString(), true);
            sbInsertInto.setLength(0);
        }
    }
    if (sbInsertInto.length() > 0) {
        if (commit > 0) {
            sbInsertInto
                    .append("COMMIT" + PublicTadpoleDefine.SQL_DELIMITER + PublicTadpoleDefine.LINE_SEPARATOR);
        }

        FileUtils.writeStringToFile(new File(strFullPath), sbInsertInto.toString(), true);
    }

    return strFullPath;
}

From source file:com.tremolosecurity.saml.Saml2Assertion.java

public String generateSaml2Response() throws Exception {
    byte[] idBytes = new byte[20];
    random.nextBytes(idBytes);/*ww  w . j  ava2s .  c o  m*/

    StringBuffer b = new StringBuffer();
    b.append('f').append(Hex.encodeHexString(idBytes));
    String id = b.toString();

    Assertion assertion = null;

    if (this.signAssertion) {
        AssertionBuilder assertionBuilder = new AssertionBuilder();
        assertion = assertionBuilder.buildObject();
        assertion.setDOM(this.generateSignedAssertion(id));

    } else {
        assertion = this.generateAssertion(id);
    }

    random.nextBytes(idBytes);

    b.setLength(0);
    b.append('f').append(Hex.encodeHexString(idBytes));
    id = b.toString();

    //assertion.setID(id);
    ResponseBuilder rb = new ResponseBuilder();
    Response r = rb.buildObject();
    r.setID(id);
    r.setIssueInstant(this.issueInstant);
    r.setDestination(recepient);

    IssuerBuilder issuerBuilder = new IssuerBuilder();

    Issuer issuer = issuerBuilder.buildObject();

    issuer.setValue(this.issuer);
    r.setIssuer(issuer);

    StatusBuilder statusBuilder = new StatusBuilder();
    Status s = statusBuilder.buildObject();
    StatusCodeBuilder scb = new StatusCodeBuilder();
    StatusCode sc = scb.buildObject();
    sc.setValue(StatusCode.SUCCESS);
    s.setStatusCode(sc);
    r.setStatus(s);

    if (this.encAssertion) {
        DataEncryptionParameters encryptionParameters = new DataEncryptionParameters();
        encryptionParameters.setAlgorithm(EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES128);

        KeyEncryptionParameters keyEncryptionParameters = new KeyEncryptionParameters();

        keyEncryptionParameters.setEncryptionCredential(new BasicX509Credential(this.encCert));
        keyEncryptionParameters.setAlgorithm(EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSAOAEP);

        Encrypter encrypter = new Encrypter(encryptionParameters, keyEncryptionParameters);
        encrypter.setKeyPlacement(Encrypter.KeyPlacement.INLINE);

        try {
            EncryptedAssertion encryptedAssertion = encrypter.encrypt(assertion);
            r.getEncryptedAssertions().add(encryptedAssertion);
        } catch (EncryptionException e) {
            throw new RuntimeException(e);
        }

        /*
                
        Credential keyEncryptionCredential = CredentialSupport.getSimpleCredential(this.encCert.getPublicKey(), null);
        EncryptionParameters encParams = new EncryptionParameters();
        encParams.setAlgorithm(EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES128);
                 
        KeyEncryptionParameters kekParams = new KeyEncryptionParameters();
        kekParams.setEncryptionCredential(keyEncryptionCredential);
        kekParams.setAlgorithm(EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSAOAEP);
        KeyInfoGeneratorFactory kigf =
            Configuration.getGlobalSecurityConfiguration()
            .getKeyInfoGeneratorManager().getDefaultManager()
            .getFactory(keyEncryptionCredential);
        kekParams.setKeyInfoGenerator(kigf.newInstance());
                 
        Encrypter samlEncrypter = new Encrypter(encParams, kekParams);
        samlEncrypter.setKeyPlacement(KeyPlacement.PEER);
                 
        try {
            EncryptedAssertion encryptedAssertion = samlEncrypter.encrypt(assertion);
            r.getEncryptedAssertions().add(encryptedAssertion);
        } catch (EncryptionException e) {
            throw new Exception("Could not encrypt response",e);
        }
          */
    } else {
        r.getAssertions().add(assertion);
    }

    if (this.signResponse) {
        if (this.sigCert == null) {
            throw new Exception("No signature key found");
        }
        BasicX509Credential signingCredential = CredentialSupport.getSimpleCredential(this.sigCert,
                this.sigKey);

        Signature signature = OpenSAMLUtils.buildSAMLObject(Signature.class);

        //SecurityHelper.prepareSignatureParams(signature, signingCredential, null, null);

        signature.setSigningCredential(signingCredential);
        signature.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1);
        signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);

        r.setSignature(signature);
        //Element e = Configuration.getMarshallerFactory().getMarshaller(r).marshall(r); 

        try {
            XMLObjectProviderRegistrySupport.getMarshallerFactory().getMarshaller(r).marshall(r);
        } catch (MarshallingException e) {
            throw new RuntimeException(e);
        }

        Signer.signObject(signature);
    }

    // Get the Subject marshaller
    Marshaller marshaller = new ResponseMarshaller();

    // Marshall the Subject
    Element responseElement = marshaller.marshall(r);

    return net.shibboleth.utilities.java.support.xml.SerializeSupport.nodeToString(responseElement);

}

From source file:com.ai.runner.center.pay.web.business.payment.util.third.unionpay.sdk.SDKUtil.java

/**
 * ???customerInfo???? pinphoneNocvn2expired <br>
 *  <br>/*from   w  w  w.  ja va 2 s.co  m*/
 * @param customerInfoMap ?? key???value?,? <br>
 *        customerInfoMap.put("certifTp", "01");               //? <br>
      customerInfoMap.put("certifId", "341126197709218366");   //??? <br>
      customerInfoMap.put("customerNm", "?");            //?? <br>
      customerInfoMap.put("smsCode", "123456");               //?? <br>
      customerInfoMap.put("pin", "111111");                  //? <br>
      customerInfoMap.put("phoneNo", "13552535506");         //? <br>
      customerInfoMap.put("cvn2", "123");                    //??cvn2? <br>
      customerInfoMap.put("expired", "1711");                  // ?? <br>
 * @param accNo  customerInfoMap?????,customerInfoMap??PIN???<br>
 * @param encoding ?encoding
 * @return base64???? <br>
 */
public static String getCustomerInfoWithEncrypt(Map<String, String> customerInfoMap, String accNo,
        String encoding) {

    StringBuffer sf = new StringBuffer("{");
    //??
    StringBuffer encryptedInfoSb = new StringBuffer("");

    for (Iterator<String> it = customerInfoMap.keySet().iterator(); it.hasNext();) {
        String key = it.next();
        String value = customerInfoMap.get(key);
        if (key.equals("phoneNo") || key.equals("cvn2") || key.equals("expired")) {
            encryptedInfoSb.append(key + SDKConstants.EQUAL + value + SDKConstants.AMPERSAND);
        } else {
            if (key.equals("pin")) {
                if (null == accNo || "".equals(accNo.trim())) {
                    LogUtil.writeLog(
                            "??PINgetCustomerInfoWithEncrypt???");
                    return "{}";
                } else {
                    value = SDKUtil.encryptPin(accNo, value, encoding);
                }
            }
            if (it.hasNext())
                sf.append(key + SDKConstants.EQUAL + value + SDKConstants.AMPERSAND);
            else
                sf.append(key + SDKConstants.EQUAL + value);
        }
    }

    if (!encryptedInfoSb.toString().equals("")) {
        //?&?
        encryptedInfoSb.setLength(encryptedInfoSb.length() - 1);

        LogUtil.writeLog("customerInfo encryptedInfo" + encryptedInfoSb.toString());
        if (sf.toString().equals("{")) //phoneNocvn2expired?&
            sf.append("encryptedInfo" + SDKConstants.EQUAL);
        else
            sf.append(SDKConstants.AMPERSAND + "encryptedInfo" + SDKConstants.EQUAL);

        sf.append(SDKUtil.encryptEpInfo(encryptedInfoSb.toString(), encoding));
    }
    sf.append("}");

    String customerInfo = sf.toString();
    LogUtil.writeLog("customerInfo" + customerInfo);
    try {
        return new String(SecureUtil.base64Encode(sf.toString().getBytes(encoding)));
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return customerInfo;
}

From source file:com.symbian.driver.plugins.ftptelnet.TelnetProcess.java

private String readUntilPrompt(int aTimeOut, boolean log) throws Exception {
    // read until we find the prompt or timeout
    // set a timer
    iStopReading = false;/*from  w w  w.  jav  a  2  s  .  c  o m*/
    if (aTimeOut > 0) {
        iTelnetTimer = startTelnetTimer(aTimeOut);
    }
    StringBuffer sb = null;
    try {
        char lastChar = ' ';
        // wait for the first data / timeout
        while (iInputStream.available() == 0 && !iStopReading) {
        }
        if (!iStopReading) {
            // this means we have some data
            sb = new StringBuffer();
            StringBuffer line = new StringBuffer();

            while (!iStopReading) {
                char ch = (char) iInputStream.read();
                line.append(ch);
                if (ch == '\n' && log) {
                    // show the progress to the user
                    LOGGER.fine(line.toString());
                    line.setLength(0);
                }
                sb.append(ch);
                if (ch == lastChar) {
                    if (sb.toString().endsWith(iPrompt)) {
                        return sb.toString();
                    }
                }
            }
        } else {
            throw new Exception("Telnet Client could not get prompt (and timedout)");
        }
    } catch (Exception lException) {
        LOGGER.log(Level.SEVERE, "An error happened while reading from Telnet server", lException);
        throw lException;
    } finally {
        LOGGER.fine("Telnet Server replied with : " + sb);
        if (iTelnetTimer != null) {
            iTelnetTimer.cancel();
            iTelnetTimer = null;
        }
    }
    LOGGER.log(Level.SEVERE, "TelNet Client Expecting : " + iPrompt + " - Got :" + sb);
    throw new Exception("TelNet Client Expecting : " + iPrompt + " - Got :" + sb);
}

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

/**
 * Splits a string using a literal string delimiter. Does not preserve blocks of characters
 * between quoteChars./*from   w ww .j a  v  a 2s .  com*/
 * 
 * @param delimitedString
 * @param delimiter
 * @return extracted tokens resulting from split operation.
 */
protected String[] extractValuesLiteralString(String delimitedString, String delimiter) {
    char[] chars = delimitedString.toCharArray();
    List strings = new ArrayList();
    StringBuffer buffer = new StringBuffer();
    for (int i = 0; i < chars.length; i++) {
        buffer.append(chars[i]);
        if (buffer.toString().endsWith(delimiter)) {
            strings.add(buffer.substring(0, buffer.length() - delimiter.length()));
            buffer.setLength(0);
        }
    }
    strings.add(buffer.toString());
    return (String[]) strings.toArray(new String[strings.size()]);
}

From source file:com.bstek.dorado.view.config.attachment.JavaScriptParser.java

private List<String> extractComment(CodeReader reader, boolean isLineComment) throws IOException {
    List<String> comments = null;
    boolean inContent = false, inSpace = false;
    StringBuffer contentLine = new StringBuffer(8);
    StringBuffer contentBuf = new StringBuffer();
    while (true) {
        char c = reader.read();
        if (c == RETURN) {
            if (contentBuf.length() > 0) {
                contentLine.append(contentBuf);
                if (contentLine.length() > 0) {
                    if (comments == null) {
                        comments = new ArrayList<String>();
                    }//from   w ww  .j  a  v  a 2  s.  c  o  m
                    comments.add(contentLine.toString());
                    inContent = false;
                    contentBuf.setLength(0);
                    contentLine.setLength(0);
                }
            }
            if (isLineComment) {
                break;
            } else {
                continue;
            }
        } else if (c == STAR && !isLineComment) {
            char lastChar = c;
            c = reader.read();
            if (c == BACKSLASH) {
                break;
            } else {
                c = lastChar;
                reader.moveCursor(-1);
            }
        }

        if (!inContent) {
            if (c == SPACE || c == TAB || c == STAR) {
                // do nothing
            } else {
                inContent = true;
                contentBuf.append(c);
            }
        } else {
            if (c == SPACE || c == TAB || c == STAR) {
                inSpace = true;
                int bufLen = contentBuf.length();
                if (bufLen > 0) {
                    contentLine.append(contentBuf);
                    contentBuf.setLength(0);
                }
            } else {
                if (inSpace) {
                    contentBuf.append(SPACE);
                    inSpace = false;
                }
                contentBuf.append(c);
            }
        }
    }

    if (contentLine.length() > 0) {
        if (comments == null) {
            comments = new ArrayList<String>();
        }
        comments.add(contentLine.toString());
    }
    return comments;
}

From source file:com.wavemaker.runtime.data.util.QueryHandler.java

public static List<String> parseSQL(String qryStr) {
    List<String> words = new ArrayList<String>();

    // First, break the query into word elements

    StringBuffer token = new StringBuffer();
    String twoLetters = null;/*from  www. j  av a2s .  c o m*/
    boolean holdIt = false;

    for (int i = 0; i < qryStr.length(); i++) {
        String aLetter = qryStr.substring(i, i + 1);
        if (holdIt) {
            if (twoLetters.equals("<") && (aLetter.equals("=") || aLetter.equals(">"))
                    || twoLetters.equals(">") && aLetter.equals("=")
                    || twoLetters.equals("|") && aLetter.equals("|")
                    || twoLetters.equals("\r") && aLetter.equals("\n")) {
                twoLetters = twoLetters + aLetter;
                words.add(twoLetters);
            } else {
                if (isDelimiter(aLetter)) {
                    words.add(twoLetters);
                    words.add(aLetter);
                } else if (aLetter.equals(" ")) {
                    words.add(twoLetters);
                }
            }
            holdIt = false;
        } else {
            if (aLetter.equals("<") || aLetter.equals(">") || aLetter.equals("|") || aLetter.equals("\r")) {
                holdIt = true;
                twoLetters = aLetter;
                if (token.length() > 0) {
                    words.add(token.toString());
                    token.setLength(0);
                }
            } else if (isDelimiter(aLetter)) {
                if (token.length() > 0) {
                    words.add(token.toString());
                    token.setLength(0);
                }
                words.add(aLetter);
            } else if (aLetter.equals(" ")) {
                if (token.length() > 0) {
                    words.add(token.toString());
                    token.setLength(0);
                }
            } else {
                token.append(aLetter);
            }
        }
    }

    if (token.length() > 0) {
        words.add(token.toString());
    }

    return words;
}

From source file:org.latticesoft.util.container.PropertyMap.java

/**
 * Writes the property into the file. If the name
 * is wild card, then the PropertyMap will not write
 * to any file.//  www. j  ava2  s  .c  om
 */
public void write() {
    if (this.name == null) {
        return;
    }
    if (this.map == null) {
        return;
    }
    StringBuffer sb = new StringBuffer();
    Iterator iter = this.map.keySet().iterator();
    List l = new ArrayList();
    while (iter.hasNext()) {
        sb.setLength(0);
        Object key = iter.next();
        Object value = map.get(key);
        if (key != null && value != null) {
            String key1 = StringUtil.replace(key.toString(), "=", "\\=", true);
            String val1 = StringUtil.replace(value.toString(), "=", "\\=", true);
            sb.append(key1);
            sb.append("=");
            sb.append(val1);
            l.add(sb.toString());
        }
    }
    String s = ConvertUtil.convertListToString(l);
    FileUtil.writeToFile(this.name, s);
}

From source file:com.mobile.blue.util.payyl.SDKUtil.java

/**
 * ???customerInfo???? pinphoneNocvn2expired <br>
 *  <br>//from   w  w w .j a  v  a  2s. com
 * 
 * @param customerInfoMap
 *            ?? key???value?,? <br>
 *            customerInfoMap.put("certifTp", "01"); //? <br>
 *            customerInfoMap.put("certifId", "341126197709218366"); //???
 *            <br>
 *            customerInfoMap.put("customerNm", "?"); //?? <br>
 *            customerInfoMap.put("smsCode", "123456"); //?? <br>
 *            customerInfoMap.put("pin", "111111"); //? <br>
 *            customerInfoMap.put("phoneNo", "13552535506"); //? <br>
 *            customerInfoMap.put("cvn2", "123"); //??cvn2? <br>
 *            customerInfoMap.put("expired", "1711"); // ?? <br>
 * @param accNo
 *            customerInfoMap?????,customerInfoMap??PIN???<br>
 * @param encoding
 *            ?encoding
 * @return base64???? <br>
 */
public static String getCustomerInfoWithEncrypt(Map<String, String> customerInfoMap, String accNo,
        String encoding) {

    StringBuffer sf = new StringBuffer("{");
    // ??
    StringBuffer encryptedInfoSb = new StringBuffer("");

    for (Iterator<String> it = customerInfoMap.keySet().iterator(); it.hasNext();) {
        String key = it.next();
        String value = customerInfoMap.get(key);
        if (key.equals("phoneNo") || key.equals("cvn2") || key.equals("expired")) {
            encryptedInfoSb.append(key + SDKConstants.EQUAL + value + SDKConstants.AMPERSAND);
        } else {
            if (key.equals("pin")) {
                if (null == accNo || "".equals(accNo.trim())) {
                    LogUtil.writeLog(
                            "??PINgetCustomerInfoWithEncrypt???");
                    return "{}";
                } else {
                    value = SDKUtil.encryptPin(accNo, value, encoding);
                }
            }
            if (it.hasNext())
                sf.append(key + SDKConstants.EQUAL + value + SDKConstants.AMPERSAND);
            else
                sf.append(key + SDKConstants.EQUAL + value);
        }
    }

    if (!encryptedInfoSb.toString().equals("")) {
        // ?&?
        encryptedInfoSb.setLength(encryptedInfoSb.length() - 1);

        LogUtil.writeLog("customerInfo encryptedInfo" + encryptedInfoSb.toString());
        if (sf.toString().equals("{")) // phoneNocvn2expired?&
            sf.append("encryptedInfo" + SDKConstants.EQUAL);
        else
            sf.append(SDKConstants.AMPERSAND + "encryptedInfo" + SDKConstants.EQUAL);

        sf.append(SDKUtil.encryptEpInfo(encryptedInfoSb.toString(), encoding));
    }
    sf.append("}");

    String customerInfo = sf.toString();
    LogUtil.writeLog("customerInfo" + customerInfo);
    try {
        return new String(SecureUtil.base64Encode(sf.toString().getBytes(encoding)));
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return customerInfo;
}

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

private String getEmailMsg(int _nSerial, String _sPatentName, boolean _bIsSuccess) {
    StringBuffer sbuff = new StringBuffer();
    try {// w ww.  jav a  2 s  .co  m
        sbuff.append(_nSerial).append("&nbsp;&nbsp;&nbsp;&nbsp;<font color=\"");
        sbuff.append(_bIsSuccess ? "#009900" : "#FF0000");
        sbuff.append("\"><font color=\"#000000\">").append(_sPatentName);
        sbuff.append("</font>").append(_bIsSuccess ? "" : "").append("</font>");
        return sbuff.toString();
    } finally {
        sbuff.setLength(0);
    }
}