Example usage for org.json.simple JSONObject get

List of usage examples for org.json.simple JSONObject get

Introduction

In this page you can find the example usage for org.json.simple JSONObject get.

Prototype

V get(Object key);

Source Link

Document

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

Usage

From source file:javarestart.JavaRestartLauncher.java

public static void main(String[] args) throws Exception {
    if (args.length < 1) {
        System.out.println("Usage: <URL> {<MainClass>}");
        return;/* w  w  w. j  av a 2 s  .  c  o m*/
    }

    if (args[0].equals("fork")) {
        String[] args2 = new String[args.length - 1];
        for (int i = 0; i < args.length - 1; i++) {
            args2[i] = args[i + 1];
        }
        fork(args2);
        return;
    }

    AppClassloader loader = new AppClassloader(args[0]);
    Thread.currentThread().setContextClassLoader(loader);
    String main;
    JSONObject obj = getJSON(args[0]);
    if (args.length < 2) {
        main = (String) obj.get("main");
    } else {
        main = args[1];
    }

    String splash = (String) obj.get("splash");
    if (splash != null) {
        SplashScreen scr = SplashScreen.getSplashScreen();
        if (scr != null) {
            URL url = loader.getResource(splash);
            scr.setImageURL(url);
        }
    }

    //auto close splash after 45 seconds
    Thread splashClose = new Thread() {
        @Override
        public void run() {
            try {
                sleep(45000);
            } catch (InterruptedException e) {
            }
            SplashScreen scr = SplashScreen.getSplashScreen();
            if ((scr != null) && (scr.isVisible())) {
                scr.close();
            }
        }
    };
    splashClose.setDaemon(true);
    splashClose.start();

    Class mainClass = loader.loadClass(main);
    Method mainMethod = mainClass.getMethod("main", String[].class);
    mainMethod.setAccessible(true);
    mainMethod.invoke(null, new Object[] { new String[0] });
}

From source file:amazonechoapi.AmazonEchoApi.java

public static void main(String[] args) throws InterruptedException, IOException {
    AmazonEchoApi amazonEchoApi = new AmazonEchoApi("https://pitangui.amazon.com", "username", "password");
    if (amazonEchoApi.httpLogin()) {
        while (true) {
            String output = amazonEchoApi.httpGet("/api/todos?type=TASK&size=1");

            // Parse JSON
            Object obj = JSONValue.parse(output);
            JSONObject jsonObject = (JSONObject) obj;
            JSONArray values = (JSONArray) jsonObject.get("values");
            JSONObject item = (JSONObject) values.get(0);

            // Get text and itemId
            String text = item.get("text").toString();
            String itemId = item.get("itemId").toString();

            if (!checkItemId(itemId)) {
                addItemId(itemId);//w w w . ja v  a  2  s.  c o m
                System.out.println(text);
                // Do something. ie Hue Lights, etc
            } else {
                System.out.println("No new commands");
            }
            // Sleep for 15 seconds
            Thread.sleep(15000);
        }

    }
}

From source file:dependencies.DependencyResolving.java

/**
 * @param args the command line arguments
 *///from   w ww.  j a  v  a2s  .  c  om
public static void main(String[] args) {
    // TODO code application logic here
    JSONParser parser = new JSONParser(); //we use JSONParser in order to be able to read from JSON file
    try { //here we declare the file reader and define the path to the file dependencies.json
        Object obj = parser.parse(new FileReader(
                "C:\\Users\\Vladimir\\Documents\\NetBeansProjects\\DependenciesResolving\\src\\dependencies\\dependencies.json"));
        JSONObject project = (JSONObject) obj; //a JSON object containing all the data in the .json file
        JSONArray dependencies = (JSONArray) project.get("dependencies"); //get array of objects with key "dependencies"
        System.out.print("We need to install the following dependencies: ");
        Iterator<String> iterator = dependencies.iterator(); //define an iterator over the array "dependencies"
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        } //on the next line we declare another object, which parses a Parser object and reads from all_packages.json
        Object obj2 = parser.parse(new FileReader(
                "C:\\Users\\Vladimir\\Documents\\NetBeansProjects\\DependenciesResolving\\src\\dependencies\\all_packages.json"));
        JSONObject tools = (JSONObject) obj2; //a JSON object containing all thr data in the file all_packages.json
        for (int i = 0; i < dependencies.size(); i++) {
            if (tools.containsKey(dependencies.get(i))) {
                System.out.println(
                        "In order to install " + dependencies.get(i) + ", we need the following programs:");
                JSONArray temporaryArray = (JSONArray) tools.get(dependencies.get(i)); //a temporary JSON array in which we store the keys and values of the dependencies
                for (i = 0; i < temporaryArray.size(); i++) {
                    System.out.println(temporaryArray.get(i));
                }
                ArrayList<Object> arraysOfJsonData = new ArrayList<Object>(); //an array in which we will store the keys of the objects, after we use the values and won't need them anymore
                for (i = 0; i < temporaryArray.size(); i++) {
                    System.out.println("Installing " + temporaryArray.get(i));
                }
                while (!temporaryArray.isEmpty()) {

                    for (Object element : temporaryArray) {

                        if (tools.containsKey(element)) {
                            JSONArray secondaryArray = (JSONArray) tools.get(element); //a temporary array within the scope of the if-statement
                            if (secondaryArray.size() != 0) {
                                System.out.println("In order to install " + element + ", we need ");
                            }
                            for (i = 0; i < secondaryArray.size(); i++) {
                                System.out.println(secondaryArray.get(i));
                            }

                            for (Object o : secondaryArray) {

                                arraysOfJsonData.add(o);
                                //here we create a file with the installed dependency
                                File file = new File(
                                        "C:\\Users\\Vladimir\\Documents\\NetBeansProjects\\DependenciesResolving\\src\\dependencies\\installed_modules\\"
                                                + o);
                                if (file.createNewFile()) {
                                    System.out.println(file.getName() + " is installed!");
                                } else {
                                }
                            }
                            secondaryArray.clear();
                        }
                    }
                    temporaryArray.clear();
                    for (i = 0; i < arraysOfJsonData.size(); i++) {
                        temporaryArray.add(arraysOfJsonData.get(i));
                    }
                    arraysOfJsonData.clear();
                }
            }
        }
        Set<String> keys = tools.keySet(); // here we define a set of keys of the objects in all_packages.json
        for (String s : keys) {
            File file = new File(
                    "C:\\Users\\Vladimir\\Documents\\NetBeansProjects\\DependenciesResolving\\src\\dependencies\\installed_modules\\"
                            + s);
            if (file.createNewFile()) {
                System.out.println(file.getName() + " is installed.");
            } else {
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(DependencyResolving.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ParseException ex) {
        Logger.getLogger(DependencyResolving.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:Neo4JDataExporter.java

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

        //            URI firstNode = createNode();
        //            addProperty(firstNode, "name", "Joe Strummer");
        //            URI secondNode = createNode();
        //            addProperty(secondNode, "band", "The Clash");
        //
        //            URI relationshipUri = addRelationship(firstNode, secondNode, "singer",
        //                    "{ \"from\" : \"1976\", \"until\" : \"1986\" }");
        //            addMetadataToProperty(relationshipUri, "stars", "5");

        String query = "start device=node:node_auto_index(objectType='Node') match device - [parent] -> interface --> neighbour where device.objectType='Node' and interface.objectType='Discovery Interface' and neighbour.objectType = 'Discovered Neighbor' return device.name, interface.name, neighbour.name";
        String params = "";
        String output = executeCypherQuery(query, params);
        JSONObject json = (JSONObject) new JSONParser().parse(output);
        System.out.println("columns=" + json.get("columns"));
        System.out.println("data=" + json.get("data"));
        HashMap map = new HashMap();

    } catch (Exception e) {

        e.printStackTrace();

    }
}

From source file:Cache.Servidor.java

public static void main(String[] args) throws IOException, ClassNotFoundException {
    // Se calcula el tamao de las particiones del cache
    // de manera que la relacin sea
    // 25% Esttico y 75% Dinmico,
    // siendo la porcin dinmica particionada en 3 partes.

    Lector l = new Lector(); // Obtener tamao total del cache.
    int tamCache = l.leerTamCache("config.txt");
    //===================================
    int tamCaches = 0;
    if (tamCache % 4 == 0) { // Asegura que el nro sea divisible por 4.
        tamCaches = tamCache / 4;/*  w ww .  j  av a  2 s. c o m*/
    } else { // Si no, suma para que lo sea.
        tamCaches = (tamCache - (tamCache) % 4 + 4) / 4;
    } // y divide por 4.

    System.out.println("Tamao total Cache: " + (int) tamCache); // imprimir tamao cache.
    System.out.println("Tamao particiones y parte esttica: " + tamCaches); // imprimir tamao particiones.
    //===================================

    lru_cache1 = new LRUCache(tamCaches); //Instanciar atributos.

    lru_cache2 = new LRUCache(tamCaches);
    lru_cache3 = new LRUCache(tamCaches);
    cestatico = new CacheEstatico(tamCaches);
    cestatico.addEntryToCache("query3", "respuesta cacheEstatico a query 3");
    cestatico.addEntryToCache("query7", "respuesta cacheEstatico a query 7");

    try {
        ServerSocket servidor = new ServerSocket(4500); // Crear un servidor en pausa hasta que un cliente llegue.
        while (true) {
            Socket clienteNuevo = servidor.accept();// Si llega se acepta.
            // Queda en pausa otra vez hasta que un objeto llegue.
            ObjectInputStream entrada = new ObjectInputStream(clienteNuevo.getInputStream());

            System.out.println("Objeto llego");
            //===================================
            Cache1 hilox1 = new Cache1(); // Instanciar hebras.
            Cache2 hilox2 = new Cache2();
            Cache3 hilox3 = new Cache3();

            // Leer el objeto, es un String.
            JSONObject request = (JSONObject) entrada.readObject();
            String b = (String) request.get("busqueda");

            //*************************Actualizar CACHE**************************************
            int actualizar = (int) request.get("actualizacion");
            // Si vienen el objeto que llego viene del Index es que va a actualizar el cache
            if (actualizar == 1) {
                int lleno = cestatico.lleno();
                if (lleno == 0) {
                    cestatico.addEntryToCache((String) request.get("busqueda"),
                            (String) request.get("respuesta"));
                } else {
                    // si el cache estatico esta lleno
                    //agrego l cache dinamico

                    if (hash(b) % 3 == 0) {
                        lru_cache1.addEntryToCache((String) request.get("busqueda"),
                                (String) request.get("respuesta"));
                    } else {
                        if (hash(b) % 3 == 1) {
                            lru_cache2.addEntryToCache((String) request.get("busqueda"),
                                    (String) request.get("respuesta"));

                        } else {
                            lru_cache3.addEntryToCache((String) request.get("busqueda"),
                                    (String) request.get("respuesta"));

                        }
                    }

                }
            } //***************************************************************
            else {

                // Para cada request del arreglo se distribuye
                // en Cache 1 2 o 3 segn su hash.
                JSONObject respuesta = new JSONObject();
                if (hash(b) % 3 == 0) {
                    respuesta = hilox1.fn(request); //Y corre la funcin de una hebra.
                } else {
                    if (hash(b) % 3 == 1) {
                        respuesta = hilox2.fn(request);
                    } else {
                        respuesta = hilox3.fn(request);
                    }
                }

                //RESPONDER DESDE EL SERVIDOR
                ObjectOutputStream resp = new ObjectOutputStream(clienteNuevo.getOutputStream());// obtengo el output del cliente para mandarle un msj
                resp.writeObject(respuesta);
                System.out.println("msj enviado desde el servidor");

                //clienteNuevo.close();
                //servidor.close();
            }

        }
    } catch (IOException ex) {
        Logger.getLogger(Servidor.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:ci6226.buildindex.java

/**
 * @param args the command line arguments
 *///  w w  w  .ja va2 s .  com
public static void main(String[] args) throws FileNotFoundException, IOException, ParseException {
    String file = "/home/steven/Dropbox/workspace/ntu_coursework/ci6226/Assiment/yelpdata/yelp_training_set/yelp_training_set_review.json";
    JSONParser parser = new JSONParser();

    BufferedReader in = new BufferedReader(new FileReader(file));
    //  List<Document> jdocs = new LinkedList<Document>();
    Date start = new Date();
    String indexPath = "./myindex";
    System.out.println("Indexing to directory '" + indexPath + "'...");
    // Analyzer analyzer= new NGramAnalyzer(2,8);
    Analyzer analyzer = new myAnalyzer();

    IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_47, analyzer);
    Directory dir = FSDirectory.open(new File(indexPath));
    // :Post-Release-Update-Version.LUCENE_XY:
    // TODO: try different analyzer,stop words,words steming check size
    //   Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_47);

    // Add new documents to an existing index:
    // iwc.setOpenMode(OpenMode.CREATE_OR_APPEND);
    iwc.setOpenMode(OpenMode.CREATE_OR_APPEND);
    // Optional: for better indexing performance, if you
    // are indexing many documents, increase the RAM
    // buffer.  But if you do this, increase the max heap
    // size to the JVM (eg add -Xmx512m or -Xmx1g):
    //
    // iwc.setRAMBufferSizeMB(256.0);
    IndexWriter writer = new IndexWriter(dir, iwc);
    //  writer.addDocuments(jdocs);
    int line = 0;
    while (in.ready()) {
        String s = in.readLine();
        Object obj = JSONValue.parse(s);
        JSONObject person = (JSONObject) obj;
        String text = (String) person.get("text");
        String user_id = (String) person.get("user_id");
        String business_id = (String) person.get("business_id");
        String review_id = (String) person.get("review_id");
        JSONObject votes = (JSONObject) person.get("votes");
        long funny = (Long) votes.get("funny");
        long cool = (Long) votes.get("cool");
        long useful = (Long) votes.get("useful");
        Document doc = new Document();
        Field review_idf = new StringField("review_id", review_id, Field.Store.YES);
        doc.add(review_idf);
        Field business_idf = new StringField("business_id", business_id, Field.Store.YES);
        doc.add(business_idf);

        //http://qindongliang1922.iteye.com/blog/2030639
        FieldType ft = new FieldType();
        ft.setIndexed(true);//  
        ft.setStored(true);//  
        ft.setStoreTermVectors(true);
        ft.setTokenized(true);
        ft.setStoreTermVectorPositions(true);//?  
        ft.setStoreTermVectorOffsets(true);//???  

        Field textf = new Field("text", text, ft);

        doc.add(textf);
        //    Field user_idf = new StringField("user_id", user_id, Field.Store.YES);
        //     doc.add(user_idf);
        //      doc.add(new LongField("cool", cool, Field.Store.YES));
        //      doc.add(new LongField("funny", funny, Field.Store.YES));
        //       doc.add(new LongField("useful", useful, Field.Store.YES));

        writer.addDocument(doc);

        System.out.println(line++);
    }

    writer.close();
    Date end = new Date();
    System.out.println(end.getTime() - start.getTime() + " total milliseconds");
    // BufferedReader in = new BufferedReader(new FileReader(file));
    //while (in.ready()) {
    //  String s = in.readLine();
    //  //System.out.println(s);
    // JSONObject jsonObject = (JSONObject) ((Object)s);
    //      String rtext = (String) jsonObject.get("text");
    //      System.out.println(rtext);
    //      //long age = (Long) jsonObject.get("age");
    //      //System.out.println(age);
    //}
    //in.close();
}

From source file:com.webkruscht.wmt.DownloadFiles.java

/**
 * @param args//from ww w.  j ava 2  s  . com
 * @throws Exception 
 */
public static void main(String[] args) throws Exception {
    WebmasterTools wmt;
    String filename;
    Date date = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
    String today = sdf.format(date);
    getProperties();
    Options options = getOptions(args);

    try {
        wmt = new WebmasterTools(username, password);

        for (SitesEntry entry : wmt.getUserSites()) {
            // only process verified sites
            if (entry.getVerified()) {
                // get download paths for site
                JSONObject data = wmt.getDownloadList(entry);
                if (data != null) {
                    for (String prop : props) {
                        String path = (String) data.get("TOP_QUERIES");
                        path += "&prop=" + prop;
                        URL url = new URL(entry.getTitle().getPlainText());
                        if (options.getStartdate() != null) {
                            path += "&db=" + options.getStartdate();
                            path += "&de=" + options.getEnddate();
                            filename = String.format("%s-%s-%s-%s-%s.csv", url.getHost(),
                                    options.getStartdate(), options.getEnddate(), prop, "TopQueries");
                        } else {
                            filename = String.format("%s-%s-%s-%s.csv", url.getHost(), today, prop,
                                    "TopQueries");
                        }
                        OutputStreamWriter out = new OutputStreamWriter(
                                new FileOutputStream(filePath + filename), "UTF-8");
                        wmt.downloadData(path, out);
                        out.close();
                    }
                    String path = (String) data.get("TOP_PAGES");
                    URL url = new URL(entry.getTitle().getPlainText());
                    filename = String.format("%s-%s-%s.csv", url.getHost(), today, "TopQueries");
                    OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(filePath + filename),
                            "UTF-8");
                    wmt.downloadData(path, out);
                    out.close();
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }

}

From source file:guardar.en.base.de.datos.MainServidor.java

public static void main(String[] args)
        throws ParserConfigurationException, SAXException, IOException, ClassNotFoundException {

    Mongo mongo = new Mongo("localhost", 27017);

    // nombre de la base de datos
    DB database = mongo.getDB("paginas");
    // coleccion de la db
    DBCollection collection = database.getCollection("indice");
    DBCollection collection_textos = database.getCollection("tabla");
    ArrayList<String> lista_textos = new ArrayList();

    try {/*from w w  w .j  a  v a2s.com*/
        ServerSocket servidor = new ServerSocket(4545); // Crear un servidor en pausa hasta que un cliente llegue.
        while (true) {
            String aux = new String();
            lista_textos.clear();
            Socket clienteNuevo = servidor.accept();// Si llega se acepta.
            // Queda en pausa otra vez hasta que un objeto llegue.
            ObjectInputStream entrada = new ObjectInputStream(clienteNuevo.getInputStream());

            JSONObject request = (JSONObject) entrada.readObject();
            String b = (String) request.get("id");
            //hacer una query a la base de datos con la palabra que se quiere obtener

            BasicDBObject query = new BasicDBObject("palabra", b);
            DBCursor cursor = collection.find(query);
            ArrayList<DocumentosDB> lista_doc = new ArrayList<>();
            // de la query tomo el campo documentos y los agrego a una lista
            try {
                while (cursor.hasNext()) {
                    //System.out.println(cursor.next());
                    BasicDBList campo_documentos = (BasicDBList) cursor.next().get("documentos");
                    // en el for voy tomando uno por uno los elementos en el campo documentos
                    for (Iterator<Object> it = campo_documentos.iterator(); it.hasNext();) {
                        BasicDBObject dbo = (BasicDBObject) it.next();
                        //DOC tiene id y frecuencia
                        DocumentosDB doc = new DocumentosDB();
                        doc.makefn2(dbo);
                        //int id = (int)doc.getId_documento();
                        //int f = (int)doc.getFrecuencia();

                        lista_doc.add(doc);

                        //*******************************************

                        //********************************************

                        //QUERY A LA COLECCION DE TEXTOS
                        /* BasicDBObject query_textos = new BasicDBObject("id", doc.getId_documento());//query
                         DBCursor cursor_textos = collection_textos.find(query_textos);
                         try {
                        while (cursor_textos.hasNext()) {
                                    
                                    
                            DBObject obj = cursor_textos.next();
                                
                            String titulo = (String) obj.get("titulo");
                            titulo = titulo + "\n\n";
                            String texto = (String) obj.get("texto");
                                
                            String texto_final = titulo + texto;
                            aux = texto_final;
                            lista_textos.add(texto_final);
                        }
                         } finally {
                        cursor_textos.close();
                         }*/
                        //System.out.println(doc.getId_documento());
                        //System.out.println(doc.getFrecuencia());

                    } // end for

                } //end while query

            } finally {
                cursor.close();
            }

            // ordeno la lista de menor a mayor
            Collections.sort(lista_doc, new Comparator<DocumentosDB>() {

                @Override
                public int compare(DocumentosDB o1, DocumentosDB o2) {
                    //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
                    return o1.getFrecuencia().compareTo(o2.getFrecuencia());
                }
            });
            int tam = lista_doc.size() - 1;
            for (int j = tam; j >= 0; j--) {

                BasicDBObject query_textos = new BasicDBObject("id",
                        (int) lista_doc.get(j).getId_documento().intValue());//query
                DBCursor cursor_textos = collection_textos.find(query_textos);// lo busco
                try {
                    while (cursor_textos.hasNext()) {

                        DBObject obj = cursor_textos.next();
                        String titulo = "*******************************";
                        titulo += (String) obj.get("titulo");
                        int f = (int) lista_doc.get(j).getFrecuencia().intValue();
                        String strinf = Integer.toString(f);
                        titulo += "******************************* frecuencia:" + strinf;
                        titulo = titulo + "\n\n";

                        String texto = (String) obj.get("texto");

                        String texto_final = titulo + texto + "\n\n";
                        aux = aux + texto_final;
                        //lista_textos.add(texto_final);
                    }
                } finally {
                    cursor_textos.close();
                }

            }

            //actualizar el cache
            try {
                Socket cliente_cache = new Socket("localhost", 4500); // nos conectamos con el servidor
                ObjectOutputStream mensaje_cache = new ObjectOutputStream(cliente_cache.getOutputStream()); // get al output del servidor, que es cliente : socket del cliente q se conecto al server
                JSONObject actualizacion_cache = new JSONObject();
                actualizacion_cache.put("actualizacion", 1);
                actualizacion_cache.put("busqueda", b);
                actualizacion_cache.put("respuesta", aux);
                mensaje_cache.writeObject(actualizacion_cache); // envio el msj al servidor
            } catch (Exception ex) {

            }

            //RESPONDER DESDE EL SERVIDORIndex al FRONT
            ObjectOutputStream resp = new ObjectOutputStream(clienteNuevo.getOutputStream());// obtengo el output del cliente para mandarle un msj
            resp.writeObject(aux);
            System.out.println("msj enviado desde el servidor");

        }
    } catch (IOException ex) {
        Logger.getLogger(MainServidor.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:cloudworker.RemoteWorker.java

public static void main(String[] args) throws Exception {
    //Command interpreter
    CommandLineInterface cmd = new CommandLineInterface(args);
    final int poolSize = Integer.parseInt(cmd.getOptionValue("s"));
    long idle_time = Long.parseLong(cmd.getOptionValue("i")); //idle time = 60 sec

    init();//from w w w.ja v  a2s.  c om
    System.out.println("Initialized one remote worker.\n");

    //Create thread pool
    ExecutorService threadPool = Executors.newFixedThreadPool(poolSize);
    BlockingExecutor blockingPool = new BlockingExecutor(threadPool, poolSize);

    //Get queue url
    GetQueueUrlResult urlResult = sqs.getQueueUrl("JobQueue");
    String jobQueueUrl = urlResult.getQueueUrl();

    // Receive messages
    //System.out.println("Receiving messages from JobQueue.\n");

    //...Check idle state
    boolean terminate = false;
    boolean startClock = true;
    long start_time = 0, end_time;

    JSONParser parser = new JSONParser();
    Runtime runtime = Runtime.getRuntime();
    String task_id = null;
    boolean runAnimoto = false;

    while (!terminate || idle_time == 0) {
        while (getQueueSize(sqs, jobQueueUrl) > 0) {

            //Batch retrieving messages
            ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest().withQueueUrl(jobQueueUrl)
                    .withMaxNumberOfMessages(10);

            List<Message> messages = sqs.receiveMessage(receiveMessageRequest).getMessages();

            for (Message message : messages) {
                //System.out.println("  Message");
                //                  System.out.println("    MessageId:     " + message.getMessageId());
                //                  System.out.println("    ReceiptHandle: " + message.getReceiptHandle());
                //                  System.out.println("    MD5OfBody:     " + message.getMD5OfBody());
                //System.out.println("    Body:          " + message.getBody());

                //Get task
                String messageBody = message.getBody();
                JSONObject json = (JSONObject) parser.parse(messageBody);

                task_id = json.get("task_id").toString();
                String task = json.get("task").toString();

                try {
                    //Check duplicate task
                    dynamoDB.addTask(task_id, task);

                    //Execute task, will be blocked if no more thread is currently available 
                    blockingPool.submitTask(new Animoto(task_id, task, sqs));

                    // Delete the message
                    String messageRecieptHandle = message.getReceiptHandle();
                    sqs.deleteMessage(new DeleteMessageRequest(jobQueueUrl, messageRecieptHandle));
                } catch (ConditionalCheckFailedException ccf) {
                    //DO something...
                }

            }

            startClock = true;

        }

        //Start clock to measure idle time
        if (startClock) {
            startClock = false;
            start_time = System.currentTimeMillis();
        } else {
            end_time = System.currentTimeMillis();
            long elapsed_time = (end_time - start_time) / 1000;
            if (elapsed_time > idle_time) {
                terminate = true;
            }
        }
    }

    //System.out.println();

    threadPool.shutdown();
    // Wait until all threads are finished
    while (!threadPool.isTerminated()) {

    }

    //Terminate running instance
    cleanUpInstance();

}

From source file:OCRRestAPI.java

public static void main(String[] args) throws Exception {
    /*/*from  w w  w  .jav  a  2  s  .  c o  m*/
              
         Sample project for OCRWebService.com (REST API).
         Extract text from scanned images and convert into editable formats.
         Please create new account with ocrwebservice.com via http://www.ocrwebservice.com/account/signup and get license code
            
     */

    // Provide your user name and license code
    String license_code = "88EF173D-CDEA-41B6-8D64-C04578ED8C4D";
    String user_name = "FERGOID";

    /*
            
      You should specify OCR settings. See full description http://www.ocrwebservice.com/service/restguide
             
      Input parameters:
             
     [language]      - Specifies the recognition language. 
                  This parameter can contain several language names separated with commas. 
                    For example "language=english,german,spanish".
               Optional parameter. By default:english
            
     [pagerange]     - Enter page numbers and/or page ranges separated by commas. 
               For example "pagerange=1,3,5-12" or "pagerange=allpages".
                    Optional parameter. By default:allpages
             
      [tobw]           - Convert image to black and white (recommend for color image and photo). 
               For example "tobw=false"
                    Optional parameter. By default:false
             
      [zone]          - Specifies the region on the image for zonal OCR. 
               The coordinates in pixels relative to the left top corner in the following format: top:left:height:width. 
               This parameter can contain several zones separated with commas. 
                 For example "zone=0:0:100:100,50:50:50:50"
                    Optional parameter.
              
      [outputformat]  - Specifies the output file format.
                    Can be specified up to two output formats, separated with commas.
               For example "outputformat=pdf,txt"
                    Optional parameter. By default:doc
            
      [gettext]      - Specifies that extracted text will be returned.
               For example "tobw=true"
                    Optional parameter. By default:false
            
       [description]  - Specifies your task description. Will be returned in response.
                    Optional parameter. 
            
            
     !!!!  For getting result you must specify "gettext" or "outputformat" !!!!  
            
    */

    // Build your OCR:

    // Extraction text with English language
    String ocrURL = "http://www.ocrwebservice.com/restservices/processDocument?gettext=true";

    // Extraction text with English and German language using zonal OCR
    ocrURL = "http://www.ocrwebservice.com/restservices/processDocument?language=english,german&zone=0:0:600:400,500:1000:150:400";

    // Convert first 5 pages of multipage document into doc and txt
    // ocrURL = "http://www.ocrwebservice.com/restservices/processDocument?language=english&pagerange=1-5&outputformat=doc,txt";

    // Full path to uploaded document
    String filePath = "sarah-morgan.jpg";

    byte[] fileContent = Files.readAllBytes(Paths.get(filePath));

    URL url = new URL(ocrURL);

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setRequestMethod("POST");

    connection.setRequestProperty("Authorization",
            "Basic " + Base64.getEncoder().encodeToString((user_name + ":" + license_code).getBytes()));

    // Specify Response format to JSON or XML (application/json or application/xml)
    connection.setRequestProperty("Content-Type", "application/json");

    connection.setRequestProperty("Content-Length", Integer.toString(fileContent.length));

    int httpCode;
    try (OutputStream stream = connection.getOutputStream()) {

        // Send POST request
        stream.write(fileContent);
        stream.close();
    } catch (Exception e) {
        System.out.println(e.toString());
    }

    httpCode = connection.getResponseCode();

    System.out.println("HTTP Response code: " + httpCode);

    // Success request
    if (httpCode == HttpURLConnection.HTTP_OK) {
        // Get response stream
        String jsonResponse = GetResponseToString(connection.getInputStream());

        // Parse and print response from OCR server
        PrintOCRResponse(jsonResponse);
    } else if (httpCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
        System.out.println("OCR Error Message: Unauthorizied request");
    } else {
        // Error occurred
        String jsonResponse = GetResponseToString(connection.getErrorStream());

        JSONParser parser = new JSONParser();
        JSONObject jsonObj = (JSONObject) parser.parse(jsonResponse);

        // Error message
        System.out.println("Error Message: " + jsonObj.get("ErrorMessage"));
    }

    connection.disconnect();

}