Example usage for java.io BufferedReader readLine

List of usage examples for java.io BufferedReader readLine

Introduction

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

Prototype

public String readLine() throws IOException 

Source Link

Document

Reads a line of text.

Usage

From source file:iac.cnr.it.TestSearcher.java

public static void main(String[] args) throws IOException, ParseException {
    /** Command line parser and options */
    CommandLineParser parser = new PosixParser();

    Options options = new Options();
    options.addOption(OPT_INDEX, true, "Index path");
    options.addOption(OPT_QUERY, true, "The query");

    CommandLine cmd = null;/*from www  .j av  a 2 s.co  m*/
    try {
        cmd = parser.parse(options, args);
    } catch (org.apache.commons.cli.ParseException e) {
        logger.fatal("Error while parsing command line arguments");
        System.exit(1);
    }

    /** Check for mandatory options */
    if (!cmd.hasOption(OPT_INDEX) || !cmd.hasOption(OPT_QUERY)) {
        usage();
        System.exit(0);
    }

    /** Read options */
    File casePath = new File(cmd.getOptionValue(OPT_INDEX));
    String query = cmd.getOptionValue(OPT_QUERY);

    /** Check correctness of the path containing an ISODAC case */
    if (!casePath.exists() || !casePath.isDirectory()) {
        logger.fatal("The case directory \"" + casePath.getAbsolutePath() + "\" is not valid");
        System.exit(1);
    }

    /** Check existance of the info.dat file */
    File infoFile = new File(casePath, INFO_FILENAME);
    if (!infoFile.exists()) {
        logger.fatal("Can't find " + INFO_FILENAME + " within the case directory (" + casePath + ")");
        System.exit(1);
    }

    /** Load the mapping image_uuid --> image_filename */
    imagesMap = new HashMap<Integer, String>();
    BufferedReader reader = new BufferedReader(new FileReader(infoFile));
    while (reader.ready()) {
        String line = reader.readLine();

        logger.info("Read the line: " + line);
        String currentID = line.split("\t")[0];
        String currentImgFile = line.split("\t")[1];
        imagesMap.put(Integer.parseInt(currentID), currentImgFile);
        logger.info("ID: " + currentID + " - IMG: " + currentImgFile + " added to the map");

    }
    reader.close();

    /** Load all the directories containing an index */
    ArrayList<String> indexesDirs = new ArrayList<String>();
    for (File f : casePath.listFiles()) {
        logger.info("Analyzing: " + f);
        if (f.isDirectory())
            indexesDirs.add(f.getAbsolutePath());
    }
    logger.info(indexesDirs.size() + " directories found!");

    /** Set-up the searcher */
    Searcher searcher = null;
    try {
        String[] array = indexesDirs.toArray(new String[indexesDirs.size()]);
        searcher = new Searcher(array);
        TopDocs results = searcher.search(query, Integer.MAX_VALUE);

        ScoreDoc[] hits = results.scoreDocs;
        int numTotalHits = results.totalHits;

        System.out.println(numTotalHits + " total matching documents");

        for (int i = 0; i < numTotalHits; i++) {
            Document doc = searcher.doc(hits[i].doc);

            String path = doc.get(FIELD_PATH);
            String filename = doc.get(FIELD_FILENAME);
            String image_uuid = doc.get(FIELD_IMAGE_ID);

            if (path != null) {
                //System.out.println((i + 1) + ". " + path + File.separator + filename + " - score: " + hits[i].score);
                //               System.out.println((i + 1) + ". " + path + File.separator + filename + " - image_file: " + image_uuid);
                System.out.println((i + 1) + ". " + path + File.separator + filename + " - image_file: "
                        + imagesMap.get(Integer.parseInt(image_uuid)));
            } else {
                System.out.println((i + 1) + ". " + "No path for this document");
            }
        }

    } catch (Exception e) {
        System.err.println("An error occurred: " + e.getMessage());
        e.printStackTrace();
    } finally {
        if (searcher != null)
            searcher.close();
    }
}

From source file:niclients.main.regni.java

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

    if (commandparser(args)) {
        if (createpub()) {
            try {
                HttpResponse response = client.execute(post);
                int resp_code = response.getStatusLine().getStatusCode();
                System.err.println("RESP_CODE: " + Integer.toString(resp_code));
                BufferedReader rd = new BufferedReader(
                        new InputStreamReader(response.getEntity().getContent()));
                String line = "";
                while ((line = rd.readLine()) != null) {
                    System.out.println(line);
                }//from ww w  .ja  v a 2  s. c  o  m

            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            System.err.println("Publish creation failed!");
        }

    } else {
        System.err.println("Command line parsing failed!");
    }
}

From source file:com.sankalp.characterreader.CharacterReader.java

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

    double learningRate = 0.55;
    List<NeuralNetwork.Layer> hiddenLayerList = new ArrayList();
    hiddenLayerList.add(new NeuralNetwork.Layer(50));
    NeuralNetwork neuralNetwork = new NeuralNetwork(new NeuralNetwork.Layer(28 * 28),
            new NeuralNetwork.Layer(10), hiddenLayerList, learningRate);

    int trainingSampleCount = 60000;
    TrainingData trainingData = new TrainingData(new File("/home/sankalpkulshrestha/mnist/train-images/"),
            trainingSampleCount, new File("/home/sankalpkulshrestha/mnist/train-labels.csv"));

    int totalEpochs = 30;
    for (int index = 0; index < totalEpochs; index++) {
        System.out.println("---------- EPOCH " + index + " ----------");
        neuralNetwork.train(trainingData);

        TrainingData testData = new TrainingData(new File("/home/sankalpkulshrestha/mnist/test-images/"), 10000,
                new File("/home/sankalpkulshrestha/mnist/test-labels.csv"));

        System.out.println("Training over");
        double accuracy = neuralNetwork.measureAccuracy(testData);
        System.out.println(accuracy);
        if (index < totalEpochs - 1) {
            trainingData.shuffle();//from  w  w w .  j a va  2s  .  c  o m
            trainingData.reset();
        }
    }
    System.out.println("Model trained. Enter image file names:");
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    int number = -1;
    List<String> expectedOutputList = FileUtils
            .readLines(new File("/home/sankalpkulshrestha/mnist/test-labels.csv"), "UTF-8");
    while ((number = Integer.parseInt(br.readLine())) != -1) {
        int output = neuralNetwork.test(new TrainingData.Sample(
                new File("/home/sankalpkulshrestha/mnist/test-images/" + number + ".jpg"), 0));
        System.out.println(output);
    }
}

From source file:TreeNode.java

public static void main(String[] argv) throws IOException {
    BinaryTree bt = new BinaryTree();
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    int val;
    char ch = ' ';
    String clearbuffer;//  ww  w. j  av  a 2 s  .  co  m
    do {
        System.out.print("Enter a number: ");
        val = Integer.parseInt(br.readLine());
        bt.insert(val);
        System.out.print("Do you wish to enter more values (Y/N).....");
        ch = (char) br.read();
        clearbuffer = br.readLine();
    } while (ch == 'y' || ch == 'Y');
    System.out.println("Postorder traversal of given tree is: ");
    bt.postorder();
    System.out.println("Preorder traversal of given tree is: ");
    bt.preorder();
    System.out.println("Inorder traversal of given tree is: ");
    bt.inorder();
}

From source file:com.makkajai.ObjCToCpp.java

/**
 * Main Method/*  w w w  .  j  a  v a2s.  co  m*/
 *
 * @param args - First argument is the input directory to scan and second is the output directory to write files to.
 * @throws IOException
 */
public static void main(String[] args) throws IOException {

    if (args.length < 2) {
        System.out.println("Invalid Arguments!");
        System.out.println(
                "Usage: java com.makkajai.ObjCToCpp \"<directory to scan for .h and .m files>\" \"<directory to write .h and .cpp files>\"");
        return;
    }

    String inputDirectory = args[0];
    String outputDirectory = args[1];
    //     String inputDirectory = "/Users/administrator/playground/projarea/math-monsters-2/makkajai-number-muncher/makkajai-ios/Makkajai/Makkajai/scenes";
    //     String outputDirectory = "/Users/administrator/playground/projarea/monster-math-cross-platform/monster-math-2/Classes/Makkajai/scenes";

    List<String> exceptFiles = new ArrayList<String>();

    if (args.length == 3) {
        BufferedReader bufferedInputStream = new BufferedReader(new FileReader(args[2]));
        String exceptFile = null;
        while ((exceptFile = bufferedInputStream.readLine()) != null) {
            if (exceptFile.equals(""))
                continue;
            exceptFiles.add(exceptFile);
        }
    }

    //Getting all the files from the input directory.
    final List<File> files = new ArrayList<File>(FileUtils.listFiles(new File(inputDirectory),
            new RegexFileFilter(FILE_NAME_WITH_H_OR_M), DirectoryFileFilter.DIRECTORY));

    //        String fileName =
    ////                "/Users/administrator/playground/projarea/math-monsters-2/makkajai-number-muncher/makkajai-ios/Makkajai/Makkajai/Utils/MakkajaiEnum"
    ////                "/Users/administrator/playground/projarea/math-monsters-2/makkajai-number-muncher/makkajai-ios/Makkajai/Makkajai/Utils/MakkajaiUtil"
    ////                "/Users/administrator/playground/projarea/math-monsters-2/makkajai-number-muncher/makkajai-ios/Makkajai/Makkajai/Home"
    ////                "/Users/administrator/playground/projarea/math-monsters-2/makkajai-number-muncher/makkajai-ios/Makkajai/Makkajai/Activities/gnumchmenu/PlayStrategy"
    ////                "/Users/administrator/playground/projarea/math-monsters-2/makkajai-number-muncher/makkajai-ios/Makkajai/Makkajai/Characters/Character"
    //                "/Users/administrator/playground/projarea/math-monsters-2/makkajai-number-muncher/makkajai-ios/Makkajai/Makkajai/Activities/gnumchmenu/GnumchScene"
    ////                "/Users/administrator/playground/projarea/math-monsters-2/makkajai-number-muncher/makkajai-ios/Makkajai/Makkajai/ParentScene"
    ////                "/Users/administrator/playground/projarea/math-monsters-2/makkajai-number-muncher/makkajai-ios/Makkajai/Makkajai/BaseSkillView"
    ////                "/Users/administrator/playground/projarea/math-monsters-2/makkajai-number-muncher/makkajai-ios/Makkajai/Makkajai/YDLayerBase"
    //                ;
    //The instance of the translator.
    ObjCToCppTranslator visitor = new ObjCToCppTranslator();

    for (int i = 0; i < files.size();) {
        File currentFile = files.get(i);
        String filePathRelativeToInput = currentFile.getAbsolutePath().replace(inputDirectory, "");
        Date startTime = new Date();
        try {
            final TranslateFileInput translateFileInput = new TranslateFileInput(inputDirectory,
                    outputDirectory, filePathRelativeToInput, false);
            if (nextFileIsM(currentFile, files, i)) {
                try {
                    if (isIgnoredFile(filePathRelativeToInput, exceptFiles))
                        continue;
                    translateFileInput.dryRun = true;
                    visitor.translateFile(translateFileInput);
                    Date stopTime = new Date();
                    System.out.println("Dry run File: " + translateFileInput.filePathRelativeToInput
                            + " Time Taken: " + getDelta(startTime, stopTime));

                    Date startTime1 = new Date();
                    translateFileInput.filePathRelativeToInput = filePathRelativeToInput.replace(H, M);
                    translateFileInput.dryRun = false;
                    visitor.translateFile(translateFileInput);
                    stopTime = new Date();
                    System.out.println("Processed File: " + translateFileInput.filePathRelativeToInput
                            + " Time Taken: " + getDelta(startTime1, stopTime));

                    Date startTime2 = new Date();
                    translateFileInput.filePathRelativeToInput = filePathRelativeToInput;
                    translateFileInput.dryRun = false;
                    visitor.translateFile(translateFileInput);
                    stopTime = new Date();
                    System.out.println("Processed File: " + translateFileInput.filePathRelativeToInput
                            + " Time Taken: " + getDelta(startTime2, stopTime));
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println("###########################Error Processing: " + filePathRelativeToInput
                            + ", Continuing with next set of tiles");
                } finally {
                    i += 2;
                }
                continue;
            }
            if (!isIgnoredFile(filePathRelativeToInput, exceptFiles))
                visitor.translateFile(translateFileInput);
            i++;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("###########################Error Processing: " + filePathRelativeToInput
                    + ", Continuing with next set of tiles");
        } finally {
            Date stopTime = new Date();
            //                System.out.println("Processed File(s): " + filePathRelativeToInput.replaceAll(H_OR_M, "") + " Time Taken: " + getDelta(startTime, stopTime));
        }
    }
}

From source file:edu.harvard.hul.ois.fits.clients.FormFileUploaderClientApplication.java

/**
 * Run the program.// ww w .j  av  a  2 s.  c o m
 *
 * @param args First argument is path to the file to analyze; second (optional) is path to server for overriding default value.
 */
public static void main(String[] args) {
    // takes file path from first program's argument
    if (args.length < 1) {
        logger.error("****** Path to input file must be first argument to program! *******");
        logger.error("===== Exiting Program =====");
        System.exit(1);
    }

    String filePath = args[0];
    File uploadFile = new File(filePath);
    if (!uploadFile.exists()) {
        logger.error("****** File does not exist at expected locations! *******");
        logger.error("===== Exiting Program =====");
        System.exit(1);
    }

    if (args.length > 1) {
        serverUrl = args[1];
    }

    logger.info("File to upload: " + filePath);

    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpPost httppost = new HttpPost(serverUrl + "false");
        FileBody bin = new FileBody(uploadFile);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addPart(FITS_FORM_FIELD_DATAFILE, bin);
        HttpEntity reqEntity = builder.build();
        httppost.setEntity(reqEntity);

        logger.info("executing request " + httppost.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httppost);
        try {
            logger.info("HTTP Response Status Line: " + response.getStatusLine());
            // Expecting a 200 Status Code
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                String reason = response.getStatusLine().getReasonPhrase();
                logger.warn("Unexpected HTTP response status code:[" + response.getStatusLine().getStatusCode()
                        + "] -- Reason (if available): " + reason);
            } else {
                HttpEntity resEntity = response.getEntity();
                InputStream is = resEntity.getContent();
                BufferedReader in = new BufferedReader(new InputStreamReader(is));

                String output;
                StringBuilder sb = new StringBuilder();
                while ((output = in.readLine()) != null) {
                    sb.append(output);
                    sb.append(System.getProperty("line.separator"));
                }
                logger.info(sb.toString());
                in.close();
                EntityUtils.consume(resEntity);
            }
        } finally {
            response.close();
        }
    } catch (Exception e) {
        logger.error("Caught exception: " + e.getMessage(), e);
    } finally {
        try {
            httpclient.close();
        } catch (IOException e) {
            logger.warn("Exception closing HTTP client: " + e.getMessage(), e);
        }
        logger.info("DONE");
    }
}

From source file:com.arsdigita.util.parameter.ParameterPrinter.java

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

    CommandLine line = null;/* w  w  w.j  av a  2s  . c  om*/
    try {
        line = new PosixParser().parse(OPTIONS, args);
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        System.exit(1);
    }

    String[] outFile = line.getArgs();
    if (outFile.length != 1) {
        System.out.println("Usage: ParameterPrinter [--html] [--file config-list-file] output-file");
        System.exit(1);
    }
    if (line.hasOption("usage")) {
        System.out.println("Usage: ParameterPrinter [--html] [--file config-list-file] output-file");
        System.exit(0);
    }

    if (line.hasOption("file")) {
        String file = line.getOptionValue("file");
        try {
            BufferedReader reader = new BufferedReader(new FileReader(file));
            String configClass;
            while ((configClass = reader.readLine()) != null) {
                register(configClass);
            }
        } catch (IOException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    } else {
        register("com.arsdigita.runtime.RuntimeConfig");
        register("com.arsdigita.web.WebConfig");
        register("com.arsdigita.templating.TemplatingConfig");
        register("com.arsdigita.kernel.KernelConfig");
        register("com.arsdigita.kernel.security.SecurityConfig");
        register("com.arsdigita.mail.MailConfig");
        register("com.arsdigita.versioning.VersioningConfig");
        register("com.arsdigita.search.SearchConfig");
        register("com.arsdigita.search.lucene.LuceneConfig");
        register("com.arsdigita.kernel.security.SecurityConfig");
        register("com.arsdigita.bebop.BebopConfig");
        register("com.arsdigita.dispatcher.DispatcherConfig");
        register("com.arsdigita.workflow.simple.WorkflowConfig");
        register("com.arsdigita.cms.ContentSectionConfig");
    }

    if (line.hasOption("html")) {
        final StringWriter sout = new StringWriter();
        final PrintWriter out = new PrintWriter(sout);

        writeXML(out);

        final XSLTemplate template = new XSLTemplate(
                ParameterPrinter.class.getResource("ParameterPrinter_html.xsl"));

        final Source source = new StreamSource(new StringReader(sout.toString()));
        final Result result = new StreamResult(new File(outFile[0]));

        template.transform(source, result);
    } else {
        final PrintWriter out = new PrintWriter(new FileWriter(outFile[0]));

        writeXML(out);
    }
}

From source file:edu.oregonstate.eecs.mcplan.domains.tetris.TetrisVisualization.java

/**
 * @param args// ww  w.  j  a va2  s. c om
 * @throws IOException
 * @throws NumberFormatException
 */
public static void main(final String[] args) throws NumberFormatException, IOException {

    //      final int[][] cells = new int[][] {
    //         new int[] { 1, 2, 3, 0, 4, 5, 0, 0, 0, 6 },
    //         new int[] { 0, 7, 0, 0, 8, 9, 0, 0, 0, 1 },
    //         new int[] { 2, 3, 4, 5, 0, 0, 0, 0, 4, 3 },
    //         new int[] { 0, 0, 0, 0, 1, 2, 0, 0, 2, 9 },
    //         new int[] { 0, 0, 0, 0, 3, 4, 0, 0, 8, 7 },
    //         new int[] { 0, 0, 0, 0, 0, 0, 0, 5, 0, 0 },
    //         new int[] { 0, 0, 0, 0, 0, 0, 0, 5, 0, 0 },
    //         new int[] { 0, 0, 0, 0, 0, 0, 0, 5, 0, 0 },
    //         new int[] { 0, 0, 0, 0, 0, 0, 0, 5, 0, 0 }
    //      };

    // This one tests cascading block falls
    //      final int[][] cells = new int[][] {
    //         new int[] { 2, 2, 2, 2, 2, 2, 0, 2, 2, 2 },
    //         new int[] { 3, 0, 0, 1, 8, 9, 1, 1, 1, 1 },
    //         new int[] { 0, 0, 0, 0, 0, 0, 1, 0, 1, 3 },
    //         new int[] { 0, 4, 4, 0, 0, 0, 1, 0, 1, 9 },
    //         new int[] { 0, 0, 4, 0, 0, 0, 0, 1, 8, 7 },
    //         new int[] { 0, 0, 4, 0, 0, 0, 0, 0, 0, 0 },
    //         new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
    //         new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
    //         new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
    //      };

    //      for( int y = 0; y < cells.length; ++y ) {
    //         for( int x = 0; x < TetrisState.Ncolumns; ++x ) {
    //            s.cells[y][x] = cells[y][x];
    //         }
    //      }

    final int T = 50;
    final int Nrows = 10;
    final RandomGenerator rng = new MersenneTwister(43);
    final TetrisParameters params = new TetrisParameters(T, Nrows);
    final TetrisFsssModel model = new TetrisFsssModel(rng, params, new TetrisBertsekasRepresenter(params));
    TetrisState s = model.initialState();

    //      for( final TetrominoType type : TetrominoType.values() ) {
    //         final Tetromino t = type.create();
    //         for( int r = 0; r < 4; ++r ) {
    //            for( int x = 0; x < TetrisState.Ncolumns; ++x ) {
    //               s = model.initialState();
    ////               Fn.assign( s.cells, 0 );
    //               s.queued_tetro = t;
    //
    //               System.out.println( "" + type + ", " + x + ", " + r );
    //
    //               final TetrisAction a = new TetrisAction( x, r );
    //               a.doAction( s );
    //
    ////               try {
    ////                  t.setCells( s, 1 );
    ////               }
    ////               catch( final TetrisGameOver ex ) {
    ////                  // TODO Auto-generated catch block
    ////                  ex.printStackTrace();
    ////               }
    //               System.out.println( s );
    //            }
    //         }
    //      }

    int steps = 0;
    while (!s.isTerminal()) {
        System.out.println(s);
        System.out.println(model.base_repr().encode(s));

        //         final int t = rng.nextInt( TetrominoType.values().length );
        //         final int r = rng.nextInt( 4 );
        //         final Tetromino tetro = TetrominoType.values()[t].create();
        //         tetro.setRotation( r );
        //         System.out.println( "Next:" );
        //         System.out.println( tetro );

        //         final int input_position = rng.nextInt( params.Ncolumns );
        //         final int input_rotation = rng.nextInt( 4 );

        // This move sequence produces a cascading clear for seed=43:
        // 00 41 21 60 91 73 41 01 01 61 83 53 23 31

        System.out.print(">>> ");
        final BufferedReader cin = new BufferedReader(new InputStreamReader(System.in));
        final int choice = Integer.parseInt(cin.readLine());
        final int input_position = choice / 10;
        final int input_rotation = choice - (input_position * 10);

        final TetrisAction a = new TetrisAction(input_position, input_rotation);
        System.out.println("Input: " + a);

        final TetrisState sprime = model.sampleTransition(s, a);
        s = sprime;

        //         tetro.setPosition( input_position, TetrisState.Nrows - 1 - tetro.getBoundingBox().top );
        //         tetro.setRotation( input_rotation );
        //         s.createTetromino( tetro );

        ++steps;

        if (s.isTerminal()) {
            break;
        }

        //         System.out.println( s );
        //         System.out.println();
        //         final int clears = s.drop();
        //         if( clears > 0 ) {
        //            System.out.println( "\tCleared " + clears );
        //         }
    }

    System.out.println("Steps: " + steps);

}

From source file:de.micromata.genome.tpsb.executor.GroovyShellExecutor.java

public static void main(String[] args) {
    String methodName = null;/* w  ww .ja  v  a 2  s. c  o m*/
    if (args.length > 0 && StringUtils.isNotBlank(args[0])) {
        methodName = args[0];
    }
    GroovyShellExecutor exec = new GroovyShellExecutor();
    //System.out.println("GroovyShellExecutor start");
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    String line;
    StringBuffer code = new StringBuffer();
    try {
        while ((line = in.readLine()) != null) {
            if (line.equals("--EOF--") == true) {
                break;
            }
            code.append(line);
            code.append("\n");

            //System.out.flush();
        }
    } catch (IOException ex) {
        throw new RuntimeException("Failure reading std in: " + ex.toString(), ex);
    }
    try {
        exec.executeCode(code.toString(), methodName);
    } catch (Throwable ex) { // NOSONAR "Illegal Catch" framework
        warn("GroovyShellExecutor failed with exception: " + ex.getClass().getName() + ": " + ex.getMessage()
                + "\n" + ExceptionUtils.getStackTrace(ex));
    }
    System.out.println("--EOP--");
    System.out.flush();
}

From source file:Naive.java

public static void main(String[] args) throws Exception {
    // Basic access authentication setup
    String key = "CHANGEME: YOUR_API_KEY";
    String secret = "CHANGEME: YOUR_API_SECRET";
    String version = "preview1"; // CHANGEME: the API version to use
    String practiceid = "000000"; // CHANGEME: the practice ID to use

    // Find the authentication path
    Map<String, String> auth_prefix = new HashMap<String, String>();
    auth_prefix.put("v1", "oauth");
    auth_prefix.put("preview1", "oauthpreview");
    auth_prefix.put("openpreview1", "oauthopenpreview");

    URL authurl = new URL("https://api.athenahealth.com/" + auth_prefix.get(version) + "/token");

    HttpURLConnection conn = (HttpURLConnection) authurl.openConnection();
    conn.setRequestMethod("POST");

    // Set the Authorization request header
    String auth = Base64.encodeBase64String((key + ':' + secret).getBytes());
    conn.setRequestProperty("Authorization", "Basic " + auth);

    // Since this is a POST, the parameters go in the body
    conn.setDoOutput(true);/*from  w  w  w. j a  v a  2 s  .  c om*/
    String contents = "grant_type=client_credentials";
    DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
    wr.writeBytes(contents);
    wr.flush();
    wr.close();

    // Read the response
    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    StringBuilder sb = new StringBuilder();
    String line;
    while ((line = rd.readLine()) != null) {
        sb.append(line);
    }
    rd.close();

    // Decode from JSON and save the token for later
    String response = sb.toString();
    JSONObject authorization = new JSONObject(response);
    String token = authorization.get("access_token").toString();

    // GET /departments
    HashMap<String, String> params = new HashMap<String, String>();
    params.put("limit", "1");

    // Set up the URL, method, and Authorization header
    URL url = new URL("https://api.athenahealth.com/" + version + "/" + practiceid + "/departments" + "?"
            + urlencode(params));
    conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    conn.setRequestProperty("Authorization", "Bearer " + token);

    rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    sb = new StringBuilder();
    while ((line = rd.readLine()) != null) {
        sb.append(line);
    }
    rd.close();

    response = sb.toString();
    JSONObject departments = new JSONObject(response);
    System.out.println(departments.toString());

    // POST /appointments/{appointmentid}/notes
    params = new HashMap<String, String>();
    params.put("notetext", "Hello from Java!");

    url = new URL("https://api.athenahealth.com/" + version + "/" + practiceid + "/appointments/1/notes");
    conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Authorization", "Bearer " + token);

    // POST parameters go in the body
    conn.setDoOutput(true);
    contents = urlencode(params);
    wr = new DataOutputStream(conn.getOutputStream());
    wr.writeBytes(contents);
    wr.flush();
    wr.close();

    rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    sb = new StringBuilder();
    while ((line = rd.readLine()) != null) {
        sb.append(line);
    }
    rd.close();

    response = sb.toString();
    JSONObject note = new JSONObject(response);
    System.out.println(note.toString());
}