Example usage for java.io BufferedReader close

List of usage examples for java.io BufferedReader close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Usage

From source file:metaTile.Main.java

/**
 * @param args/*from   w w w .ja  v a2s. c o  m*/
 * @throws IOException 
 */
public static void main(String[] args) throws IOException {
    try {
        /* parse the command line arguments */
        // create the command line parser
        CommandLineParser parser = new PosixParser();

        // create the Options
        Options options = new Options();
        options.addOption("i", "input", true, "File to read original tile list from.");
        options.addOption("o", "output", true, "File to write shorter meta-tile list to.");
        options.addOption("m", "metatiles", true,
                "Number of tiles in x and y direction to group into one meta-tile.");

        // parse the command line arguments
        CommandLine commandLine = parser.parse(options, args);

        if (!commandLine.hasOption("input") || !commandLine.hasOption("output")
                || !commandLine.hasOption("metatiles"))
            printUsage(options);

        String inputFileName = commandLine.getOptionValue("input");
        String outputFileName = commandLine.getOptionValue("output");
        int metaTileSize = Integer.parseInt(commandLine.getOptionValue("metatiles"));

        ArrayList<RenderingTile> tiles = new ArrayList<RenderingTile>();

        BufferedReader tileListReader = new BufferedReader(new FileReader(new File(inputFileName)));

        BufferedWriter renderMetatileListWriter = new BufferedWriter(new FileWriter(new File(outputFileName)));

        String line = tileListReader.readLine();
        while (line != null) {
            String[] columns = line.split("/");

            if (columns.length == 3)
                tiles.add(new RenderingTile(Integer.parseInt(columns[0]), Integer.parseInt(columns[1]),
                        Integer.parseInt(columns[2])));

            line = tileListReader.readLine();
        }

        tileListReader.close();

        int hits = 0;

        // tiles which we are already rendering as the top left corner of 4x4 metatiles
        HashSet<RenderingTile> whitelist = new HashSet<RenderingTile>();

        // for each tile in the list see if it has a meta-tile in the whitelist already
        for (int i = 0; i < tiles.size(); i++) {
            boolean hit = false; // by default we aren't already rendering this tile as part of another metatile
            for (int dx = 0; dx < metaTileSize; dx++) {
                for (int dy = 0; dy < metaTileSize; dy++) {
                    RenderingTile candidate = new RenderingTile(tiles.get(i).z, tiles.get(i).x - dx,
                            tiles.get(i).y - dy);
                    if (whitelist.contains(candidate)) {
                        hit = true;
                        // now exit the two for loops iterating over tiles inside a meta-tile
                        dx = metaTileSize;
                        dy = metaTileSize;
                    }
                }
            }

            // if this tile doesn't already have a meta-tile in the whitelist, add it
            if (hit == false) {
                hits++;
                renderMetatileListWriter.write(tiles.get(i).toString() + "/" + metaTileSize + "\n");
                whitelist.add(tiles.get(i));
            }
        }
        renderMetatileListWriter.close();
        System.out.println(
                "Reduced " + tiles.size() + " tiles into " + hits + " metatiles of size " + metaTileSize);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.flaptor.hounder.indexer.RmiIndexerStub.java

public static void main(String[] args) {

    // create the parser
    CommandLineParser parser = new PosixParser();
    CommandLine line = null;/*from   w w w .jav  a  2s.c  o  m*/
    Options options = getOptions();
    try {
        // parse the command line arguments
        line = parser.parse(options, args);
    } catch (ParseException exp) {
        // oops, something went wrong
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("RmiIndexerStub -h <hostName> -p <basePort> [options] ", options);
        System.exit(1);
    }

    boolean doOptimize = line.hasOption("optimize");
    boolean doCheckpoint = line.hasOption("checkpoint");
    boolean doStop = line.hasOption("stop");
    Integer port = ((Long) line.getOptionObject("port")).intValue();
    String host = line.getOptionValue("host");

    try {
        RmiIndexerStub stub = new RmiIndexerStub(port, host);

        if (line.hasOption("deleteUrl")) {
            String url = line.getOptionValue("deleteUrl");
            Document dom = generateDeleteDocument(url);
            indexOrFail(stub, dom, "Could not delete " + url);
            System.out.println("delete " + url + " command accepted by indexer");
        }

        if (line.hasOption("deleteFile")) {

            BufferedReader reader = new BufferedReader(new FileReader(line.getOptionValue("deleteFile")));
            while (reader.ready()) {
                String url = reader.readLine();
                if (url.length() > 0 && url.charAt(0) != '#') { // ignore empty lines and comments
                    Document dom = generateDeleteDocument(url);
                    indexOrFail(stub, dom, "Could not delete " + url);
                    System.out.println("delete " + url + " command accepted by indexer");
                }
            }
            reader.close();
        }

        if (doOptimize) {
            Document dom = generateCommandDocument("optimize");
            indexOrFail(stub, dom, "Could not send optimize command.");
            System.out.println("optimize command accepted by indexer");
        }

        if (doCheckpoint) {
            Document dom = generateCommandDocument("checkpoint");
            indexOrFail(stub, dom, "Could not send checkpoint command.");
            System.out.println("checkpoint command accepted by indexer");

        }
        if (doStop) {
            Document dom = generateCommandDocument("close");
            indexOrFail(stub, dom, "Could not send stop command.");
            System.out.println("stop command accepted by indexer");
        }
    } catch (Exception e) {
        System.err.println("An error occurred: " + e.getMessage());
        e.printStackTrace();
    }
}

From source file:EchoClient.java

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

   ServerSocket serverSocket = null;
   try {/*w  w  w  .  j a v  a  2 s. c om*/
      serverSocket = new ServerSocket(4444);
   } catch (IOException e) {
      System.err.println("Could not listen on port: 4444.");
      System.exit(1);
   }

   Socket clientSocket = null;
   try {
      clientSocket = serverSocket.accept();
   } catch (IOException e) {
      System.err.println("Accept failed.");
      System.exit(1);
   }

   PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
   BufferedReader in = new BufferedReader(new InputStreamReader(
         clientSocket.getInputStream()));
   String inputLine, outputLine;
   KnockKnockProtocol kkp = new KnockKnockProtocol();

   outputLine = kkp.processInput(null);
   out.println(outputLine);

   while ((inputLine = in.readLine()) != null) {
      outputLine = kkp.processInput(inputLine);
      out.println(outputLine);
      if (outputLine.equals("Bye."))
         break;
   }
   out.close();
   in.close();
   clientSocket.close();
   serverSocket.close();
}

From source file:com.jkoolcloud.jesl.simulator.TNT4JSimulator.java

public static void main(String[] args) {
    boolean isTTY = (System.console() != null);
    long startTime = System.currentTimeMillis();

    try {/*from  w ww  .j  ava2  s.  c o m*/
        SAXParserFactory parserFactory = SAXParserFactory.newInstance();
        SAXParser theParser = parserFactory.newSAXParser();
        TNT4JSimulatorParserHandler xmlHandler = new TNT4JSimulatorParserHandler();

        processArgs(xmlHandler, args);

        TrackerConfig simConfig = DefaultConfigFactory.getInstance().getConfig(TNT4JSimulator.class.getName());
        logger = TrackingLogger.getInstance(simConfig.build());
        if (logger.isSet(OpLevel.TRACE))
            traceLevel = OpLevel.TRACE;
        else if (logger.isSet(OpLevel.DEBUG))
            traceLevel = OpLevel.DEBUG;

        if (runType == SimulatorRunType.RUN_SIM) {
            if (StringUtils.isEmpty(simFileName)) {
                simFileName = "tnt4j-sim.xml";
                String fileName = readFromConsole("Simulation file [" + simFileName + "]: ");

                if (!StringUtils.isEmpty(fileName))
                    simFileName = fileName;
            }

            StringBuffer simDef = new StringBuffer();
            BufferedReader simLoader = new BufferedReader(new FileReader(simFileName));
            String line;
            while ((line = simLoader.readLine()) != null)
                simDef.append(line).append("\n");
            simLoader.close();

            info("jKool Activity Simulator Run starting: file=" + simFileName + ", iterations=" + numIterations
                    + ", ttl.sec=" + ttl);
            startTime = System.currentTimeMillis();

            if (isTTY && numIterations > 1)
                System.out.print("Iteration: ");
            int itTrcWidth = 0;
            for (iteration = 1; iteration <= numIterations; iteration++) {
                itTrcWidth = printProgress("Executing Iteration", iteration, itTrcWidth);

                theParser.parse(new InputSource(new StringReader(simDef.toString())), xmlHandler);

                if (!Utils.isEmpty(jkFileName)) {
                    PrintWriter gwFile = new PrintWriter(new FileOutputStream(jkFileName, true));
                    gwFile.println("");
                    gwFile.close();
                }
            }
            if (numIterations > 1)
                System.out.println("");

            info("jKool Activity Simulator Run finished, elapsed time = "
                    + DurationFormatUtils.formatDurationHMS(System.currentTimeMillis() - startTime));
            printMetrics(xmlHandler.getSinkStats(), "Total Sink Statistics");
        } else if (runType == SimulatorRunType.REPLAY_SIM) {
            info("jKool Activity Simulator Replay starting: file=" + jkFileName + ", iterations="
                    + numIterations);
            connect();
            startTime = System.currentTimeMillis();

            // Determine number of lines in file
            BufferedReader gwFile = new BufferedReader(new java.io.FileReader(jkFileName));
            for (numIterations = 0; gwFile.readLine() != null; numIterations++)
                ;
            gwFile.close();

            // Reopen the file and
            gwFile = new BufferedReader(new java.io.FileReader(jkFileName));
            if (isTTY && numIterations > 1)
                System.out.print("Processing Line: ");
            int itTrcWidth = 0;
            String gwMsg;
            iteration = 0;
            while ((gwMsg = gwFile.readLine()) != null) {
                iteration++;
                if (isTTY)
                    itTrcWidth = printProgress("Processing Line", iteration, itTrcWidth);
                gwConn.write(gwMsg);
            }
            if (isTTY && numIterations > 1)
                System.out.println("");
            long endTime = System.currentTimeMillis();

            info("jKool Activity Simulator Replay finished, elasped.time = "
                    + DurationFormatUtils.formatDurationHMS(endTime - startTime));
        }
    } catch (Exception e) {
        if (e instanceof SAXParseException) {
            SAXParseException spe = (SAXParseException) e;
            error("Error at line: " + spe.getLineNumber() + ", column: " + spe.getColumnNumber(), e);
        } else {
            error("Error running simulator", e);
        }
    } finally {
        try {
            Thread.sleep(1000L);
        } catch (Exception e) {
        }
        TNT4JSimulator.disconnect();
    }

    System.exit(0);
}

From source file:nab.detectors.htmjava.HTMModel.java

/**
 * Launch htm.java NAB detector/* w  w w .j  ava2 s . c  o  m*/
 *
 * Usage:
 *      As a standalone application (for debug purpose only):
 *
 *          java -jar htm.java-nab.jar "{\"modelParams\":{....}}" < nab_data.csv > anomalies.out
 *
 *      For complete list of command line options use:
 *
 *          java -jar htm.java-nab.jar --help
 *
 *      As a NAB detector (see 'htmjava_detector.py'):
 *
 *          python run.py --detect --score --normalize -d htmjava
 *
 *      Logging options, see "log4j.properties":
 *
 *          - "LOGLEVEL": Controls log output (default: "OFF")
 *          - "LOGGER": Either "CONSOLE" or "FILE" (default: "CONSOLE")
 *          - "LOGFILE": Log file destination (default: "htmjava.log")
 *
 *      For example:
 *
 *          java -DLOGLEVEL=TRACE -DLOGGER=FILE -jar htm.java-nab.jar "{\"modelParams\":{....}}" < nab_data.csv > anomalies.out
 *
 */
@SuppressWarnings("resource")
public static void main(String[] args) {
    try {
        LOGGER.trace("main({})", Arrays.asList(args));
        // Parse command line args
        OptionParser parser = new OptionParser();
        parser.nonOptions("OPF parameters object (JSON)");
        parser.acceptsAll(Arrays.asList("p", "params"),
                "OPF parameters file (JSON).\n(default: first non-option argument)").withOptionalArg()
                .ofType(File.class);
        parser.acceptsAll(Arrays.asList("i", "input"), "Input data file (csv).\n(default: stdin)")
                .withOptionalArg().ofType(File.class);
        parser.acceptsAll(Arrays.asList("o", "output"), "Output results file (csv).\n(default: stdout)")
                .withOptionalArg().ofType(File.class);
        parser.acceptsAll(Arrays.asList("s", "skip"), "Header lines to skip").withOptionalArg()
                .ofType(Integer.class).defaultsTo(0);
        parser.acceptsAll(Arrays.asList("h", "?", "help"), "Help");
        OptionSet options = parser.parse(args);
        if (args.length == 0 || options.has("h")) {
            parser.printHelpOn(System.out);
            return;
        }

        // Get in/out files
        final PrintStream output;
        final InputStream input;
        if (options.has("i")) {
            input = new FileInputStream((File) options.valueOf("i"));
        } else {
            input = System.in;
        }
        if (options.has("o")) {
            output = new PrintStream((File) options.valueOf("o"));
        } else {
            output = System.out;
        }

        // Parse OPF Model Parameters
        JsonNode params;
        ObjectMapper mapper = new ObjectMapper();
        if (options.has("p")) {
            params = mapper.readTree((File) options.valueOf("p"));
        } else if (options.nonOptionArguments().isEmpty()) {
            try {
                input.close();
            } catch (Exception ignore) {
            }
            if (options.has("o")) {
                try {
                    output.flush();
                    output.close();
                } catch (Exception ignore) {
                }
            }
            throw new IllegalArgumentException("Expecting OPF parameters. See 'help' for more information");
        } else {
            params = mapper.readTree((String) options.nonOptionArguments().get(0));
        }

        // Number of header lines to skip
        int skip = (int) options.valueOf("s");

        // Force timezone to UTC
        DateTimeZone.setDefault(DateTimeZone.UTC);

        // Create NAB Network Model
        HTMModel model = new HTMModel(params);
        Network network = model.getNetwork();
        network.observe().subscribe((inference) -> {
            double score = inference.getAnomalyScore();
            int record = inference.getRecordNum();
            LOGGER.trace("record = {}, score = {}", record, score);
            // Output raw anomaly score
            output.println(score);
        }, (error) -> {
            LOGGER.error("Error processing data", error);
        }, () -> {
            LOGGER.trace("Done processing data");
            if (LOGGER.isDebugEnabled()) {
                model.showDebugInfo();
            }
        });
        network.start();

        // Pipe data to network
        Publisher publisher = model.getPublisher();
        BufferedReader in = new BufferedReader(new InputStreamReader(input));
        String line;
        while ((line = in.readLine()) != null && line.trim().length() > 0) {
            // Skip header lines
            if (skip > 0) {
                skip--;
                continue;
            }
            publisher.onNext(line);
        }
        publisher.onComplete();
        in.close();
        LOGGER.trace("Done publishing data");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:ivory.core.tokenize.Tokenizer.java

@SuppressWarnings("static-access")
public static void main(String[] args) {
    Options options = new Options();
    options.addOption(OptionBuilder.withArgName("full path to model file or directory").hasArg()
            .withDescription("model file").create("model"));
    options.addOption(OptionBuilder.withArgName("full path to input file").hasArg()
            .withDescription("input file").isRequired().create("input"));
    options.addOption(OptionBuilder.withArgName("full path to output file").hasArg()
            .withDescription("output file").isRequired().create("output"));
    options.addOption(OptionBuilder.withArgName("en | zh | de | fr | ar | tr | es").hasArg()
            .withDescription("2-character language code").isRequired().create("lang"));
    options.addOption(OptionBuilder.withArgName("path to stopwords list").hasArg()
            .withDescription("one stopword per line").create("stopword"));
    options.addOption(OptionBuilder.withArgName("path to stemmed stopwords list").hasArg()
            .withDescription("one stemmed stopword per line").create("stemmed_stopword"));
    options.addOption(OptionBuilder.withArgName("true|false").hasArg().withDescription("turn on/off stemming")
            .create("stem"));
    options.addOption(OptionBuilder.withDescription("Hadoop option to load external jars")
            .withArgName("jar packages").hasArg().create("libjars"));

    CommandLine cmdline;/*from ww w  .java 2 s.c  o  m*/
    CommandLineParser parser = new GnuParser();
    try {
        String stopwordList = null, stemmedStopwordList = null, modelFile = null;
        boolean isStem = true;
        cmdline = parser.parse(options, args);
        if (cmdline.hasOption("stopword")) {
            stopwordList = cmdline.getOptionValue("stopword");
        }
        if (cmdline.hasOption("stemmed_stopword")) {
            stemmedStopwordList = cmdline.getOptionValue("stemmed_stopword");
        }
        if (cmdline.hasOption("stem")) {
            isStem = Boolean.parseBoolean(cmdline.getOptionValue("stem"));
        }
        if (cmdline.hasOption("model")) {
            modelFile = cmdline.getOptionValue("model");
        }

        ivory.core.tokenize.Tokenizer tokenizer = TokenizerFactory.createTokenizer(
                cmdline.getOptionValue("lang"), modelFile, isStem, stopwordList, stemmedStopwordList, null);
        BufferedWriter out = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(cmdline.getOptionValue("output")), "UTF8"));
        BufferedReader in = new BufferedReader(
                new InputStreamReader(new FileInputStream(cmdline.getOptionValue("input")), "UTF8"));

        String line = null;
        while ((line = in.readLine()) != null) {
            String[] tokens = tokenizer.processContent(line);
            String s = "";
            for (String token : tokens) {
                s += token + " ";
            }
            out.write(s.trim() + "\n");
        }
        in.close();
        out.close();

    } catch (Exception exp) {
        System.out.println(exp);
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("Tokenizer", options);
        System.exit(-1);
    }
}

From source file:MainClass.java

public static void main(String[] args) throws IOException {
    SSLServerSocketFactory ssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
    ServerSocket ss = ssf.createServerSocket(8080);

    while (true) {
        try {/*from   w ww.  j a v  a  2s.  c  om*/
            Socket s = ss.accept();
            OutputStream out = s.getOutputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));

            String line = null;
            while (((line = in.readLine()) != null) && (!("".equals(line)))) {
                System.out.println(line);
            }
            StringBuffer buffer = new StringBuffer();
            buffer.append("<HTML><HEAD><TITLE>HTTPS Server</TITLE></HEAD>\n");
            buffer.append("<BODY>\n<H1>Success!</H1></BODY></HTML>\n");

            String string = buffer.toString();
            byte[] data = string.getBytes();
            out.write("HTTP/1.0 200 OK\n".getBytes());
            out.write(new String("Content-Length: " + data.length + "\n").getBytes());
            out.write("Content-Type: text/html\n\n".getBytes());
            out.write(data);
            out.flush();

            out.close();
            in.close();
            s.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:AdminExample.java

public static void main(String[] args) {
    HttpURLConnection connection = null;
    StringBuilder response = new StringBuilder();

    //We are using Jackson JSON parser to serialize and deserialize the JSON. See http://wiki.fasterxml.com/JacksonHome
    //Feel free to use which ever library you prefer.
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    String accessToken = "";//Insert your access token here. Note this must be from an account that is an Admin of an account.
    String user1Email = ""; //You need access to these two email account.
    String user2Email = ""; //Note Gmail and Hotmail allow email aliasing. 
    //joe@gmail.com will get email sent to joe+user1@gmail.com 

    try {//  w w  w.  j  a v a2  s  . com
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Adding user " + user1Email);

        //Add the users:
        User user = new User();
        user.setEmail(user1Email);
        user.setAdmin(false);
        user.setLicensedSheetCreator(true);

        connection = (HttpURLConnection) new URL(USERS_URL).openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), user);
        Result<User> newUser1Result = mapper.readValue(connection.getInputStream(),
                new TypeReference<Result<User>>() {
                });
        System.out.println(
                "User " + newUser1Result.result.email + " added with userId " + newUser1Result.result.getId());

        user = new User();
        user.setEmail(user2Email);
        user.setAdmin(true);
        user.setLicensedSheetCreator(true);

        connection = (HttpURLConnection) new URL(USERS_URL).openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), user);
        Result<User> newUser2Result = mapper.readValue(connection.getInputStream(),
                new TypeReference<Result<User>>() {
                });
        System.out.println(
                "User " + newUser2Result.result.email + " added with userId " + newUser2Result.result.getId());
        System.out.println("Please visit the email inbox for the users " + user1Email + " and  " + user2Email
                + " and confirm membership to the account.");
        System.out.print("Press Enter to continue");
        in.readLine();

        //List all the users of the org
        connection = (HttpURLConnection) new URL(USERS_URL).openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        List<User> users = mapper.readValue(connection.getInputStream(), new TypeReference<List<User>>() {
        });

        System.out.println("The following are members of your account: ");

        for (User orgUser : users) {
            System.out.println("\t" + orgUser.getEmail());
        }

        //Create a sheet as the admin
        Sheet newSheet = new Sheet();
        newSheet.setName("Admin's Sheet");
        newSheet.setColumns(Arrays.asList(new Column("Column 1", "TEXT_NUMBER", null, true, null),
                new Column("Column 2", "TEXT_NUMBER", null, null, null),
                new Column("Column 3", "TEXT_NUMBER", null, null, null)));
        connection = (HttpURLConnection) new URL(SHEETS_URL).openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), newSheet);
        mapper.readValue(connection.getInputStream(), new TypeReference<Result<Sheet>>() {
        });

        //Create a sheet as user1
        newSheet = new Sheet();
        newSheet.setName("User 1's Sheet");
        newSheet.setColumns(Arrays.asList(new Column("Column 1", "TEXT_NUMBER", null, true, null),
                new Column("Column 2", "TEXT_NUMBER", null, null, null),
                new Column("Column 3", "TEXT_NUMBER", null, null, null)));
        connection = (HttpURLConnection) new URL(SHEETS_URL).openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        //Here is where the magic happens - Any action performed in this call will be on behalf of the
        //user provided. Note that this person must be a confirmed member of your org. 
        //Also note that the email address is url-encoded.
        connection.addRequestProperty("Assume-User", URLEncoder.encode(user1Email, "UTF-8"));
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), newSheet);
        mapper.readValue(connection.getInputStream(), new TypeReference<Result<Sheet>>() {
        });

        //Create a sheet as user2
        newSheet = new Sheet();
        newSheet.setName("User 2's Sheet");
        newSheet.setColumns(Arrays.asList(new Column("Column 1", "TEXT_NUMBER", null, true, null),
                new Column("Column 2", "TEXT_NUMBER", null, null, null),
                new Column("Column 3", "TEXT_NUMBER", null, null, null)));
        connection = (HttpURLConnection) new URL(SHEETS_URL).openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Assume-User", URLEncoder.encode(user2Email, "UTF-8"));
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), newSheet);
        mapper.readValue(connection.getInputStream(), new TypeReference<Result<Sheet>>() {
        });

        //List all the sheets in the org:
        System.out.println("The following sheets are owned by members of your account: ");
        connection = (HttpURLConnection) new URL(USERS_SHEETS_URL).openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        List<Sheet> allSheets = mapper.readValue(connection.getInputStream(), new TypeReference<List<Sheet>>() {
        });

        for (Sheet orgSheet : allSheets) {
            System.out.println("\t" + orgSheet.getName() + " - " + orgSheet.getOwner());
        }

        //Now delete user1 and transfer their sheets to user2
        connection = (HttpURLConnection) new URL(USER_URL.replace(ID, newUser1Result.getResult().getId() + "")
                + "?transferTo=" + newUser2Result.getResult().getId()).openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Assume-User", URLEncoder.encode(user2Email, "UTF-8"));
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setRequestMethod("DELETE");
        Result<Object> resultObject = mapper.readValue(connection.getInputStream(),
                new TypeReference<Result<Object>>() {
                });

        System.out.println("Sheets transferred : " + resultObject.getSheetsTransferred());

    } catch (IOException e) {

        InputStream is = connection == null ? null : ((HttpURLConnection) connection).getErrorStream();
        if (is != null) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            String line;
            try {
                response = new StringBuilder();
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();
                Result<?> result = mapper.readValue(response.toString(), Result.class);
                System.err.println(result.message);

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

    } catch (Exception e) {
        System.out.println("Something broke: " + e.getMessage());
        e.printStackTrace();
    }
}

From source file:com.tamingtext.classifier.mlt.TestMoreLikeThis.java

public static void main(String[] args) throws Exception {
    DefaultOptionBuilder obuilder = new DefaultOptionBuilder();
    ArgumentBuilder abuilder = new ArgumentBuilder();
    GroupBuilder gbuilder = new GroupBuilder();

    Option helpOpt = DefaultOptionCreator.helpOption();

    Option inputDirOpt = obuilder.withLongName("input").withRequired(true)
            .withArgument(abuilder.withName("input").withMinimum(1).withMaximum(1).create())
            .withDescription("The input directory").withShortName("i").create();

    Option modelOpt = obuilder.withLongName("model").withRequired(true)
            .withArgument(abuilder.withName("index").withMinimum(1).withMaximum(1).create())
            .withDescription("The directory containing the index model").withShortName("m").create();

    Option categoryFieldOpt = obuilder.withLongName("categoryField").withRequired(true)
            .withArgument(abuilder.withName("index").withMinimum(1).withMaximum(1).create())
            .withDescription("Name of the field containing category information").withShortName("catf")
            .create();/* ww w.  j a v  a2s. c o  m*/

    Option contentFieldOpt = obuilder.withLongName("contentField").withRequired(true)
            .withArgument(abuilder.withName("index").withMinimum(1).withMaximum(1).create())
            .withDescription("Name of the field containing content information").withShortName("contf")
            .create();

    Option maxResultsOpt = obuilder.withLongName("maxResults").withRequired(false)
            .withArgument(abuilder.withName("gramSize").withMinimum(1).withMaximum(1).create())
            .withDescription("Number of results to retrive, default: 10 ").withShortName("r").create();

    Option gramSizeOpt = obuilder.withLongName("gramSize").withRequired(false)
            .withArgument(abuilder.withName("gramSize").withMinimum(1).withMaximum(1).create())
            .withDescription("Size of the n-gram. Default Value: 1 ").withShortName("ng").create();

    Option typeOpt = obuilder.withLongName("classifierType").withRequired(false)
            .withArgument(abuilder.withName("classifierType").withMinimum(1).withMaximum(1).create())
            .withDescription("Type of classifier: knn|tfidf. Default: bayes").withShortName("type").create();

    Group group = gbuilder.withName("Options").withOption(gramSizeOpt).withOption(helpOpt)
            .withOption(inputDirOpt).withOption(modelOpt).withOption(typeOpt).withOption(contentFieldOpt)
            .withOption(categoryFieldOpt).withOption(maxResultsOpt).create();

    try {
        Parser parser = new Parser();

        parser.setGroup(group);
        parser.setHelpOption(helpOpt);
        CommandLine cmdLine = parser.parse(args);
        if (cmdLine.hasOption(helpOpt)) {
            CommandLineUtil.printHelp(group);
            return;
        }

        String classifierType = (String) cmdLine.getValue(typeOpt);

        int gramSize = 1;
        if (cmdLine.hasOption(gramSizeOpt)) {
            gramSize = Integer.parseInt((String) cmdLine.getValue(gramSizeOpt));
        }

        int maxResults = 10;
        if (cmdLine.hasOption(maxResultsOpt)) {
            maxResults = Integer.parseInt((String) cmdLine.getValue(maxResultsOpt));
        }

        String inputPath = (String) cmdLine.getValue(inputDirOpt);
        String modelPath = (String) cmdLine.getValue(modelOpt);
        String categoryField = (String) cmdLine.getValue(categoryFieldOpt);
        String contentField = (String) cmdLine.getValue(contentFieldOpt);

        MatchMode mode;

        if ("knn".equalsIgnoreCase(classifierType)) {
            mode = MatchMode.KNN;
        } else if ("tfidf".equalsIgnoreCase(classifierType)) {
            mode = MatchMode.TFIDF;
        } else {
            throw new IllegalArgumentException("Unkown classifierType: " + classifierType);
        }

        Directory directory = FSDirectory.open(new File(modelPath));
        IndexReader indexReader = IndexReader.open(directory);
        Analyzer analyzer //<co id="mlt.analyzersetup"/>
                = new EnglishAnalyzer(Version.LUCENE_36);

        MoreLikeThisCategorizer categorizer = new MoreLikeThisCategorizer(indexReader, categoryField);
        categorizer.setAnalyzer(analyzer);
        categorizer.setMatchMode(mode);
        categorizer.setFieldNames(new String[] { contentField });
        categorizer.setMaxResults(maxResults);
        categorizer.setNgramSize(gramSize);

        File f = new File(inputPath);
        if (!f.isDirectory()) {
            throw new IllegalArgumentException(f + " is not a directory or does not exit");
        }

        File[] inputFiles = FileUtil.buildFileList(f);

        String line = null;
        //<start id="lucene.examples.mlt.test"/>
        final ClassifierResult UNKNOWN = new ClassifierResult("unknown", 1.0);

        ResultAnalyzer resultAnalyzer = //<co id="co.mlt.ra"/>
                new ResultAnalyzer(categorizer.getCategories(), UNKNOWN.getLabel());

        for (File ff : inputFiles) { //<co id="co.mlt.read"/>
            BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(ff), "UTF-8"));
            while ((line = in.readLine()) != null) {
                String[] parts = line.split("\t");
                if (parts.length != 2) {
                    continue;
                }

                CategoryHits[] hits //<co id="co.mlt.cat"/>
                        = categorizer.categorize(new StringReader(parts[1]));
                ClassifierResult result = hits.length > 0 ? hits[0] : UNKNOWN;
                resultAnalyzer.addInstance(parts[0], result); //<co id="co.mlt.an"/>
            }

            in.close();
        }

        System.out.println(resultAnalyzer.toString());//<co id="co.mlt.print"/>
        /*
        <calloutlist>
          <callout arearefs="co.mlt.ra">Create <classname>ResultAnalyzer</classname></callout>
          <callout arearefs="co.mlt.read">Read Test data</callout>
          <callout arearefs="co.mlt.cat">Categorize</callout>
          <callout arearefs="co.mlt.an">Collect Results</callout>
          <callout arearefs="co.mlt.print">Display Results</callout>
        </calloutlist>
        */
        //<end id="lucene.examples.mlt.test"/>
    } catch (OptionException e) {
        log.error("Error while parsing options", e);
    }
}

From source file:com.maya.portAuthority.googleMaps.Instructions.java

public static void main(String[] args) throws Exception {
    String jsonData = "";
    BufferedReader br = null;
    try {/*  w ww.  j  ava  2 s  .co  m*/
        String line;
        // To test: Store JSON by striking
        // https://maps.googleapis.com/maps/api/directions/json?origin=40.4419433,-80.00331349999999&destination=40.44088273536,-80.000846662042&mode=walk&transit_mode=walking&key=AIzaSyBzW19DGDOi_20t46SazRquCLw9UNp_C8s
        // in a file, and provide file location below:
        br = new BufferedReader(new FileReader("C:\\Users\\Adithya\\Desktop\\testjson.txt"));
        while ((line = br.readLine()) != null) {
            jsonData += line + "\n";
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (br != null)
                br.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    // System.out.println("File Content: \n" + jsonData);
    JSONObject obj = new JSONObject(jsonData);
    System.out.println(Instructions.getInstructions(obj));
    System.out.println(Instructions.printWayPoints(obj));

}