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:SifterJava.java

public static void main(String[] args) throws Exception {
    /** Enter your sifter account and access key in the 
    ** string fields below *///  w w w .  j a v a  2  s  . c  o  m

    // create URL object to SifterAPI
    String yourAccount = "your-account"; // enter your account name
    String yourDomain = yourAccount + ".sifterapp.com";
    URL sifter = new URL("https", yourDomain, "/api/projects");

    // open connectino to SifterAPI
    URLConnection sifterConnection = sifter.openConnection();

    // add Access Key to header request
    String yourAccessKey = "your-32char-sifterapi-access-key"; // enter your access key
    sifterConnection.setRequestProperty("X-Sifter-Token", yourAccessKey);

    // add Accept: application/json to header - also not necessary
    sifterConnection.addRequestProperty("Accept", "application/json");

    // URLconnection.connect() not necessary
    // getInputStream will connect

    // don't make a content handler, org.json reads a stream!

    // create buffer and open input stream
    BufferedReader in = new BufferedReader(new InputStreamReader(sifterConnection.getInputStream()));
    // don't readline, create stringbuilder, append, create string

    // construct json tokener from input stream or buffered reader
    JSONTokener x = new JSONTokener(in);

    // initialize "projects" JSONObject from string
    JSONObject projects = new JSONObject(x);

    // prettyprint "projects"
    System.out.println("************ projects ************");
    System.out.println(projects.toString(2));

    // array of projects
    JSONArray array = projects.getJSONArray("projects");
    int arrayLength = array.length();
    JSONObject[] p = new JSONObject[arrayLength];

    // projects
    for (int i = 0; i < arrayLength; i++) {
        p[i] = array.getJSONObject(i);
        System.out.println("************ project: " + (i + 1) + " ************");
        System.out.println(p[i].toString(2));
    }

    // check field names
    String[] checkNames = { "api_url", "archived", "api_issues_url", "milestones_url", "api_milestones_url",
            "api_categories_url", "issues_url", "name", "url", "api_people_url", "primary_company_name" };

    // project field names
    String[] fieldNames = JSONObject.getNames(p[0]);
    int numKeys = p[0].length();
    SifterProj[] proj = new SifterProj[arrayLength];

    for (int j = 0; j < arrayLength; j++) {
        proj[j] = new SifterProj(p[j].get("api_url").toString(), p[j].get("archived").toString(),
                p[j].get("api_issues_url").toString(), p[j].get("milestones_url").toString(),
                p[j].get("api_milestones_url").toString(), p[j].get("api_categories_url").toString(),
                p[j].get("issues_url").toString(), p[j].get("name").toString(), p[j].get("url").toString(),
                p[j].get("api_people_url").toString(), p[j].get("primary_company_name").toString());
        System.out.println("************ project: " + (j + 1) + " ************");
        for (int i = 0; i < numKeys; i++) {
            System.out.print(fieldNames[i]);
            System.out.print(" : ");
            System.out.println(p[j].get(fieldNames[i]));
        }
    }
}

From source file:de.uzk.hki.da.main.SIPBuilder.java

public static void main(String[] args) {

    TTCCLayout layout = new TTCCLayout();
    layout.setDateFormat("yyyy'-'MM'-'dd' 'HH':'mm':'ss");
    layout.setThreadPrinting(false);//ww w.  j a  va  2  s. com
    ConsoleAppender consoleAppender = new ConsoleAppender(layout);
    logger.addAppender(consoleAppender);
    logger.setLevel(Level.DEBUG);

    properties = new Properties();
    try {
        properties.load(new InputStreamReader(
                (ClassLoader.getSystemResourceAsStream("configuration/config.properties"))));
    } catch (FileNotFoundException e1) {
        System.exit(Feedback.GUI_ERROR.toInt());
    } catch (IOException e2) {
        System.exit(Feedback.GUI_ERROR.toInt());
    }

    try {
        if (SystemUtils.IS_OS_WINDOWS)
            System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.out), true, "CP850"));
        else
            System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.out), true, "UTF-8"));
    } catch (UnsupportedEncodingException e) {
        return;
    }

    String mainFolderPath = SIPBuilder.class.getProtectionDomain().getCodeSource().getLocation().getPath();
    String confFolderPath, dataFolderPath;
    try {
        mainFolderPath = URLDecoder.decode(mainFolderPath, "UTF-8");
        confFolderPath = new File(mainFolderPath).getParent() + File.separator + "conf";
        dataFolderPath = new File(mainFolderPath).getParent() + File.separator + "data";
    } catch (UnsupportedEncodingException e) {
        confFolderPath = "conf";
        dataFolderPath = "data";
    }
    System.out.println("ConfFolderPath:" + confFolderPath);
    if (args.length == 0)
        startGUIMode(confFolderPath, dataFolderPath);
    else
        startCLIMode(confFolderPath, dataFolderPath, args);
}

From source file:postenergy.TestHttpClient.java

public static void main(String[] args) {
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost("https://www.google.com/accounts/ClientLogin");

    try {/*from www.  j a v a2 s .  c  om*/

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
        nameValuePairs.add(new BasicNameValuePair("Email", "youremail"));
        nameValuePairs.add(new BasicNameValuePair("Passwd", "yourpassword"));
        nameValuePairs.add(new BasicNameValuePair("accountType", "GOOGLE"));
        nameValuePairs.add(new BasicNameValuePair("source", "Google-cURL-Example"));
        nameValuePairs.add(new BasicNameValuePair("service", "ac2dm"));

        post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = client.execute(post);
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        String line = "";
        while ((line = rd.readLine()) != null) {
            System.out.println(line);
            if (line.startsWith("Auth=")) {
                String key = line.substring(5);
                // do something with the key
            }

        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:CatFile.java

public static void main(String[] av) {
    CatFile c = new CatFile();
    if (av.length == 0)
        c.process(new BufferedReader(new InputStreamReader(System.in)));
    else//from  ww w .ja  v a2 s  .com
        for (int i = 0; i < av.length; i++)
            try {
                c.process(new BufferedReader(new FileReader(av[i])));
            } catch (FileNotFoundException e) {
                System.err.println(e);
            }
}

From source file:yangqi.hc.HttpClientTest.java

/**
 * @param args/*from  ww w  . j av a2 s  .c  om*/
 * @throws IOException
 * @throws ClientProtocolException
 */
public static void main(String[] args) throws ClientProtocolException, IOException {
    // TODO Auto-generated method stub
    HttpClient httpclient = new DefaultHttpClient();

    // Prepare a request object
    HttpGet httpget = new HttpGet("http://www.apache.org/");

    // Execute the request
    HttpResponse response = httpclient.execute(httpget);

    // Examine the response status
    System.out.println(response.getStatusLine());

    System.out.println(response.getLocale());

    for (Header header : response.getAllHeaders()) {
        System.out.println(header.toString());
    }

    // Get hold of the response entity
    HttpEntity entity = response.getEntity();

    System.out.println("==========entity=========");
    System.out.println(entity.getContentLength());
    System.out.println(entity.getContentType());
    System.out.println(entity.getContentEncoding());

    // If the response does not enclose an entity, there is no need
    // to worry about connection release
    if (entity != null) {
        InputStream instream = entity.getContent();
        try {

            BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
            // do something useful with the response
            System.out.println(reader.readLine());

        } catch (IOException ex) {

            // In case of an IOException the connection will be released
            // back to the connection manager automatically
            throw ex;

        } catch (RuntimeException ex) {

            // In case of an unexpected exception you may want to abort
            // the HTTP request in order to shut down the underlying
            // connection and release it back to the connection manager.
            httpget.abort();
            throw ex;

        } finally {

            // Closing the input stream will trigger connection release
            instream.close();

        }

        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }

}

From source file:com.discursive.jccook.slide.GetExample.java

public static void main(String[] args) throws HttpException, IOException {
    HttpClient client = new HttpClient();

    String url = "http://www.discursive.com/jccook/dav/test.html";
    Credentials credentials = new UsernamePasswordCredentials("davuser", "davpass");

    // List resources in top directory
    WebdavResource resource = new WebdavResource(url, credentials);

    System.out.println("The three ways to Read resources.");

    // Read to a temporary file
    File tempFile = new File(resource.getName());
    resource.getMethod(tempFile);/*from   ww w .  jav  a 2  s .c  om*/
    System.out.println("1. " + resource.getName() + " saved in file: " + tempFile.toString());

    // Read as a String
    String resourceData = resource.getMethodDataAsString();
    System.out.println("2. Contents of " + resource.getName() + " as String.");
    System.out.println(resourceData);

    // Read with a stream
    InputStream resourceStream = resource.getMethodData();
    Reader reader = new InputStreamReader(resourceStream);
    StringWriter writer = new StringWriter();
    while (reader.ready()) {
        writer.write(reader.read());
    }
    System.out.println("3. Contents of " + resource.getName() + " from InputStream.");
    System.out.println(writer.toString());

    resource.close();

}

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

public static void main(String... args) throws IOException { // create command line Options object
    Options options = new Options();
    Option opt = new Option("in", true, "input file oe-supported");
    opt.setRequired(true);/*  ww w  .j  a v a  2  s .c om*/
    options.addOption(opt);

    opt = new Option("out", true, "output file oe-supported");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option("fragFile", true, "file with single 3d substructure query");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option("isMDL", false,
            "if given the fragFile is suposed to be an mdl query file, query features are supported.");
    opt.setRequired(false);
    options.addOption(opt);

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        System.err.println(e.getMessage());
        exitWithHelp(options);
    }
    args = cmd.getArgs();

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

    String inFile = cmd.getOptionValue("in");
    String outFile = cmd.getOptionValue("out");
    String fragFile = cmd.getOptionValue("fragFile");

    // read fragment
    OESubSearch ss;
    oemolistream ifs = new oemolistream(fragFile);
    OEMolBase mol;
    if (!cmd.hasOption("isMDL")) {
        mol = new OEGraphMol();
        oechem.OEReadMolecule(ifs, mol);
        ss = new OESubSearch(mol, OEExprOpts.AtomicNumber, OEExprOpts.BondOrder);
    } else {
        int aromodel = OEIFlavor.Generic.OEAroModelOpenEye;
        int qflavor = ifs.GetFlavor(ifs.GetFormat());
        ifs.SetFlavor(ifs.GetFormat(), (qflavor | aromodel));
        int opts = OEMDLQueryOpts.Default | OEMDLQueryOpts.SuppressExplicitH;
        OEQMol qmol = new OEQMol();
        oechem.OEReadMDLQueryFile(ifs, qmol, opts);
        ss = new OESubSearch(qmol);
        mol = qmol;
    }

    double nSSatoms = mol.NumAtoms();
    double sssCoords[] = new double[mol.GetMaxAtomIdx() * 3];
    mol.GetCoords(sssCoords);
    mol.Clear();
    ifs.close();

    if (!ss.IsValid())
        throw new Error("Invalid query " + args[0]);

    ifs = new oemolistream(inFile);
    oemolostream ofs = new oemolostream(outFile);
    int count = 0;

    while (oechem.OEReadMolecule(ifs, mol)) {
        count++;
        double rmsd = Double.MAX_VALUE;
        double molCoords[] = new double[mol.GetMaxAtomIdx() * 3];
        mol.GetCoords(molCoords);

        for (OEMatchBase mb : ss.Match(mol, false)) {
            double r = 0;
            for (OEMatchPairAtom mp : mb.GetAtoms()) {
                OEAtomBase asss = mp.getPattern();
                double sx = sssCoords[asss.GetIdx() * 3];
                double sy = sssCoords[asss.GetIdx() * 3];
                double sz = sssCoords[asss.GetIdx() * 3];

                OEAtomBase amol = mp.getTarget();
                double mx = molCoords[amol.GetIdx() * 3];
                double my = molCoords[amol.GetIdx() * 3];
                double mz = molCoords[amol.GetIdx() * 3];

                r += Math.sqrt((sx - mx) * (sx - mx) + (sy - my) * (sy - my) + (sz - mz) * (sz - mz));
            }
            r /= nSSatoms;
            rmsd = Math.min(rmsd, r);
        }

        if (rmsd != Double.MAX_VALUE)
            oechem.OESetSDData(mol, "SSSrmsd", String.format("%.3f", rmsd));

        oechem.OEWriteMolecule(ofs, mol);
        mol.Clear();
    }

    ifs.close();
    ofs.close();

    mol.delete();
    ss.delete();
}

From source file:com.game.GameLauncherApplication.java

public static void main(String[] args) throws Exception {
    // System.exit is common for Batch applications since the exit code can be used to
    // drive a workflow
    //      System.exit(SpringApplication.exit(SpringApplication.run(
    //            SampleBatchApplication.class, args)));

    String s = "Y";
    while ("Y".equalsIgnoreCase(s.trim())) {
        ticTacToeGame.startGame();/*from   ww w .j  a  v  a  2s  . c o m*/
        System.out.println(" Do you want to play more to Play more enter Y ");
        BufferedReader BR = new BufferedReader(new InputStreamReader(System.in));
        s = BR.readLine();
        if (s != null && !s.isEmpty()) {
            s = s.trim();
        }

    }

}

From source file:Undent.java

public static void main(String[] av) {
    Undent c = new Undent();
    if (av.length == 0)
        c.process(new BufferedReader(new InputStreamReader(System.in)));
    else//  w w  w .  j a v  a 2  s  .  c  o  m
        for (int i = 0; i < av.length; i++) {
            try {
                c.process(new BufferedReader(new FileReader(av[i])));
            } catch (FileNotFoundException e) {
                System.err.println(e);
            }
        }
}

From source file:CSVFile.java

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

    // Construct a new CSV parser.
    CSV csv = new CSV();

    if (args.length == 0) { // read standard input
        BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
        process(csv, is);//  w  w w .  j ava 2 s. c  o  m
    } else {
        for (int i = 0; i < args.length; i++) {
            process(csv, new BufferedReader(new FileReader(args[i])));
        }
    }
}