Example usage for org.json.simple JSONObject JSONObject

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

Introduction

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

Prototype

JSONObject

Source Link

Usage

From source file:at.nonblocking.cliwix.cli.CliwixCliClient.java

public static void main(String[] args) throws Exception {
    Options options = null;//w w  w  . ja v  a  2s . c  om

    try {
        options = Options.parseArgs(args);
    } catch (CliwixCliClientArgumentException e) {
        if (debug)
            console.printStacktrace(e);
        console.printlnError("Error: Invalid arguments: " + e.getMessage());
        Options.printUsage();
        console.exit(EXIT_STATUS_FAIL);
        return;
    }

    if (options == null || Options.COMMAND_HELP.equals(options.getCommand())) {
        Options.printUsage();
        console.exit(0);
        return;
    }

    if (Options.COMMAND_CREATE_CONFIG.equals(options.getCommand())) {
        if (args.length < 2) {
            console.printlnError("Error: No config file location given!");
            console.exit(EXIT_STATUS_FAIL);
            return;
        }
        File configFile = new File(args[1]);
        options.copyDefaultPropertiesTo(configFile);
        console.println("Configuration saved under: " + configFile.getAbsolutePath());
        console.exit(0);
        return;
    }

    debug = options.isDebug();

    String cliwixServerUrl = options.getServerCliwixUrl();
    String username = options.getServerUsername();
    String password = options.getServerPassword();

    if (cliwixServerUrl == null) {
        console.printlnError("Error: Property server.cliwix.url is required!");
        console.exit(EXIT_STATUS_FAIL);
        return;
    }

    cookieManager.clear();

    //Login
    if (username != null && password != null) {
        JSONObject loginData = new JSONObject();
        loginData.put("username", username);
        loginData.put("password", password);
        JSONObject result = postJson(cliwixServerUrl, "/services/login", loginData);
        JSONObject loginResult = (JSONObject) result.get("loginResult");

        if (loginResult.get("succeeded") == Boolean.TRUE) {
            console.println("Login successful");
        } else {
            console.printlnError("Error: Login failed! Reason: " + loginData.get("errorMessage"));
            console.exit(EXIT_STATUS_FAIL);
            return;
        }

    } else if (username != null) {
        console.printlnError("Error: If -user is set -pass is required!");
        console.exit(EXIT_STATUS_FAIL);
        return;
    } else if (password != null) {
        console.printlnError("Error: If -pass is set -user is required!");
        console.exit(EXIT_STATUS_FAIL);
        return;
    }

    switch (options.getCommand()) {
    case Options.COMMAND_INFO:
        doInfo(cliwixServerUrl, options);
        break;
    case Options.COMMAND_EXPORT:
        doExport(cliwixServerUrl, options);
        break;
    case Options.COMMAND_IMPORT:
        doImport(cliwixServerUrl, options);
        break;
    default:
    case Options.COMMAND_HELP:
        Options.printUsage();
    }
}

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 w  w .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:fr.bmartel.protocol.google.main.LaunchOauthApiServer.java

/**
 * The main method.//  w  w  w.ja  v a 2  s  .  c o  m
 *
 * @param args the arguments
 */
public static void main(String[] args) {

    webPath = "";
    clientId = "";
    clientSecret = "";

    if (args.length == 3) {

        for (int i = 0; i < 3; i++) {
            if (args[i].toLowerCase().startsWith("webpath="))
                webPath = args[i].substring(args[i].indexOf("webpath=") + "webpath=".length() + 1,
                        args[i].length());
            if (args[i].toLowerCase().startsWith("clientid="))
                clientId = args[i].substring(args[i].indexOf("clientid=") + "clientid=".length() + 1,
                        args[i].length());
            if (args[i].toLowerCase().startsWith("clientsecret="))
                clientSecret = args[i].substring(
                        args[i].indexOf("clientsecret=") + "clientsecret=".length() + 1, args[i].length());
        }

        if (webPath.equals("")) {
            printHelp("Error web path is missing");
            return;
        } else if (clientId.equals("")) {
            printHelp("Error client Id is missing");
            return;
        } else if (clientSecret.equals("")) {
            printHelp("Error client secret is missing");
            return;
        }
    } else {
        printHelp("");
        return;
    }
    // start http server
    HttpServer server = new HttpServer(SERVER_PORT);

    websocketServer = new WebsocketServer(WEBSOCKET_SERVER_PORT);

    websocketServer.addServerEventListener(new IClientEventListener() {

        @SuppressWarnings("unchecked")
        @Override
        public void onMessageReceivedFromClient(final IWebsocketClient client, String message) {

            JSONObject obj = (JSONObject) JSONValue.parse(message);

            if (obj != null && obj.containsKey(JsonConstants.API_ACTION)) {

                System.out.println("[API] > " + obj.toJSONString());

                String action = obj.get(JsonConstants.API_ACTION).toString();

                if (action != null) {
                    if (action.equals(JsonConstants.API_REGISTRATION_STATE)) {

                        JSONObject registrationResponse = new JSONObject();

                        if (calendarNotifManager != null
                                && calendarNotifManager.getOauthRegistration() != null) {

                            registrationResponse.put(JsonConstants.GOOGLE_OAUTH_DEVICE_CODE,
                                    calendarNotifManager.getOauthRegistration().getDeviceCode());
                            registrationResponse.put(JsonConstants.GOOGLE_OAUTH_EXPIRING_BEFORE,
                                    calendarNotifManager.getOauthRegistration().getExpiringBefore());
                            registrationResponse.put(JsonConstants.GOOGLE_OAUTH_INTERVAL,
                                    calendarNotifManager.getOauthRegistration().getInterval());
                            registrationResponse.put(JsonConstants.GOOGLE_OAUTH_USERCODE,
                                    calendarNotifManager.getOauthRegistration().getUserCode());
                            registrationResponse.put(JsonConstants.GOOGLE_OAUTH_VERIFICATION_URL,
                                    calendarNotifManager.getOauthRegistration().getVerificationUrl());

                        }

                        System.out.println("[API] < " + registrationResponse.toJSONString());
                        client.sendMessage(registrationResponse.toJSONString());

                    } else if (action.equals(JsonConstants.API_TOKEN_STATE)) {

                        JSONObject requestTokenResponse = new JSONObject();

                        if (calendarNotifManager != null && calendarNotifManager.getCurrentToken() != null) {

                            requestTokenResponse.put(JsonConstants.GOOGLE_OAUTH_ACCESS_TOKEN,
                                    calendarNotifManager.getCurrentToken().getAccessToken());
                            requestTokenResponse.put(JsonConstants.GOOGLE_OAUTH_TOKEN_TYPE,
                                    calendarNotifManager.getCurrentToken().getTokenType());
                            requestTokenResponse.put(JsonConstants.GOOGLE_OAUTH_EXPIRE_IN,
                                    calendarNotifManager.getCurrentToken().getExpiresIn());

                        }
                        System.out.println("[API] < " + requestTokenResponse.toJSONString());
                        client.sendMessage(requestTokenResponse.toJSONString());

                    } else if (action.equals(JsonConstants.API_REGISTRATION)) {

                        calendarNotifManager = new CalendarNotifManager(clientId, clientSecret);

                        calendarNotifManager.requestDeviceAuth(new IOauthDeviceResponseListener() {

                            @Override
                            public void onResponseReceived(OauthForDeviceResponse response) {
                                if (response != null) {
                                    JSONObject registrationResponse = new JSONObject();
                                    registrationResponse.put(JsonConstants.GOOGLE_OAUTH_DEVICE_CODE,
                                            response.getDeviceCode());
                                    registrationResponse.put(JsonConstants.GOOGLE_OAUTH_EXPIRING_BEFORE,
                                            response.getExpiringBefore());
                                    registrationResponse.put(JsonConstants.GOOGLE_OAUTH_INTERVAL,
                                            response.getInterval());
                                    registrationResponse.put(JsonConstants.GOOGLE_OAUTH_USERCODE,
                                            response.getUserCode());
                                    registrationResponse.put(JsonConstants.GOOGLE_OAUTH_VERIFICATION_URL,
                                            response.getVerificationUrl());

                                    System.out.println("[API] < " + registrationResponse.toJSONString());

                                    client.sendMessage(registrationResponse.toJSONString());
                                }
                            }
                        });
                    } else if (action.equals(JsonConstants.API_REQUEST_TOKEN)) {

                        if (calendarNotifManager != null) {
                            calendarNotifManager.requestToken(new IRequestTokenListener() {

                                @Override
                                public void onRequestTokenReceived(OauthToken token) {
                                    if (token != null) {
                                        JSONObject requestTokenResponse = new JSONObject();
                                        requestTokenResponse.put(JsonConstants.GOOGLE_OAUTH_ACCESS_TOKEN,
                                                token.getAccessToken());
                                        requestTokenResponse.put(JsonConstants.GOOGLE_OAUTH_TOKEN_TYPE,
                                                token.getTokenType());
                                        requestTokenResponse.put(JsonConstants.GOOGLE_OAUTH_EXPIRE_IN,
                                                token.getExpiresIn());

                                        System.out.println("[API] < " + requestTokenResponse.toJSONString());

                                        client.sendMessage(requestTokenResponse.toJSONString());
                                    }
                                }

                                @Override
                                public void onRequestTokenError(String description) {
                                    String response = "{\"error\":\"request token error\",\"error_description\":\""
                                            + description + "\"}";

                                    System.out.println("[API] < " + response);

                                    client.sendMessage(response);
                                }
                            });
                        }
                    } else if (action.equals(JsonConstants.API_REVOKE_TOKEN)) {

                        if (calendarNotifManager != null) {
                            calendarNotifManager.revokeToken(new IRevokeTokenListener() {

                                @Override
                                public void onSuccess() {

                                    System.out.println("[API] < " + "{\"revokeToken\":\"success\"}");

                                    client.sendMessage("{\"revokeToken\":\"success\"}");
                                }

                                @Override
                                public void onError(String description) {

                                    String response = "{\"error\":\"request token error\",\"error_description\":\""
                                            + description + "\"}";

                                    System.out.println("[API] < " + response);

                                    client.sendMessage(response);
                                }
                            });
                        }
                    } else if (action.equals(JsonConstants.API_USER_PROFILE)) {
                        if (calendarNotifManager != null) {
                            calendarNotifManager.getUserProfileManager()
                                    .getUserProfile(new IUserProfileListener() {

                                        @Override
                                        public void onSuccess(UserProfile userProfile) {
                                            if (userProfile != null) {
                                                JSONObject userProfileResponse = new JSONObject();
                                                userProfileResponse.put(JsonConstants.GOOGLE_API_PROFILE_GENDER,
                                                        userProfile.getGender());
                                                userProfileResponse.put(
                                                        JsonConstants.GOOGLE_API_PROFILE_DISPLAY_NAME,
                                                        userProfile.getDisplayName());
                                                userProfileResponse.put(
                                                        JsonConstants.GOOGLE_API_PROFILE_FAMILY_NAME,
                                                        userProfile.getFamilyName());
                                                userProfileResponse.put(
                                                        JsonConstants.GOOGLE_API_PROFILE_GIVEN_NAME,
                                                        userProfile.getGivenName());
                                                userProfileResponse.put(
                                                        JsonConstants.GOOGLE_API_PROFILE_LANGUAGE,
                                                        userProfile.getLanguage());

                                                System.out.println(
                                                        "[API] < " + userProfileResponse.toJSONString());

                                                client.sendMessage(userProfileResponse.toJSONString());
                                            }
                                        }

                                        @Override
                                        public void onError(String description) {

                                            String response = "{\"error\":\"request token error\",\"error_description\":\""
                                                    + description + "\"}";

                                            System.out.println("[API] < " + response);

                                            client.sendMessage(response);
                                        }
                                    });
                        }
                    } else if (action.equals(JsonConstants.API_CREATE_EVENT)
                            && obj.containsKey(JsonConstants.API_DATE_BEGIN)
                            && obj.containsKey(JsonConstants.API_DATE_END)
                            && obj.containsKey(JsonConstants.API_SUMMARY)) {

                        String dateBegin = obj.get(JsonConstants.API_DATE_BEGIN).toString();
                        String dateEnd = obj.get(JsonConstants.API_DATE_END).toString();
                        String summary = obj.get(JsonConstants.API_SUMMARY).toString();

                        if (calendarNotifManager != null) {

                            calendarNotifManager.getCalendarManager().createEvent(dateBegin, dateEnd, summary,
                                    new ICreateEventListener() {

                                        @Override
                                        public void onError(String description) {

                                            String response = "{\"error\":\"request token error\",\"error_description\":\""
                                                    + description + "\"}";

                                            System.out.println("[API] < " + response);

                                            client.sendMessage(
                                                    "{\"error\":\"request token error\",\"error_description\":\""
                                                            + description + "\"}");
                                        }

                                        @Override
                                        public void onCreateSuccess(String id) {

                                            String response = "{\"createEvent\":\"success\",\"eventId\":\"" + id
                                                    + "\"}";

                                            System.out.println("[API] < " + response);

                                            client.sendMessage(response);
                                        }
                                    });
                        }
                    } else if (action.equals(JsonConstants.API_DELETE_EVENT)
                            && obj.containsKey(JsonConstants.API_EVENT_ID)) {

                        final String eventId = obj.get(JsonConstants.API_EVENT_ID).toString();

                        calendarNotifManager.getCalendarManager().deleteEvent(eventId,
                                new IDeleteEventListener() {

                                    @Override
                                    public void onSuccess() {

                                        String response = "{\"deleteEvent\":\"success\",\"eventId\":\""
                                                + eventId + "\"}";

                                        System.out.println("[API] < " + response);

                                        client.sendMessage(response);
                                    }

                                    @Override
                                    public void onError(String description) {

                                        String response = "{\"error\":\"request token error\",\"error_description\":\""
                                                + description + "\"}";

                                        System.out.println("[API] < " + response);

                                        client.sendMessage(response);
                                    }
                                });

                    } else if (action.equals(JsonConstants.API_GET_EVENTS)
                            && obj.containsKey(JsonConstants.API_DATE_BEGIN)
                            && obj.containsKey(JsonConstants.API_DATE_END) && obj.containsKey("searchText")
                            && calendarNotifManager != null) {

                        String dateBegin = obj.get(JsonConstants.API_DATE_BEGIN).toString();
                        String dateEnd = obj.get(JsonConstants.API_DATE_END).toString();
                        String searchText = obj.get(JsonConstants.API_SEARCH_TEXT).toString();

                        calendarNotifManager.getCalendarManager().getEventList(dateBegin, dateEnd, searchText,
                                new IEventListListener() {

                                    @Override
                                    public void onEventListReceived(List<CalendarEvents> calendarEventList) {

                                        String response = "{\"eventList\":" + CalendarUtils
                                                .convertCalendarListToJsonArray(calendarEventList)
                                                .toJSONString() + "}";

                                        System.out.println("[API] < " + response);

                                        client.sendMessage(response);
                                    }

                                    @Override
                                    public void onError(String description) {

                                        String response = "{\"error\":\"request token error\",\"error_description\":\""
                                                + description + "\"}";

                                        System.out.println("[API] < " + response);

                                        client.sendMessage(response);
                                    }
                                });

                    } else if (action.equals(JsonConstants.API_SUBSCRIBE_EVENT)
                            && obj.containsKey(JsonConstants.API_EVENT_ID)
                            && obj.containsKey(JsonConstants.API_TIME_ABOUT_TO_START)) {

                        String eventId = obj.get(JsonConstants.API_EVENT_ID).toString();
                        int timeAboutToStart = Integer
                                .parseInt(obj.get(JsonConstants.API_TIME_ABOUT_TO_START).toString());

                        calendarNotifManager.getNotificationManager().subscribeEvent(eventId, timeAboutToStart,
                                new IEventListener() {

                                    @Override
                                    public void onEventStart(String eventId, String summary) {

                                        String response = "{\"subscribedEvent\":\"" + eventId
                                                + "\",\"eventType\":\"started\",\"summary\":\"" + summary
                                                + "\"}";

                                        System.out.println("[API] < " + response);

                                        client.sendMessage(response);
                                    }

                                    @Override
                                    public void onEventAboutToStart(String eventId, String summary) {

                                        String response = "{\"subscribedEvent\":\"" + eventId
                                                + "\",\"eventType\":\"aboutToStart\",\"summary\":\"" + summary
                                                + "\"}";

                                        System.out.println("[API] < " + response);

                                        client.sendMessage(response);
                                    }
                                });

                    } else if (action.equals(JsonConstants.API_UNSUBSCRIBE_EVENT)
                            && obj.containsKey(JsonConstants.API_EVENT_ID)) {
                        String eventId = obj.get(JsonConstants.API_EVENT_ID).toString();

                        calendarNotifManager.getNotificationManager().unsubscribeEvent(eventId);
                    } else {
                        System.out.println("[API] Error api target is inconsistent");
                    }
                }
            }
        }

        @Override
        public void onClientConnection(IWebsocketClient client) {
            System.out.println("Websocket client connected");
        }

        @Override
        public void onClientClose(IWebsocketClient client) {
            System.out.println("Websocket client disconnected");
        }
    });

    Runnable websocketTask = new Runnable() {

        @Override
        public void run() {
            websocketServer.start();
        }
    };

    Thread thread = new Thread(websocketTask, "WEBSOCKET_THREAD");

    thread.start();

    server.addServerEventListener(new IHttpServerEventListener() {

        @Override
        public void onHttpFrameReceived(IHttpFrame httpFrame, HttpStates receptionStates,
                IHttpStream httpStream) {

            // check if http frame is OK
            if (receptionStates == HttpStates.HTTP_FRAME_OK) {

                // you can check here http frame type (response or request
                // frame)
                if (httpFrame.isHttpRequestFrame()) {

                    // we want to send a message to client for http GET
                    // request on page with uri /index
                    if (httpFrame.getMethod().equals("GET") && httpFrame.getUri().equals("/gcalendar")) {

                        String defaultPage = "";
                        try {
                            defaultPage = FileUtils.readFile(webPath + "/index.html", "UTF-8");
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                        // return default html page for this HTTP Server
                        httpStream.writeHttpFrame(new HttpResponseFrame(StatusCodeList.OK,
                                new HttpVersion(1, 1), new HashMap<String, String>(), defaultPage.getBytes())
                                        .toString().getBytes());

                    } else if (httpFrame.getMethod().equals("GET")
                            && (httpFrame.getUri().endsWith(".css") || httpFrame.getUri().endsWith(".js"))) {

                        String defaultPage = "";
                        try {
                            defaultPage = FileUtils.readFile(webPath + httpFrame.getUri(), "UTF-8");
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                        // return default html page for this HTTP Server
                        httpStream.writeHttpFrame(new HttpResponseFrame(StatusCodeList.OK,
                                new HttpVersion(1, 1), new HashMap<String, String>(), defaultPage.getBytes())
                                        .toString().getBytes());
                    }
                }
            }
        }
    });

    server.start();
    thread.interrupt();

}

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  ww  .j  ava  2s . c o m
        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:co.alligo.toasted.routes.ServerList.java

public static String serverList(Request req, Response res, Servers servers) {

    JSONObject response = new JSONObject();
    JSONObject result = new JSONObject();

    res.header("Content-Type", "application/json");

    response.put("listVersion", 1);

    result.put("code", 0);
    result.put("msg", "OK");
    result.put("servers", servers.getServers());

    response.put("result", result);

    return (String) response.toJSONString();
}

From source file:co.edu.UNal.ArquitecturaDeSoftware.Bienestar.Vista.Util.java

public static void errordeRespuesta(ArrayList r, PrintWriter out) {
    System.err.print(//from  w w  w .  j a v  a2s  .  com
            "Respuesta inesperada del control !! r.size:" + r.size() + "|r0:" + r.get(0) + "|r1:" + r.get(1));
    JSONObject obj = new JSONObject();
    obj.put("isError", true);
    obj.put("errorDescrip", "Error inesperado");
    out.print(obj);
}

From source file:com.oic.utils.Tools.java

public static JSONObject convertPosToJSON(Position pos) {
    JSONObject json = new JSONObject();
    json.put("x", pos.getX());
    json.put("y", pos.getY());
    json.put("width", pos.getWidth());
    json.put("height", pos.getHeight());
    return json;/*w  ww  .j a  va 2  s .  c o m*/
}

From source file:co.alligo.toasted.routes.Announce.java

public static String announce(Request req, Response res, Servers servers) {
    JSONObject json = new JSONObject();
    JSONObject result = new JSONObject();
    String ip = req.ip();/*from w  w w . j av a 2 s  . co  m*/
    String port;

    res.header("Content-Type", "application/json");

    if (!(req.headers("x-forwarded-for") == null)) {
        ip = req.headers("x-forwarded-for");
    }

    if (req.attribute("port") == null) {
        result.put("code", 1);
        result.put("msg", "Invalid parameters, valid parameters are 'port' (int) and 'shutdown' (bool)");
        json.put("result", result);
        return json.toJSONString();
    } else {
        port = req.attribute("port").toString();
    }

    if ("true".equals(req.attribute("shutdown").toString())) {
        servers.delServer(ip, port);
    } else {
        if (checkGameServer(ip, port)) {
            servers.addServer(ip, port);
            result.put("code", 0);
            result.put("msg", "Added server to list.");
            System.out.println("Added server to list" + ip + ":" + port);
            json.put("result", result);
            return json.toJSONString();

        } else {
            result.put("code", 0);
            result.put("msg", "Failed to contact game server, are the ports open and forwarded correctly?");
            json.put("result", result);
            return json.toJSONString();
        }
    }

    return "500 Internal Server Error";
}

From source file:naftoreiclag.villagefive.SaveLoad.java

public static void save(World data) throws IOException {
    JSONObject obj = new JSONObject();
    obj.put("world", data);
    FileWriter fw = new FileWriter(new File("saves/save.json"));
    obj.writeJSONString(fw);/*w  ww.  j a  v a2  s . c  o  m*/
    fw.flush();
}

From source file:component.Configuration.java

public static void createConfigFile() throws IOException {
    JSONObject config = new JSONObject();
    List<String> queryList = new ArrayList<>();
    Map<String, List<String>> queries = new HashMap<>();
    try (Writer writer = new FileWriter("config.json", false)) {
        queryList.add("full_message:(Exception)");
        queryList.add("full_message:(Error)");
        config.put("queries", queryList);
        config.put("range", 3600);

        config.writeJSONString(writer);/*from   w  w w .  jav  a2  s . c om*/
        writer.flush();
    }
}