Example usage for java.lang StringBuffer StringBuffer

List of usage examples for java.lang StringBuffer StringBuffer

Introduction

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

Prototype

@HotSpotIntrinsicCandidate
public StringBuffer() 

Source Link

Document

Constructs a string buffer with no characters in it and an initial capacity of 16 characters.

Usage

From source file:RegexTest.java

public static void main(String[] args) {
    Pattern p = Pattern.compile(REGEX);
    Matcher m = p.matcher(INPUT); // get a matcher object
    StringBuffer sb = new StringBuffer();
    while (m.find()) {
        m.appendReplacement(sb, REPLACE);
    }//  ww w.j  av a 2  s.  co  m
    m.appendTail(sb);
    System.out.println(sb.toString());
}

From source file:StringBufferDemo.java

public static void main(String[] argv) {
    String s1 = "Hello" + ", " + "World";
    System.out.println(s1);/* w w w.ja  v  a  2  s  . com*/

    // Build a StringBuffer, and append some things to it.
    StringBuffer sb2 = new StringBuffer();
    sb2.append("Hello");
    sb2.append(',');
    sb2.append(' ');
    sb2.append("World");

    // Get the StringBuffer's value as a String, and print it.
    String s2 = sb2.toString();
    System.out.println(s2);

    // Now do the above all over again, but in a more 
    // concise (and typical "real-world" Java) fashion.

    StringBuffer sb3 = new StringBuffer().append("Hello").append(',').append(' ').append("World");
    System.out.println(sb3.toString());

    // Exercise for the reader: do it all AGAIN but without
    // creating any temporary variables.
}

From source file:com.leixl.easyframework.action.httpclient.TestHttpPost.java

public static void main(String[] args) {

    Map<String, Object> paramMap = new HashMap<String, Object>();
    paramMap.put("uid", 1);
    paramMap.put("desc",
            "?????");
    paramMap.put("payStatus", 1);

    //HttpConnUtils.postHttpContent(URL, paramMap);

    //HttpClient/*w ww .  j ava 2 s.c  om*/
    HttpClient httpClient = new HttpClient();
    PostMethod postMethod = new PostMethod(URL);
    // ??
    NameValuePair[] data = { new NameValuePair("uid", "1"),
            new NameValuePair("desc",
                    "?????"),
            new NameValuePair("payStatus", "1") };
    // ?postMethod
    postMethod.setRequestBody(data);
    // postMethod
    int statusCode;
    try {
        statusCode = httpClient.executeMethod(postMethod);
        if (statusCode == HttpStatus.SC_OK) {
            StringBuffer contentBuffer = new StringBuffer();
            InputStream in = postMethod.getResponseBodyAsStream();
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(in, postMethod.getResponseCharSet()));
            String inputLine = null;
            while ((inputLine = reader.readLine()) != null) {
                contentBuffer.append(inputLine);
                System.out.println("input line:" + inputLine);
                contentBuffer.append("/n");
            }
            in.close();

        } else if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY
                || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
            // ???
            Header locationHeader = postMethod.getResponseHeader("location");
            String location = null;
            if (locationHeader != null) {
                location = locationHeader.getValue();
                System.out.println("The page was redirected to:" + location);
            } else {
                System.err.println("Location field value is null.");
            }
        }
    } catch (HttpException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:GoogleImages.java

public static void main(String[] args) throws InterruptedException {
    String searchTerm = "s woman"; // term to search for (use spaces to separate terms)
    int offset = 40; // we can only 20 results at a time - use this to offset and get more!
    String fileSize = "50mp"; // specify file size in mexapixels (S/M/L not figured out yet)
    String source = null; // string to save raw HTML source code

    // format spaces in URL to avoid problems
    searchTerm = searchTerm.replaceAll(" ", "%20");

    // get Google image search HTML source code; mostly built from PhyloWidget example:
    // http://code.google.com/p/phylowidget/source/browse/trunk/PhyloWidget/src/org/phylowidget/render/images/ImageSearcher.java
    int offset2 = 0;
    Set urlsss = new HashSet<String>();
    while (offset2 < 600) {
        try {//w ww  .  j a v  a 2 s  .c  om
            URL query = new URL("https://www.google.ru/search?start=" + offset2
                    + "&q=angry+woman&newwindow=1&client=opera&hs=bPE&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiAgcKozIfNAhWoHJoKHSb_AUoQ_AUIBygB&biw=1517&bih=731&dpr=0.9#imgrc=G_1tH3YOPcc8KM%3A");
            HttpURLConnection urlc = (HttpURLConnection) query.openConnection(); // start connection...
            urlc.setInstanceFollowRedirects(true);
            urlc.setRequestProperty("User-Agent", "");
            urlc.connect();
            BufferedReader in = new BufferedReader(new InputStreamReader(urlc.getInputStream())); // stream in HTTP source to file
            StringBuffer response = new StringBuffer();
            char[] buffer = new char[1024];
            while (true) {
                int charsRead = in.read(buffer);
                if (charsRead == -1) {
                    break;
                }
                response.append(buffer, 0, charsRead);
            }
            in.close(); // close input stream (also closes network connection)
            source = response.toString();
        } // any problems connecting? let us know
        catch (Exception e) {
            e.printStackTrace();
        }

        // print full source code (for debugging)
        // println(source);
        // extract image URLs only, starting with 'imgurl'
        if (source != null) {
            //                System.out.println(source);
            int c = StringUtils.countMatches(source, "http://www.vmir.su");
            System.out.println(c);
            int index = source.indexOf("src=");
            System.out.println(source.subSequence(index, index + 200));
            while (index >= 0) {
                System.out.println(index);
                index = source.indexOf("src=", index + 1);
                if (index == -1) {
                    break;
                }
                String rr = source.substring(index,
                        index + 200 > source.length() ? source.length() : index + 200);

                if (rr.contains("\"")) {
                    rr = rr.substring(5, rr.indexOf("\"", 5));
                }
                System.out.println(rr);
                urlsss.add(rr);
            }
        }
        offset2 += 20;
        Thread.sleep(1000);
        System.out.println("off set = " + offset2);

    }

    System.out.println(urlsss);
    urlsss.forEach(new Consumer<String>() {

        public void accept(String s) {
            try {
                saveImage(s, "C:\\Users\\Java\\Desktop\\ang\\" + UUID.randomUUID().toString() + ".jpg");
            } catch (IOException ex) {
                Logger.getLogger(GoogleImages.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    });
    //            String[][] m = matchAll(source, "img height=\"\\d+\" src=\"([^\"]+)\"");

    // older regex, no longer working but left for posterity
    // built partially from: http://www.mkyong.com/regular-expressions/how-to-validate-image-file-extension-with-regular-expression
    // String[][] m = matchAll(source, "imgurl=(.*?\\.(?i)(jpg|jpeg|png|gif|bmp|tif|tiff))");    // (?i) means case-insensitive
    //            for (int i = 0; i < m.length; i++) {                                                          // iterate all results of the match
    //                println(i + ":\t" + m[i][1]);                                                         // print (or store them)**
    //            }
}

From source file:net.sf.ehcache.distribution.RemoteDebugger.java

/**
 * A Remote Debugger which prints out the cache size of the monitored cache.
 * Additional logging messages can be observed by setting the logging level to debug
 * or trace for net.sf.ehcache.distribution
 *
 * @param args path_to_ehcache.xml and a cache name
 * @throws InterruptedException thrown when it is interrupted. It will keep going until then.
 *///  w  ww . ja v a2 s .  c o  m
public static void main(String[] args) throws InterruptedException {

    if (args.length < 1 || args.length > 2) {
        LOG.info(
                "Command line to list caches to monitor: java -jar ehcache-remote-debugger.jar path_to_ehcache.xml\n"
                        + "Command line to monitor a specific cache: java -jar ehcache-remote-debugger.jar path_to_ehcache.xml"
                        + " cacheName");
        System.exit(2);
    }

    if (!LOG.isTraceEnabled()) {
        LOG.info("Increase the net.sf.ehcache.distribution logging level to debug or trace to see distributed"
                + " cache operations as they occur.");
    }

    CacheManager manager = new CacheManager(args[0]);
    String[] cacheNames = manager.getCacheNames();
    StringBuffer availableCaches = new StringBuffer();
    if (args.length == 1) {
        for (int i = 0; i < cacheNames.length; i++) {
            String name = cacheNames[i];
            availableCaches.append(name).append(' ');
        }
        LOG.info("Available caches are: " + availableCaches);
        System.exit(1);
    } else {
        String cacheName = args[1];
        Ehcache cache = manager.getCache(cacheName);
        if (cache == null) {
            LOG.error("No cache named " + cacheName + " exists. Available caches are: " + availableCaches);
        } else {
            LOG.info("Monitoring cache: " + cacheName);

            while (true) {
                Thread.sleep(TWO_SECONDS);
                LOG.info("Cache size: " + cache.getSize());
            }
        }
    }
}

From source file:ReplayTest.java

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

    int cnt = 0;//  w  w w . jav a  2 s  .  co  m
    String operateTime = "";
    String operateType = "";
    String uuid = "";
    String programId = "";
    List<String> lines = Files.readLines(new File("e:\\test\\sample4.txt"), Charsets.UTF_8);
    System.out.println(lines.size());
    for (String value1 : lines) {
        String[] values = value1.split(SPLIT_T);
        //logArr16?operateDate=2014-04-25 17:59:59 621, operateType=STARTUP, deviceCode=010333501065233, versionId=, mac=10:48:b1:06:4d:23, platformId=00000032AmlogicMDZ-05-201302261821793, ipAddress=60.10.133.10
        if (values.length != 16) {
            continue;
        }
        String logContent = values[15];

        if (logContent == null || logContent.trim().length() <= 0) {
            System.out.println("logContent");
            return;
        }
        String[] contentArr = logContent.split(COMMA_SIGN);//content

        if (contentArr == null || contentArr.length != 3) {
            System.out.println("logContentArr:" + contentArr.length);
            return;
        }

        StringBuffer stringBuffer = new StringBuffer();

        //1.CNTVID??
        stringBuffer.append(StringsUtils.getEncodeingStr(values[3])).append(SPLIT);

        //2.IP?
        if (null == values[7] || EMPTY.equals(values[7])) {
            stringBuffer.append(StringsUtils.getEncodeingStr(EMPTY)).append(SPLIT);
        } else {
            stringBuffer.append(StringsUtils.getEncodeingStr(values[7].trim())).append(SPLIT);
        }

        //3.OperateTtype   ? 1: 2:?
        operateType = StringUtils.substringAfter(contentArr[0].trim(), EQUAL_SIGN);
        if (null == operateType || EMPTY.equals(operateType)) {
            stringBuffer.append(StringsUtils.getEncodeingStr(EMPTY)).append(SPLIT);
        } else if ("on".equals(operateType)) {
            stringBuffer.append(StringsUtils.getEncodeingStr("1")).append(SPLIT);
        } else if ("out".equals(operateType)) {
            stringBuffer.append(StringsUtils.getEncodeingStr("2")).append(SPLIT);
        }

        // 4.operateTime  ?
        operateTime = DateUtil.convertDateToString("yyyyMMdd HHmmss",
                DateUtil.convertStringToDate("yyyy-MM-dd HH:mm:ss SSS", values[10].trim()));
        if (operateTime == null || EMPTY.equals(operateTime)) {
            stringBuffer.append(StringsUtils.getEncodeingStr(EMPTY)).append(SPLIT);
        } else {
            stringBuffer.append(StringsUtils.getEncodeingStr(operateTime)).append(SPLIT);
        }
        //5.url_addr ?
        stringBuffer.append(StringsUtils.getEncodeingStr(EMPTY)).append(SPLIT);

        //6.channel?
        uuid = StringUtils.substringAfter(contentArr[1].trim(), EQUAL_SIGN);
        if (uuid == null || EMPTY.equals(uuid)) {
            stringBuffer.append(StringsUtils.getEncodeingStr(EMPTY)).append(SPLIT);
        } else {
            stringBuffer.append(StringsUtils.getEncodeingStr(uuid)).append(SPLIT);
        }

        //7.programId id
        programId = StringUtils.substringAfter(contentArr[2].trim(), EQUAL_SIGN);
        if (!programId.matches("\\d+")) { //id????
            return;
        } else {
            stringBuffer.append(StringsUtils.getEncodeingStr(programId)).append(SPLIT);
        }

        //8.EPGCode EPG?,?EPGCode?
        stringBuffer.append(StringsUtils.getEncodeingStr("06")).append(SPLIT);

        //9.DataSource??12
        stringBuffer.append(DATA_SOURCE).append(SPLIT);

        //10.Fsource???????
        stringBuffer.append(F_SOURCE).append(SPLIT);

        //11.resolution ?,?
        stringBuffer.append(StringsUtils.getEncodeingStr(EMPTY));

        System.out.println(stringBuffer.toString());
        cnt++;
    }
    System.out.println(":" + cnt);
}

From source file:com.gemini.httpclienttest.HttpClientTestMain.java

public static void main(String[] args) {
    //authenticate with the server
    URL url;// ww  w. ja  v a 2  s  . c om
    try {
        url = new URL("http://198.11.209.34:5000/v2.0/tokens");
    } catch (MalformedURLException ex) {
        System.out.printf("Invalid Endpoint - not a valid URL {}", "http://198.11.209.34:5000/v2.0");
        return;
    }
    CloseableHttpClient httpclient = HttpClientBuilder.create().build();
    try {
        HttpPost httpPost = new HttpPost(url.toString());
        httpPost.setHeader("Content-Type", "application/json");
        StringEntity strEntity = new StringEntity(
                "{\"auth\":{\"tenantName\":\"Gemini-network-prj\",\"passwordCredentials\":{\"username\":\"sri\",\"password\":\"srikumar12\"}}}");
        httpPost.setEntity(strEntity);
        //System.out.println("Executing request " + httpget.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httpPost);
        try {
            //get the response status code 
            String respStatus = response.getStatusLine().getReasonPhrase();

            //get the response body
            int bytes = response.getEntity().getContent().available();
            InputStream body = response.getEntity().getContent();
            BufferedReader in = new BufferedReader(new InputStreamReader(body));
            String line;
            StringBuffer sbJSON = new StringBuffer();
            while ((line = in.readLine()) != null) {
                sbJSON.append(line);
            }
            String json = sbJSON.toString();
            EntityUtils.consume(response.getEntity());

            GsonBuilder gsonBuilder = new GsonBuilder();
            Object parsedJson = gsonBuilder.create().fromJson(json, Object.class);
            System.out.printf("Parsed json is of type %s\n\n", parsedJson.getClass().toString());
            if (parsedJson instanceof com.google.gson.internal.LinkedTreeMap) {
                com.google.gson.internal.LinkedTreeMap treeJson = (com.google.gson.internal.LinkedTreeMap) parsedJson;
                if (treeJson.containsKey("id")) {
                    String s = (String) treeJson.getOrDefault("id", "no key provided");
                    System.out.printf("\n\ntree contained id %s\n", s);
                } else {
                    System.out.printf("\n\ntree does not contain key id\n");
                }
            }
        } catch (IOException ex) {
            System.out.print(ex);
        } finally {
            response.close();
        }
    } catch (IOException ex) {
        System.out.print(ex);
    } finally {
        //lots of exceptions, just the connection and exit
        try {
            httpclient.close();
        } catch (IOException | NoSuchMethodError ex) {
            System.out.print(ex);
            return;
        }
    }
}

From source file:org.berlin.crawl.util.ListSeedsMain.java

public static void main(final String[] args) {
    logger.info("Running");
    final ApplicationContext ctx = new ClassPathXmlApplicationContext(
            "/org/berlin/batch/batch-databot-context.xml");
    final BotCrawlerDAO dao = new BotCrawlerDAO();
    final SessionFactory sf = (SessionFactory) ctx.getBean("sessionFactory");
    Session session = sf.openSession();/*from   w ww  . j av  a  2s.  com*/

    final StringBuffer buf = new StringBuffer();
    final List<String> seeds = dao.findHosts(session);
    final String nl = System.getProperty("line.separator");
    buf.append(nl);
    for (final String seed : seeds) {
        buf.append(PREFIX);
        buf.append(seed);
        buf.append(POST1);
        buf.append("/");
        buf.append(POST2);
        buf.append(nl);
    } // End of the for //
    logger.info(buf.toString());

    // Now print the number of links //
    final List<Long> ii = dao.countLinks(session);
    logger.warn("Count of Links : " + ii);

    // Also print top hosts //
    final List<Object[]> hosts = dao.findTopHosts(session);
    Collections.reverse(hosts);
    for (final Object[] oo : hosts) {
        System.out.println(oo[0] + " // " + oo[1].getClass());
    }

    if (session != null) {
        // May not need to close the session
        session.close();
    } // End of the if //
    logger.info("Done");
}

From source file:com.interacciones.mxcashmarketdata.driver.util.AppropriateFormat.java

public static void main(String[] args) throws Throwable {
    init(args);// w  w w  .  j  a v  a 2s .  c om

    long time = System.currentTimeMillis();
    //for (;;) {
    try {
        //read
        file = new File(source);
        is = new FileInputStream(file);
        isr = new InputStreamReader(is);
        br = new BufferedReader(isr);
        //write
        filewrite = new File(destination);
        fos = new FileOutputStream(filewrite);
        bos = new BufferedOutputStream(fos);

        int data = 0;
        int count = 0;

        StringBuffer message = new StringBuffer();
        while (data != -1) {
            data = br.read();
            message.append((char) data);
            count++;
            if (data == 10) {
                transform(message);
                count = 0;
                message.delete(INIT_ASCII, message.length());
            }
        }
    } catch (Exception e) {
        LOGGER.error("Warning " + e.getMessage());
        e.printStackTrace();
    } finally {
        close();
    }
    //}
    time = System.currentTimeMillis() - time;
    LOGGER.info("Time " + time);
}

From source file:grnet.filter.XMLFiltering.java

public static void main(String[] args) throws IOException {
    // TODO Auto-generated method ssstub

    Enviroment enviroment = new Enviroment(args[0]);

    if (enviroment.envCreation) {
        Core core = new Core();

        XMLSource source = new XMLSource(args[0]);

        File sourceFile = source.getSource();

        if (sourceFile.exists()) {

            Collection<File> xmls = source.getXMLs();

            System.out.println("Filtering repository:" + enviroment.dataProviderFilteredIn.getName());

            System.out.println("Number of files to filter:" + xmls.size());

            Iterator<File> iterator = xmls.iterator();

            FilteringReport report = null;
            if (enviroment.getArguments().getProps().getProperty(Constants.createReport)
                    .equalsIgnoreCase("true")) {
                report = new FilteringReport(enviroment.getArguments().getDestFolderLocation(),
                        enviroment.getDataProviderFilteredIn().getName());
            }/*from  w  w  w. j a  va  2s  . c om*/

            ConnectionFactory factory = new ConnectionFactory();
            factory.setHost(enviroment.getArguments().getQueueHost());
            factory.setUsername(enviroment.getArguments().getQueueUserName());
            factory.setPassword(enviroment.getArguments().getQueuePassword());

            while (iterator.hasNext()) {

                StringBuffer logString = new StringBuffer();
                logString.append(enviroment.dataProviderFilteredIn.getName());
                File xmlFile = iterator.next();

                String name = xmlFile.getName();
                name = name.substring(0, name.indexOf(".xml"));
                logString.append(" " + name);

                boolean xmlIsFilteredIn = core.filterXML(xmlFile, enviroment.getArguments().getQueries());

                if (xmlIsFilteredIn) {
                    logString.append(" " + "FilteredIn");
                    slf4jLogger.info(logString.toString());

                    Connection connection = factory.newConnection();
                    Channel channel = connection.createChannel();
                    channel.queueDeclare(QUEUE_NAME, false, false, false, null);

                    channel.basicPublish("", QUEUE_NAME, null, logString.toString().getBytes());
                    channel.close();
                    connection.close();

                    try {
                        if (report != null) {
                            report.appendXMLFileNameNStatus(xmlFile.getPath(), Constants.filteredInData);
                            report.raiseFilteredInFilesNum();
                        }

                        FileUtils.copyFileToDirectory(xmlFile, enviroment.getDataProviderFilteredIn());
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        // e.printStackTrace();
                        e.printStackTrace();
                        System.out.println("Filtering failed.");
                    }
                } else {
                    logString.append(" " + "FilteredOut");
                    slf4jLogger.info(logString.toString());

                    Connection connection = factory.newConnection();
                    Channel channel = connection.createChannel();
                    channel.queueDeclare(QUEUE_NAME, false, false, false, null);

                    channel.basicPublish("", QUEUE_NAME, null, logString.toString().getBytes());
                    channel.close();
                    connection.close();
                    try {
                        if (report != null) {
                            report.appendXMLFileNameNStatus(xmlFile.getPath(), Constants.filteredOutData);
                            report.raiseFilteredOutFilesNum();
                        }
                        FileUtils.copyFileToDirectory(xmlFile, enviroment.getDataProviderFilteredOuT());
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        // e.printStackTrace();
                        e.printStackTrace();
                        System.out.println("Filtering failed.");
                    }
                }
            }
            if (report != null) {

                report.appendXPathExpression(enviroment.getArguments().getQueries());

                report.appendGeneralInfo();
            }
            System.out.println("Filtering is done.");
        }

    }
}