Example usage for java.io PrintStream print

List of usage examples for java.io PrintStream print

Introduction

In this page you can find the example usage for java.io PrintStream print.

Prototype

public void print(Object obj) 

Source Link

Document

Prints an object.

Usage

From source file:org.apache.bookkeeper.common.conf.ConfigDef.java

private void writeNSharps(PrintStream stream, int num) {
    IntStream.range(0, num).forEach(ignored -> stream.print("#"));
}

From source file:org.apache.commons.digester3.examples.xmlrules.addressbook.Address.java

public void print(PrintStream out, int indentAmount) {
    StringBuilder indentStr = new StringBuilder(indentAmount);
    for (; indentAmount > 0; --indentAmount) {
        indentStr.append(' ');
    }//from   w  ww.j  a  va 2  s .  co m

    out.print(indentStr);
    out.print("address type: ");
    out.println(type);

    out.print(indentStr);
    out.println("  " + street);

    out.print(indentStr);
    out.println("  " + city + " " + state + " " + zip);

    out.print(indentStr);
    out.println("  " + country);
}

From source file:herbie.running.population.algorithms.AbstractClassifiedFrequencyAnalysis.java

/**
 * @param crosstabFormat indicates if absolute numbers or percentage of all legs are printed
 * @param isCumulative indicates if cumulative numbers are printed
 * @param numberOfQuantiles number of quantiles desired
 *///from ww  w  .  j av a2s .  co m
public void printQuantiles(boolean isCumulative, int numberOfQuantiles, PrintStream out) {
    out.println();
    /*
     * header - start
     */
    out.print("#p");
    for (String mode : this.frequencies.keySet()) {
        out.print("\t" + mode);
    }
    out.println();
    /*
     * header - end
     */

    /*
     * table - start
     */
    double[] quantiles = new double[numberOfQuantiles];
    for (int ii = 0; ii < numberOfQuantiles; ii++) {
        quantiles[ii] = ((double) ii + 1) / (numberOfQuantiles);
    }

    for (int ii = 0; ii < numberOfQuantiles; ii++) {
        out.print(percentFormat.format(quantiles[ii]));
        for (String mode : this.frequencies.keySet()) {
            out.print("\t");
            out.print(classFormat
                    .format(StatUtils.percentile(this.rawData.get(mode).getElements(), quantiles[ii] * 100.0)));
        }
        out.println();
    }
    /*
     * table - end
     */
    out.println();
}

From source file:XMLWriter.java

/**
 * Wrier the argument String any encoded on a stream
 * @param any//from   ww  w.  j a  va2s. c  o m
 * @param stream
 */
public static void encodeOn(String any, PrintStream stream) {
    /**
     * See google groups
     * http://groups.google.com/groups?q=java+escape+xml&start=10&hl=en&lr=
     * &ie=UTF-8&selm=JPyaOQm2Fo7O2PeLfDykYBAsjKGw%404ax.com&rnum=12
     */
    if (any == null || any.length() < 1) {
        return;
    }
    for (int i = 0; i < any.length(); i++) {
        char c = any.charAt(i);
        int v = (int) c;
        if (v < 32 || v > 127 || v == 38 || v == 60 || v == 62 || v == 34) {
            // we must escape a character in format &#22;
            // 38 is ampersand &
            // 60 is smaller <
            // 62 is larger >
            // 34 is quote "
            stream.print('&');
            stream.print('#');
            stream.print(v);
            stream.print(';');
        } else {
            stream.print(c);
        }
    }
}

From source file:org.apache.commons.digester3.examples.api.addressbook.Address.java

public void print(java.io.PrintStream out, int indentAmount) {
    StringBuilder indentStr = new StringBuilder(indentAmount);
    for (; indentAmount > 0; --indentAmount) {
        indentStr.append(' ');
    }/*from ww w.j ava 2s.  c  om*/

    out.print(indentStr);
    out.print("address type: ");
    out.println(type);

    out.print(indentStr);
    out.println("  " + street);

    out.print(indentStr);
    out.println("  " + city + " " + state + " " + zip);

    out.print(indentStr);
    out.println("  " + country);
}

From source file:no.met.jtimeseries.netcdf.NetcdfChartProvider.java

public void getCsv(PrintStream out, Iterable<String> variables) throws ParseException, IOException {

    Vector<NumberPhenomenon> data = getWantedPhenomena(variables);

    // header/*ww  w  . ja  va 2s. c  o m*/
    out.print("# Time");
    for (NumberPhenomenon p : data)
        out.print(",\t" + p.getPhenomenonName() + " (" + p.getPhenomenonUnit() + ")");
    out.println();

    TreeMap<Date, Double[]> displayData = new TreeMap<Date, Double[]>();
    for (int i = 0; i < data.size(); i++) {
        for (NumberValueItem atom : data.get(i)) {
            Double[] d = displayData.get(atom.getTimeFrom());
            if (d == null) {
                d = new Double[data.size()];
                displayData.put(atom.getTimeFrom(), d);
            }
            d[i] = atom.getValue();
        }
    }

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    for (Entry<Date, Double[]> element : displayData.entrySet()) {
        out.print(format.format(element.getKey()));
        Double[] d = element.getValue();
        for (int i = 0; i < d.length; i++)
            out.print(",\t" + d[i]);
        out.println();
    }
}

From source file:cc.kave.commons.pointsto.evaluation.ProjectTrainValidateEvaluation.java

private void printSummary(List<String> names) {
    double[][] grid = new double[names.size()][names.size()];

    for (Map.Entry<ICoReTypeName, List<EvaluationResult>> resultEntry : results.entrySet()) {
        for (EvaluationResult result : resultEntry.getValue()) {
            grid[names.indexOf(result.training)][names.indexOf(result.validation)] += result.score;
        }/*  w ww  .ja v a2  s  .  c o  m*/
    }

    PrintStream printer = System.out;
    double numTypes = results.size();
    for (int i = 0; i < names.size(); ++i) {
        printer.print(names.get(i));

        for (int j = 0; j < names.size(); ++j) {
            printer.print(' ');
            printer.printf(Locale.US, "%.3f", grid[i][j] / numTypes);
        }
        printer.println();
    }
}

From source file:com.github.vatbub.awsvpnlauncher.Main.java

/**
 * Launches a new VPN server on AWS EC2 if everything is configured
 *
 * @see PropertyNotConfiguredException/*from  ww w  .j  a v a2s . com*/
 * @see #terminate()
 */
private static void launch() {
    File privateKey = new File(prefs.getPreference(Property.privateKeyFile));
    vpnPassword = prefs.getPreference(Property.openvpnPassword);

    if (!privateKey.exists() && !privateKey.isFile()) {
        throw new IllegalArgumentException("The file specified as " + Property.privateKeyFile.toString()
                + " does not exist or is not a file.");
    }

    FOKLogger.info(Main.class.getName(), "Preparing...");

    try {
        // Check if our security group exists already
        FOKLogger.info(Main.class.getName(), "Checking for the required security group...");
        DescribeSecurityGroupsRequest describeSecurityGroupsRequest = new DescribeSecurityGroupsRequest()
                .withGroupNames(securityGroupName);

        List<String> securityGroups = new ArrayList<>();
        boolean created = false; // will become true if the security group had to be created to avoid duplicate logs
        String securityGroupId;
        try {
            DescribeSecurityGroupsResult describeSecurityGroupsResult = client
                    .describeSecurityGroups(describeSecurityGroupsRequest);
            securityGroupId = describeSecurityGroupsResult.getSecurityGroups().get(0).getGroupId();
        } catch (AmazonEC2Exception e) {
            // Security group does not exist, create the security group
            created = true;
            FOKLogger.info(Main.class.getName(), "Creating the required security group...");
            CreateSecurityGroupRequest createSecurityGroupRequest = new CreateSecurityGroupRequest()
                    .withGroupName(securityGroupName).withDescription(
                            "This security group was automatically created to run a OpenVPN Access Server.");
            CreateSecurityGroupResult createSecurityGroupResult = client
                    .createSecurityGroup(createSecurityGroupRequest);

            securityGroupId = createSecurityGroupResult.getGroupId();

            IpRange ipRange = new IpRange().withCidrIp("0.0.0.0/0");
            IpPermission sshPermission1 = new IpPermission().withIpv4Ranges(ipRange).withIpProtocol("tcp")
                    .withFromPort(22).withToPort(22);
            IpPermission sshPermission2 = new IpPermission().withIpv4Ranges(ipRange).withIpProtocol("tcp")
                    .withFromPort(943).withToPort(943);
            IpPermission httpsPermission1 = new IpPermission().withIpv4Ranges(ipRange).withIpProtocol("tcp")
                    .withFromPort(443).withToPort(443);
            IpPermission httpsPermission2 = new IpPermission().withIpv4Ranges(ipRange).withIpProtocol("udp")
                    .withFromPort(1194).withToPort(1194);

            AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest = new AuthorizeSecurityGroupIngressRequest()
                    .withGroupName(securityGroupName).withIpPermissions(sshPermission1)
                    .withIpPermissions(sshPermission2).withIpPermissions(httpsPermission1)
                    .withIpPermissions(httpsPermission2);

            // retry while the security group is not yet ready
            int retries = 0;
            long lastPollTime = System.currentTimeMillis();
            boolean requestIsFailing = true;

            do {
                // we're waiting

                if (System.currentTimeMillis() - lastPollTime >= Math.pow(2, retries) * 100) {
                    retries = retries + 1;
                    lastPollTime = System.currentTimeMillis();
                    try {
                        client.authorizeSecurityGroupIngress(authorizeSecurityGroupIngressRequest);
                        // no exception => we made it
                        requestIsFailing = false;
                    } catch (AmazonEC2Exception e2) {
                        FOKLogger.info(Main.class.getName(),
                                "Still waiting for the security group to be created, api error message is currently: "
                                        + e2.getMessage());
                        requestIsFailing = true;
                    }
                }
            } while (requestIsFailing);
            FOKLogger.info(Main.class.getName(), "The required security group has been successfully created!");
        }

        if (!created) {
            FOKLogger.info(Main.class.getName(), "The required security group already exists, we can continue");
        }
        securityGroups.add(securityGroupId);

        securityGroups.add(securityGroupId);

        FOKLogger.info(Main.class.getName(), "Creating the RunInstanceRequest...");
        RunInstancesRequest request = new RunInstancesRequest(getAmiId(awsRegion), 1, 1);
        request.setInstanceType(InstanceType.T2Micro);
        request.setKeyName(prefs.getPreference(Property.awsKeyPairName));
        request.setSecurityGroupIds(securityGroups);

        FOKLogger.info(Main.class.getName(), "Starting the EC2 instance...");
        RunInstancesResult result = client.runInstances(request);
        List<Instance> instances = result.getReservation().getInstances();

        // SSH config
        FOKLogger.info(Main.class.getName(), "Configuring SSH...");
        Properties sshConfig = new Properties();
        sshConfig.put("StrictHostKeyChecking", "no");
        JSch jsch = new JSch();
        jsch.addIdentity(privateKey.getAbsolutePath());
        int retries = 0;

        for (Instance instance : instances) {
            // write the instance id to a properties file to be able to terminate it later on again
            prefs.reload();
            if (prefs.getPreference("instanceIDs", "").equals("")) {
                prefs.setPreference("instanceIDs", instance.getInstanceId());
            } else {
                prefs.setPreference("instanceIDs",
                        prefs.getPreference("instanceIDs", "") + ";" + instance.getInstanceId());
            }

            // Connect to the instance using ssh
            FOKLogger.info(Main.class.getName(), "Waiting for the instance to boot...");

            long lastPrintTime = System.currentTimeMillis();
            DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest();
            List<String> instanceId = new ArrayList<>(1);
            instanceId.add(instance.getInstanceId());
            describeInstancesRequest.setInstanceIds(instanceId);
            DescribeInstancesResult describeInstancesResult;
            newInstance = instance;

            do {
                // we're waiting

                if (System.currentTimeMillis() - lastPrintTime >= Math.pow(2, retries) * 100) {
                    retries = retries + 1;
                    describeInstancesResult = client.describeInstances(describeInstancesRequest);
                    newInstance = describeInstancesResult.getReservations().get(0).getInstances().get(0);
                    lastPrintTime = System.currentTimeMillis();
                    if (newInstance.getState().getCode() != 16) {
                        FOKLogger.info(Main.class.getName(),
                                "Still waiting for the instance to boot, current instance state is "
                                        + newInstance.getState().getName());
                    }
                }
            } while (newInstance.getState().getCode() != 16);

            FOKLogger.info(Main.class.getName(), "Instance is " + newInstance.getState().getName());

            // generate the ssh ip of the instance
            String sshIp = newInstance.getPublicDnsName();

            FOKLogger.info(Main.class.getName(), "The instance id is " + newInstance.getInstanceId());
            FOKLogger.info(Main.class.getName(), "The instance ip is " + newInstance.getPublicIpAddress());
            FOKLogger.info(Main.class.getName(), "Connecting using ssh to " + sshUsername + "@" + sshIp);
            FOKLogger.info(Main.class.getName(),
                    "The instance will need some time to configure ssh on its end so some connection timeouts are normal");
            boolean retry;
            session = jsch.getSession(sshUsername, sshIp, 22);
            session.setConfig(sshConfig);
            do {
                try {
                    session.connect();
                    retry = false;
                } catch (Exception e) {
                    FOKLogger.info(Main.class.getName(), e.getClass().getName() + ": " + e.getMessage()
                            + ", retrying, Press Ctrl+C to cancel");
                    retry = true;
                }
            } while (retry);

            FOKLogger.info(Main.class.getName(),
                    "----------------------------------------------------------------------");
            FOKLogger.info(Main.class.getName(), "The following is the out- and input of the ssh session.");
            FOKLogger.info(Main.class.getName(), "Please note that out- and input may appear out of sync.");
            FOKLogger.info(Main.class.getName(),
                    "----------------------------------------------------------------------");

            PipedInputStream sshIn = new PipedInputStream();
            PipedOutputStream sshIn2 = new PipedOutputStream(sshIn);
            PrintStream sshInCommandStream = new PrintStream(sshIn2);
            Channel channel = session.openChannel("shell");
            channel.setInputStream(sshIn);
            channel.setOutputStream(new MyPrintStream());
            channel.connect();

            sshInCommandStream.print("yes\n");
            sshInCommandStream.print("yes\n");
            sshInCommandStream.print("1\n");
            sshInCommandStream.print("\n");
            sshInCommandStream.print("\n");
            sshInCommandStream.print("yes\n");
            sshInCommandStream.print("yes\n");
            sshInCommandStream.print("\n");
            sshInCommandStream.print("\n");
            sshInCommandStream.print("\n");
            sshInCommandStream.print("\n");
            sshInCommandStream.print("echo \"" + adminUsername + ":" + vpnPassword + "\" | sudo chpasswd\n");
            sshInCommandStream.print("exit\n");

            NullOutputStream nullOutputStream = new NullOutputStream();
            Thread watchForSSHDisconnectThread = new Thread(() -> {
                while (channel.isConnected()) {
                    nullOutputStream.write(0);
                }
                // disconnected
                cont();
            });
            watchForSSHDisconnectThread.setName("watchForSSHDisconnectThread");
            watchForSSHDisconnectThread.start();
        }
    } catch (JSchException | IOException e) {
        e.printStackTrace();
        if (session != null) {
            session.disconnect();
        }
        System.exit(1);
    }
}

From source file:haven.Utils.java

public static void dumparr(Object[] arr, PrintStream out, boolean term) {
    out.print('[');
    boolean f = true;
    for (Object o : arr) {
        if (!f)// ww w .j  a  v a  2  s.c o m
            out.print(", ");
        f = false;
        if (o instanceof Object[])
            dumparr((Object[]) o, out, false);
        else
            out.print(o);
    }
    out.print(']');
    if (term)
        out.println();
}

From source file:com.juick.android.Utils.java

public static RESTResponse postForm(final Context context, final String url, ArrayList<NameValuePair> data) {
    try {// w  ww .  j  a v  a  2  s .co  m
        final String end = "\r\n";
        final String twoHyphens = "--";
        final String boundary = "****+++++******+++++++********";

        URL apiUrl = new URL(url);

        final HttpURLConnection conn = (HttpURLConnection) apiUrl.openConnection();
        conn.setConnectTimeout(10000);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Charset", "UTF-8");
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        conn.connect();
        OutputStream out = conn.getOutputStream();

        PrintStream ps = new PrintStream(out);
        int index = 0;
        byte[] block = new byte[1024];
        for (NameValuePair nameValuePair : data) {
            ps.print(twoHyphens + boundary + end);
            ps.print("Content-Disposition: form-data; name=\"" + nameValuePair.getName() + "\"" + end + end);
            final InputStream value = nameValuePair.getValue();
            while (true) {
                final int rd = value.read(block, 0, block.length);
                if (rd < 1) {
                    break;
                }
                ps.write(block, 0, rd);
            }
            value.close();
            ps.print(end);
        }
        ps.print(twoHyphens + boundary + twoHyphens + end);
        ps.close();
        boolean b = conn.getResponseCode() == 200;
        if (!b) {
            return new RESTResponse("HTTP " + conn.getResponseCode() + ": " + conn.getResponseMessage(), false,
                    null);
        } else {
            InputStream inputStream = conn.getInputStream();
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                byte[] arr = new byte[1024];
                while (true) {
                    int rd = inputStream.read(arr);
                    if (rd < 1)
                        break;
                    baos.write(arr, 0, rd);
                }
                if (conn.getHeaderField("X-GZIPCompress") != null) {
                    return new RESTResponse(null, false, baos.toString(0));
                } else {
                    return new RESTResponse(null, false, baos.toString());
                }
            } finally {
                inputStream.close();
            }
        }
    } catch (IOException e) {
        return new RESTResponse(e.toString(), false, null);
    }
}