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:com.ge.research.semtk.services.client.RestClient.java

/**
 * Make the service call.  /*from   w  w  w  . j  ava  2 s .  co  m*/
 * @return an Object that can be cast to a JSONObject.  Subclasses may override and return a more useful Object.   
 */
public Object execute() throws ConnectException, Exception {

    // TODO can we do this before calling execute()?
    buildParametersJSON(); // set all parameters available upon instantiation

    System.out.println("EXECUTE ON " + this.conf.getServiceURL());

    if (parametersJSON == null) {
        throw new Exception("Service parameters not set");
    }

    DefaultHttpClient httpclient = new DefaultHttpClient();

    // immediate line below removed to perform htmml encoding in stream
    // HttpEntity entity = new ByteArrayEntity(parametersJSON.toJSONString().getBytes("UTF-8"));

    // js version:  return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/%/g, "&#37;")

    HttpEntity entity = new ByteArrayEntity(parametersJSON.toString().getBytes("UTF-8"));
    HttpPost httppost = new HttpPost(this.conf.getServiceURL());
    httppost.setEntity(entity);
    httppost.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");

    // execute
    HttpHost targetHost = new HttpHost(this.conf.getServiceServer(), this.conf.getServicePort(),
            this.conf.getServiceProtocol());
    HttpResponse httpresponse = httpclient.execute(targetHost, httppost);

    // handle the output         
    String responseTxt = EntityUtils.toString(httpresponse.getEntity(), "UTF-8");
    httpclient.close();
    if (responseTxt == null) {
        throw new Exception("Received null response text");
    }
    if (responseTxt.trim().isEmpty()) {
        handleEmptyResponse(); // implementation-specific behavior
    }

    if (responseTxt.length() < 500) {
        System.err.println("RestClient received: " + responseTxt);
    } else {
        System.err.println("RestClient received: " + responseTxt.substring(0, 200) + "... ("
                + responseTxt.length() + " chars)");
    }

    JSONObject responseParsed = (JSONObject) JSONValue.parse(responseTxt);
    if (responseParsed == null) {
        System.err.println("The response could not be transformed into json");
        if (responseTxt.contains("Error")) {
            throw new Exception(responseTxt);
        }
    }
    return responseParsed;
}

From source file:importer.handler.get.ImporterGetHandler.java

/**
 * Use this method to retrieve the doc just to see its format
 * @param db the database to fetch from//w w  w  . j  a  v  a2s.c  om
 * @param docID the doc's ID
 * @return a JSON doc as returned by Mongo
 * @throws ImporterException 
 */
JSONObject loadJSONDocument(String db, String docID) throws ImporterException {
    try {
        String data = Connector.getConnection().getFromDb(db, docID);
        if (data.length() > 0) {
            JSONObject doc = (JSONObject) JSONValue.parse(data);
            if (doc != null)
                return doc;
        }
        throw new ImporterException("Doc not found " + docID);
    } catch (Exception e) {
        throw new ImporterException(e);
    }
}

From source file:edu.rit.chrisbitler.ritcraft.slackintegration.SlackIntegration.java

private void startRTM() throws IOException, URISyntaxException, DeploymentException {
    URL url = new URL("https://www.slack.com/api/rtm.start?token=" + BOT_TOKEN);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setInstanceFollowRedirects(true);
    conn.connect();/* w ww . jav a 2s  .  c om*/
    JSONObject returnVal = (JSONObject) JSONValue.parse(new InputStreamReader((InputStream) conn.getContent()));
    String wsUrl = (String) returnVal.get("url");

    //unescape the wsUrl string's slashes
    wsUrl = wsUrl.replace("\\", "");

    //Query the users so we can link user id -> username
    System.out.println("Querying slack users..");
    UserList.queryUsers();

    System.out.println("Recieved WebSocket URI from slack, connecting... " + wsUrl);

    //Connect via the real-time messaging client and the websocket.
    ClientEndpointConfig cec = ClientEndpointConfig.Builder.create().build();
    client = ClientManager.createClient();
    rtm = new RTMClient();
    client.connectToServer(rtm, cec, new URI(wsUrl));
}

From source file:de.dailab.plistacontest.client.ClientAndContestHandler0MQ.java

/**
 * Method to handle incoming messages from the server.
 * //from ww w.  jav  a2s  .  c o  m
 * @param messageType
 *                the messageType of the incoming contest server message.
 * @param properties
 *                
 * @param entities
 * @return the response to the contest server
 */
private String handleIdomaarMessage(final String messageType, final String properties, final String entities) {
    // write all data from the server to a file
    logger.info(messageType + "\t" + properties + "\t" + entities);

    // create an jSON object from the String
    final JSONObject jOP = (JSONObject) JSONValue.parse(properties);
    final JSONObject jOE = (JSONObject) JSONValue.parse(entities);

    // merge the different jsonObjects and correct missing itemIDs
    jOP.putAll(jOE);
    Object itemID = jOP.get("itemID");
    if (itemID == null) {
        jOP.put("itemID", 0);
    }

    // define a response object
    String response = null;

    if ("impression".equalsIgnoreCase(messageType)) {

        // parse the type of the event
        final RecommenderItem item = RecommenderItem.parseEventNotification(jOP.toJSONString());
        final String eventNotificationType = item.getNotificationType();

        // new items shall be added to the list of items
        if (item.getItemID() != null) {
            recommenderItemTable.handleItemUpdate(item);
        }
        response = "handle impression eventNotification successful";

        // impression refers to articles read by the user
        if ("recommendation_request".equalsIgnoreCase(eventNotificationType)) {

            // we mark this information in the article table
            if (item.getItemID() != null) {

                item.setNumberOfRequestedResults(6);
                //List<Long> suggestedItemIDs = item.getListOfDisplayedRecs();
                List<Long> suggestedItemIDs = recommenderItemTable.getLastItems(item);
                response = "{" + "\"recs\": {" + "\"ints\": {" + "\"3\": " + suggestedItemIDs + "}" + "}}";

            } else {
                System.err.println("invalid itemID - requests are only valid for 'normal' articles");
            }
            // click refers to recommendations clicked by the user
        } else if ("click".equalsIgnoreCase(eventNotificationType)) {

            // we mark this information in the article table
            if (item.getItemID() != null) {
                // new items shall be added to the list of items
                recommenderItemTable.handleItemUpdate(item);

                response = "handle impression eventNotification successful";
            }
            response = "handle click eventNotification successful";

        } else {
            System.out.println("unknown event-type: " + eventNotificationType + " (message ignored)");
        }

    } else if ("error_notification".equalsIgnoreCase(messageType)) {

        System.out.println("error-notification: " + jOP.toString() + jOE.toJSONString());

    } else {
        System.out.println("unknown MessageType: " + messageType);
        // Error handling
        logger.info(jOP.toString() + jOE.toJSONString());
        // this.contestRecommender.error(jObj.toString());
    }
    return response;
}

From source file:ch.uzh.ddis.thesis.lambda_architecture.speed.spout.kafka.DynamicBrokersReader.java

/**
 * get /brokers/topics/distributedTopic/partitions/1/state
 * { "controller_epoch":4, "isr":[ 1, 0 ], "leader":1, "leader_epoch":1, "version":1 }
 *
 * @param partition/*from  www  .j  a v a  2s.  c  om*/
 * @return
 */
private int getLeaderFor(long partition) {
    try {
        String topicBrokersPath = partitionPath();
        byte[] hostPortData = _curator.getData().forPath(topicBrokersPath + "/" + partition + "/state");
        Map<Object, Object> value = (Map<Object, Object>) JSONValue.parse(new String(hostPortData, "UTF-8"));
        Integer leader = ((Number) value.get("leader")).intValue();
        return leader;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.yahoo.storm.yarn.StormMasterCommand.java

public static void downloadStormYaml(StormMaster.Client client, String storm_yaml_output) {
    String conf_str = "Not Avaialble";

    //fetch storm.yaml from Master
    try {/*  w w w  .  j  av  a  2  s  . com*/
        conf_str = client.getStormConf();
    } catch (TTransportException ex) {
        LOG.error("Exception in downloading storm.yaml", ex);
    } catch (TException ex) {
        LOG.error("Exception in downloading storm.yaml", ex);
    }

    //storm the fetched storm.yaml into storm_yaml_output or stdout
    try {
        Object json = JSONValue.parse(conf_str);
        Map<?, ?> conf = (Map<?, ?>) json;
        Yaml yaml = new Yaml();

        if (storm_yaml_output == null) {
            LOG.info("storm.yaml downloaded:");
            System.out.println(yaml.dump(conf));
        } else {
            FileWriter out = new FileWriter(storm_yaml_output);
            yaml.dump(conf, out);
            out.flush();
            out.close();
            LOG.info("storm.yaml downloaded into " + storm_yaml_output);
        }
    } catch (Exception ex) {
        LOG.error("Exception in storing storm.yaml. ", ex);
    }
}

From source file:com.noelportugal.amazonecho.AmazonEchoApi.java

public String getLatestTodo() throws IOException {

    String output = httpGet("/api/todos?type=TASK&size=1");
    //   System.out.println(output);
    // Parse JSON
    Object obj = JSONValue.parse(output);
    JSONObject jsonObject = (JSONObject) obj;
    JSONArray values = (JSONArray) jsonObject.get("values");
    JSONObject item = (JSONObject) values.get(0);
    //System.out.println(item);
    // Get text and itemId
    String text = item.get("text").toString();
    String itemId = item.get("itemId").toString();

    if (!checkItemId(itemId)) {

        return text;
    } else {/*from   w  w  w  . jav a2 s  .c o m*/
        return null;
    }
}

From source file:com.hortonworks.amstore.view.TaskManagerService.java

/**
 * Handles: DELETE /taskmanager/postinstalltasks Removes a task from the
 * list of tasks This is done because of BUG: a call to
 * viewContext.putInstanceData inside the servlet returns ERROR 500 after a
 * while./*  ww w .ja  va  2s.c  om*/
 * 
 * @param headers
 *            http headers
 * @param ui
 *            uri info
 *
 * @return the response
 */
@DELETE
@Path("/postinstalltasks/{uri}")
@Produces({ "text/html" })
public Response delPostInstallTasks(@PathParam("uri") String uri, @Context HttpHeaders headers,
        @Context UriInfo ui) throws IOException {

    String response = "";
    try {

        String current = viewContext.getInstanceData("post-install-tasks");
        if (current == null)
            current = "[]";

        JSONArray array = (JSONArray) JSONValue.parse(current);
        array.remove(URLDecoder.decode(uri));

        viewContext.putInstanceData("post-install-tasks", array.toString());

        /*
         * } catch( ParseException pe){ System.out.println("position: " +
         * pe.getPosition()); System.out.println(pe); }
         */
    } catch (Exception e) {
        response += "Failed to remove: current=" + uri + "<br>";
        response += "Error in service: " + e.toString();
        return Response.ok(response).type("text/html").build();
    }

    String entity = "{ \"status\": \"ok\" }";
    return Response.ok(entity).type("text/html").build();
}

From source file:com.quartercode.quarterbukkit.api.query.ServerModsAPIQuery.java

/**
 * Executes the stored query and returns the result as a {@link JSONArray}.
 * The query string ({@link #getQuery()}) is attached to {@code https://api.curseforge.com/servermods/}.
 * The GET response of that {@link URL} is then parsed to a {@link JSONArray}.
 * /*from w w  w  .java  2  s. c  om*/
 * @return The response of the server mods api.
 * @throws QueryException Something goes wrong while querying the server mods api.
 */
public JSONArray execute() throws QueryException {

    // Build request url using the query
    URL requestUrl = null;
    try {
        requestUrl = new URL(HOST + query);
    } catch (MalformedURLException e) {
        throw new QueryException(QueryExceptionType.MALFORMED_URL, this, HOST + query, e);
    }

    // Open connection to request url
    URLConnection request = null;
    try {
        request = requestUrl.openConnection();
    } catch (IOException e) {
        throw new QueryException(QueryExceptionType.CANNOT_OPEN_CONNECTION, this, requestUrl.toExternalForm(),
                e);
    }

    // Set connection timeout
    request.setConnectTimeout(CONNECTION_TIMEOUT);

    // Set user agent
    request.addRequestProperty("User-Agent", USER_AGENT);

    // Set api key (if provided)
    String apiKey = QuarterBukkit.getPlugin().getConfig().getString("server-mods-api-key");
    if (apiKey != null && !apiKey.isEmpty()) {
        request.addRequestProperty("X-API-Key", apiKey);
    }

    // We want to read the results
    request.setDoOutput(true);

    // Read first line from the response
    BufferedReader reader = null;
    String response = null;
    try {
        reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
        response = reader.readLine();
    } catch (IOException e) {
        if (e.getMessage().contains("HTTP response code: 403")) {
            throw new QueryException(QueryExceptionType.INVALID_API_KEY, this, requestUrl.toExternalForm(), e);
        } else {
            throw new QueryException(QueryExceptionType.CANNOT_READ_RESPONSE, this, requestUrl.toExternalForm(),
                    e);
        }
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                throw new QueryException(QueryExceptionType.CANNOT_CLOSE_RESPONSE_STREAM, this,
                        requestUrl.toExternalForm(), e);
            }
        }
    }

    // Parse the response
    Object jsonResponse = JSONValue.parse(response);

    if (jsonResponse instanceof JSONArray) {
        return (JSONArray) jsonResponse;
    } else {
        throw new QueryException(QueryExceptionType.INVALID_RESPONSE, this, requestUrl.toExternalForm());
    }
}

From source file:action.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   w w w. j a  va 2s. c  o  m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpSession session = request.getSession();
    String form_action = (String) request.getParameter("form_action");
    if (form_action == null) {
        form_action = "";
    }
    PrintWriter out = response.getWriter();
    if (form_action.equalsIgnoreCase("cekauth")) {
        StringBuffer sb = new StringBuffer();
        String line = null;
        LinkedHashMap record = new LinkedHashMap();
        try {
            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            Object obj = JSONValue.parse(sb.toString());
            JSONObject obj1 = (JSONObject) obj;
            String admin = "N";
            String icw = "N";
            String email = obj1.get("email").toString();
            String first_name = obj1.get("first_name").toString();
            String gender = obj1.get("gender").toString();
            String id = obj1.get("id").toString();
            String last_name = obj1.get("last_name").toString();
            String link = obj1.get("link").toString();
            String name = obj1.get("name").toString();
            String verified = obj1.get("verified").toString();

            DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
            Key linkKey = KeyFactory.createKey("userTable", "user");
            // Run an ancestor query to ensure we see the most up-to-date
            // view of the Greetings belonging to the selected Guestbook.

            Filter posisinama = new FilterPredicate("link", FilterOperator.EQUAL, link.toLowerCase());
            // Run an ancestor query to ensure we see the most up-to-date
            // view of the Greetings belonging to the selected Guestbook.
            Query query = new Query("userTable", linkKey).setFilter(posisinama);
            List<Entity> userTables = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(1));
            Date date = new Date();

            if (userTables.isEmpty()) {
                Entity userTable = new Entity("userTable", linkKey);
                userTable.setProperty("email", email);
                userTable.setProperty("first_name", first_name);
                userTable.setProperty("gender", gender);
                userTable.setProperty("id", id);
                userTable.setProperty("last_name", last_name);
                userTable.setProperty("link", link.toLowerCase());
                userTable.setProperty("name", name);
                userTable.setProperty("verified", verified);
                userTable.setProperty("lastLogin", date);
                if (email.equalsIgnoreCase("khairul.anshar@gmail.com")
                        || id.equalsIgnoreCase("112525777678499279265")
                        || id.equalsIgnoreCase("10152397276159760")
                        || name.equalsIgnoreCase("Khairul Anshar")) {
                    userTable.setProperty("admin", "Y");
                    userTable.setProperty("icw", "Y");
                } else {
                    userTable.setProperty("admin", admin);
                    userTable.setProperty("icw", "N");
                }
                userTable.setProperty("imported", "N");
                datastore.put(userTable);
            } else {
                for (Entity userTable : userTables) {
                    admin = userTable.getProperty("admin").toString();
                    try {
                        icw = userTable.getProperty("icw").toString();
                    } catch (Exception e) {
                        userTable.setProperty("icw", "N");
                        icw = "N";
                    }
                    userTable.setProperty("lastLogin", date);
                    datastore.put(userTable);
                }
            }
            if (email.equalsIgnoreCase("khairul.anshar@gmail.com")
                    || id.equalsIgnoreCase("112525777678499279265") || id.equalsIgnoreCase("10152397276159760")
                    || name.equalsIgnoreCase("Khairul Anshar")) {
                admin = "Y";
                icw = "Y";
            }
            obj1.put("admin", admin);
            obj1.put("icw", icw);
            session.setAttribute("userAccount", obj1);
            record.put("userAccount", obj1);
        } catch (Exception e) {
        }

        response.setContentType("text/html;charset=UTF-8");
        out.print(JSONValue.toJSONString(record));
        out.flush();

    }
    if (form_action.equalsIgnoreCase("getiframeData")) {
        StringBuffer sb = new StringBuffer();
        String line = null;
        LinkedHashMap record = new LinkedHashMap();
        try {
            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            Object obj = JSONValue.parse(sb.toString());
            //JSONArray records = (JSONArray) obj;
            JSONObject obj1 = (JSONObject) obj;
            String src = obj1.get("src").toString();

            final URL url = new URL(src);
            final URLConnection urlConnection = url.openConnection();
            urlConnection.setDoOutput(true);
            urlConnection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            urlConnection.connect();
            final InputStream inputStream = urlConnection.getInputStream();
            InputStreamReader is = new InputStreamReader(inputStream);
            StringBuilder sb1 = new StringBuilder();
            BufferedReader br = new BufferedReader(is);
            String read = br.readLine();
            while (read != null) {
                sb1.append(read);
                read = br.readLine();
            }
            record.put("data", sb1.toString());
            record.put("status", "OK");
        } catch (Exception e) {
            record.put("status", "error");
            record.put("errormsg", e.toString());
        }
        response.setContentType("text/html;charset=UTF-8");
        out.print(JSONValue.toJSONString(record));
        out.flush();
    }
    if (form_action.equalsIgnoreCase("postCommentPosisi")) {
        StringBuffer sb = new StringBuffer();
        String line = null;
        LinkedHashMap record = new LinkedHashMap();
        try {
            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            Object obj = JSONValue.parse(sb.toString());
            //JSONArray records = (JSONArray) obj;
            JSONObject obj1 = (JSONObject) obj;
            JSONObject userAccount = (JSONObject) session.getAttribute("userAccount");
            String dept = obj1.get("dept").toString();
            String star = obj1.get("star").toString();
            String comment = obj1.get("comment").toString();
            String id = userAccount.get("id").toString();
            String name = userAccount.get("name").toString();
            String link = userAccount.get("link").toString();
            postData2(name, dept, "", star, comment, id, "AlasanStarCalonPosisi", "dept", dept, link);

            record.put("status", "OK");
        } catch (Exception e) {
            record.put("status", "error");
            record.put("errormsg", e.toString());
        }
        response.setContentType("text/html;charset=UTF-8");
        out.print(JSONValue.toJSONString(record));
        out.flush();
    }
    if (form_action.equalsIgnoreCase("postLikeComment")) {
        StringBuffer sb = new StringBuffer();
        String line = null;
        LinkedHashMap record = new LinkedHashMap();
        try {
            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            Object obj = JSONValue.parse(sb.toString());
            //JSONArray records = (JSONArray) obj;
            JSONObject obj1 = (JSONObject) obj;
            String id = obj1.get("id").toString();
            String star = obj1.get("star").toString();

            JSONObject userAccount = (JSONObject) session.getAttribute("userAccount");
            String name = userAccount.get("name").toString();
            String link = userAccount.get("link").toString();
            postData11("AlasanStarLike", "id", id, star, link, name);
            record.put("status", "OK");
        } catch (Exception e) {
            record.put("status", "error");
            record.put("errormsg", e.toString());
        }
        response.setContentType("text/html;charset=UTF-8");
        out.print(JSONValue.toJSONString(record));
        out.flush();
    }
    if (form_action.equalsIgnoreCase("getLikeComment")) {
        StringBuffer sb = new StringBuffer();
        String line = null;
        LinkedHashMap record = new LinkedHashMap();
        String idx_ = "";
        try {
            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            Object obj = JSONValue.parse(sb.toString());
            //JSONArray records = (JSONArray) obj;
            JSONObject obj1 = (JSONObject) obj;
            idx_ = obj1.get("id").toString();
            DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
            LinkedHashMap record11 = new LinkedHashMap();
            String link_ = "";
            try {
                JSONObject userAccount = (JSONObject) session.getAttribute("userAccount");
                link_ = userAccount.get("link").toString();
            } catch (Exception e) {
            }
            Key guestbookKey = KeyFactory.createKey("id", idx_);
            // Run an ancestor query to ensure we see the most up-to-date
            // view of the Greetings belonging to the selected Guestbook.
            Query query = new Query("AlasanStarLike", guestbookKey).addSort("date",
                    Query.SortDirection.DESCENDING);
            //List<Entity> AlasanStars = datastore.prepare(query);
            PreparedQuery pq = datastore.prepare(query);
            JSONArray obj11 = new JSONArray();
            JSONArray obj11p = new JSONArray();
            JSONArray obj11n = new JSONArray();
            int i = 0;
            int ip = 0;
            int in = 0;
            double total = 0;
            double totalp = 0;
            double totaln = 0;
            for (Entity AlasanStar : pq.asIterable()) {
                LinkedHashMap record1 = new LinkedHashMap();
                String date = AlasanStar.getProperty("date").toString();
                String star = AlasanStar.getProperty("star").toString();
                String name = AlasanStar.getProperty("user").toString();
                String link = AlasanStar.getProperty("link").toString();
                record1.put("date", date);
                record1.put("star", star);
                record1.put("name", name);
                record1.put("link", link);
                obj11.add(record1);
                i++;
                double d = Double.parseDouble(star);
                total = total + d;
                if (d >= 0) {
                    obj11p.add(record1);
                    ip++;
                    totalp = totalp + d;
                } else {
                    obj11n.add(record1);
                    in++;
                    totaln = totaln + d;
                }
                if (link_.equalsIgnoreCase(link)) {
                    record11.put("date", date);
                    record11.put("star", star);
                    record11.put("name", name);
                    record11.put("link", link);
                }
            }
            double avg = total / i;
            if (i == 0) {
                avg = 0;
            }
            DecimalFormat df = new DecimalFormat("#.##");
            record.put("total", total);
            record.put("totalp", totalp);
            record.put("totaln", totaln);
            record.put("avg", df.format(avg));
            //record.put("AlasanStars", obj11);
            record.put("AlasanStarsp", obj11p);
            record.put("AlasanStarsn", obj11n);
            record.put("AlasanStar", record11);
            record.put("status", "OK");
        } catch (Exception e) {
            record.put("status", "error");
            record.put("errormsg", e.toString());
        }
        response.setContentType("text/html;charset=UTF-8");
        out.print(JSONValue.toJSONString(record));
        out.flush();
    }
    if (form_action.equalsIgnoreCase("getMyCommentPosisi")) {
        StringBuffer sb = new StringBuffer();
        String line = null;
        LinkedHashMap record = new LinkedHashMap();
        String dept = "";
        DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
        LinkedHashMap record1 = new LinkedHashMap();

        try {
            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            Object obj = JSONValue.parse(sb.toString());
            //JSONArray records = (JSONArray) obj;
            JSONObject obj1 = (JSONObject) obj;
            dept = obj1.get("dept").toString();
            String link_ = "";
            try {
                JSONObject userAccount = (JSONObject) session.getAttribute("userAccount");
                link_ = userAccount.get("link").toString();
            } catch (Exception e) {
            }
            LinkedHashMap record11 = new LinkedHashMap();
            Key guestbookKey = KeyFactory.createKey("dept", dept);
            Query query = new Query("AlasanStarCalonPosisi", guestbookKey).addSort("date",
                    Query.SortDirection.DESCENDING);
            PreparedQuery pq = datastore.prepare(query);
            JSONArray obj11 = new JSONArray();
            JSONArray obj11p = new JSONArray();
            JSONArray obj11n = new JSONArray();
            int i = 0;
            int ip = 0;
            int in = 0;
            double total = 0;
            double totalp = 0;
            double totaln = 0;
            for (Entity AlasanStar : pq.asIterable()) {
                record1 = new LinkedHashMap();
                String id = AlasanStar.getProperty("user").toString();
                //DateTime dateTime = AlasanStar.getProperties().getDateTimeValue();
                Date time = (Date) AlasanStar.getProperty("date");
                String date = time.toString();//AlasanStar.getProperty("date").toString();
                String star = AlasanStar.getProperty("star").toString();
                String comment = AlasanStar.getProperty("comment").toString();
                comment = comment.replaceAll("\n", "<br/>");
                String name = AlasanStar.getProperty("name").toString();
                String link = AlasanStar.getProperty("link").toString();
                String id__ = AlasanStar.getKey().toString();
                record1.put("id_", id__);
                record1.put("id", id);
                record1.put("date", date);
                record1.put("star", star);
                record1.put("comment", comment);
                record1.put("name", name);
                record1.put("link", link);
                obj11.add(record1);
                i++;
                double d = Double.parseDouble(star);
                total = total + d;
                if (d >= 0) {
                    obj11p.add(record1);
                    ip++;
                    totalp = totalp + d;
                } else {
                    obj11n.add(record1);
                    in++;
                    totaln = totaln + d;
                }
                if (link_.equalsIgnoreCase(link)) {
                    record11.put("id_", id__);
                    record11.put("id", id);
                    record11.put("date", date);
                    record11.put("star", star);
                    record11.put("comment", comment);
                    record11.put("name", name);
                    record11.put("link", link);
                }
            }
            double avg = total / i;
            if (i == 0) {
                avg = 0;
            }
            DecimalFormat df = new DecimalFormat("#.##");
            record.put("total", total);
            record.put("totalp", totalp);
            record.put("totaln", totaln);
            record.put("avg", df.format(avg));
            //record.put("AlasanStars", obj11);
            record.put("AlasanStarsp", obj11p);
            record.put("AlasanStarsn", obj11n);
            record.put("AlasanStar", record11);
            record.put("status", "OK");
        } catch (Exception e) {
            record.put("status", "error");
            record.put("errormsg", e.toString());
        }
        response.setContentType("text/html;charset=UTF-8");
        out.print(JSONValue.toJSONString(record));
        out.flush();
    }
    if (form_action.equalsIgnoreCase("postComment")) {
        StringBuffer sb = new StringBuffer();
        String line = null;
        LinkedHashMap record = new LinkedHashMap();
        try {
            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            Object obj = JSONValue.parse(sb.toString());
            //JSONArray records = (JSONArray) obj;
            JSONObject obj1 = (JSONObject) obj;
            JSONObject userAccount = (JSONObject) session.getAttribute("userAccount");
            String dept = obj1.get("dept").toString();
            String namaCalon = obj1.get("namaCalon").toString();
            String star = obj1.get("star").toString();
            String comment = obj1.get("comment").toString();
            String id = userAccount.get("id").toString();
            String name = userAccount.get("name").toString();
            String link = userAccount.get("link").toString();
            postData2(name, dept, namaCalon, star, comment, id, "AlasanStarCalon", dept, namaCalon, link);
            record.put("status", "OK");
        } catch (Exception e) {
            record.put("status", "error");
            record.put("errormsg", e.toString());
        }
        response.setContentType("text/html;charset=UTF-8");
        out.print(JSONValue.toJSONString(record));
        out.flush();
    }
    if (form_action.equalsIgnoreCase("getMyComment")) {
        StringBuffer sb = new StringBuffer();
        String line = null;
        LinkedHashMap record = new LinkedHashMap();
        String dept = "";
        String namaCalon = "";
        try {
            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            Object obj = JSONValue.parse(sb.toString());
            //JSONArray records = (JSONArray) obj;
            JSONObject obj1 = (JSONObject) obj;
            dept = obj1.get("dept").toString();
            namaCalon = obj1.get("namaCalon").toString();
            DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
            String link_ = "";
            LinkedHashMap record11 = new LinkedHashMap();
            try {
                JSONObject userAccount = (JSONObject) session.getAttribute("userAccount");
                link_ = userAccount.get("link").toString();
            } catch (Exception e) {
            }
            Key guestbookKey = KeyFactory.createKey(dept, namaCalon);
            Query query = new Query("AlasanStarCalon", guestbookKey).addSort("date",
                    Query.SortDirection.DESCENDING);
            PreparedQuery pq = datastore.prepare(query);
            JSONArray obj11 = new JSONArray();
            JSONArray obj11p = new JSONArray();
            JSONArray obj11n = new JSONArray();
            int i = 0;
            int ip = 0;
            int in = 0;
            double total = 0;
            double totalp = 0;
            double totaln = 0;
            for (Entity AlasanStar : pq.asIterable()) {
                LinkedHashMap record1 = new LinkedHashMap();
                String id = AlasanStar.getProperty("user").toString();
                Date time = (Date) AlasanStar.getProperty("date");
                String date = time.toString();//AlasanStar.getProperty("date").toString();
                String star = AlasanStar.getProperty("star").toString();
                String comment = AlasanStar.getProperty("comment").toString();
                comment = comment.replaceAll("\n", "<br/>");
                String name = AlasanStar.getProperty("name").toString();
                String link = AlasanStar.getProperty("link").toString();
                String id__ = AlasanStar.getKey().toString();
                record1.put("id_", id__);
                record1.put("id", id);
                record1.put("date", date);
                record1.put("star", star);
                record1.put("comment", comment);
                record1.put("name", name);
                record1.put("link", link);
                obj11.add(record1);
                i++;
                double d = Double.parseDouble(star);
                total = total + d;
                if (d >= 0) {
                    obj11p.add(record1);
                    ip++;
                    totalp = totalp + d;
                } else {
                    obj11n.add(record1);
                    in++;
                    totaln = totaln + d;
                }
                if (link_.equalsIgnoreCase(link)) {
                    record11.put("id_", id__);
                    record11.put("id", id);
                    record11.put("date", date);
                    record11.put("star", star);
                    record11.put("comment", comment);
                    record11.put("name", name);
                    record11.put("link", link);
                }
            }
            double avg = total / i;
            if (i == 0) {
                avg = 0;
            }
            DecimalFormat df = new DecimalFormat("#.##");
            record.put("total", total);
            record.put("totalp", totalp);
            record.put("totaln", totaln);
            record.put("avg", df.format(avg));
            record.put("AlasanStarsp", obj11p);
            record.put("AlasanStarsn", obj11n);
            record.put("AlasanStar", record11);
            record.put("status", "OK");
        } catch (Exception e) {
            record.put("status", "error");
            record.put("errormsg", e.toString());
        }
        response.setContentType("text/html;charset=UTF-8");
        out.print(JSONValue.toJSONString(record));
        out.flush();
    }
    if (form_action.equalsIgnoreCase("getAlasanStarCalon")) {
        StringBuffer sb = new StringBuffer();
        String line = null;
        LinkedHashMap record = new LinkedHashMap();
        try {
            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            Object obj = JSONValue.parse(sb.toString());
            //JSONArray records = (JSONArray) obj;
            JSONObject obj1 = (JSONObject) obj;
            JSONObject userAccount = (JSONObject) session.getAttribute("userAccount");
            String dept = obj1.get("dept").toString();
            String namaCalon = obj1.get("namaCalon").toString();
            DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
            Key guestbookKey = KeyFactory.createKey(dept, namaCalon);
            // Run an ancestor query to ensure we see the most up-to-date
            // view of the Greetings belonging to the selected Guestbook.
            Query query = new Query("AlasanStarCalon", guestbookKey).addSort("date",
                    Query.SortDirection.DESCENDING);
            //List<Entity> AlasanStars = datastore.prepare(query);
            PreparedQuery pq = datastore.prepare(query);
            JSONArray obj11 = new JSONArray();
            int i = 0;
            double total = 0;
            for (Entity AlasanStar : pq.asIterable()) {
                LinkedHashMap record1 = new LinkedHashMap();
                String id = AlasanStar.getProperty("user").toString();
                String date = AlasanStar.getProperty("date").toString();
                String star = AlasanStar.getProperty("star").toString();
                String comment = AlasanStar.getProperty("comment").toString();
                comment = comment.replaceAll("\n", "<br/>");
                String name = AlasanStar.getProperty("name").toString();
                String link = AlasanStar.getProperty("link").toString();
                String id__ = AlasanStar.getKey().toString();
                record1.put("id_", id__);
                record1.put("id", id);
                record1.put("date", date);
                record1.put("star", star);
                record1.put("comment", comment);
                record1.put("name", name);
                record1.put("link", link);
                obj11.add(record1);
                i++;
                double d = Double.parseDouble(star);
                total = total + d;
            }
            double avg = total / i;
            if (i == 0) {
                avg = 0;
            }
            DecimalFormat df = new DecimalFormat("#.##");
            record.put("total", total);
            record.put("avg", df.format(avg));
            record.put("AlasanStars", obj11);
            record.put("status", "OK");
        } catch (Exception e) {
            record.put("status", "error");
            record.put("errormsg", e.toString());
        }
        response.setContentType("text/html;charset=UTF-8");
        out.print(JSONValue.toJSONString(record));
        out.flush();
    }

    if (form_action.equalsIgnoreCase("postUsulan")) {
        StringBuffer sb = new StringBuffer();
        String line = null;
        LinkedHashMap record = new LinkedHashMap();
        try {
            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            Object obj = JSONValue.parse(sb.toString());
            //JSONArray records = (JSONArray) obj;
            JSONObject obj1 = (JSONObject) obj;
            String dept = obj1.get("dept").toString();
            String usulan = obj1.get("usulan").toString();

            JSONObject userAccount = (JSONObject) session.getAttribute("userAccount");
            String id = userAccount.get("id").toString();
            String name = userAccount.get("name").toString();
            String email = userAccount.get("email").toString();
            String link = userAccount.get("link").toString();
            Key usulanCalonKey = KeyFactory.createKey("dept", dept);
            Date date = new Date();
            Entity usulanCalon = new Entity("usulanCalon", usulanCalonKey);
            usulanCalon.setProperty("user", id);
            usulanCalon.setProperty("name", name);
            usulanCalon.setProperty("email", email);
            usulanCalon.setProperty("link", link);
            usulanCalon.setProperty("date", date);
            usulanCalon.setProperty("usulan", usulan);
            DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
            usulanCalon.setProperty("imported", "N");
            datastore.put(usulanCalon);
            record.put("status", "OK");
        } catch (Exception e) {
            record.put("status", "error");
            record.put("errormsg", e.toString());
        }
        response.setContentType("text/html;charset=UTF-8");
        out.print(JSONValue.toJSONString(record));
        out.flush();
    }

    if (form_action.equalsIgnoreCase("getSet1")) {
        StringBuffer sb = new StringBuffer();
        String line = null;
        LinkedHashMap record = new LinkedHashMap();
        try {
            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            Object obj = JSONValue.parse(sb.toString());
            //JSONArray records = (JSONArray) obj;
            JSONObject obj1 = (JSONObject) obj;
            String input = obj1.get("input").toString();
            String type = obj1.get("type").toString();
            DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
            Key typeKey = KeyFactory.createKey("posisi", type.toLowerCase().replaceAll(" ", ""));
            // Run an ancestor query to ensure we see the most up-to-date
            // view of the Greetings belonging to the selected Guestbook.
            Query query = new Query("posisi", typeKey).addSort("date", Query.SortDirection.ASCENDING);
            //List<Entity> AlasanStars = datastore.prepare(query);
            PreparedQuery pq = datastore.prepare(query);
            JSONArray obj11 = new JSONArray();
            String id = "";
            try {
                JSONObject userAccount = (JSONObject) session.getAttribute("userAccount");
                id = userAccount.get("id").toString();
            } catch (Exception ex1) {
            }
            for (Entity typeEntity : pq.asIterable()) {
                String reviewed = typeEntity.getProperty("reviewed").toString();
                if (reviewed.equalsIgnoreCase("Y")) {
                    LinkedHashMap record1 = new LinkedHashMap();
                    String posisi = typeEntity.getProperty("posisi").toString();
                    String nama = typeEntity.getProperty("nama").toString();
                    String link = typeEntity.getProperty("link").toString();
                    String date = typeEntity.getProperty("date").toString();
                    record1.put("posisi", posisi);
                    record1.put("nama", nama);
                    record1.put("link", link);
                    record1.put("date", date);
                    String detail1 = "";
                    try {
                        Text detail0 = (Text) typeEntity.getProperty("detail");
                        detail1 = detail0.getValue();
                    } catch (Exception e) {
                        detail1 = "";
                    }
                    record1.put("detail", detail1);
                    obj11.add(record1);
                } else {
                    String user = typeEntity.getProperty("user").toString();
                    if (user.equalsIgnoreCase(id)) {
                        LinkedHashMap record1 = new LinkedHashMap();
                        String posisi = typeEntity.getProperty("posisi").toString();
                        String nama = typeEntity.getProperty("nama").toString();
                        String link = typeEntity.getProperty("link").toString();
                        String date = typeEntity.getProperty("date").toString();
                        record1.put("posisi", posisi);
                        record1.put("nama", nama);
                        record1.put("link", link);
                        record1.put("date", date);
                        String detail1 = "";
                        try {
                            Text detail0 = (Text) typeEntity.getProperty("detail");
                            detail1 = detail0.getValue();
                        } catch (Exception e) {
                            detail1 = "";
                        }
                        record1.put("detail", detail1);
                        obj11.add(record1);
                    }
                }
            }
            record.put("records", obj11);
            record.put("status", "OK");
        } catch (Exception e) {
            record.put("status", "error");
            record.put("errormsg", e.toString());
        }
        response.setContentType("text/html;charset=UTF-8");
        out.print(JSONValue.toJSONString(record));
        out.flush();
    }
    if (form_action.equalsIgnoreCase("setSet1")) {
        StringBuffer sb = new StringBuffer();
        String line = null;
        LinkedHashMap record = new LinkedHashMap();
        try {

            JSONObject userAccount = (JSONObject) session.getAttribute("userAccount");
            String id = userAccount.get("id").toString();
            String nama = userAccount.get("name").toString();
            String email = userAccount.get("email").toString();
            String link = userAccount.get("link").toString();
            String admin = userAccount.get("admin").toString();

            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            Object obj = JSONValue.parse(sb.toString());
            //JSONArray records = (JSONArray) obj;
            JSONObject obj1 = (JSONObject) obj;
            String input = obj1.get("input").toString();
            String type = obj1.get("type").toString();
            String value = obj1.get("value").toString();
            String detail = obj1.get("value1").toString();
            Key typeKey = KeyFactory.createKey("posisi", type.toLowerCase().replaceAll(" ", ""));
            Filter posisinama = new FilterPredicate("posisi", FilterOperator.EQUAL, value);
            // Run an ancestor query to ensure we see the most up-to-date
            // view of the Greetings belonging to the selected Guestbook.
            Query query = new Query("posisi", typeKey).setFilter(posisinama);
            //Query query = new Query("posisi", typeKey);//.addSort("date", Query.SortDirection.DESCENDING);
            //List<Entity> AlasanStars = datastore.prepare(query);
            DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
            PreparedQuery pq = datastore.prepare(query);
            boolean found = pq.asIterable().iterator().hasNext();

            if (found) {
                if (admin.equalsIgnoreCase("Y")) {
                    for (Entity psosisiEntity : pq.asList(FetchOptions.Builder.withLimit(1))) {
                        Date date = new Date();
                        psosisiEntity.setProperty("date", date);
                        psosisiEntity.setProperty("detail", new Text(detail));
                        datastore.put(psosisiEntity);
                    }
                }
            }

            if (!found) {
                Date date = new Date();
                Entity psosisiEntity = new Entity("posisi", typeKey);
                psosisiEntity.setProperty("user", id);
                psosisiEntity.setProperty("link", link);
                psosisiEntity.setProperty("nama", nama);
                psosisiEntity.setProperty("email", email);
                psosisiEntity.setProperty("date", date);
                psosisiEntity.setProperty("posisi", value);
                psosisiEntity.setProperty("detail", new Text(detail));
                if (email.equalsIgnoreCase("khairul.anshar@gmail.com")
                        || id.equalsIgnoreCase("112525777678499279265")
                        || id.equalsIgnoreCase("10152397276159760") || nama.equalsIgnoreCase("Khairul Anshar")
                        || admin.equalsIgnoreCase("Y")) {
                    psosisiEntity.setProperty("reviewed", "Y");
                    psosisiEntity.setProperty("nama", "Kawal Menteri");
                    psosisiEntity.setProperty("link", "https://www.facebook.com/KawalMenteri");
                } else {
                    psosisiEntity.setProperty("reviewed", "N");
                }
                psosisiEntity.setProperty("imported", "N");
                datastore.put(psosisiEntity);
            }

            query = new Query("posisi", typeKey).addSort("date", Query.SortDirection.ASCENDING);
            pq = datastore.prepare(query);
            JSONArray obj11 = new JSONArray();

            for (Entity typeEntity : pq.asIterable()) {
                String reviewed = typeEntity.getProperty("reviewed").toString();
                if (reviewed.equalsIgnoreCase("Y")) {
                    LinkedHashMap record1 = new LinkedHashMap();
                    String posisi = typeEntity.getProperty("posisi").toString();
                    String nama1 = typeEntity.getProperty("nama").toString();
                    String link1 = typeEntity.getProperty("link").toString();
                    String date = typeEntity.getProperty("date").toString();
                    record1.put("posisi", posisi);
                    record1.put("nama", nama1);
                    record1.put("link", link1);
                    record1.put("date", date);
                    String detail1 = "";
                    try {
                        Text detail0 = (Text) typeEntity.getProperty("detail");
                        detail1 = detail0.getValue();
                    } catch (Exception e) {
                        detail1 = "";
                    }
                    record1.put("detail", detail1);
                    obj11.add(record1);
                } else {
                    String user = typeEntity.getProperty("user").toString();
                    if (user.equalsIgnoreCase(id) || (email.equalsIgnoreCase("khairul.anshar@gmail.com")
                            || id.equalsIgnoreCase("112525777678499279265")
                            || id.equalsIgnoreCase("10152397276159760")
                            || nama.equalsIgnoreCase("Khairul Anshar") || admin.equalsIgnoreCase("Y"))) {
                        LinkedHashMap record1 = new LinkedHashMap();
                        String posisi = typeEntity.getProperty("posisi").toString();
                        String nama1 = typeEntity.getProperty("nama").toString();
                        String link1 = typeEntity.getProperty("link").toString();
                        String date = typeEntity.getProperty("date").toString();
                        record1.put("posisi", posisi);
                        record1.put("nama", nama1);
                        record1.put("link", link1);
                        record1.put("date", date);
                        String detail1 = "";
                        try {
                            Text detail0 = (Text) typeEntity.getProperty("detail");
                            detail1 = detail0.getValue();
                        } catch (Exception e) {
                            detail1 = "";
                        }
                        record1.put("detail", detail1);
                        obj11.add(record1);
                    }
                }
            }

            record.put("records", obj11);
            record.put("status", "OK");
        } catch (Exception e) {
            record.put("status", "error");
            record.put("errormsg", e.toString());
        }
        response.setContentType("text/html;charset=UTF-8");
        out.print(JSONValue.toJSONString(record));
        out.flush();
    }

    if (form_action.equalsIgnoreCase("getSet2")) {
        StringBuffer sb = new StringBuffer();
        String line = null;
        LinkedHashMap record = new LinkedHashMap();
        try {
            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            Object obj = JSONValue.parse(sb.toString());
            //JSONArray records = (JSONArray) obj;
            JSONObject obj1 = (JSONObject) obj;
            String input = obj1.get("input").toString();
            String input0 = obj1.get("input0").toString();
            String type0 = obj1.get("type0").toString();
            DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
            Key typeKey = KeyFactory.createKey("kandidat" + type0, input);
            // Run an ancestor query to ensure we see the most up-to-date
            // view of the Greetings belonging to the selected Guestbook.
            Query query = new Query("kandidat", typeKey).addSort("date", Query.SortDirection.ASCENDING);
            //List<Entity> AlasanStars = datastore.prepare(query);
            PreparedQuery pq = datastore.prepare(query);
            JSONArray obj11 = new JSONArray();
            String id = "";
            String nama = "";
            String email = "";
            String link = "";
            String admin = "";
            String icw = "";
            try {
                JSONObject userAccount = (JSONObject) session.getAttribute("userAccount");
                id = userAccount.get("id").toString();
                nama = userAccount.get("name").toString();
                email = userAccount.get("email").toString();
                link = userAccount.get("link").toString();
                admin = userAccount.get("admin").toString();
                icw = userAccount.get("icw").toString();
            } catch (Exception ex1) {
            }
            for (Entity typeEntity : pq.asIterable()) {
                String reviewed = typeEntity.getProperty("reviewed").toString();
                if (reviewed.equalsIgnoreCase("Y")) {
                    LinkedHashMap record1 = new LinkedHashMap();
                    String kandidat = typeEntity.getProperty("kandidat").toString();
                    String desc = typeEntity.getProperty("desc").toString();
                    Text detail0 = (Text) typeEntity.getProperty("detail");
                    String detail = detail0.getValue();
                    String nama1 = typeEntity.getProperty("nama").toString();
                    String link1 = typeEntity.getProperty("link").toString();
                    String date = typeEntity.getProperty("date").toString();
                    String icwcomment = "";
                    try {
                        icwcomment = typeEntity.getProperty("icwcomment").toString();
                    } catch (Exception e) {
                        icwcomment = "";
                    }
                    record1.put("key", "kandidat" + type0);
                    record1.put("val", input);
                    record1.put("kandidat", kandidat);
                    record1.put("desc", desc);
                    record1.put("detail", detail);
                    record1.put("nama", nama1);
                    record1.put("link", link1);
                    record1.put("date", date);
                    record1.put("icwcomment", icwcomment);
                    obj11.add(record1);
                } else {
                    String user = typeEntity.getProperty("user").toString();
                    if (user.equalsIgnoreCase(id) || (email.equalsIgnoreCase("khairul.anshar@gmail.com")
                            || id.equalsIgnoreCase("112525777678499279265")
                            || id.equalsIgnoreCase("10152397276159760")
                            || nama.equalsIgnoreCase("Khairul Anshar") || admin.equalsIgnoreCase("Y"))) {
                        LinkedHashMap record1 = new LinkedHashMap();
                        String kandidat = typeEntity.getProperty("kandidat").toString();
                        String desc = typeEntity.getProperty("desc").toString();
                        Text detail0 = (Text) typeEntity.getProperty("detail");
                        String detail = detail0.getValue();
                        String nama1 = typeEntity.getProperty("nama").toString();
                        String link1 = typeEntity.getProperty("link").toString();
                        String date = typeEntity.getProperty("date").toString();
                        record1.put("key", "kandidat" + type0);
                        record1.put("val", input);
                        record1.put("kandidat", kandidat);
                        record1.put("desc", desc);
                        record1.put("detail", detail);
                        record1.put("nama", nama1);
                        record1.put("link", link1);
                        record1.put("date", date);
                        String icwcomment = "";

                        if (email.equalsIgnoreCase("khairul.anshar@gmail.com")
                                || id.equalsIgnoreCase("112525777678499279265")
                                || id.equalsIgnoreCase("10152397276159760")
                                || nama.equalsIgnoreCase("Khairul Anshar") || admin.equalsIgnoreCase("Y")
                                || icw.equalsIgnoreCase("Y")) {
                            try {
                                icwcomment = typeEntity.getProperty("icwcomment").toString();
                            } catch (Exception e) {
                                icwcomment = "";
                            }
                        }
                        record1.put("icwcomment", icwcomment);
                        obj11.add(record1);
                    }
                }
            }
            record.put("records", obj11);
            record.put("status", "OK");
        } catch (Exception e) {
            record.put("status", "error");
            record.put("errormsg", e.toString());
        }
        response.setContentType("text/html;charset=UTF-8");
        out.print(JSONValue.toJSONString(record));
        out.flush();
    }
    if (form_action.equalsIgnoreCase("setIcwComment")) {
        StringBuffer sb = new StringBuffer();
        String line = null;
        LinkedHashMap record = new LinkedHashMap();
        try {
            JSONObject userAccount = (JSONObject) session.getAttribute("userAccount");
            String icw = userAccount.get("icw").toString();
            if (icw.equalsIgnoreCase("N")) {

            } else {
                BufferedReader reader = request.getReader();
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
                Object obj = JSONValue.parse(sb.toString());
                //JSONArray records = (JSONArray) obj;
                JSONObject obj1 = (JSONObject) obj;

                String input = obj1.get("input").toString();
                String input0 = obj1.get("input0").toString();
                String type0 = obj1.get("type0").toString();
                String value = obj1.get("value").toString();
                String menteri = obj1.get("menteri").toString();
                String kandidat = obj1.get("kandidat").toString();
                Key typeKey = KeyFactory.createKey("kandidat" + type0, input);
                // Run an ancestor query to ensure we see the most up-to-date
                // view of the Greetings belonging to the selected Guestbook.

                Filter namaKandidat = new FilterPredicate("kandidat", FilterOperator.EQUAL, kandidat);
                // Run an ancestor query to ensure we see the most up-to-date
                // view of the Greetings belonging to the selected Guestbook.
                Query query = new Query("kandidat", typeKey).setFilter(namaKandidat);
                //Query query = new Query("posisi", typeKey);//.addSort("date", Query.SortDirection.DESCENDING);
                //List<Entity> AlasanStars = datastore.prepare(query);
                DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

                for (Entity psosisiEntity : datastore.prepare(query)
                        .asList(FetchOptions.Builder.withLimit(1))) {
                    psosisiEntity.setProperty("icwcomment", value);
                    datastore.put(psosisiEntity);
                }

            }
            record.put("status", "OK");
        } catch (Exception e) {
            record.put("status", "error");
            record.put("errormsg", e.toString());
        }
        response.setContentType("text/html;charset=UTF-8");
        out.print(JSONValue.toJSONString(record));
        out.flush();
    }
    if (form_action.equalsIgnoreCase("setSet2")) {
        StringBuffer sb = new StringBuffer();
        String line = null;
        LinkedHashMap record = new LinkedHashMap();
        try {
            JSONObject userAccount = (JSONObject) session.getAttribute("userAccount");
            String id = userAccount.get("id").toString();
            String nama = userAccount.get("name").toString();
            String email = userAccount.get("email").toString();
            String link = userAccount.get("link").toString();
            String admin = userAccount.get("admin").toString();
            String icw = userAccount.get("icw").toString();

            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            Object obj = JSONValue.parse(sb.toString());
            //JSONArray records = (JSONArray) obj;
            JSONObject obj1 = (JSONObject) obj;

            String input = obj1.get("input").toString();
            String input0 = obj1.get("input0").toString();
            String type0 = obj1.get("type0").toString();
            String value = obj1.get("value").toString();
            String value1 = obj1.get("value1").toString();
            String value2 = obj1.get("value2").toString();
            String menteri = obj1.get("menteri").toString();
            Key typeKey = KeyFactory.createKey("kandidat" + type0, input);
            // Run an ancestor query to ensure we see the most up-to-date
            // view of the Greetings belonging to the selected Guestbook.

            Filter namaKandidat = new FilterPredicate("kandidat", FilterOperator.EQUAL, value);
            // Run an ancestor query to ensure we see the most up-to-date
            // view of the Greetings belonging to the selected Guestbook.
            Query query = new Query("kandidat", typeKey).setFilter(namaKandidat);
            //Query query = new Query("posisi", typeKey);//.addSort("date", Query.SortDirection.DESCENDING);
            //List<Entity> AlasanStars = datastore.prepare(query);
            DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
            PreparedQuery pq = datastore.prepare(query);
            boolean found = pq.asIterable().iterator().hasNext();

            if (found) {
                if (admin.equalsIgnoreCase("Y")) {
                    for (Entity psosisiEntity : pq.asList(FetchOptions.Builder.withLimit(1))) {
                        Date date = new Date();
                        psosisiEntity.setProperty("date", date);
                        psosisiEntity.setProperty("detail", new Text(value2));
                        datastore.put(psosisiEntity);
                    }
                }
            }

            if (!found) {

                Date date = new Date();
                Entity psosisiEntity = new Entity("kandidat", typeKey);
                psosisiEntity.setProperty("user", id);
                psosisiEntity.setProperty("link", link);
                psosisiEntity.setProperty("nama", nama);
                psosisiEntity.setProperty("email", email);
                psosisiEntity.setProperty("date", date);
                psosisiEntity.setProperty("kandidat", value);
                psosisiEntity.setProperty("desc", value1);
                psosisiEntity.setProperty("posisi", menteri);
                psosisiEntity.setProperty("detail", new Text(value2));
                psosisiEntity.setProperty("icwcomment", "");

                if (email.equalsIgnoreCase("khairul.anshar@gmail.com")
                        || id.equalsIgnoreCase("112525777678499279265")
                        || id.equalsIgnoreCase("10152397276159760") || nama.equalsIgnoreCase("Khairul Anshar")
                        || admin.equalsIgnoreCase("Y")) {
                    psosisiEntity.setProperty("reviewed", "Y");
                    psosisiEntity.setProperty("nama", "Kawal Menteri");
                    psosisiEntity.setProperty("link", "https://www.facebook.com/KawalMenteri");
                } else {
                    psosisiEntity.setProperty("reviewed", "N");
                }
                psosisiEntity.setProperty("imported", "N");
                datastore.put(psosisiEntity);
            }

            query = new Query("kandidat", typeKey).addSort("date", Query.SortDirection.ASCENDING);
            pq = datastore.prepare(query);
            JSONArray obj11 = new JSONArray();

            for (Entity typeEntity : pq.asIterable()) {
                String reviewed = typeEntity.getProperty("reviewed").toString();
                if (reviewed.equalsIgnoreCase("Y")) {
                    LinkedHashMap record1 = new LinkedHashMap();
                    String kandidat = typeEntity.getProperty("kandidat").toString();
                    String desc = typeEntity.getProperty("desc").toString();
                    Text detail0 = (Text) typeEntity.getProperty("detail");
                    String detail = detail0.getValue();
                    String nama1 = typeEntity.getProperty("nama").toString();
                    String link1 = typeEntity.getProperty("link").toString();
                    String date = typeEntity.getProperty("date").toString();
                    String icwcomment = "";
                    try {
                        icwcomment = typeEntity.getProperty("icwcomment").toString();
                    } catch (Exception e) {
                        icwcomment = "";
                    }
                    record1.put("key", "kandidat" + type0);
                    record1.put("val", input);
                    record1.put("kandidat", kandidat);
                    record1.put("desc", desc);
                    record1.put("detail", detail);
                    record1.put("nama", nama1);
                    record1.put("link", link1);
                    record1.put("date", date);
                    record1.put("icwcomment", icwcomment);
                    obj11.add(record1);
                } else {
                    String user = typeEntity.getProperty("user").toString();
                    if (user.equalsIgnoreCase(id) || (email.equalsIgnoreCase("khairul.anshar@gmail.com")
                            || id.equalsIgnoreCase("112525777678499279265")
                            || id.equalsIgnoreCase("10152397276159760")
                            || nama.equalsIgnoreCase("Khairul Anshar") || admin.equalsIgnoreCase("Y"))) {
                        LinkedHashMap record1 = new LinkedHashMap();
                        String kandidat = typeEntity.getProperty("kandidat").toString();
                        String desc = typeEntity.getProperty("desc").toString();
                        Text detail0 = (Text) typeEntity.getProperty("detail");
                        String detail = detail0.getValue();
                        String nama1 = typeEntity.getProperty("nama").toString();
                        String link1 = typeEntity.getProperty("link").toString();
                        String date = typeEntity.getProperty("date").toString();
                        record1.put("key", "kandidat" + type0);
                        record1.put("val", input);
                        record1.put("kandidat", kandidat);
                        record1.put("desc", desc);
                        record1.put("detail", detail);
                        record1.put("nama", nama1);
                        record1.put("link", link1);
                        record1.put("date", date);
                        String icwcomment = "";

                        if (email.equalsIgnoreCase("khairul.anshar@gmail.com")
                                || id.equalsIgnoreCase("112525777678499279265")
                                || id.equalsIgnoreCase("10152397276159760")
                                || nama.equalsIgnoreCase("Khairul Anshar") || admin.equalsIgnoreCase("Y")
                                || icw.equalsIgnoreCase("Y")) {
                            try {
                                icwcomment = typeEntity.getProperty("icwcomment").toString();
                            } catch (Exception e) {
                                icwcomment = "";
                            }
                        }
                        record1.put("icwcomment", icwcomment);
                        obj11.add(record1);
                    }
                }
            }

            record.put("records", obj11);
            record.put("status", "OK");
        } catch (Exception e) {
            record.put("status", "error");
            record.put("errormsg", e.toString());
        }
        response.setContentType("text/html;charset=UTF-8");
        out.print(JSONValue.toJSONString(record));
        out.flush();
    }
}