Example usage for org.json.simple JSONValue parse

List of usage examples for org.json.simple JSONValue parse

Introduction

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

Prototype

public static Object parse(String s) 

Source Link

Usage

From source file:app.WebSocketServer.java

public static void main(final String[] args) {
    Undertow server = Undertow.builder().addHttpListener(3030, "0.0.0.0")
            .setHandler(path().addPrefixPath("/ws", websocket(new WebSocketConnectionCallback() {
                @Override//from   www .  ja v  a  2  s. co m
                public void onConnect(WebSocketHttpExchange exchange, WebSocketChannel channel) {
                    channels.add(channel);
                    channel.getReceiveSetter().set(new AbstractReceiveListener() {
                        @Override
                        protected void onFullTextMessage(WebSocketChannel channel,
                                BufferedTextMessage message) {
                            JSONObject msg = (JSONObject) JSONValue.parse(message.getData());

                            switch (msg.get("type").toString()) {
                            case "broadcast":
                                final String outbound = msg.toJSONString();
                                channels.forEach(gc -> WebSockets.sendText(outbound, gc, null));
                                msg.replace("type", "broadcastResult");
                                WebSockets.sendText(msg.toJSONString(), channel, null);
                                break;
                            case "echo":
                                WebSockets.sendText(msg.toJSONString(), channel, null);
                                break;
                            default:
                                System.out.println("Unknown message type");
                            }
                        }
                    });

                    channel.addCloseTask(new ChannelListener<WebSocketChannel>() {
                        @Override
                        public void handleEvent(WebSocketChannel channel) {
                            channels.remove(channel);
                        }
                    });
                    channel.resumeReceives();
                }
            }))).build();
    server.start();
}

From source file:ci6226.buildindex.java

/**
 * @param args the command line arguments
 *//*w  w  w.j a v a 2 s  .  c  om*/
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: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);/*from  w  w  w  .  j  a v  a 2 s.  co  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:fr.bmartel.protocol.google.main.LaunchOauthApiServer.java

/**
 * The main method.// w  w w.j  av 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:com.github.pmerienne.trident.cf.testing.DRPCUtils.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public static List<List<Object>> extractValues(String drpcResult) {
    List<List<Object>> values = (List) JSONValue.parse(drpcResult);
    return values;
}

From source file:com.github.pmerienne.cf.util.DRPCUtils.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T extends Object> List<List<T>> extractValues(String drpcResult) {
    List<List<T>> values = (List) JSONValue.parse(drpcResult);
    return values;
}

From source file:com.github.pmerienne.trident.cf.testing.DRPCUtils.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public static Object extractSingleValue(String drpcResult) {
    List<List<Object>> values = (List) JSONValue.parse(drpcResult);
    return values.get(0).get(0);
}

From source file:co.edu.unal.arqdsoft.presentacion.JSON.java

/**
 * /*from   w w  w  . jav  a 2  s. c o m*/
 * @param request
 * @return JSONObject con los parametros del request
 * @throws Exception 
 */
public static JSONObject toObject(HttpServletRequest request) throws Exception {
    if (request.getParameter("accion") != null) {//Servidor independiente
        JSONObject r = new JSONObject();
        r.put("accion", request.getParameter("accion"));
        r.put("datos", request.getParameter("datos"));
        return r;
    } else {//Servidor base netbeans
        InputStream is = request.getInputStream();
        byte[] charr = new byte[is.available()];
        is.read(charr);
        return (JSONObject) JSONValue.parse(new String(charr, "UTF-8"));
    }
}

From source file:com.github.pmerienne.cf.util.DRPCUtils.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T extends Object> T extractSingleValue(String drpcResult, int index) {
    List<List<Object>> values = (List) JSONValue.parse(drpcResult);
    return (T) values.get(0).get(index);
}

From source file:myproject.MyServer.java

public static void Query(HttpServletRequest request, HttpServletResponse response) throws IOException {
    try {/*from w  w  w . j  a  v  a2s  .c  om*/
        String jsonString = IOUtils.toString(request.getInputStream());
        JSONObject json = (JSONObject) JSONValue.parse(jsonString);
        String query = (String) json.get("query");
        String result = database.runQuery(query);
        response.getWriter().write(result);
    } catch (Exception ex) {
        JSONObject output = new JSONObject();
        output.put("error", "Connection failed: " + ex.getMessage());
        response.getWriter().write(JSONValue.toJSONString(output));
    }
}