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, CharsetDecoder dec) 

Source Link

Document

Creates an InputStreamReader that uses the given charset decoder.

Usage

From source file:CharsetDetector.java

public static void main(String[] args) {
    File f = new File("example.txt");

    String[] charsetsToBeTested = { "UTF-8", "windows-1253", "ISO-8859-7" };

    CharsetDetector cd = new CharsetDetector();
    Charset charset = cd.detectCharset(f, charsetsToBeTested);

    if (charset != null) {
        try {//from   ww w. j av a  2s  .c om
            InputStreamReader reader = new InputStreamReader(new FileInputStream(f), charset);
            int c = 0;
            while ((c = reader.read()) != -1) {
                System.out.print((char) c);
            }
            reader.close();
        } catch (FileNotFoundException fnfe) {
            fnfe.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }

    } else {
        System.out.println("Unrecognized charset.");
    }
}

From source file:an.dpr.cyclingresultsapi.ClientExecuteProxy.java

public static void main(String[] args) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    StringBuilder ret = new StringBuilder();
    try {//from ww  w .j  a  va 2 s .co  m
        //http://cyclingresults-dprsoft.rhcloud.com/rest/competitions/query/20140101,20140601,1,1,UWT
        //            HttpHost target = new HttpHost("cyclingresults-dprsoft.rhcloud.com", 80, "http");
        HttpHost proxy = null;// = new HttpHost("proxy.sdc.hp.com", 8080, "http");
        HttpHost target = new HttpHost("localhost", 8282, "http");

        RequestConfig config = RequestConfig.custom()
                //                    .setProxy(proxy)
                .build();
        HttpGet request = new HttpGet("/rest/competitions/query/20130801,20130901,1,1,UWT");
        request.setConfig(config);

        System.out.println("Executing request " + request.getRequestLine() + " to " + target + " via " + proxy);

        CloseableHttpResponse response = httpclient.execute(target, request);
        InputStreamReader isr = new InputStreamReader(response.getEntity().getContent(), "cp1252");
        BufferedReader br = new BufferedReader(isr);
        String line;
        while ((line = br.readLine()) != null) {
            ret.append(line);
        }
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            EntityUtils.consume(response.getEntity());
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
    System.out.println(ret.toString());
}

From source file:org.openeclass.EclassMobile.java

public static void main(String[] args) {

    try {/*from   w ww.j a  v  a 2s.  c o  m*/
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("https://myeclass/modules/mobile/mlogin.php");
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("uname", mUsername));
        nvps.add(new BasicNameValuePair("pass", mPassword));
        httppost.setEntity(new UrlEncodedFormEntity(nvps));

        System.out.println("twra tha kanei add");
        System.out.println("prin to response");

        HttpResponse response = httpclient.execute(httppost);
        StatusLine status = response.getStatusLine();

        if (status.getStatusCode() != 200)
            System.out.println("Invalid response from server: " + status.toString());

        System.out.println("meta to response");

        Header[] head = response.getAllHeaders();

        for (int i = 0; i < head.length; i++)
            System.out.println("to head exei " + head[i]);

        System.out.println("Login form get: " + response.getStatusLine());

        HttpEntity entity = response.getEntity();
        InputStream ips = entity.getContent();
        BufferedReader buf = new BufferedReader(new InputStreamReader(ips, "UTF-8"), 1024);

        StringBuilder sb = new StringBuilder();
        String s = "";

        while ((s = buf.readLine()) != null) {
            sb.append(s);
        }
        System.out.println("to sb einai " + sb.toString());

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

From source file:com.ibm.jaql.lang.Jaql.java

public static void main(String args[]) throws Exception {
    InputStream in;/*from   www. j av a2  s . c o  m*/
    if (args.length > 0) {
        in = new FileInputStream(args[0]);
    } else {
        in = System.in;
    }
    run("<stdin>", new InputStreamReader(in, "UTF-8"));
    // System.exit(0); // possible jvm 1.6 work around for "JDWP Unable to get JNI 1.2 environment"
}

From source file:ProxyTunnelDemo.java

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

    ProxyClient proxyclient = new ProxyClient();
    // set the host the proxy should create a connection to
    ////from w w w  .  jav a  2  s .co m
    // Note:  By default port 80 will be used. Some proxies only allow conections
    // to ports 443 and 8443.  This is because the HTTP CONNECT method was intented
    // to be used for tunneling HTTPS.
    proxyclient.getHostConfiguration().setHost("www.yahoo.com");
    // set the proxy host and port
    proxyclient.getHostConfiguration().setProxy("10.0.1.1", 3128);
    // set the proxy credentials, only necessary for authenticating proxies
    proxyclient.getState().setProxyCredentials(new AuthScope("10.0.1.1", 3128, null),
            new UsernamePasswordCredentials("proxy", "proxy"));

    // create the socket
    ProxyClient.ConnectResponse response = proxyclient.connect();

    if (response.getSocket() != null) {
        Socket socket = response.getSocket();
        try {
            // go ahead and do an HTTP GET using the socket
            Writer out = new OutputStreamWriter(socket.getOutputStream(), "ISO-8859-1");
            out.write("GET http://www.yahoo.com/ HTTP/1.1\r\n");
            out.write("Host: www.yahoo.com\r\n");
            out.write("Agent: whatever\r\n");
            out.write("\r\n");
            out.flush();
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(socket.getInputStream(), "ISO-8859-1"));
            String line = null;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
        } finally {
            // be sure to close the socket when we're done
            socket.close();
        }
    } else {
        // the proxy connect was not successful, check connect method for reasons why
        System.out.println("Connect failed: " + response.getConnectMethod().getStatusLine());
        System.out.println(response.getConnectMethod().getResponseBodyAsString());
    }
}

From source file:Main.java

/** Simple command-line based search demo. */
public static void main(String[] args) throws Exception {
    String usage = "Usage:\tjava SearchFiles [-index dir] [-field f] [-repeat n] [-queries file] [-query string] [-raw] [-paging hitsPerPage]\n\nSee http://lucene.apache.org/core/4_1_0/demo/ for details.";
    if (args.length > 0 && ("-h".equals(args[0]) || "-help".equals(args[0]))) {
        System.out.println(usage);
        System.exit(0);//from   ww w  .  j ava2 s  .  c o  m
    }

    String index = "index";
    String field = "contents";
    String queries = null;
    int repeat = 0;
    boolean raw = false;
    String queryString = null;
    int hitsPerPage = 10;

    for (int i = 0; i < args.length; i++) {
        if ("-index".equals(args[i])) {
            index = args[i + 1];
            i++;
        } else if ("-field".equals(args[i])) {
            field = args[i + 1];
            i++;
        } else if ("-queries".equals(args[i])) {
            queries = args[i + 1];
            i++;
        } else if ("-query".equals(args[i])) {
            queryString = args[i + 1];
            i++;
        } else if ("-repeat".equals(args[i])) {
            repeat = Integer.parseInt(args[i + 1]);
            i++;
        } else if ("-raw".equals(args[i])) {
            raw = true;
        } else if ("-paging".equals(args[i])) {
            hitsPerPage = Integer.parseInt(args[i + 1]);
            if (hitsPerPage <= 0) {
                System.err.println("There must be at least 1 hit per page.");
                System.exit(1);
            }
            i++;
        }
    }

    IndexReader reader = DirectoryReader.open(FSDirectory.open(new File(index)));
    IndexSearcher searcher = new IndexSearcher(reader);
    // :Post-Release-Update-Version.LUCENE_XY:
    Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_4_10_0);

    BufferedReader in = null;
    if (queries != null) {
        in = new BufferedReader(new InputStreamReader(new FileInputStream(queries), StandardCharsets.UTF_8));
    } else {
        in = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8));
    }
    // :Post-Release-Update-Version.LUCENE_XY:
    QueryParser parser = new QueryParser(Version.LUCENE_4_10_0, field, analyzer);
    while (true) {
        if (queries == null && queryString == null) { // prompt the user
            System.out.println("Enter query: ");
        }

        String line = queryString != null ? queryString : in.readLine();

        if (line == null || line.length() == -1) {
            break;
        }

        line = line.trim();
        if (line.length() == 0) {
            break;
        }

        Query query = parser.parse(line);
        System.out.println("Searching for: " + query.toString(field));

        if (repeat > 0) { // repeat & time as benchmark
            Date start = new Date();
            for (int i = 0; i < repeat; i++) {
                searcher.search(query, null, 100);
            }
            Date end = new Date();
            System.out.println("Time: " + (end.getTime() - start.getTime()) + "ms");
        }

        doPagingSearch(in, searcher, query, hitsPerPage, raw, queries == null && queryString == null);

        if (queryString != null) {
            break;
        }
    }
    reader.close();
}

From source file:de.tu_dortmund.ub.data.dswarm.TaskProcessingUnit.java

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

    // default config
    String configFile = DEFAULT_CONF_FOLDER_NAME + File.separatorChar + DEFAULT_CONFIG_PROPERTIES_FILE_NAME;

    // read program parameters
    if (args.length > 0) {

        for (final String arg : args) {

            LOG.info("arg = " + arg);

            if (arg.startsWith("-conf=")) {

                configFile = arg.split("=")[1];
            }/*from  ww w  .java2  s  .c  o  m*/
        }
    }

    final Properties config;

    // Init properties
    try {

        try (final InputStream inputStream = new FileInputStream(configFile)) {

            try (final BufferedReader reader = new BufferedReader(
                    new InputStreamReader(inputStream, TPUUtil.UTF_8))) {

                config = new Properties();
                config.load(reader);
            }
        }
    } catch (final IOException e) {

        LOG.error("something went wrong", e);
        LOG.error(String.format("FATAL ERROR: Could not read '%s'!", configFile));

        throw e;
    }

    startTPU(configFile, config);
}

From source file:herddb.server.ServerMain.java

public static void main(String... args) {
    try {//from w  w w. j  a v a2  s  . co  m
        LOG.log(Level.INFO, "Starting HerdDB version {0}", herddb.utils.Version.getVERSION());
        Properties configuration = new Properties();

        boolean configFileFromParameter = false;
        for (int i = 0; i < args.length; i++) {
            String arg = args[i];
            if (!arg.startsWith("-")) {
                File configFile = new File(args[i]).getAbsoluteFile();
                LOG.log(Level.INFO, "Reading configuration from {0}", configFile);
                try (InputStreamReader reader = new InputStreamReader(new FileInputStream(configFile),
                        StandardCharsets.UTF_8)) {
                    configuration.load(reader);
                }
                configFileFromParameter = true;
            } else if (arg.equals("--use-env")) {
                System.getenv().forEach((key, value) -> {
                    System.out.println("Considering env as system property " + key + " -> " + value);
                    System.setProperty(key, value);
                });
            } else if (arg.startsWith("-D")) {
                int equals = arg.indexOf('=');
                if (equals > 0) {
                    String key = arg.substring(2, equals);
                    String value = arg.substring(equals + 1);
                    System.setProperty(key, value);
                }
            }
        }
        if (!configFileFromParameter) {
            File configFile = new File("conf/server.properties").getAbsoluteFile();
            LOG.log(Level.INFO, "Reading configuration from {0}", configFile);
            if (configFile.isFile()) {
                try (InputStreamReader reader = new InputStreamReader(new FileInputStream(configFile),
                        StandardCharsets.UTF_8)) {
                    configuration.load(reader);
                }
            }
        }

        System.getProperties().forEach((k, v) -> {
            String key = k + "";
            if (!key.startsWith("java") && !key.startsWith("user")) {
                configuration.put(k, v);
            }
        });

        LogManager.getLogManager().readConfiguration();

        Runtime.getRuntime().addShutdownHook(new Thread("ctrlc-hook") {

            @Override
            public void run() {
                System.out.println("Ctrl-C trapped. Shutting down");
                ServerMain _brokerMain = runningInstance;
                if (_brokerMain != null) {
                    _brokerMain.close();
                }
            }

        });
        runningInstance = new ServerMain(configuration);
        runningInstance.start();

        runningInstance.join();

    } catch (Throwable t) {
        t.printStackTrace();
        System.exit(1);
    }
}

From source file:com.tamingtext.classifier.bayes.ClassifyDocument.java

public static void main(String[] args) {
    log.info("Command-line arguments: " + Arrays.toString(args));

    DefaultOptionBuilder obuilder = new DefaultOptionBuilder();
    ArgumentBuilder abuilder = new ArgumentBuilder();
    GroupBuilder gbuilder = new GroupBuilder();

    Option inputOpt = obuilder.withLongName("input").withRequired(true)
            .withArgument(abuilder.withName("input").withMinimum(1).withMaximum(1).create())
            .withDescription("Input file").withShortName("i").create();

    Option modelOpt = obuilder.withLongName("model").withRequired(true)
            .withArgument(abuilder.withName("model").withMinimum(1).withMaximum(1).create())
            .withDescription("Model to use when classifying data").withShortName("m").create();

    Option helpOpt = obuilder.withLongName("help").withDescription("Print out help").withShortName("h")
            .create();//  www  .  j a va2s .com

    Group group = gbuilder.withName("Options").withOption(inputOpt).withOption(modelOpt).withOption(helpOpt)
            .create();

    try {
        Parser parser = new Parser();
        parser.setGroup(group);
        CommandLine cmdLine = parser.parse(args);

        if (cmdLine.hasOption(helpOpt)) {
            CommandLineUtil.printHelp(group);
            return;
        }

        File inputFile = new File(cmdLine.getValue(inputOpt).toString());

        if (!inputFile.isFile()) {
            throw new IllegalArgumentException(inputFile + " does not exist or is not a file");
        }

        File modelDir = new File(cmdLine.getValue(modelOpt).toString());

        if (!modelDir.isDirectory()) {
            throw new IllegalArgumentException(modelDir + " does not exist or is not a directory");
        }

        BayesParameters p = new BayesParameters();
        p.set("basePath", modelDir.getCanonicalPath());
        Datastore ds = new InMemoryBayesDatastore(p);
        Algorithm a = new BayesAlgorithm();
        ClassifierContext ctx = new ClassifierContext(a, ds);
        ctx.initialize();

        //TODO: make the analyzer configurable
        StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_36);
        TokenStream ts = analyzer.tokenStream(null,
                new InputStreamReader(new FileInputStream(inputFile), "UTF-8"));

        ArrayList<String> tokens = new ArrayList<String>(1000);
        while (ts.incrementToken()) {
            tokens.add(ts.getAttribute(CharTermAttribute.class).toString());
        }
        String[] document = tokens.toArray(new String[tokens.size()]);

        ClassifierResult[] cr = ctx.classifyDocument(document, "unknown", 5);

        for (ClassifierResult r : cr) {
            System.err.println(r.getLabel() + "\t" + r.getScore());
        }
    } catch (OptionException e) {
        log.error("Exception", e);
        CommandLineUtil.printHelp(group);
    } catch (IOException e) {
        log.error("IOException", e);
    } catch (InvalidDatastoreException e) {
        log.error("InvalidDataStoreException", e);
    } finally {

    }
}

From source file:com.indeed.imhotep.builder.tsv.KerberosUtils.java

/**
 * Use for testing keytab logins//from   w  w  w  .j  a va 2  s .  c  om
 */
public static void main(String[] args) throws Exception {
    KerberosUtils.loginFromKeytab(new BaseConfiguration());
    final FileSystem fileSystem = FileSystem.get(new org.apache.hadoop.conf.Configuration());
    final Path path = new Path("/CLUSTERNAME");
    if (fileSystem.exists(path)) {
        System.out.println(CharStreams.toString(new InputStreamReader(fileSystem.open(path), Charsets.UTF_8)));
    }
}