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

/** Grab the sales rank off the web page and log it. */
public static void main(String[] args) throws Exception {

    Properties p = new Properties();
    String title = p.getProperty("title", "NO TITLE IN PROPERTIES");
    // The url must have the "isbn=" at the very end, or otherwise
    // be amenable to being string-catted to, like the default.
    String url = p.getProperty("url", "http://test.ing/test.cgi?isbn=");
    // The 10-digit ISBN for the book.
    String isbn = p.getProperty("isbn", "0000000000");
    // The RE pattern (MUST have ONE capture group for the number)
    String pattern = p.getProperty("pattern", "Rank: (\\d+)");

    // Looking for something like this in the input:
    //    <b>QuickBookShop.web Sales Rank: </b>
    //    26,252//from w ww.j a va  2 s .c  o m
    //    </font><br>

    Pattern r = Pattern.compile(pattern);

    // Open the URL and get a Reader from it.
    BufferedReader is = new BufferedReader(new InputStreamReader(new URL(url + isbn).openStream()));
    // Read the URL looking for the rank information, as
    // a single long string, so can match RE across multi-lines.
    String input = "input from console";
    // System.out.println(input);

    // If found, append to sales data file.
    Matcher m = r.matcher(input);
    if (m.find()) {
        PrintWriter pw = new PrintWriter(new FileWriter(DATA_FILE, true));
        String date = // `date +'%m %d %H %M %S %Y'`;
                new SimpleDateFormat("MM dd hh mm ss yyyy ").format(new Date());
        // Paren 1 is the digits (and maybe ','s) that matched; remove comma
        Matcher noComma = Pattern.compile(",").matcher(m.group(1));
        pw.println(date + noComma.replaceAll(""));
        pw.close();
    } else {
        System.err.println("WARNING: pattern `" + pattern + "' did not match in `" + url + isbn + "'!");
    }

    // Whether current data found or not, draw the graph, using
    // external plotting program against all historical data.
    // Could use gnuplot, R, any other math/graph program.
    // Better yet: use one of the Java plotting APIs.

    String gnuplot_cmd = "set term png\n" + "set output \"" + GRAPH_FILE + "\"\n" + "set xdata time\n"
            + "set ylabel \"Book sales rank\"\n" + "set bmargin 3\n" + "set logscale y\n"
            + "set yrange [1:60000] reverse\n" + "set timefmt \"%m %d %H %M %S %Y\"\n" + "plot \"" + DATA_FILE
            + "\" using 1:7 title \"" + title + "\" with lines\n";

    Process proc = Runtime.getRuntime().exec("/usr/local/bin/gnuplot");
    PrintWriter gp = new PrintWriter(proc.getOutputStream());
    gp.print(gnuplot_cmd);
    gp.close();
}

From source file:bluevia.examples.MODemo.java

/**
 * @param args//from   w w  w .  ja v  a2  s  .  co  m
 */
public static void main(String[] args) throws IOException {

    BufferedReader iReader = null;
    String apiDataFile = "API-AccessToken.ini";

    String consumer_key;
    String consumer_secret;
    String registrationId;

    OAuthConsumer apiConsumer = null;
    HttpURLConnection request = null;
    URL moAPIurl = null;

    Logger logger = Logger.getLogger("moSMSDemo.class");
    int i = 0;
    int rc = 0;

    Thread mThread = Thread.currentThread();

    try {
        System.setProperty("debug", "1");

        iReader = new BufferedReader(new FileReader(apiDataFile));

        // Private data: consumer info + access token info + phone info
        consumer_key = iReader.readLine();
        consumer_secret = iReader.readLine();
        registrationId = iReader.readLine();

        // Set up the oAuthConsumer
        while (true) {
            try {

                logger.log(Level.INFO, String.format("#%d: %s\n", ++i, "Requesting messages..."));

                apiConsumer = new DefaultOAuthConsumer(consumer_key, consumer_secret);

                apiConsumer.setMessageSigner(new HmacSha1MessageSigner());

                moAPIurl = new URL("https://api.bluevia.com/services/REST/SMS/inbound/" + registrationId
                        + "/messages?version=v1&alt=json");

                request = (HttpURLConnection) moAPIurl.openConnection();
                request.setRequestMethod("GET");

                apiConsumer.sign(request);

                StringBuffer doc = new StringBuffer();
                BufferedReader br = null;

                rc = request.getResponseCode();
                if (rc == HttpURLConnection.HTTP_OK) {
                    br = new BufferedReader(new InputStreamReader(request.getInputStream()));

                    String line = br.readLine();
                    while (line != null) {
                        doc.append(line);
                        line = br.readLine();
                    }

                    System.out.printf("Output message: %s\n", doc.toString());
                    try {
                        JSONObject apiResponse1 = new JSONObject(doc.toString());
                        String aux = apiResponse1.getString("receivedSMS");
                        if (aux != null) {
                            String szMessage;
                            String szOrigin;
                            String szDate;

                            JSONObject smsPool = apiResponse1.getJSONObject("receivedSMS");
                            JSONArray smsInfo = smsPool.optJSONArray("receivedSMS");
                            if (smsInfo != null) {
                                for (i = 0; i < smsInfo.length(); i++) {
                                    szMessage = smsInfo.getJSONObject(i).getString("message");
                                    szOrigin = smsInfo.getJSONObject(i).getJSONObject("originAddress")
                                            .getString("phoneNumber");
                                    szDate = smsInfo.getJSONObject(i).getString("dateTime");
                                    System.out.printf("#%d %s\n - from %s\n - message:%s\n", i, szDate,
                                            szOrigin, szMessage);
                                }
                            } else {
                                JSONObject sms = smsPool.getJSONObject("receivedSMS");
                                szMessage = sms.getString("message");
                                szOrigin = sms.getJSONObject("originAddress").getString("phoneNumber");
                                szDate = sms.getString("dateTime");
                                System.out.printf("#%d %s\n - from %s\n - message:%s\n", i, szDate, szOrigin,
                                        szMessage);
                            }
                        }
                    } catch (JSONException e) {
                        System.err.println("JSON error: " + e.getMessage());
                    }

                } else if (rc == HttpURLConnection.HTTP_NO_CONTENT)
                    System.out.printf("No content\n");
                else
                    System.err.printf("Error: %d:%s\n", rc, request.getResponseMessage());

                request.disconnect();

            } catch (Exception e) {
                System.err.println("Exception: " + e.getMessage());
            }
            mThread.sleep(15000);
        }
    } catch (Exception e) {
        System.err.println("Exception: " + e.getMessage());
    }
}

From source file:SequentialPageRank.java

@SuppressWarnings({ "static-access" })
public static void main(String[] args) throws IOException {
    Options options = new Options();

    options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("input path").create(INPUT));
    options.addOption(//w w  w  .  j a va  2  s.  c o m
            OptionBuilder.withArgName("val").hasArg().withDescription("random jump factor").create(JUMP));

    CommandLine cmdline = null;
    CommandLineParser parser = new GnuParser();

    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Error parsing command line: " + exp.getMessage());
        System.exit(-1);
    }

    if (!cmdline.hasOption(INPUT)) {
        System.out.println("args: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.setWidth(120);
        formatter.printHelp(SequentialPageRank.class.getName(), options);
        ToolRunner.printGenericCommandUsage(System.out);
        System.exit(-1);
    }

    String infile = cmdline.getOptionValue(INPUT);
    float alpha = cmdline.hasOption(JUMP) ? Float.parseFloat(cmdline.getOptionValue(JUMP)) : 0.15f;

    int edgeCnt = 0;
    DirectedSparseGraph<String, Integer> graph = new DirectedSparseGraph<String, Integer>();

    BufferedReader data = new BufferedReader(new InputStreamReader(new FileInputStream(infile)));

    String line;
    while ((line = data.readLine()) != null) {
        line.trim();
        String[] arr = line.split("\\t");

        for (int i = 1; i < arr.length; i++) {
            graph.addEdge(new Integer(edgeCnt++), arr[0], arr[i]);
        }
    }

    data.close();

    WeakComponentClusterer<String, Integer> clusterer = new WeakComponentClusterer<String, Integer>();

    Set<Set<String>> components = clusterer.transform(graph);
    int numComponents = components.size();
    System.out.println("Number of components: " + numComponents);
    System.out.println("Number of edges: " + graph.getEdgeCount());
    System.out.println("Number of nodes: " + graph.getVertexCount());
    System.out.println("Random jump factor: " + alpha);

    // Compute PageRank.
    PageRank<String, Integer> ranker = new PageRank<String, Integer>(graph, alpha);
    ranker.evaluate();

    // Use priority queue to sort vertices by PageRank values.
    PriorityQueue<Ranking<String>> q = new PriorityQueue<Ranking<String>>();
    int i = 0;
    for (String pmid : graph.getVertices()) {
        q.add(new Ranking<String>(i++, ranker.getVertexScore(pmid), pmid));
    }

    // Print PageRank values.
    System.out.println("\nPageRank of nodes, in descending order:");
    Ranking<String> r = null;
    while ((r = q.poll()) != null) {
        System.out.println(r.rankScore + "\t" + r.getRanked());
    }
}

From source file:at.tuwien.aic.Main.java

/**
 * Main entry point/*  w w w .ja v a  2s  .c  o  m*/
 *
 * @param args
 */
@SuppressWarnings("empty-statement")
public static void main(String[] args) throws IOException, InterruptedException {

    try {
        System.out.println(new java.io.File(".").getCanonicalPath());
    } catch (IOException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }

    TweetCrawler tc = null;

    try {
        tc = TweetCrawler.getInstance();
    } catch (UnknownHostException ex) {
        logger.severe("Could not connect to mongoDb");
        exitWithError(2);
        return;
    }

    int action;

    while (true) {
        action = getDecision("The following actions can be executed",
                new String[] { "Subscribe to topic", "Query topic", "Test preprocessing",
                        "Recreate the evaluation model", "Quit the application" },
                "What action do you want to execute?");

        switch (action) {
        case 1:
            tc.collectTweets(new DefaultTweetHandler() {
                @Override
                public boolean isMatch(String topic) {
                    return true;
                }
            }, getNonEmptyString(
                    "Which topic do you want to subscribe to (use spaces to specify more than one keyword)?")
                            .split(" "));

            System.out.println("Starting to collection tweets");
            System.out.println("Press enter to quit collecting");

            while (System.in.read() != 10)
                ;

            tc.stopCollecting();

            break;
        case 2:
            System.out.println("Enter tweet");
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            String tweet = br.readLine();
            //double prediction = ClassifyTweet.classifyTweets(c, tweet, 2);
            System.exit(0);
            //classifyTopic();
            break;
        case 3:
            int subAction = getDecision("The following preprocessing steps are available",
                    new String[] { "Stop word removal", "Stemming", "Both" }, "What do you want to test?");

            switch (subAction) {
            case 1:
                stopWords();
                break;
            case 2:
                stem();
                break;
            case 3:
                stem(stopWords());
            default:
                break;
            }

            break;
        case 4:
            //ClassifyTweet.classifyTweetArff(c, "resources/unlabeled.arff", "resources/train.arff");
            ArrayList<String> tweets = new ArrayList<>();
            ArrayList<String> processedTweets = new ArrayList<>();

            //Positive Tweets
            tweets.add(
                    "#Office365 is the fastest growing business in Microsofts history, one out of four enterprise clients owns #Office365 in the past 12 months");
            tweets.add("oh yeah back to microsoft word it's great haha");
            tweets.add(
                    "Microsoft Visual Studio 2013 Ultimate: excellent tool, but a bit pricey at $13K - http://t.co/qbc4MHeOrF");
            tweets.add(
                    "Apple 'absolutely' plans to release new product types this year - Design Week: Design WeekApple 'absolutely' p... http://t.co/EK4rIbaHa0");
            tweets.add(
                    "RT @ReformedBroker: \"Apple can't innovate.\" Motherf***er you're watching a movie on a 4 ounce plate of glass.");
            tweets.add(
                    "What's the best brand of shoes?! Lol. There's too damn many, what do you prefer. Me is some Adidas.");
            tweets.add(
                    "I want ?? @AdorableWords: Tribal/Aztec pattern Nike free runs ?? http://t.co/WBxT8CNsPN?");
            tweets.add(
                    "I achieved the Streak Week trophy with my Nike+ FuelBand. #nikeplus http://t.co/OgtpRcoSvp");
            tweets.add("RT @DriveOfAthletes: Retweet for Nike! Favorite for UA! http://t.co/sKZ8hb27xH");

            //Neutral Tweets
            tweets.add("This site is giving away Free Microsoft Points #XBOX LIVE http://t.co/ZR1ythfqJ4");
            tweets.add(
                    "How To Save The World: 1. Open Microsoft Word. 2. In a size 12-36 font, type \"The World\". 3. Click save.");
            tweets.add(
                    "Microsoft Special Deals for Education: Microsoft special deals for Students, faculty and staff: http://t.co/Hf0b2ixPZa");
            tweets.add(
                    "Microsoft is about to take Windows XP off life support On April 8, Windows XP's life is coming to an end. On that d http://t.co/kcSf4uIqW4");
            tweets.add("Microsoft open sources its internet servers http://t.co/oLNTlVjE6Y");
            tweets.add(
                    "The Apple Macintosh computer turns 30 - ... http://t.co/CAfq09Jgn7 #CarlIcahn #IsaacsonIt #SteveJobs #WalterIsaacson");
            tweets.add(
                    "News Update| Samsung opens 60 dedicated stores in Europe with Carphone Warehouse http://t.co/1voh4yPMpN");
            tweets.add("I posted a new photo to Facebook http://t.co/fI40hwklUj");
            tweets.add(
                    "Brand New Men's ADIDAS VIGOR TR 3 Athletic Running shoes. Size: 11.5 http://t.co/oPuFoXLpeI");
            tweets.add("I just ran 2.58 mi with Nike+. http://t.co/pYLkhBxH4Y #nikeplus");
            tweets.add("Why is facebook still a thing");

            //Negative Tweets
            tweets.add("Thank God for microsoft programs.....");
            tweets.add(
                    "RT @verge: UK government once again threatens to ditch Microsoft Office http://t.co/vhvybI1GwI");
            tweets.add("Apple charge far too much for very poor phone cases");
            tweets.add("Here's Why Everyone Is Worried About Apple's iPhone Sales http://t.co/Eq3oPt76AG");
            tweets.add("Is Apple Ready to Disrupt Another Industry? http://t.co/07gedlN0cs via @zite");
            tweets.add(
                    "Tim Cook Officially Admits iPhone 5c Didnt Meet Expectations http://t.co/OdzGZOmdv7 #iPhone #Apple");
            tweets.add("@MushIsAJedi @HeyItsAmine i dont rlly like samsung that much");
            tweets.add("twitter facebook die shit");
            tweets.add(
                    "I am thinking of leaving Facebook for a while... To much spying going on.. I am sick and tired of thinking about... http:/)/t.co/ULydkDEube");
            tweets.add("RT @OfficialSheIdon: RIP Facebook, too many of our parents joined.");

            StopWordRemoval swr = new StopWordRemoval("resources/stopwords.txt");

            for (String t : tweets) {
                t = swr.processText(t);
                processedTweets.add(t);
            }

            for (int i = 0; i < 28; i++) {
                if (i != 4) {
                    ArrayList<Integer> results = ClassifyTweet.classifyTweets(processedTweets, i);

                    int correctCount = 0;
                    int positiveCorrect = 0;
                    int neutralCorrect = 0;
                    int negativeCorrect = 0;
                    int falsePosNeu = 0;
                    int falsePosNeg = 0;
                    int falseNeuPos = 0;
                    int falseNeuNeg = 0;
                    int falseNegNeu = 0;
                    int falseNegPos = 0;

                    for (int j = 0; j < 30; j++) {
                        int pred = results.get(j);

                        if (j >= 0 && j < 10) {
                            if (pred == 1) {
                                correctCount++;
                                positiveCorrect++;
                            } else if (pred == 0) {
                                falsePosNeu++;
                            } else if (pred == -1) {
                                falsePosNeg++;
                            }
                        } else if (j >= 10 && j < 20) {
                            if (pred == 0) {
                                correctCount++;
                                neutralCorrect++;
                            } else if (pred == 1) {
                                falseNeuPos++;
                            } else if (pred == -1) {
                                falseNeuNeg++;
                            }

                        } else if (j >= 20 && j < 30) {
                            if (pred == -1) {
                                correctCount++;
                                negativeCorrect++;
                            } else if (pred == 0) {
                                falseNegNeu++;
                            } else if (pred == 1) {
                                falseNegPos++;
                            }
                        }
                    }

                    System.out.println("Correct Predictions: " + correctCount + " / 30");
                    System.out.println("Correct Positive: " + positiveCorrect + " / 10");
                    System.out.println("Correct Neutral: " + neutralCorrect + " / 10");
                    System.out.println("Correct Negative: " + negativeCorrect + " / 10");

                    System.out.println("False Positive as Neutral: " + falsePosNeu);
                    System.out.println("False Positive as Negative: " + falsePosNeg);

                    System.out.println("False Neutral as Positive: " + falseNeuPos);
                    System.out.println("False Neutral as Negative: " + falseNeuNeg);

                    System.out.println("False Negative as Positive: " + falseNegPos);
                    System.out.println("False Negative as Neutral: " + falseNegNeu);
                }

            }

            exit();
        case 5:
            exit();
        }
    }
}

From source file:mobisocial.nfcserver.DesktopNfcServer.java

public static void main(String[] args) {
    try {/*from   w  w  w  .  ja  va 2  s  .  c  om*/
        Contract server;
        if (args.length > 0 && args[0].equals("tcp")) { // recoverable failure; if args is null, length == 0.
            server = new TcpNdefServer(args);
        } else if (args.length > 0 && args[0].equals("junction")) {
            server = new JunctionNdefServer(args);
        } else {
            server = new BluetoothNdefServer(args); //Builder<BluetoothNdefServer>().build();
        }
        String content = ConnectionHandoverManager.USER_HANDOVER_PREFIX
                + Base64.encodeBase64URLSafeString(getHandoverNdef(server.getHandoverUrl()).toByteArray());
        System.out.println("Welcome to DesktopNfc!");
        System.out.println("Service running on " + server.getHandoverUrl());
        System.out.println("Your configuration QR is: " + QR.getQrl(content)); // QRL
        server.start();

        NfcInterface nfc = getInstance();
        final String PROMPT = "> ";
        BufferedReader lineReader = new BufferedReader(new InputStreamReader(System.in));
        while (true) {
            System.out.print(PROMPT);
            String line = lineReader.readLine().trim();
            nfc.share(line);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:httpclient.client.ClientInteractiveAuthentication.java

public static void main(String[] args) throws Exception {
    DefaultHttpClient httpclient = new DefaultHttpClient();

    // Create local execution context
    HttpContext localContext = new BasicHttpContext();

    HttpGet httpget = new HttpGet("http://localhost/test");

    boolean trying = true;
    while (trying) {
        System.out.println("executing request " + httpget.getRequestLine());
        HttpResponse response = httpclient.execute(httpget, localContext);

        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());

        // Consume response content
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            entity.consumeContent();/*from   w w  w  .j  a  v  a2 s .c  om*/
        }

        int sc = response.getStatusLine().getStatusCode();

        AuthState authState = null;
        if (sc == HttpStatus.SC_UNAUTHORIZED) {
            // Target host authentication required
            authState = (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE);
        }
        if (sc == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
            // Proxy authentication required
            authState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE);
        }

        if (authState != null) {
            System.out.println("----------------------------------------");
            AuthScope authScope = authState.getAuthScope();
            System.out.println("Please provide credentials");
            System.out.println(" Host: " + authScope.getHost() + ":" + authScope.getPort());
            System.out.println(" Realm: " + authScope.getRealm());

            BufferedReader console = new BufferedReader(new InputStreamReader(System.in));

            System.out.print("Enter username: ");
            String user = console.readLine();
            System.out.print("Enter password: ");
            String password = console.readLine();

            if (user != null && user.length() > 0) {
                Credentials creds = new UsernamePasswordCredentials(user, password);
                httpclient.getCredentialsProvider().setCredentials(authScope, creds);
                trying = true;
            } else {
                trying = false;
            }
        } else {
            trying = false;
        }
    }

    // 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:ch.swisscom.mid.verifier.MobileIdCmsVerifier.java

public static void main(String[] args) {

    if (args == null || args.length < 1) {
        System.out.println("Usage: ch.swisscom.mid.verifier.MobileIdCmsVerifier [OPTIONS]");
        System.out.println();/*from ww w.  j  a  v a  2  s.c  om*/
        System.out.println("Options:");
        System.out.println(
                "  -cms=VALUE or -stdin   - base64 encoded CMS/PKCS7 signature string, either as VALUE or via standard input");
        System.out.println(
                "  -jks=VALUE             - optional path to truststore file (default is 'jks/truststore.jks')");
        System.out.println("  -jkspwd=VALUE          - optional truststore password (default is 'secret')");
        System.out.println();
        System.out.println("Example:");
        System.out.println("  java ch.swisscom.mid.verifier.MobileIdCmsVerifier -cms=MIII...");
        System.out.println("  echo -n MIII... | java ch.swisscom.mid.verifier.MobileIdCmsVerifier -stdin");
        System.exit(1);
    }

    try {

        MobileIdCmsVerifier verifier = null;

        String jks = "jks/truststore.jks";
        String jkspwd = "secret";

        String param;
        for (int i = 0; i < args.length; i++) {
            param = args[i].toLowerCase();
            if (param.contains("-jks=")) {
                jks = args[i].substring(args[i].indexOf("=") + 1).trim();
            } else if (param.contains("-jkspwd=")) {
                jkspwd = args[i].substring(args[i].indexOf("=") + 1).trim();
            } else if (param.contains("-cms=")) {
                verifier = new MobileIdCmsVerifier(args[i].substring(args[i].indexOf("=") + 1).trim());
            } else if (param.contains("-stdin")) {
                BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
                String stdin;
                if ((stdin = in.readLine()) != null && stdin.length() != 0)
                    verifier = new MobileIdCmsVerifier(stdin.trim());
            }
        }

        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(new FileInputStream(jks), jkspwd.toCharArray());

        // If you are behind a Proxy..
        // System.setProperty("proxyHost", "10.185.32.54");
        // System.setProperty("proxyPort", "8079");
        // or set it via VM arguments: -DproxySet=true -DproxyHost=10.185.32.54 -DproxyPort=8079

        // Print Issuer/SubjectDN/SerialNumber of all x509 certificates that can be found in the CMSSignedData
        verifier.printAllX509Certificates();

        // Print Signer's X509 Certificate Details
        System.out.println("X509 SignerCert SerialNumber: " + verifier.getX509SerialNumber());
        System.out.println("X509 SignerCert Issuer: " + verifier.getX509IssuerDN());
        System.out.println("X509 SignerCert Subject DN: " + verifier.getX509SubjectDN());
        System.out.println("X509 SignerCert Validity Not Before: " + verifier.getX509NotBefore());
        System.out.println("X509 SignerCert Validity Not After: " + verifier.getX509NotAfter());
        System.out.println("X509 SignerCert Validity currently valid: " + verifier.isCertCurrentlyValid());

        System.out.println("User's unique Mobile ID SerialNumber: " + verifier.getMIDSerialNumber());

        // Print signed content (should be equal to the DTBS Message of the Signature Request)
        System.out.println("Signed Data: " + verifier.getSignedData());

        // Verify the signature on the SignerInformation object
        System.out.println("Signature Valid: " + verifier.isVerified());

        // Validate certificate path against trust anchor incl. OCSP revocation check
        System.out.println("X509 SignerCert Valid (Path+OCSP): " + verifier.isCertValid(keyStore));

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

From source file:com.music.tools.SongDBDownloader.java

public static void main(String[] args) throws Exception {
    HttpClient client = new DefaultHttpClient();

    //        HttpHost proxy = new HttpHost("localhost", 8888);
    //        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

    HttpContext ctx = new BasicHttpContext();

    HttpUriRequest req = new HttpGet(
            "http://www.hooktheory.com/analysis/view/the-beatles/i-want-to-hold-your-hand");
    client.execute(req, ctx);//from  w ww.  j  av  a  2  s .com
    req.abort();

    List<String> urls = getSongUrls(
            "http://www.hooktheory.com/analysis/browseSearch?sQuery=&sOrderBy=views&nResultsPerPage=525&nPage=1",
            client, ctx);
    List<List<? extends NameValuePair>> paramsList = new ArrayList<>(urls.size());
    for (String songUrl : urls) {
        paramsList.addAll(getSongParams(songUrl, client, ctx));
    }
    int i = 0;
    for (List<? extends NameValuePair> params : paramsList) {

        HttpPost request = new HttpPost("http://www.hooktheory.com/songs/getXML");

        request.setHeader("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:15.0) Gecko/20100101 Firefox/15.0.1");
        request.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        request.setHeader("Accept-Encoding", "gzip, deflate");
        request.setHeader("Accept-Language", "en,en-us;q=0.7,bg;q=0.3");
        request.setHeader("Content-Type", "application/x-www-form-urlencoded");
        request.setHeader("Origin", "http://www.hooktheory.com");
        request.setHeader("Referer",
                URLEncoder.encode("http://www.hooktheory.com/swf/DNALive Version 1.0.131.swf", "utf-8"));

        HttpEntity entity = new UrlEncodedFormEntity(params);
        request.setEntity(entity);

        try {
            HttpResponse response = client.execute(request, ctx);
            if (response.getStatusLine().getStatusCode() == 200) {
                InputStream is = response.getEntity().getContent();
                String xml = CharStreams.toString(new InputStreamReader(is));
                is.close();
                Files.write(xml, new File("c:/tmp/musicdb/" + i + ".xml"), Charset.forName("utf-8"));
            } else {
                System.out.println(response.getStatusLine());
                System.out.println(params);
            }
            i++;
            request.abort();
        } catch (Exception ex) {
            System.out.println(params);
            ex.printStackTrace();
        }
    }
}

From source file:com.gomoob.embedded.EmbeddedMongo.java

/**
 * Main entry of the program./*from  w ww . j  a  va 2s  . c  om*/
 * 
 * @param args arguments used to customize starting.
 * 
 * @throws Exception If an error occured while executing the server.
 */
public static void main(String[] args) throws Exception {

    // Creates a default execution context, then the configuration of this context can be changed depending on the 
    // command line parameters received.
    context = new Context();

    // Parse the command line
    parseCommandLine(args);

    boolean terminated = false;

    System.out.println("MONGOD_HOST=" + context.getMongoContext().getNet().getServerAddress().getHostName());
    System.out.println("MONGOD_PORT=" + context.getMongoContext().getNet().getPort());
    System.out.println("SERVER_SOCKET_PORT=" + context.getSocketContext().getServerSocket().getLocalPort());

    Socket socket = null;
    BufferedReader reader = null;
    Writer writer = null;

    while (!terminated) {

        socket = context.getSocketContext().getServerSocket().accept();

        reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        writer = new OutputStreamWriter(new DataOutputStream(socket.getOutputStream()));

        System.out.println("Waiting for command...");
        String commandString = reader.readLine();
        System.out.println(commandString);

        ICommand command = parseCommandString(commandString);

        IResponse response = command.run(context);

        writer.write(response.toJSON());

        writer.close();

        // If the current socket is opened close it
        if (!socket.isClosed()) {
            socket.close();
        }

        // If stop is required
        terminated = response.isTerminationRequired();

    }

    context.getSocketContext().getServerSocket().close();
}

From source file:io.apiman.tools.jdbc.ApimanJdbcServer.java

public static void main(String[] args) {
    try {/*  w w w.  j a v a2  s.  com*/
        File dataDir = new File("target/h2");
        String url = "jdbc:h2:tcp://localhost:9092/apiman";

        if (dataDir.exists()) {
            FileUtils.deleteDirectory(dataDir);
        }
        dataDir.mkdirs();

        Server.createTcpServer("-tcpPassword", "sa", "-baseDir", dataDir.getAbsolutePath(), "-tcpPort", "9092",
                "-tcpAllowOthers").start();
        Class.forName("org.h2.Driver");

        try (Connection connection = DriverManager.getConnection(url, "sa", "")) {
            System.out.println("Connection Established: " + connection.getMetaData().getDatabaseProductName()
                    + "/" + connection.getCatalog());
            executeUpdate(connection,
                    "CREATE TABLE users ( username varchar(255) NOT NULL, password varchar(255) NOT NULL, PRIMARY KEY (username))");
            executeUpdate(connection,
                    "INSERT INTO users (username, password) VALUES ('bwayne', 'ae2efd698aefdf366736a4eda1bc5241f9fbfec7')");
            executeUpdate(connection,
                    "INSERT INTO users (username, password) VALUES ('ckent', 'ea59f7ca52a2087c99374caba0ff29be1b2dcdbf')");
            executeUpdate(connection,
                    "INSERT INTO users (username, password) VALUES ('ballen', 'ea59f7ca52a2087c99374caba0ff29be1b2dcdbf')");
            executeUpdate(connection,
                    "CREATE TABLE roles (rolename varchar(255) NOT NULL, username varchar(255) NOT NULL)");
            executeUpdate(connection, "INSERT INTO roles (rolename, username) VALUES ('user', 'bwayne')");
            executeUpdate(connection, "INSERT INTO roles (rolename, username) VALUES ('admin', 'bwayne')");
            executeUpdate(connection, "INSERT INTO roles (rolename, username) VALUES ('ckent', 'user')");
            executeUpdate(connection, "INSERT INTO roles (rolename, username) VALUES ('ballen', 'user')");
        }

        System.out.println("======================================================");
        System.out.println("JDBC (H2) server started successfully.");
        System.out.println("");
        System.out.println("  Data: " + dataDir.getAbsolutePath());
        System.out.println("  JDBC URL: " + url);
        System.out.println("  JDBC User: sa");
        System.out.println("  JDBC Password: ");
        System.out.println(
                "  Authentication Query:   SELECT * FROM users u WHERE u.username = ? AND u.password = ?");
        System.out.println("  Authorization Query:    SELECT r.rolename FROM roles r WHERE r.username = ?");
        System.out.println("======================================================");
        System.out.println("");
        System.out.println("");
        System.out.println("Press Enter to stop the JDBC server.");
        new BufferedReader(new InputStreamReader(System.in)).readLine();

        System.out.println("Shutting down the JDBC server...");

        Server.shutdownTcpServer("tcp://localhost:9092", "", true, true);

        System.out.println("Done!");
    } catch (Exception e) {
        e.printStackTrace();
    }
}