Example usage for java.io InputStreamReader InputStreamReader

List of usage examples for java.io InputStreamReader InputStreamReader

Introduction

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

Prototype

public InputStreamReader(InputStream in) 

Source Link

Document

Creates an InputStreamReader that uses the default charset.

Usage

From source file:com.yahoo.athenz.example.ntoken.HttpExampleClient.java

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

    // parse our command line to retrieve required input

    CommandLine cmd = parseCommandLine(args);

    String domainName = cmd.getOptionValue("domain");
    String serviceName = cmd.getOptionValue("service");
    String privateKeyPath = cmd.getOptionValue("pkey");
    String keyId = cmd.getOptionValue("keyid");
    String url = cmd.getOptionValue("url");

    // we need to generate our principal credentials (ntoken). In
    // addition to the domain and service names, we need the
    // the service's private key and the key identifier - the
    // service with the corresponding public key must already be
    // registered in ZMS

    PrivateKey privateKey = Crypto.loadPrivateKey(new File(privateKeyPath));
    ServiceIdentityProvider identityProvider = new SimpleServiceIdentityProvider(domainName, serviceName,
            privateKey, keyId);/*from  ww w  .j ava 2 s . co  m*/
    Principal principal = identityProvider.getIdentity(domainName, serviceName);

    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    // set our Athenz credentials. The authority in the principal provides
    // the header name that we must use for credentials while the principal
    // itself provides the credentials (ntoken).

    con.setRequestProperty(principal.getAuthority().getHeader(), principal.getCredentials());

    // now process our request

    int responseCode = con.getResponseCode();
    switch (responseCode) {
    case HttpURLConnection.HTTP_FORBIDDEN:
        System.out.println("Request was forbidden - not authorized: " + con.getResponseMessage());
        break;
    case HttpURLConnection.HTTP_OK:
        System.out.println("Successful response: ");
        try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                System.out.println(inputLine);
            }
        }
        break;
    default:
        System.out.println("Request failed - response status code: " + responseCode);
    }
}

From source file:com.wxpay.ClientCustomSSL.java

public final static void main(String[] args) throws Exception {
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    FileInputStream instream = new FileInputStream(new File("E:/apiclient_cert1.p12"));
    try {/*w  ww .j  a  v  a2 s .  c o m*/
        keyStore.load(instream, "1269885501".toCharArray());
    } finally {
        instream.close();
    }

    // Trust own CA and all self-signed certs
    SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, "1269885501".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 {

        HttpGet httpget = new HttpGet("https://api.mch.weixin.qq.com/secapi/pay/refund");

        System.out.println("executing request" + httpget.getRequestLine());

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

            System.out.println("----------------------------------------");
            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;
                while ((text = bufferedReader.readLine()) != null) {
                    System.out.println(text);
                }

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

From source file:org.gzk.image.junit.ClientCustomSSL.java

public final static void main(String[] args) throws Exception {
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    FileInputStream instream = new FileInputStream(new File("D:/apiclient_cert.p12"));
    try {//  w  w w .ja v a 2  s  . c  o  m
        keyStore.load(instream, "1374938902".toCharArray());
    } finally {
        instream.close();
    }
    // Trust own CA and all self-signed certs
    SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, "1374938902".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 {

        HttpGet httpget = new HttpGet("https://api.mch.weixin.qq.com/secapi/pay/refund");

        System.out.println("executing request" + httpget.getRequestLine());

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

            System.out.println("----------------------------------------");
            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;
                while ((text = bufferedReader.readLine()) != null) {
                    System.out.println(text);
                }

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

From source file:com.magicbeans.banjiuwan.util.ClientCustomSSL.java

public final static void main(String[] args) throws Exception {
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    FileInputStream instream = new FileInputStream(new File("D:/10016225.p12"));
    try {//from w w w .ja v  a2  s  .c o  m
        keyStore.load(instream, "10016225".toCharArray());
    } finally {
        instream.close();
    }

    // Trust own CA and all self-signed certs
    SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, "10016225".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 {

        HttpGet httpget = new HttpGet("https://api.mch.weixin.qq.com/secapi/pay/refund");

        System.out.println("executing request" + httpget.getRequestLine());

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

            System.out.println("----------------------------------------");
            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;
                while ((text = bufferedReader.readLine()) != null) {
                    System.out.println(text);
                }

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

From source file:com.adobe.aem.demo.Analytics.java

public static void main(String[] args) {

    String hostname = null;/*from   w w  w . j ava 2  s .  co  m*/
    String url = null;
    String eventfile = null;

    // Command line options for this tool
    Options options = new Options();
    options.addOption("h", true, "Hostname");
    options.addOption("u", true, "Url");
    options.addOption("f", true, "Event data file");
    CommandLineParser parser = new BasicParser();
    try {
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("u")) {
            url = cmd.getOptionValue("u");
        }

        if (cmd.hasOption("f")) {
            eventfile = cmd.getOptionValue("f");
        }

        if (cmd.hasOption("h")) {
            hostname = cmd.getOptionValue("h");
        }

        if (eventfile == null || hostname == null || url == null) {
            System.out.println("Command line parameters: -h hostname -u url -f path_to_XML_file");
            System.exit(-1);
        }

    } catch (ParseException ex) {

        logger.error(ex.getMessage());

    }

    URLConnection urlConn = null;
    DataOutputStream printout = null;
    BufferedReader input = null;
    String u = "http://" + hostname + "/" + url;
    String tmp = null;
    try {

        URL myurl = new URL(u);
        urlConn = myurl.openConnection();
        urlConn.setDoInput(true);
        urlConn.setDoOutput(true);
        urlConn.setUseCaches(false);
        urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        printout = new DataOutputStream(urlConn.getOutputStream());

        String xml = readFile(eventfile, StandardCharsets.UTF_8);
        printout.writeBytes(xml);
        printout.flush();
        printout.close();

        input = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));

        logger.debug(xml);
        while (null != ((tmp = input.readLine()))) {
            logger.debug(tmp);
        }
        printout.close();
        input.close();

    } catch (Exception ex) {

        logger.error(ex.getMessage());

    }

}

From source file:keepassj.cli.KeepassjCli.java

/**
 * @param args the command line arguments
 * @throws org.apache.commons.cli.ParseException
 * @throws java.io.IOException//from w  w w .  j  a  v a 2  s  . c  o m
 */
public static void main(String[] args) throws ParseException, IOException {
    Options options = KeepassjCli.getOptions();
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(options, args);
    if (!KeepassjCli.validateOptions(cmd)) {
        HelpFormatter help = new HelpFormatter();
        help.printHelp("Usage: java -jar KeepassjCli -f dbfile [options]", options);
    } else {
        String password;
        if (cmd.hasOption('p')) {
            password = cmd.getOptionValue('p');
        } else {
            Console console = System.console();
            char[] hiddenString = console.readPassword("Enter password for %s\n", cmd.getOptionValue('f'));
            password = String.valueOf(hiddenString);
        }
        KeepassjCli instance = new KeepassjCli(cmd.getOptionValue('f'), password, cmd.getOptionValue('k'));
        System.out.println("Description:" + instance.db.getDescription());
        PwGroup rootGroup = instance.db.getRootGroup();
        System.out.println(String.valueOf(rootGroup.GetEntriesCount(true)) + " entries");
        if (cmd.hasOption('l')) {
            instance.printEntries(rootGroup.GetEntries(true), false);
        } else if (cmd.hasOption('s')) {
            PwObjectList<PwEntry> results = instance.search(cmd.getOptionValue('s'));
            System.out.println("Found " + results.getUCount() + " results for:" + cmd.getOptionValue('s'));
            instance.printEntries(results, false);
        } else if (cmd.hasOption('i')) {
            System.out.println("Entering interactive mode.");
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
            String input = null;
            PwObjectList<PwEntry> results = null;
            while (!"\\q".equals(input)) {
                if (results != null) {
                    System.out.println("Would you like to view a specific entry? y/n");
                    input = bufferedReader.readLine();
                    if ("y".equalsIgnoreCase(input)) {
                        System.out.print("Enter the title number:");
                        input = bufferedReader.readLine();
                        instance.printCompleteEntry(results.GetAt(Integer.parseInt(input) - 1)); // Since humans start counting at 1
                    }
                    results = null;
                    System.out.println();
                } else {
                    System.out.print("Enter something to search for (or \\q to quit):");
                    input = bufferedReader.readLine();
                    if (!"\\q".equalsIgnoreCase(input)) {
                        results = instance.search(input);
                        instance.printEntries(results, true);
                    }
                }
            }
        }

        // Close before exit
        instance.db.Close();
    }
}

From source file:com.genentech.chemistry.openEye.apps.SDFMCSSSphereExclusion.java

public static void main(String... args) throws IOException {
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;/*  w  ww . j a v a2s  .com*/
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        System.err.println(e.getMessage());
        exitWithHelp();
    }
    args = cmd.getArgs();

    if (cmd.hasOption("d")) {
        System.err.println("Start debugger and press return:");
        new BufferedReader(new InputStreamReader(System.in)).readLine();
    }

    // the only reason not to match centroids in reverse order id if
    // a non-centroid is to be assigned to multiple centroids
    boolean printSphereMatchCount = cmd.hasOption("printSphereMatchCount");
    boolean reverseMatch = !cmd.hasOption("checkSpheresInOrder") && !printSphereMatchCount;
    boolean printAll = cmd.hasOption("printAll") || printSphereMatchCount;
    double radius = Double.parseDouble(cmd.getOptionValue("radius"));
    String inFile = cmd.getOptionValue("in");
    String outFile = cmd.getOptionValue("out");
    String refFile = cmd.getOptionValue("ref");

    SimComparatorFactory<OEMolBase, OEMolBase, SimComparator<OEMolBase>> compFact;
    compFact = getComparatorFactory(cmd);

    SphereExclusion<OEMolBase, SimComparator<OEMolBase>> alg = new SphereExclusion<OEMolBase, SimComparator<OEMolBase>>(
            compFact, refFile, outFile, radius, reverseMatch, printSphereMatchCount, printAll);
    alg.run(inFile);
    alg.close();
}

From source file:edu.mit.fss.examples.TDRSSFederate.java

/**
 * The main method. This configures the Orekit data path, creates the
 * SaudiComsat federate objects and launches the associated graphical user
 * interface./*  ww  w  . j  a  va  2s .c  o  m*/
 *
 * @param args the arguments
 * @throws RTIexception the RTI exception
 * @throws URISyntaxException 
 */
public static void main(String[] args) throws RTIexception, URISyntaxException {
    BasicConfigurator.configure();

    logger.debug("Setting Orekit data path.");
    System.setProperty(DataProvidersManager.OREKIT_DATA_PATH,
            new File(TDRSSFederate.class.getResource("/orekit-data.zip").toURI()).getAbsolutePath());

    logger.trace("Creating federate instance.");
    final TDRSSFederate federate = new TDRSSFederate();

    logger.trace("Setting minimum step duration and time step.");
    long timeStep = 60 * 1000, minimumStepDuration = 100;
    federate.setMinimumStepDuration(minimumStepDuration);
    federate.setTimeStep(timeStep);

    logger.debug("Loading TLE data from file.");
    final List<Component> panels = new ArrayList<Component>();
    for (String satName : Arrays.asList("TDRS 3", "TDRS 5", "TDRS 6", "TDRS 7", "TDRS 8", "TDRS 9", "TDRS 10",
            "TDRS 11")) {
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    federate.getClass().getClassLoader().getResourceAsStream("edu/mit/fss/examples/data.tle")));

            while (br.ready()) {
                if (br.readLine().matches(".*" + satName + ".*")) {
                    logger.debug("Found " + satName + " data.");

                    logger.trace("Adding " + satName + " supplier space system.");
                    SpaceSystem system = new SpaceSystem(satName, new TLE(br.readLine(), br.readLine()),
                            5123e3);
                    federate.addObject(system);

                    panels.add(new SpaceSystemPanel(federate, system));

                    try {
                        logger.trace("Setting inital time.");
                        federate.setInitialTime(system.getInitialState().getDate()
                                .toDate(TimeScalesFactory.getUTC()).getTime());
                    } catch (IllegalArgumentException | OrekitException e) {
                        logger.error(e.getMessage());
                        e.printStackTrace();
                    }
                    break;
                }
            }
            br.close();
        } catch (IllegalArgumentException | OrekitException | IOException e) {
            e.printStackTrace();
            logger.fatal(e);
        }
    }

    try {
        logger.trace("Adding WSGT ground station.");
        SurfaceSystem wsgt = new SurfaceSystem("WSGT",
                new GeodeticPoint(FastMath.toRadians(32.5007), FastMath.toRadians(-106.6086), 1474),
                new AbsoluteDate(), 5123e3, 5);
        federate.addObject(wsgt);
        panels.add(new SurfaceSystemPanel(federate, wsgt));

        logger.trace("Adding STGT ground station.");
        SurfaceSystem stgt = new SurfaceSystem("STGT",
                new GeodeticPoint(FastMath.toRadians(32.5430), FastMath.toRadians(-106.6120), 1468),
                new AbsoluteDate(), 5123e3, 5);
        federate.addObject(stgt);
        panels.add(new SurfaceSystemPanel(federate, stgt));

        logger.trace("Adding GRGT ground station.");
        SurfaceSystem grgt = new SurfaceSystem("GRGT",
                new GeodeticPoint(FastMath.toRadians(13.6148), FastMath.toRadians(144.8565), 142),
                new AbsoluteDate(), 5123e3, 5);
        federate.addObject(grgt);
        panels.add(new SurfaceSystemPanel(federate, grgt));
    } catch (OrekitException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    }

    logger.debug("Launching the graphical user interface.");
    try {
        SwingUtilities.invokeAndWait(new Runnable() {
            @Override
            public void run() {
                MemberFrame frame = new MemberFrame(federate, new MultiComponentPanel(panels));
                frame.pack();
                frame.setVisible(true);
            }
        });
    } catch (InvocationTargetException | InterruptedException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    }

    logger.trace("Setting federate name, type, and FOM path.");
    federate.getConnection().setFederateName("TDRSS");
    federate.getConnection().setFederateType("FSS Supplier");
    federate.getConnection().setFederationName("FSS");
    federate.getConnection().setFomPath(
            new File(federate.getClass().getClassLoader().getResource("edu/mit/fss/hla/fss.xml").toURI())
                    .getAbsolutePath());
    federate.getConnection().setOfflineMode(false);
    federate.connect();
}

From source file:com.interacciones.mxcashmarketdata.driver.client.DriverClient.java

public static void main(String[] args) throws Throwable {
    init(args);/*from www .j  a  v a2  s .  c  om*/

    NioSocketConnector connector = new NioSocketConnector();

    // Configure the service.
    connector.setConnectTimeoutMillis(CONNECT_TIMEOUT);
    if (USE_CUSTOM_CODEC) {
        connector.getFilterChain().addLast("codec",
                new ProtocolCodecFilter(new SumUpProtocolCodecFactory(false)));
    } else {
        connector.getFilterChain().addLast("codec",
                new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));
    }
    int[] values = new int[] {};
    connector.getFilterChain().addLast("logger", new LoggingFilter());
    connector.setHandler(new ClientSessionHandler(values));

    long time = System.currentTimeMillis();
    IoSession session;
    for (;;) {
        try {
            System.out.println(host + " " + port + " " + fileTest);
            ConnectFuture future = connector.connect(new InetSocketAddress(host, port));
            future.awaitUninterruptibly();
            session = future.getSession();

            File file = new File(fileTest);
            FileInputStream is = new FileInputStream(file);
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);

            int data = br.read();
            int count = 0;

            IoBuffer ib = IoBuffer.allocate(274);
            ib.setAutoExpand(true);
            boolean flagcount = false;

            while (data != -1) {
                data = br.read();
                ib.put((byte) data);

                if (flagcount) {
                    count++;
                }
                if (data == 13) {
                    count = 1;
                    flagcount = true;
                    LOGGER.debug(ib.toString());
                }
                if (count == 4) {
                    ib.flip();
                    session.write(ib);
                    ib = IoBuffer.allocate(274);
                    ib.setAutoExpand(true);
                    flagcount = false;
                    count = 0;
                    //Thread.sleep(500);
                }
            }

            break;
        } catch (RuntimeIoException e) {
            LOGGER.error("Failed to connect.");
            e.printStackTrace();
            Thread.sleep(5000);
        }
    }
    time = System.currentTimeMillis() - time;
    LOGGER.info("Time " + time);
    // wait until the summation is done
    session.getCloseFuture().awaitUninterruptibly();
    connector.dispose();
}

From source file:PlyBounder.java

public static void main(String[] args) {

    // Get the commandline arguments
    Options options = new Options();
    // Available options
    Option plyPath = OptionBuilder.withArgName("dir").hasArg()
            .withDescription("directory containing input .ply files").create("plyPath");
    Option boundingbox = OptionBuilder.withArgName("string").hasArg()
            .withDescription("bounding box in WKT notation").create("boundingbox");
    Option outputPlyFile = OptionBuilder.withArgName("file").hasArg().withDescription("output PLY file name")
            .create("outputPlyFile");
    options.addOption(plyPath);//from  w w w .j a v  a2 s. co m
    options.addOption(boundingbox);
    options.addOption(outputPlyFile);

    String plydir = ".";
    String boundingboxstr = "";
    String outputfilename = "";

    CommandLineParser parser = new DefaultParser();
    try {
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);

        boundingboxstr = line.getOptionValue("boundingbox");
        outputfilename = line.getOptionValue("outputPlyFile");

        if (line.hasOption("plyPath")) {
            // print the value of block-size
            plydir = line.getOptionValue("plyPath");
            System.out.println("Using plyPath=" + plydir);
        } else {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("PlyBounder", options);
        }
        //System.out.println( "plyPath=" + line.getOptionValue( "plyPath" ) );
    } catch (ParseException exp) {
        System.err.println("Error getting arguments: " + exp.getMessage());
    }

    // input directory
    // Get list of files
    File dir = new File(plydir);

    //System.out.println("Getting all files in " + dir.getCanonicalPath());
    List<File> files = (List<File>) FileUtils.listFiles(dir, new String[] { "ply", "PLY" }, false);
    for (File file : files) {
        try {
            System.out.println("file=" + file.getCanonicalPath());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    String sometempfile = "magweg.wkt";
    String s = null;

    // Loop through .ply files in directory
    for (File file : files) {
        try {
            String cmdl[] = { "./ply-tool.py", "intersection", file.getCanonicalPath(), boundingboxstr,
                    sometempfile };
            //System.out.println("Running: " + Arrays.toString(cmdl));
            Process p = Runtime.getRuntime().exec(cmdl);

            BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));

            BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));

            // read the output from the command
            System.out.println("cmdout:\n");
            while ((s = stdInput.readLine()) != null) {
                System.out.println(s);
            }

            // read any errors from the attempted command
            System.out.println("cmderr:\n");
            while ((s = stdError.readLine()) != null) {
                System.out.println(s);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // Write new .ply file
    //ply-tool write setfile outputPlyFile
    try {
        String cmdl = "./ply-tool.py write " + sometempfile + " " + outputfilename;
        System.out.println("Running: " + cmdl);
        Process p = Runtime.getRuntime().exec(cmdl);

        BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));

        BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));

        // read the output from the command
        System.out.println("cmdout:\n");
        while ((s = stdInput.readLine()) != null) {
            System.out.println(s);
        }

        // read any errors from the attempted command
        System.out.println("cmderr:\n");
        while ((s = stdError.readLine()) != null) {
            System.out.println(s);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    // Done
    System.out.println("Done");
}