Example usage for java.lang StringBuffer toString

List of usage examples for java.lang StringBuffer toString

Introduction

In this page you can find the example usage for java.lang StringBuffer toString.

Prototype

@Override
    @HotSpotIntrinsicCandidate
    public synchronized String toString() 

Source Link

Usage

From source file:ReplaceDemo.java

public static void main(String[] argv) {

    // Make an RE pattern to match almost any form (deamon, demon, etc.).
    String patt = "d[ae]{1,2}mon"; // i.e., 1 or 2 'a' or 'e' any combo

    // A test input.
    String input = "Unix hath demons and deamons in it!";
    System.out.println("Input: " + input);

    // Run it from a RE instance and see that it works
    Pattern r = Pattern.compile(patt);
    Matcher m = r.matcher(input);
    System.out.println("ReplaceAll: " + m.replaceAll("daemon"));

    // Show the appendReplacement method
    m.reset();/*from w  ww  . jav a2  s. c  o  m*/
    StringBuffer sb = new StringBuffer();
    System.out.print("Append methods: ");
    while (m.find()) {
        m.appendReplacement(sb, "daemon"); // Copy to before first match,
        // plus the word "daemon"
    }
    m.appendTail(sb); // copy remainder
    System.out.println(sb.toString());
}

From source file:at.treedb.util.Compress.java

/**
 * //from w ww . j  a  va 2 s . c  o  m
 * @param args
 * @throws IOException
 */
public static void main(String[] args) throws IOException {
    StringBuffer buf = new StringBuffer();
    buf.append("7z-compression with following parameters: ");
    for (String s : args) {
        buf.append(s);
        buf.append(' ');
    }
    System.out.println(buf.toString());
    Compress c = new Compress(args[0], args[1], args[2], Arrays.copyOfRange(args, 3, args.length));
    c.compress();
}

From source file:MainClass.java

public static void main(String[] args) throws IOException {
    SSLServerSocketFactory ssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
    SSLServerSocket ss = (SSLServerSocket) ssf.createServerSocket(8080);
    ss.setNeedClientAuth(true);//from   w w w  .  j a v a2  s  .  com

    while (true) {
        try {
            Socket s = ss.accept();
            OutputStream out = s.getOutputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
            String line = null;
            while (((line = in.readLine()) != null) && (!("".equals(line)))) {
                System.out.println(line);
            }
            System.out.println("");

            StringBuffer buffer = new StringBuffer();
            buffer.append("<HTML>\n");
            buffer.append("<HEAD><TITLE>HTTPS Server</TITLE></HEAD>\n");
            buffer.append("<BODY>\n");
            buffer.append("<H1>Success!</H1>\n");
            buffer.append("</BODY>\n");
            buffer.append("</HTML>\n");

            String string = buffer.toString();
            byte[] data = string.getBytes();
            out.write("HTTP/1.0 200 OK\n".getBytes());
            out.write(new String("Content-Length: " + data.length + "\n").getBytes());
            out.write("Content-Type: text/html\n\n".getBytes());
            out.write(data);
            out.flush();

            out.close();
            in.close();
            s.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:Main.java

public static void main(String[] arguments) throws Exception {
    StringBuffer output = new StringBuffer();

    FileReader file = new FileReader("a.htm");
    BufferedReader buff = new BufferedReader(file);
    boolean eof = false;
    while (!eof) {
        String line = buff.readLine();
        if (line == null)
            eof = true;//from ww w  . j  a  v a2s.  c o m
        else
            output.append(line + "\n");
    }
    buff.close();

    String page = output.toString();
    Pattern pattern = Pattern.compile("<a.+href=\"(.+?)\"");
    Matcher matcher = pattern.matcher(page);
    while (matcher.find()) {
        System.out.println(matcher.group(1));
    }
}

From source file:com.renren.ntc.sg.util.wxpay.https.ClientCustomSSL.java

public final static void main(String[] args) throws Exception {
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    FileInputStream instream = new FileInputStream(
            new File("/Users/allenz/Downloads/wx_cert/apiclient_cert.p12"));
    try {//from w  ww. j  av a  2s  .c o  m
        keyStore.load(instream, Constants.mch_id.toCharArray());
    } finally {
        instream.close();
    }

    // Trust own CA and all self-signed certs
    SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, Constants.mch_id.toCharArray())
            .build();
    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    try {

        HttpPost post = new HttpPost("https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers");
        System.out.println("executing request" + post.getRequestLine());

        String openid = "oQfDLjmZD7Lgynv6vuoBlWXUY_ic";
        String nonce_str = Sha1Util.getNonceStr();
        String orderId = SUtils.getOrderId();
        String re_user_name = "?";
        String amount = "1";
        String desc = "";
        String spbill_create_ip = "123.56.102.224";

        String txt = TXT.replace("{mch_appid}", Constants.mch_appid);
        txt = txt.replace("{mchid}", Constants.mch_id);
        txt = txt.replace("{openid}", openid);
        txt = txt.replace("{nonce_str}", nonce_str);
        txt = txt.replace("{partner_trade_no}", orderId);
        txt = txt.replace("{check_name}", "FORCE_CHECK");
        txt = txt.replace("{re_user_name}", re_user_name);
        txt = txt.replace("{amount}", amount);
        txt = txt.replace("{desc}", desc);
        txt = txt.replace("{spbill_create_ip}", spbill_create_ip);

        SortedMap<String, String> map = new TreeMap<String, String>();
        map.put("mch_appid", Constants.mch_appid);
        map.put("mchid", Constants.mch_id);
        map.put("openid", openid);
        map.put("nonce_str", nonce_str);
        map.put("partner_trade_no", orderId);
        //FORCE_CHECK| OPTION_CHECK | NO_CHECK
        map.put("check_name", "OPTION_CHECK");
        map.put("re_user_name", re_user_name);
        map.put("amount", amount);
        map.put("desc", desc);
        map.put("spbill_create_ip", spbill_create_ip);

        String sign = SUtils.createSign(map).toUpperCase();
        txt = txt.replace("{sign}", sign);

        post.setEntity(new StringEntity(txt, "utf-8"));

        CloseableHttpResponse response = httpclient.execute(post);
        try {
            HttpEntity entity = response.getEntity();

            System.out.println(response.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent()));
                String text;
                StringBuffer sb = new StringBuffer();
                while ((text = bufferedReader.readLine()) != null) {
                    sb.append(text);
                }
                String resp = sb.toString();
                LoggerUtils.getInstance().log(String.format("req %s rec %s", txt, resp));
                if (isOk(resp)) {

                    String payment_no = getValue(resp, "payment_no");
                    LoggerUtils.getInstance()
                            .log(String.format("order %s pay OK   payment_no %s", orderId, payment_no));
                }

            }
            EntityUtils.consume(entity);
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:MD5.java

public static void main(String[] args) {

    //String password = args[0];
    String password = "test";

    MessageDigest digest = null;//from   w ww  . ja va2  s  .co  m

    try {
        digest = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }

    try {
        digest.update(password.getBytes("UTF-8"));
    } catch (UnsupportedEncodingException ex) {
        ex.printStackTrace();
    }

    byte[] rawData = digest.digest();
    StringBuffer printable = new StringBuffer();

    for (int i = 0; i < rawData.length; i++) {
        printable.append(carr[((rawData[i] & 0xF0) >> 4)]);
        printable.append(carr[(rawData[i] & 0x0F)]);
    }
    String phpbbPassword = printable.toString();

    System.out.println("PHPBB           : " + phpbbPassword);
    System.out.println("MVNFORUM        : " + getMD5_Base64(password));
    System.out.println("PHPBB->MVNFORUM : " + getBase64FromHEX(phpbbPassword));
}

From source file:nz.co.jsrsolutions.ds3.DataScraper3.java

public static void main(String[] args) {

    logger.info("Starting application [ ds3 ] ...");

    ClassPathXmlApplicationContext context = null;

    try {// w  w  w .j a v a2s.c o m

        CommandLineParser parser = new GnuParser();

        CommandLine commandLine = parser.parse(CommandLineOptions.Options, args);

        if (commandLine.getOptions().length > 0 && !commandLine.hasOption(CommandLineOptions.HELP)) {

            StringBuffer environment = new StringBuffer();
            environment.append(SPRING_CONFIG_PREFIX);
            environment.append(commandLine.getOptionValue(CommandLineOptions.ENVIRONMENT));
            environment.append(SPRING_CONFIG_SUFFIX);

            context = new ClassPathXmlApplicationContext(environment.toString());
            context.registerShutdownHook();

            if (commandLine.hasOption(CommandLineOptions.SCHEDULED)) {

                Scheduler scheduler = context.getBean(SCHEDULER_BEAN_ID, Scheduler.class);
                scheduler.start();

                Object lock = new Object();
                synchronized (lock) {
                    lock.wait();
                }

            } else {
                DataScraper3Controller controller = context.getBean(CONTROLLER_BEAN_ID,
                        DataScraper3Controller.class);
                controller.executeCommandLine(commandLine);
            }

        } else {

            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("ds3", CommandLineOptions.Options);

        }

    } catch (DataScraper3Exception ds3e) {
        logger.error("Failed to execute command", ds3e);
    } catch (ParseException pe) {

        logger.error("Failed to parse command line", pe);

    } catch (Exception e) {

        logger.error("Failed to execute command", e);

    } finally {
        if (context != null) {
            context.close();
        }
    }

    logger.info("Exiting application [ ds3 ] ...");

}

From source file:io.s4.util.AvroSchemaSupplementer.java

public static void main(String args[]) {
    if (args.length < 1) {
        System.err.println("No schema filename specified");
        System.exit(1);//from ww  w  .  ja  v a2 s.co  m
    }

    String filename = args[0];
    FileReader fr = null;
    BufferedReader br = null;
    InputStreamReader isr = null;
    try {
        if (filename == "-") {
            isr = new InputStreamReader(System.in);
            br = new BufferedReader(isr);
        } else {
            fr = new FileReader(filename);
            br = new BufferedReader(fr);
        }

        String inputLine = "";
        StringBuffer jsonBuffer = new StringBuffer();
        while ((inputLine = br.readLine()) != null) {
            jsonBuffer.append(inputLine);
        }

        JSONObject jsonRecord = new JSONObject(jsonBuffer.toString());

        JSONObject keyPathElementSchema = new JSONObject();
        keyPathElementSchema.put("name", "KeyPathElement");
        keyPathElementSchema.put("type", "record");

        JSONArray fieldsArray = new JSONArray();
        JSONObject fieldRecord = new JSONObject();
        fieldRecord.put("name", "index");
        JSONArray typeArray = new JSONArray("[\"int\", \"null\"]");
        fieldRecord.put("type", typeArray);
        fieldsArray.put(fieldRecord);
        fieldRecord = new JSONObject();
        fieldRecord.put("name", "keyName");
        typeArray = new JSONArray("[\"string\", \"null\"]");
        fieldRecord.put("type", typeArray);
        fieldsArray.put(fieldRecord);

        keyPathElementSchema.put("fields", fieldsArray);

        JSONObject keyInfoSchema = new JSONObject();
        keyInfoSchema.put("name", "KeyInfo");
        keyInfoSchema.put("type", "record");

        fieldsArray = new JSONArray();
        fieldRecord = new JSONObject();
        fieldRecord.put("name", "keyPath");
        typeArray = new JSONArray("[\"string\", \"null\"]");
        fieldRecord.put("type", typeArray);
        fieldsArray.put(fieldRecord);
        fieldRecord = new JSONObject();
        fieldRecord.put("name", "fullKeyPath");
        typeArray = new JSONArray("[\"string\", \"null\"]");
        fieldRecord.put("type", typeArray);
        fieldsArray.put(fieldRecord);
        fieldRecord = new JSONObject();
        fieldRecord.put("name", "keyPathElementList");
        JSONObject typeRecord = new JSONObject();
        typeRecord.put("type", "array");
        typeRecord.put("items", keyPathElementSchema);
        fieldRecord.put("type", typeRecord);
        fieldsArray.put(fieldRecord);

        keyInfoSchema.put("fields", fieldsArray);

        JSONObject partitionInfoSchema = new JSONObject();
        partitionInfoSchema.put("name", "PartitionInfo");
        partitionInfoSchema.put("type", "record");
        fieldsArray = new JSONArray();
        fieldRecord = new JSONObject();
        fieldRecord.put("name", "partitionId");
        typeArray = new JSONArray("[\"int\", \"null\"]");
        fieldRecord.put("type", typeArray);
        fieldsArray.put(fieldRecord);
        fieldRecord = new JSONObject();
        fieldRecord.put("name", "compoundKey");
        typeArray = new JSONArray("[\"string\", \"null\"]");
        fieldRecord.put("type", typeArray);
        fieldsArray.put(fieldRecord);
        fieldRecord = new JSONObject();
        fieldRecord.put("name", "compoundValue");
        typeArray = new JSONArray("[\"string\", \"null\"]");
        fieldRecord.put("type", typeArray);
        fieldsArray.put(fieldRecord);
        fieldRecord = new JSONObject();
        fieldRecord.put("name", "keyInfoList");
        typeRecord = new JSONObject();
        typeRecord.put("type", "array");
        typeRecord.put("items", keyInfoSchema);
        fieldRecord.put("type", typeRecord);
        fieldsArray.put(fieldRecord);

        partitionInfoSchema.put("fields", fieldsArray);

        fieldRecord = new JSONObject();
        fieldRecord.put("name", "S4__PartitionInfo");
        typeRecord = new JSONObject();
        typeRecord.put("type", "array");
        typeRecord.put("items", partitionInfoSchema);
        fieldRecord.put("type", typeRecord);

        fieldsArray = jsonRecord.getJSONArray("fields");
        fieldsArray.put(fieldRecord);

        System.out.println(jsonRecord.toString(3));
    } catch (Exception ioe) {
        throw new RuntimeException(ioe);
    } finally {
        if (br != null)
            try {
                br.close();
            } catch (Exception e) {
            }
        if (isr != null)
            try {
                isr.close();
            } catch (Exception e) {
            }
        if (fr != null)
            try {
                fr.close();
            } catch (Exception e) {
            }
    }
}

From source file:HTTPServer.java

public static void main(String[] args) throws Exception {

    ServerSocket sSocket = new ServerSocket(1777);
    while (true) {
        System.out.println("Waiting for a client...");
        Socket newSocket = sSocket.accept();
        System.out.println("accepted the socket");

        OutputStream os = newSocket.getOutputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(newSocket.getInputStream()));

        String inLine = null;/*  w w w  . ja  va  2 s . c o m*/
        while (((inLine = br.readLine()) != null) && (!(inLine.equals("")))) {
            System.out.println(inLine);
        }
        System.out.println("");

        StringBuffer sb = new StringBuffer();
        sb.append("<html>\n");
        sb.append("<head>\n");
        sb.append("<title>Java \n");
        sb.append("</title>\n");
        sb.append("</head>\n");
        sb.append("<body>\n");
        sb.append("<H1>HTTPServer Works!</H1>\n");
        sb.append("</body>\n");
        sb.append("</html>\n");

        String string = sb.toString();

        byte[] byteArray = string.getBytes();

        os.write("HTTP/1.0 200 OK\n".getBytes());
        os.write(new String("Content-Length: " + byteArray.length + "\n").getBytes());
        os.write("Content-Type: text/html\n\n".getBytes());

        os.write(byteArray);
        os.flush();

        os.close();
        br.close();
        newSocket.close();
    }

}

From source file:edu.cmu.lti.oaqa.apps.Client.java

public static void main(String args[]) {
    BufferedReader inp = new BufferedReader(new InputStreamReader(System.in));

    Options opt = new Options();

    Option o = new Option(PORT_SHORT_PARAM, PORT_LONG_PARAM, true, PORT_DESC);
    o.setRequired(true);/* w  w  w .  j  av a  2s.c om*/
    opt.addOption(o);
    o = new Option(HOST_SHORT_PARAM, HOST_LONG_PARAM, true, HOST_DESC);
    o.setRequired(true);
    opt.addOption(o);
    opt.addOption(K_SHORT_PARAM, K_LONG_PARAM, true, K_DESC);
    opt.addOption(R_SHORT_PARAM, R_LONG_PARAM, true, R_DESC);
    opt.addOption(QUERY_TIME_SHORT_PARAM, QUERY_TIME_LONG_PARAM, true, QUERY_TIME_DESC);
    opt.addOption(RET_OBJ_SHORT_PARAM, RET_OBJ_LONG_PARAM, false, RET_OBJ_DESC);
    opt.addOption(RET_EXTERN_ID_SHORT_PARAM, RET_EXTERN_ID_LONG_PARAM, false, RET_EXTERN_ID_DESC);

    CommandLineParser parser = new org.apache.commons.cli.GnuParser();

    try {
        CommandLine cmd = parser.parse(opt, args);

        String host = cmd.getOptionValue(HOST_SHORT_PARAM);

        String tmp = null;

        tmp = cmd.getOptionValue(PORT_SHORT_PARAM);

        int port = -1;

        try {
            port = Integer.parseInt(tmp);
        } catch (NumberFormatException e) {
            Usage("Port should be integer!");
        }

        boolean retObj = cmd.hasOption(RET_OBJ_SHORT_PARAM);
        boolean retExternId = cmd.hasOption(RET_EXTERN_ID_SHORT_PARAM);

        String queryTimeParams = cmd.getOptionValue(QUERY_TIME_SHORT_PARAM);
        if (null == queryTimeParams)
            queryTimeParams = "";

        SearchType searchType = SearchType.kKNNSearch;
        int k = 0;
        double r = 0;

        if (cmd.hasOption(K_SHORT_PARAM)) {
            if (cmd.hasOption(R_SHORT_PARAM)) {
                Usage("Range search is not allowed if the KNN search is specified!");
            }
            tmp = cmd.getOptionValue(K_SHORT_PARAM);
            try {
                k = Integer.parseInt(tmp);
            } catch (NumberFormatException e) {
                Usage("K should be integer!");
            }
            searchType = SearchType.kKNNSearch;
        } else if (cmd.hasOption(R_SHORT_PARAM)) {
            if (cmd.hasOption(K_SHORT_PARAM)) {
                Usage("KNN search is not allowed if the range search is specified!");
            }
            searchType = SearchType.kRangeSearch;
            tmp = cmd.getOptionValue(R_SHORT_PARAM);
            try {
                r = Double.parseDouble(tmp);
            } catch (NumberFormatException e) {
                Usage("The range value should be numeric!");
            }
        } else {
            Usage("One has to specify either range or KNN-search parameter");
        }

        String separator = System.getProperty("line.separator");

        StringBuffer sb = new StringBuffer();
        String s;

        while ((s = inp.readLine()) != null) {
            sb.append(s);
            sb.append(separator);
        }

        String queryObj = sb.toString();

        try {
            TTransport transport = new TSocket(host, port);
            transport.open();

            TProtocol protocol = new TBinaryProtocol(transport);
            QueryService.Client client = new QueryService.Client(protocol);

            if (!queryTimeParams.isEmpty())
                client.setQueryTimeParams(queryTimeParams);

            List<ReplyEntry> res = null;

            long t1 = System.nanoTime();

            if (searchType == SearchType.kKNNSearch) {
                System.out.println(String.format("Running a %d-NN search", k));
                res = client.knnQuery(k, queryObj, retExternId, retObj);
            } else {
                System.out.println(String.format("Running a range search (r=%g)", r));
                res = client.rangeQuery(r, queryObj, retExternId, retObj);
            }

            long t2 = System.nanoTime();

            System.out.println(String.format("Finished in %g ms", (t2 - t1) / 1e6));

            for (ReplyEntry e : res) {
                System.out.println(String.format("id=%d dist=%g %s", e.getId(), e.getDist(),
                        retExternId ? "externId=" + e.getExternId() : ""));
                if (retObj)
                    System.out.println(e.getObj());
            }

            transport.close(); // Close transport/socket !
        } catch (TException te) {
            System.err.println("Apache Thrift exception: " + te);
            te.printStackTrace();
        }

    } catch (ParseException e) {
        Usage("Cannot parse arguments");
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }
}