Example usage for javax.servlet.http HttpServletRequest getReader

List of usage examples for javax.servlet.http HttpServletRequest getReader

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getReader.

Prototype

public BufferedReader getReader() throws IOException;

Source Link

Document

Retrieves the body of the request as character data using a BufferedReader.

Usage

From source file:servlets.Samples_servlets.java

private void update_biocondition_handler(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {//  w  w  w  . ja  v a2 s  .  com
        ArrayList<String> BLOCKED_IDs = new ArrayList<String>();
        boolean ROLLBACK_NEEDED = false;
        DAO dao_instance = null;

        try {

            /**
             * *******************************************************
             * STEP 1 CHECK IF THE USER IS LOGGED CORRECTLY IN THE APP. IF
             * ERROR --> throws exception if not valid session, GO TO STEP
             * 6b ELSE --> GO TO STEP 2
             * *******************************************************
             */
            JsonParser parser = new JsonParser();
            JsonObject requestData = (JsonObject) parser.parse(request.getReader());

            String loggedUser = requestData.get("loggedUser").getAsString();
            String loggedUserID = requestData.get("loggedUserID").getAsString();
            String sessionToken = requestData.get("sessionToken").getAsString();

            if (!checkAccessPermissions(loggedUser, sessionToken)) {
                throw new AccessControlException("Your session is invalid. User or session token not allowed.");
            }

            /**
             * *******************************************************
             * STEP 3 Get the Object by parsing the JSON data. IF ERROR -->
             * throws JsonParseException, GO TO STEP 6b ELSE --> GO TO STEP
             * 4 *******************************************************
             */
            BioCondition biocondition = BioCondition.fromJSON(requestData.get("biocondition_json_data"));

            dao_instance = DAOProvider.getDAOByName("BioCondition");
            //CHECK IF CURRENT USER IS A VALID OWNER (AVOID HACKING)
            boolean loadRecursive = false;
            BioCondition bioconditionAux = (BioCondition) dao_instance
                    .findByID(biocondition.getBioConditionID(), new Object[] { loadRecursive });
            if (!bioconditionAux.isOwner(loggedUserID) && !loggedUserID.equals("admin")) {
                throw new AccessControlException(
                        "Cannot update selected Biological Condition. Current user has not privileges over this Biological Condition.");
            }

            /**
             * *******************************************************
             * STEP 4 READ ALL BIOREPLICATES AND AS AND CREATE THE LIST OF
             * TASKS.
             * *******************************************************
             */
            Bioreplicate_JDBCDAO bioreplicateDAO = (Bioreplicate_JDBCDAO) (DAOProvider
                    .getDAOByName("Bioreplicate"));
            AnalyticalReplicate_JDBCDAO analyticalSampleDAO = (AnalyticalReplicate_JDBCDAO) (DAOProvider
                    .getDAOByName("AnalyticalReplicate"));

            ArrayList<Bioreplicate> to_be_created_BR = new ArrayList<Bioreplicate>();
            ArrayList<Bioreplicate> to_be_updated_BR = new ArrayList<Bioreplicate>();
            ArrayList<String> to_be_deleted_BR = new ArrayList<String>();

            ArrayList<AnalyticalReplicate> to_be_created_AS = new ArrayList<AnalyticalReplicate>();
            ArrayList<AnalyticalReplicate> to_be_updated_AS = new ArrayList<AnalyticalReplicate>();
            ArrayList<String> to_be_deleted_AS = new ArrayList<String>();

            for (Bioreplicate bioreplicate : biocondition.getAssociatedBioreplicates()) {
                if ("new_deleted".equals(bioreplicate.getStatus())) {
                    continue; //ignore
                } else if ("deleted".equals(bioreplicate.getStatus())
                        || "edited_deleted".equals(bioreplicate.getStatus())) {
                    to_be_deleted_BR.add(bioreplicate.getBioreplicateID()); //DELETES THE AS
                } else if ("new".equals(bioreplicate.getStatus())) {
                    Object[] params = { biocondition.getBioConditionID() };
                    String nextID = bioreplicateDAO.getNextObjectID(params);
                    BLOCKED_IDs.add(nextID);
                    bioreplicate.setBioreplicate_id(nextID);
                    bioreplicate.setBioConditionID(biocondition.getBioConditionID());
                    to_be_created_BR.add(bioreplicate); //CREATES THE AS
                } else {
                    if ("edited".equals(bioreplicate.getStatus())) {
                        to_be_updated_BR.add(bioreplicate);
                    }
                    for (AnalyticalReplicate analyticalReplicate : bioreplicate
                            .getAssociatedAnalyticalReplicates()) {
                        if ("new_deleted".equals(analyticalReplicate.getStatus())) {
                            continue; //ignore
                        } else if ("deleted".equals(analyticalReplicate.getStatus())
                                || "edited_deleted".equals(analyticalReplicate.getStatus())) {
                            to_be_deleted_AS.add(analyticalReplicate.getAnalytical_rep_id());
                        } else if ("new".equals(analyticalReplicate.getStatus())) {
                            Object[] params = { bioreplicate.getBioreplicateID() };
                            String nextID = analyticalSampleDAO.getNextObjectID(params);
                            BLOCKED_IDs.add(nextID);
                            analyticalReplicate.setAnalyticalReplicateID(nextID);
                            analyticalReplicate.setBioreplicateID(bioreplicate.getBioreplicateID());
                            to_be_created_AS.add(analyticalReplicate); //CREATES THE AS
                        } else if ("edited".equals(analyticalReplicate.getStatus())) {
                            to_be_updated_AS.add(analyticalReplicate);
                        }
                    }
                }
            }

            /**
             * *******************************************************
             * STEP 5 UPDATE THE BIOCONDITION IN DATABASE. IF ERROR -->
             * throws SQL Exception, GO TO STEP ? ELSE --> GO TO STEP 5
             * *******************************************************
             */
            dao_instance.disableAutocommit();
            ROLLBACK_NEEDED = true;
            dao_instance.update(biocondition);

            /**
             * *******************************************************
             * STEP 6 APPLY THE BIOREPLICATE TASKS IN DATABASE. IF ERROR -->
             * throws SQL Exception, GO TO STEP ? ELSE --> GO TO STEP 8
             * *******************************************************
             */
            bioreplicateDAO.insert(to_be_created_BR.toArray(new Bioreplicate[] {}));
            bioreplicateDAO.update(to_be_updated_BR.toArray(new Bioreplicate[] {}));
            bioreplicateDAO.remove(to_be_deleted_BR.toArray(new String[] {}));

            /**
             * *******************************************************
             * STEP 7 APPLY THE ANALYTICAL REP TASKS IN DATABASE. IF ERROR
             * --> throws SQL Exception, GO TO STEP ? ELSE --> GO TO STEP 9
             * *******************************************************
             */
            analyticalSampleDAO.insert(to_be_created_AS.toArray(new AnalyticalReplicate[] {}));
            analyticalSampleDAO.update(to_be_updated_AS.toArray(new AnalyticalReplicate[] {}));
            analyticalSampleDAO.remove(to_be_deleted_AS.toArray(new String[] {}));

            /**
             * *******************************************************
             * STEP 9 COMMIT CHANGES TO DATABASE. throws SQLException IF
             * ERROR --> throws SQL Exception, GO TO STEP ? ELSE --> GO TO
             * STEP 10
             * *******************************************************
             */
            dao_instance.doCommit();

        } catch (Exception e) {
            if (e.getClass().getSimpleName().equals("MySQLIntegrityConstraintViolationException")) {
                ServerErrorManager.handleException(null, null, null,
                        "Unable to update the Biological condition information.</br>One or more Analysis are associated with at least a deleted element.</br>Remove or Edit first those Analysis or change the associated Analytical sample and try again later.");
            } else {
                ServerErrorManager.handleException(e, Samples_servlets.class.getName(),
                        "update_biocondition_handler", e.getMessage());
            }
        } finally {
            /**
             * *******************************************************
             * STEP 9b CATCH ERROR, CLEAN CHANGES. throws SQLException
             * *******************************************************
             */
            if (ServerErrorManager.errorStatus()) {
                response.setStatus(400);
                response.getWriter().print(ServerErrorManager.getErrorResponse());

                if (ROLLBACK_NEEDED) {
                    dao_instance.doRollback();
                }
            } else {
                JsonObject obj = new JsonObject();
                obj.add("success", new JsonPrimitive(true));
                response.getWriter().print(obj.toString());
            }

            for (String BLOCKED_ID : BLOCKED_IDs) {
                BlockedElementsManager.getBlockedElementsManager().unlockID(BLOCKED_ID);
            }
            /**
             * *******************************************************
             * STEP 11 Close connection.
             * ********************************************************
             */
            if (dao_instance != null) {
                dao_instance.closeConnection();
            }
        }
        //CATCH IF THE ERROR OCCURRED IN ROLL BACK OR CONNECTION CLOSE 
    } catch (Exception e) {
        ServerErrorManager.handleException(e, Samples_servlets.class.getName(), "update_biocondition_handler",
                e.getMessage());
        response.setStatus(400);
        response.getWriter().print(ServerErrorManager.getErrorResponse());
    }
}

From source file:action.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  w w w . ja  va  2 s .  com
 *
 * @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();
    }
}

From source file:de.tu_dortmund.ub.api.paaa.PaaaEndpoint.java

/**
 * PAAA services/*  ww w  . j  a v a  2  s.c  om*/
 */
private void provideService(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
        String format, String patronid, String token, String service) throws IOException {

    String baseurl = httpServletRequest.getServerName() + ":" + httpServletRequest.getServerPort();
    this.logger.info("[" + config.getProperty("service.name") + "] " + "baseurl = " + baseurl);

    ObjectMapper mapper = new ObjectMapper();

    if (Lookup.lookupAll(IntegratedLibrarySystem.class).size() > 0) {

        try {
            IntegratedLibrarySystem integratedLibrarySystem = Lookup.lookup(IntegratedLibrarySystem.class);
            // init ILS
            integratedLibrarySystem.init(this.config);

            switch (service) {

            case "signup": {

                Patron patron = null;

                // read Patron
                StringBuffer jb = new StringBuffer();
                String line = null;
                try {
                    BufferedReader reader = httpServletRequest.getReader();
                    while ((line = reader.readLine()) != null)
                        jb.append(line);
                } catch (Exception e) {
                    /*report an error*/ }

                Patron patron2create = mapper.readValue(jb.toString(), Patron.class);
                if (patron2create.getAccount() == null || patron2create.getAccount().equals("")) {
                    if (!patronid.equals("")) {
                        patron2create.setAccount(patronid);
                    } else {
                        patron2create.setAccount(UUID.randomUUID().toString());
                    }
                }

                patron = integratedLibrarySystem.signup(patron2create);

                this.logger.info("[" + config.getProperty("service.name") + "] " + token + " performed '"
                        + service + "' event for patron '" + patronid + "' >>> success!");

                if (patron != null) {

                    Block block = new Block();
                    LocalDateTime timePoint = LocalDateTime.now();
                    block.setDate(timePoint.getYear() + "-"
                            + (timePoint.getMonthValue() < 10 ? "0" + timePoint.getMonthValue()
                                    : timePoint.getMonthValue())
                            + "-" + (timePoint.getDayOfMonth() < 10 ? "0" + timePoint.getDayOfMonth()
                                    : timePoint.getDayOfMonth()));
                    block.setKey("93");
                    integratedLibrarySystem.blockpatron(patron, block);

                    StringWriter json = new StringWriter();
                    mapper.writeValue(json, patron);
                    this.logger.debug("[" + config.getProperty("service.name") + "] " + json);

                    // If request contains parameter 'redirect_uri', then redirect mit access_token and patronid
                    if (httpServletRequest.getParameter("redirect_uri") != null) {
                        this.logger.debug("[" + config.getProperty("service.name") + "] " + "REDIRECT? "
                                + httpServletRequest.getParameter("redirect_uri"));

                        httpServletResponse.sendRedirect(httpServletRequest.getParameter("redirect_uri")
                                + "&patron=" + patronid + "&token=" + token);
                    } else {
                        httpServletResponse.setContentType("application/json");
                        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

                        httpServletResponse.getWriter().println(json);
                    }
                } else {
                    this.logger.error("[" + config.getProperty("service.name") + "] "
                            + HttpServletResponse.SC_SERVICE_UNAVAILABLE + ": ILS!");

                    httpServletResponse.setHeader("WWW-Authentificate", "Bearer");
                    httpServletResponse.setHeader("WWW-Authentificate", "Bearer realm=\"PAAA\"");
                    httpServletResponse.setContentType("application/json");
                    httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

                    // Error handling mit suppress_response_codes=true
                    if (httpServletRequest.getParameter("suppress_response_codes") != null) {
                        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                    }
                    // Error handling mit suppress_response_codes=false (=default)
                    else {
                        httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                    }

                    // Json fr Response body
                    RequestError requestError = new RequestError();
                    requestError.setError(this.config.getProperty(
                            "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE)));
                    requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                    requestError.setDescription(this.config.getProperty("error."
                            + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description"));
                    requestError.setErrorUri(this.config.getProperty(
                            "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri"));

                    StringWriter json = new StringWriter();
                    mapper.writeValue(json, requestError);
                    this.logger.debug("[" + config.getProperty("service.name") + "] " + json);

                    // send response
                    httpServletResponse.getWriter().println(json);
                }

                break;
            }
            case "newpatron": {

                Patron patron = null;

                // read Patron
                StringBuffer jb = new StringBuffer();
                String line = null;
                try {
                    BufferedReader reader = httpServletRequest.getReader();
                    while ((line = reader.readLine()) != null)
                        jb.append(line);
                } catch (Exception e) {
                    /*report an error*/ }

                Patron patron2create = mapper.readValue(jb.toString(), Patron.class);
                patron2create.setAccount(patronid);

                patron = integratedLibrarySystem.newpatron(patron2create);

                this.logger.info("[" + config.getProperty("service.name") + "] " + token + " performed '"
                        + service + "' event for patron '" + patronid + "' >>> success!");

                if (patron != null) {

                    StringWriter json = new StringWriter();
                    mapper.writeValue(json, patron);
                    this.logger.debug("[" + config.getProperty("service.name") + "] " + json);

                    // If request contains parameter 'redirect_uri', then redirect mit access_token and patronid
                    if (httpServletRequest.getParameter("redirect_uri") != null) {
                        this.logger.debug("[" + config.getProperty("service.name") + "] " + "REDIRECT? "
                                + httpServletRequest.getParameter("redirect_uri"));

                        httpServletResponse.sendRedirect(httpServletRequest.getParameter("redirect_uri")
                                + "&patron=" + patronid + "&token=" + token);
                    } else {
                        httpServletResponse.setContentType("application/json");
                        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

                        httpServletResponse.getWriter().println(json);
                    }
                } else {
                    this.logger.error("[" + config.getProperty("service.name") + "] "
                            + HttpServletResponse.SC_SERVICE_UNAVAILABLE + ": ILS!");

                    httpServletResponse.setHeader("WWW-Authentificate", "Bearer");
                    httpServletResponse.setHeader("WWW-Authentificate", "Bearer realm=\"PAAA\"");
                    httpServletResponse.setContentType("application/json");
                    httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

                    // Error handling mit suppress_response_codes=true
                    if (httpServletRequest.getParameter("suppress_response_codes") != null) {
                        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                    }
                    // Error handling mit suppress_response_codes=false (=default)
                    else {
                        httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                    }

                    // Json fr Response body
                    RequestError requestError = new RequestError();
                    requestError.setError(this.config.getProperty(
                            "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE)));
                    requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                    requestError.setDescription(this.config.getProperty("error."
                            + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description"));
                    requestError.setErrorUri(this.config.getProperty(
                            "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri"));

                    StringWriter json = new StringWriter();
                    mapper.writeValue(json, requestError);
                    this.logger.debug("[" + config.getProperty("service.name") + "] " + json);

                    // send response
                    httpServletResponse.getWriter().println(json);
                }

                break;
            }
            case "updatepatron": {

                Patron patron = null;

                // read Patron
                StringBuffer jb = new StringBuffer();
                String line = null;
                try {
                    BufferedReader reader = httpServletRequest.getReader();
                    while ((line = reader.readLine()) != null)
                        jb.append(line);
                } catch (Exception e) {
                    /*report an error*/ }

                Patron patron2update = mapper.readValue(jb.toString(), Patron.class);
                patron2update.setAccount(patronid);

                // TODO Was tun bei nderung des 'status'?

                patron = integratedLibrarySystem.updatepatron(patron2update);

                this.logger.info("[" + config.getProperty("service.name") + "] " + token + " performed '"
                        + service + "' event for patron '" + patronid + "' >>> success!");

                if (patron != null) {

                    StringWriter json = new StringWriter();
                    mapper.writeValue(json, patron);
                    this.logger.debug("[" + config.getProperty("service.name") + "] " + json);

                    // If request contains parameter 'redirect_uri', then redirect mit access_token and patronid
                    if (httpServletRequest.getParameter("redirect_uri") != null) {
                        this.logger.debug("[" + config.getProperty("service.name") + "] " + "REDIRECT? "
                                + httpServletRequest.getParameter("redirect_uri"));

                        httpServletResponse.sendRedirect(httpServletRequest.getParameter("redirect_uri")
                                + "&patron=" + patronid + "&token=" + token);
                    } else {
                        httpServletResponse.setContentType("application/json");
                        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

                        httpServletResponse.getWriter().println(json);
                    }
                } else {
                    this.logger.error("[" + config.getProperty("service.name") + "] "
                            + HttpServletResponse.SC_SERVICE_UNAVAILABLE + ": ILS!");

                    httpServletResponse.setHeader("WWW-Authentificate", "Bearer");
                    httpServletResponse.setHeader("WWW-Authentificate", "Bearer realm=\"PAAA\"");
                    httpServletResponse.setContentType("application/json");
                    httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

                    // Error handling mit suppress_response_codes=true
                    if (httpServletRequest.getParameter("suppress_response_codes") != null) {
                        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                    }
                    // Error handling mit suppress_response_codes=false (=default)
                    else {
                        httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                    }

                    // Json fr Response body
                    RequestError requestError = new RequestError();
                    requestError.setError(this.config.getProperty(
                            "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE)));
                    requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                    requestError.setDescription(this.config.getProperty("error."
                            + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description"));
                    requestError.setErrorUri(this.config.getProperty(
                            "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri"));

                    StringWriter json = new StringWriter();
                    mapper.writeValue(json, requestError);
                    this.logger.debug("[" + config.getProperty("service.name") + "] " + json);

                    // send response
                    httpServletResponse.getWriter().println(json);
                }

                break;
            }
            case "blockpatron": {

                Patron patron = null;

                // read Patron
                StringBuffer jb = new StringBuffer();
                String line = null;
                try {
                    BufferedReader reader = httpServletRequest.getReader();
                    while ((line = reader.readLine()) != null)
                        jb.append(line);
                } catch (Exception e) {
                    /*report an error*/ }

                Patron patron2block = new Patron();
                patron2block.setAccount(patronid);
                Block block = mapper.readValue(jb.toString(), Block.class);

                patron = integratedLibrarySystem.blockpatron(patron2block, block);

                this.logger.info("[" + config.getProperty("service.name") + "] " + token + " performed '"
                        + service + "' event for patron '" + patronid + "' >>> success!");

                if (patron != null) {

                    StringWriter json = new StringWriter();
                    mapper.writeValue(json, patron);
                    this.logger.debug("[" + config.getProperty("service.name") + "] " + json);

                    // If request contains parameter 'redirect_uri', then redirect mit access_token and patronid
                    if (httpServletRequest.getParameter("redirect_uri") != null) {
                        this.logger.debug("[" + config.getProperty("service.name") + "] " + "REDIRECT? "
                                + httpServletRequest.getParameter("redirect_uri"));

                        httpServletResponse.sendRedirect(httpServletRequest.getParameter("redirect_uri")
                                + "&patron=" + patronid + "&token=" + token);
                    } else {
                        httpServletResponse.setContentType("application/json");
                        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

                        httpServletResponse.getWriter().println(json);
                    }
                } else {
                    this.logger.error("[" + config.getProperty("service.name") + "] "
                            + HttpServletResponse.SC_SERVICE_UNAVAILABLE + ": ILS!");

                    httpServletResponse.setHeader("WWW-Authentificate", "Bearer");
                    httpServletResponse.setHeader("WWW-Authentificate", "Bearer realm=\"PAAA\"");
                    httpServletResponse.setContentType("application/json");
                    httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

                    // Error handling mit suppress_response_codes=true
                    if (httpServletRequest.getParameter("suppress_response_codes") != null) {
                        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                    }
                    // Error handling mit suppress_response_codes=false (=default)
                    else {
                        httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                    }

                    // Json fr Response body
                    RequestError requestError = new RequestError();
                    requestError.setError(this.config.getProperty(
                            "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE)));
                    requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                    requestError.setDescription(this.config.getProperty("error."
                            + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description"));
                    requestError.setErrorUri(this.config.getProperty(
                            "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri"));

                    StringWriter json = new StringWriter();
                    mapper.writeValue(json, requestError);
                    this.logger.debug("[" + config.getProperty("service.name") + "] " + json);

                    // send response
                    httpServletResponse.getWriter().println(json);
                }

                break;
            }
            case "unblockpatron": {

                Patron patron = null;

                // read Patron
                StringBuffer jb = new StringBuffer();
                String line = null;
                try {
                    BufferedReader reader = httpServletRequest.getReader();
                    while ((line = reader.readLine()) != null)
                        jb.append(line);
                } catch (Exception e) {
                    /*report an error*/ }

                Patron patron2unblock = new Patron();
                patron2unblock.setAccount(patronid);
                Block block = mapper.readValue(jb.toString(), Block.class);

                patron = integratedLibrarySystem.unblockpatron(patron2unblock, block);

                this.logger.info("[" + config.getProperty("service.name") + "] " + token + " performed '"
                        + service + "' event for patron '" + patronid + "' >>> success!");

                if (patron != null) {

                    StringWriter json = new StringWriter();
                    mapper.writeValue(json, patron);
                    this.logger.debug("[" + config.getProperty("service.name") + "] " + json);

                    // If request contains parameter 'redirect_uri', then redirect mit access_token and patronid
                    if (httpServletRequest.getParameter("redirect_uri") != null) {
                        this.logger.debug("[" + config.getProperty("service.name") + "] " + "REDIRECT? "
                                + httpServletRequest.getParameter("redirect_uri"));

                        httpServletResponse.sendRedirect(httpServletRequest.getParameter("redirect_uri")
                                + "&patron=" + patronid + "&token=" + token);
                    } else {
                        httpServletResponse.setContentType("application/json");
                        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

                        httpServletResponse.getWriter().println(json);
                    }
                } else {
                    this.logger.error("[" + config.getProperty("service.name") + "] "
                            + HttpServletResponse.SC_SERVICE_UNAVAILABLE + ": ILS!");

                    httpServletResponse.setHeader("WWW-Authentificate", "Bearer");
                    httpServletResponse.setHeader("WWW-Authentificate", "Bearer realm=\"PAAA\"");
                    httpServletResponse.setContentType("application/json");
                    httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

                    // Error handling mit suppress_response_codes=true
                    if (httpServletRequest.getParameter("suppress_response_codes") != null) {
                        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                    }
                    // Error handling mit suppress_response_codes=false (=default)
                    else {
                        httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                    }

                    // Json fr Response body
                    RequestError requestError = new RequestError();
                    requestError.setError(this.config.getProperty(
                            "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE)));
                    requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                    requestError.setDescription(this.config.getProperty("error."
                            + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description"));
                    requestError.setErrorUri(this.config.getProperty(
                            "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri"));

                    StringWriter json = new StringWriter();
                    mapper.writeValue(json, requestError);
                    this.logger.debug("[" + config.getProperty("service.name") + "] " + json);

                    // send response
                    httpServletResponse.getWriter().println(json);
                }

                break;
            }
            case "deletepatron": {

                Patron patron = null;

                Patron patron2delete = new Patron();
                patron2delete.setAccount(patronid);

                patron = integratedLibrarySystem.deletepatron(patron2delete);

                this.logger.info("[" + config.getProperty("service.name") + "] " + token + " performed '"
                        + service + "' event for patron '" + patronid + "' >>> success!");

                if (patron != null) {

                    StringWriter json = new StringWriter();
                    mapper.writeValue(json, patron);
                    this.logger.debug("[" + config.getProperty("service.name") + "] " + json);

                    // If request contains parameter 'redirect_uri', then redirect mit access_token and patronid
                    if (httpServletRequest.getParameter("redirect_uri") != null) {
                        this.logger.debug("[" + config.getProperty("service.name") + "] " + "REDIRECT? "
                                + httpServletRequest.getParameter("redirect_uri"));

                        httpServletResponse.sendRedirect(httpServletRequest.getParameter("redirect_uri")
                                + "&patron=" + patronid + "&token=" + token);
                    } else {
                        httpServletResponse.setContentType("application/json");
                        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

                        httpServletResponse.getWriter().println(json);
                    }
                } else {
                    this.logger.error("[" + config.getProperty("service.name") + "] "
                            + HttpServletResponse.SC_SERVICE_UNAVAILABLE + ": ILS!");

                    httpServletResponse.setHeader("WWW-Authentificate", "Bearer");
                    httpServletResponse.setHeader("WWW-Authentificate", "Bearer realm=\"PAAA\"");
                    httpServletResponse.setContentType("application/json");
                    httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

                    // Error handling mit suppress_response_codes=true
                    if (httpServletRequest.getParameter("suppress_response_codes") != null) {
                        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                    }
                    // Error handling mit suppress_response_codes=false (=default)
                    else {
                        httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                    }

                    // Json fr Response body
                    RequestError requestError = new RequestError();
                    requestError.setError(this.config.getProperty(
                            "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE)));
                    requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                    requestError.setDescription(this.config.getProperty("error."
                            + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description"));
                    requestError.setErrorUri(this.config.getProperty(
                            "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri"));

                    StringWriter json = new StringWriter();
                    mapper.writeValue(json, requestError);
                    this.logger.debug("[" + config.getProperty("service.name") + "] " + json);

                    // send response
                    httpServletResponse.getWriter().println(json);
                }

                break;
            }
            case "newfee": {

                Patron patron = null;
                Fee resultFee = null;

                patron = new Patron();
                patron.setAccount(patronid);

                // read Fee
                StringBuffer jb = new StringBuffer();
                String line = null;
                try {
                    BufferedReader reader = httpServletRequest.getReader();
                    while ((line = reader.readLine()) != null)
                        jb.append(line);
                } catch (Exception e) {
                    /*report an error*/ }

                this.logger.debug("[" + config.getProperty("service.name") + "] " + "Fee = " + jb);

                Fee fee = mapper.readValue(jb.toString(), Fee.class);

                resultFee = integratedLibrarySystem.newfee(patron, fee);

                this.logger.info("[" + config.getProperty("service.name") + "] " + token + " performed '"
                        + service + "' event for patron '" + patronid + "' >>> success!");
                StringWriter stringWriter = new StringWriter();
                mapper.writeValue(stringWriter, resultFee);
                this.logger.debug(
                        "[" + config.getProperty("service.name") + "] " + "Fee: " + stringWriter.toString());

                if (patron != null) {

                    StringWriter json = new StringWriter();
                    mapper.writeValue(json, resultFee);
                    this.logger.debug(json);

                    // If request contains parameter 'redirect_uri', then redirect mit access_token and patronid
                    if (httpServletRequest.getParameter("redirect_uri") != null) {
                        this.logger.debug("[" + config.getProperty("service.name") + "] " + "REDIRECT? "
                                + httpServletRequest.getParameter("redirect_uri"));

                        httpServletResponse.sendRedirect(httpServletRequest.getParameter("redirect_uri")
                                + "&patron=" + patronid + "&token=" + token);
                    } else {
                        httpServletResponse.setContentType("application/json");
                        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

                        httpServletResponse.getWriter().println(json);
                    }
                } else {
                    this.logger.error("[" + config.getProperty("service.name") + "] "
                            + HttpServletResponse.SC_SERVICE_UNAVAILABLE + ": ILS!");

                    httpServletResponse.setHeader("WWW-Authentificate", "Bearer");
                    httpServletResponse.setHeader("WWW-Authentificate", "Bearer realm=\"PAAA\"");
                    httpServletResponse.setContentType("application/json");
                    httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

                    // Error handling mit suppress_response_codes=true
                    if (httpServletRequest.getParameter("suppress_response_codes") != null) {
                        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                    }
                    // Error handling mit suppress_response_codes=false (=default)
                    else {
                        httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                    }

                    // Json fr Response body
                    RequestError requestError = new RequestError();
                    requestError.setError(this.config.getProperty(
                            "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE)));
                    requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                    requestError.setDescription(this.config.getProperty("error."
                            + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description"));
                    requestError.setErrorUri(this.config.getProperty(
                            "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri"));

                    StringWriter json = new StringWriter();
                    mapper.writeValue(json, requestError);
                    this.logger.debug("[" + config.getProperty("service.name") + "] " + json);

                    // send response
                    httpServletResponse.getWriter().println(json);
                }

                break;
            }
            default: {
                // TODO: keine gltige Funktion
            }
            }
        } catch (ILSException e) {

            this.logger.info("[" + config.getProperty("service.name") + "] " + token + " performed '" + service
                    + "' event for patron '" + patronid + "' >>> failed!");
            this.logger.error("[" + config.getProperty("service.name") + "] "
                    + HttpServletResponse.SC_INTERNAL_SERVER_ERROR + ": ILS Error! " + e.getMessage());

            // TODO e.getMessage = 403
            if (e.getMessage().equals("403")) {

                // TODO >> properties
                httpServletResponse.setHeader("WWW-Authentificate", "Bearer");
                httpServletResponse.setHeader("WWW-Authentificate", "Bearer realm=\"PAAA\"");
                httpServletResponse.setContentType("application/json");
                httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

                // Error handling mit suppress_response_codes=true
                if (httpServletRequest.getParameter("suppress_response_codes") != null) {
                    httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                }
                // Error handling mit suppress_response_codes=false (=default)
                else {
                    httpServletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
                }

                // Json fr Response body
                RequestError requestError = new RequestError();
                requestError.setError(
                        this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_FORBIDDEN)));
                requestError.setCode(HttpServletResponse.SC_FORBIDDEN);
                requestError.setDescription(this.config.getProperty(
                        "error." + Integer.toString(HttpServletResponse.SC_FORBIDDEN) + ".description"));
                requestError.setErrorUri(this.config
                        .getProperty("error." + Integer.toString(HttpServletResponse.SC_FORBIDDEN) + ".uri"));

                StringWriter json = new StringWriter();
                mapper.writeValue(json, requestError);
                this.logger.debug("[" + config.getProperty("service.name") + "] " + json);

                // send response
                httpServletResponse.getWriter().println(json);
            } else {

                // Mail to Bib-IT wg. Socket-Error
                try {

                    StringWriter sw = new StringWriter();
                    PrintWriter pw = new PrintWriter(sw);
                    e.printStackTrace(pw);

                    Mailer mailer = new Mailer(this.config.getProperty("service.mailer.conf"));
                    mailer.postMail(
                            "[" + this.config.getProperty("service.name") + "] ILS Error! " + e.getMessage(),
                            sw.toString());

                } catch (MessagingException | IOException e1) {

                    this.logger.error(e1.getMessage(), e1.getCause());
                }

                // TODO >> properties
                httpServletResponse.setHeader("WWW-Authentificate", "Bearer");
                httpServletResponse.setHeader("WWW-Authentificate", "Bearer realm=\"PAAA\"");
                httpServletResponse.setContentType("application/json");
                httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

                // Error handling mit suppress_response_codes=true
                if (httpServletRequest.getParameter("suppress_response_codes") != null) {
                    httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                }
                // Error handling mit suppress_response_codes=false (=default)
                else {
                    httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                }

                // Json fr Response body
                RequestError requestError = new RequestError();
                requestError.setError(this.config.getProperty(
                        "error." + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)));
                requestError.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                requestError.setDescription(this.config.getProperty("error."
                        + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR) + ".description"));
                requestError.setErrorUri(this.config.getProperty(
                        "error." + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR) + ".uri"));

                StringWriter json = new StringWriter();
                mapper.writeValue(json, requestError);
                this.logger.debug("[" + config.getProperty("service.name") + "] " + json);

                // send response
                httpServletResponse.getWriter().println(json);
            }
        }
    } else {

        this.logger.error("[" + config.getProperty("service.name") + "] "
                + HttpServletResponse.SC_INTERNAL_SERVER_ERROR + ": Config Error!");

        httpServletResponse.setHeader("WWW-Authentificate", "Bearer");
        httpServletResponse.setHeader("WWW-Authentificate", "Bearer realm=\"PAAA\"");
        httpServletResponse.setContentType("application/json");
        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

        // Error handling mit suppress_response_codes=true
        if (httpServletRequest.getParameter("suppress_response_codes") != null) {
            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
        }
        // Error handling mit suppress_response_codes=false (=default)
        else {
            httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }

        // Json fr Response body
        RequestError requestError = new RequestError();
        requestError.setError(this.config
                .getProperty("error." + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)));
        requestError.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        requestError.setDescription(this.config.getProperty(
                "error." + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR) + ".description"));
        requestError.setErrorUri(this.config.getProperty(
                "error." + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR) + ".uri"));

        StringWriter json = new StringWriter();
        mapper.writeValue(json, requestError);
        this.logger.debug("[" + config.getProperty("service.name") + "] " + json);

        // send response
        httpServletResponse.getWriter().println(json);
    }

}

From source file:es.tid.fiware.fiwareconnectors.cygnus.handlers.OrionRestHandler.java

@Override
public List<Event> getEvents(javax.servlet.http.HttpServletRequest request) throws Exception {
    // get a transaction id and store it in the log4j Mapped Diagnostic Context (MDC); this way it will be
    // accessible by the whole source code
    String transId = generateTransId();
    MDC.put(Constants.TRANSACTION_ID, transId);
    logger.info("Starting transaction (" + transId + ")");

    // check the method
    String method = request.getMethod().toUpperCase(Locale.ENGLISH);

    if (!method.equals("POST")) {
        logger.warn("Bad HTTP notification (" + method + " method not supported)");
        throw new MethodNotSupportedException(method + " method not supported");
    } // if//from   w  ww. ja v  a 2s  .c o m

    // check the notificationsTarget
    String target = request.getRequestURI();

    if (!target.equals(notificationsTarget)) {
        logger.warn("Bad HTTP notification (" + target + " target not supported)");
        throw new HTTPBadRequestException(target + " target not supported");
    } // if

    // check the headers looking for not supported user agents, content type and tenant/organization
    Enumeration headerNames = request.getHeaderNames();
    String contentType = null;
    String organization = null;

    while (headerNames.hasMoreElements()) {
        String headerName = ((String) headerNames.nextElement()).toLowerCase(Locale.ENGLISH);
        String headerValue = request.getHeader(headerName).toLowerCase(Locale.ENGLISH);

        if (headerName.equals(Constants.USER_AGENT)) {
            if (!headerValue.startsWith("orion")) {
                logger.warn("Bad HTTP notification (" + headerValue + " user agent not supported)");
                throw new HTTPBadRequestException(headerValue + " user agent not supported");
            } // if
        } else if (headerName.equals(Constants.CONTENT_TYPE)) {
            if (!headerValue.contains("application/json") && !headerValue.contains("application/xml")) {
                logger.warn("Bad HTTP notification (" + headerValue + " content type not supported)");
                throw new HTTPBadRequestException(headerValue + " content type not supported");
            } else {
                contentType = headerValue;
            } // if else
        } else if (headerName.equals(Constants.ORG_HEADER)) {
            if (headerValue.length() > Constants.ORG_MAX_LEN) {
                logger.warn("Bad HTTP notification (organization length greater than " + Constants.ORG_MAX_LEN
                        + ")");
                throw new HTTPBadRequestException(
                        "organization length greater than " + Constants.ORG_MAX_LEN + ")");
            } else {
                organization = Utils.encode(headerValue);
            } // if else
        } // if else if
    } // for

    // get the data content
    String data = "";
    String line;
    BufferedReader reader = request.getReader();

    while ((line = reader.readLine()) != null) {
        data += line;
    } // while

    if (data.length() == 0) {
        logger.warn("Bad HTTP notification (No content in the request)");
        throw new HTTPBadRequestException("No content in the request");
    } // if

    // data adaptation; two replacements:
    //   1. replace all the appearances of "contextValue" with "value" in order Orion versions under 0.10.0 may
    //      work (Json content type only)
    //   2. replace all the white lines between tags with nothing; the regex ">[ ]*<" means "all the white spaces
    //      between '>' and '<', e.g. "<tag1>1</tag1>      <tag2>2</tag2>" becomes "<tag1>1</tag1><tag2>2</tag2>"

    if (contentType.equals("application/json")) {
        data = data.replaceAll("contextValue", "value");
    } // if

    data = data.replaceAll(">[ ]*<", "><");
    logger.info("Received data (" + data + ")");

    // create the appropiate headers
    Map<String, String> eventHeaders = new HashMap<String, String>();
    eventHeaders.put(Constants.CONTENT_TYPE, contentType);
    logger.debug("Adding flume event header (name=" + Constants.CONTENT_TYPE + ", value=" + contentType + ")");
    eventHeaders.put(Constants.ORG_HEADER, organization == null ? defaultOrg : organization);
    logger.debug("Adding flume event header (name=" + Constants.ORG_HEADER + ", value="
            + (organization == null ? defaultOrg : organization) + ")");
    eventHeaders.put(Constants.TRANSACTION_ID, transId);
    logger.debug("Adding flume event header (name=" + Constants.TRANSACTION_ID + ", value=" + transId + ")");
    eventHeaders.put(Constants.TTL, eventsTTL);
    logger.debug("Adding flume event header (name=" + Constants.TTL + ", value=" + eventsTTL + ")");

    // create the event list containing only one event
    ArrayList<Event> eventList = new ArrayList<Event>();
    Event event = EventBuilder.withBody(data.getBytes(), eventHeaders);
    eventList.add(event);
    logger.info("Event put in the channel (id=" + event.hashCode() + ", ttl=" + eventsTTL + ")");
    return eventList;
}

From source file:servlets.Samples_servlets.java

/**
 *
 * @param request/*from  w ww  .j a v  a 2 s.  c  o  m*/
 * @param response
 * @throws ServletException
 * @throws IOException
 */
private void add_external_samples_handler(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        boolean ROLLBACK_NEEDED = false;
        DAO dao_instance = null;
        ArrayList<String> LOCKED_IDS = new ArrayList<String>();
        ArrayList<BioCondition> newSamples = new ArrayList<BioCondition>();

        try {
            /**
             * *******************************************************
             * STEP 1 CHECK IF THE USER IS LOGGED CORRECTLY IN THE APP. IF
             * ERROR --> throws exception if not valid session, GO TO STEP
             * 6b ELSE --> GO TO STEP 2
             * *******************************************************
             */
            Map<String, Cookie> cookies = this.getCookies(request);
            String loggedUser = cookies.get("loggedUser").getValue();
            String sessionToken = cookies.get("sessionToken").getValue();

            if (!checkAccessPermissions(loggedUser, sessionToken)) {
                throw new AccessControlException("Your session is invalid. User or session token not allowed.");
            }

            /**
             * *******************************************************
             * STEP 2 Get the new ID for the BIOCONDITION. IF ERROR -->
             * throws SQL Exception, GO TO STEP 6b ELSE --> GO TO STEP 3
             * *******************************************************
             */
            JsonParser parser = new JsonParser();
            JsonObject requestData = (JsonObject) parser.parse(request.getReader());

            JsonObject model = requestData.get("model").getAsJsonObject();
            JsonArray samples = requestData.get("samples").getAsJsonArray();

            /**
             * *******************************************************
             * STEP 3 Create new objects for each provided sample id. IF
             * ERROR --> throws JsonParseException, GO TO STEP 6b ELSE -->
             * GO TO STEP
             * *******************************************************
             */
            dao_instance = DAOProvider.getDAOByName("BioCondition");
            String newID;
            BioCondition biocondition;
            for (JsonElement sample : samples) {
                newID = dao_instance.getNextObjectID(null);
                LOCKED_IDS.add(newID);
                biocondition = BioCondition.fromJSON(model);
                biocondition.setBioConditionID(newID);
                biocondition.setTitle(sample.getAsJsonObject().get("name").getAsString());
                biocondition.setExternal(true);
                biocondition.setExternalSampleID(sample.getAsJsonObject().get("id").getAsString());
                newSamples.add(biocondition);
            }

            /**
             * *******************************************************
             * STEP 5 Add the new Object in the DATABASE. IF ERROR -->
             * throws SQL Exception, GO TO STEP 6b ELSE --> GO TO STEP 6
             * *******************************************************
             */
            dao_instance.disableAutocommit();
            ROLLBACK_NEEDED = true;
            for (BioCondition _biocondition : newSamples) {
                dao_instance.insert(_biocondition);
            }

            /**
             * *******************************************************
             * STEP 6 COMMIT CHANGES TO DATABASE. throws SQLException IF
             * ERROR --> throws SQL Exception, GO TO STEP 6b ELSE --> GO TO
             * STEP 7
             * *******************************************************
             */
            dao_instance.doCommit();

        } catch (Exception e) {
            ServerErrorManager.handleException(e, Samples_servlets.class.getName(),
                    "add_external_samples_handler", e.getMessage());
        } finally {
            /**
             * *******************************************************
             * STEP 6b CATCH ERROR, CLEAN CHANGES. throws SQLException
             * *******************************************************
             */
            if (ServerErrorManager.errorStatus()) {
                response.setStatus(400);
                response.getWriter().print(ServerErrorManager.getErrorResponse());

                if (ROLLBACK_NEEDED) {
                    dao_instance.doRollback();
                }
            } else {
                JsonArray newIDs = new JsonArray();
                for (String locked_id : LOCKED_IDS) {
                    newIDs.add(new JsonPrimitive(locked_id));
                }

                JsonObject obj = new JsonObject();
                obj.add("new_ids", newIDs);
                response.getWriter().print(obj.toString());
            }

            if (LOCKED_IDS.size() > 0) {
                for (String LOCKED_ID : LOCKED_IDS) {
                    BlockedElementsManager.getBlockedElementsManager().unlockID(LOCKED_ID);
                }
            }
            /**
             * *******************************************************
             * STEP 8 Close connection.
             * ********************************************************
             */
            if (dao_instance != null) {
                dao_instance.closeConnection();
            }
        }
        //CATCH IF THE ERROR OCCURRED IN ROLL BACK OR CONNECTION CLOSE 
    } catch (Exception e) {
        ServerErrorManager.handleException(e, Samples_servlets.class.getName(), "add_external_samples_handler",
                e.getMessage());
        response.setStatus(400);
        response.getWriter().print(ServerErrorManager.getErrorResponse());
    }
}

From source file:com.telefonica.iot.cygnus.handlers.OrionRestHandler.java

@Override
public List<Event> getEvents(javax.servlet.http.HttpServletRequest request) throws Exception {
    // get a transaction id and store it in the log4j Mapped Diagnostic Context (MDC); this way it will be
    // accessible by the whole source code
    String transId = generateTransId();
    MDC.put(Constants.HEADER_TRANSACTION_ID, transId);
    LOGGER.info("Starting transaction (" + transId + ")");

    // check the method
    String method = request.getMethod().toUpperCase(Locale.ENGLISH);

    if (!method.equals("POST")) {
        LOGGER.warn("Bad HTTP notification (" + method + " method not supported)");
        throw new MethodNotSupportedException(method + " method not supported");
    } // if/*from   w w w.  j  a v  a 2  s  .  c o m*/

    // check the notificationTarget
    String target = request.getRequestURI();

    if (!target.equals(notificationTarget)) {
        LOGGER.warn("Bad HTTP notification (" + target + " target not supported)");
        throw new HTTPBadRequestException(target + " target not supported");
    } // if

    // check the headers looking for not supported user agents, content type and tenant/organization
    Enumeration headerNames = request.getHeaderNames();
    String contentType = null;
    String service = null;
    String servicePath = null;

    while (headerNames.hasMoreElements()) {
        String headerName = ((String) headerNames.nextElement()).toLowerCase(Locale.ENGLISH);
        String headerValue = request.getHeader(headerName).toLowerCase(Locale.ENGLISH);

        if (headerName.equals(Constants.HEADER_USER_AGENT)) {
            if (!headerValue.startsWith("orion")) {
                LOGGER.warn("Bad HTTP notification (" + headerValue + " user agent not supported)");
                throw new HTTPBadRequestException(headerValue + " user agent not supported");
            } // if
        } else if (headerName.equals(Constants.HEADER_CONTENT_TYPE)) {
            if (!headerValue.contains("application/json") && !headerValue.contains("application/xml")) {
                LOGGER.warn("Bad HTTP notification (" + headerValue + " content type not supported)");
                throw new HTTPBadRequestException(headerValue + " content type not supported");
            } else {
                contentType = headerValue;
            } // if else
        } else if (headerName.equals(Constants.HEADER_SERVICE)) {
            if (headerValue.length() > Constants.SERVICE_HEADER_MAX_LEN) {
                LOGGER.warn("Bad HTTP notification ('fiware-service' header length greater than "
                        + Constants.SERVICE_HEADER_MAX_LEN + ")");
                throw new HTTPBadRequestException("'fiware-service' header length greater than "
                        + Constants.SERVICE_HEADER_MAX_LEN + ")");
            } else {
                service = Utils.encode(headerValue);
            } // if else
        } else if (headerName.equals(Constants.HEADER_SERVICE_PATH)) {
            if (headerValue.length() > Constants.SERVICE_PATH_HEADER_MAX_LEN) {
                LOGGER.warn("Bad HTTP notification ('fiware-servicePath' header length greater than "
                        + Constants.SERVICE_PATH_HEADER_MAX_LEN + ")");
                throw new HTTPBadRequestException("'fiware-servicePath' header length greater than "
                        + Constants.SERVICE_PATH_HEADER_MAX_LEN + ")");
            } else {
                servicePath = Utils.encode(headerValue);
            } // if else
        } // if else if
    } // for

    // get the data content
    String data = "";
    String line;
    BufferedReader reader = request.getReader();

    while ((line = reader.readLine()) != null) {
        data += line;
    } // while

    if (data.length() == 0) {
        LOGGER.warn("Bad HTTP notification (No content in the request)");
        throw new HTTPBadRequestException("No content in the request");
    } // if

    // data adaptation; two replacements:
    //   1. replace all the appearances of "contextValue" with "value" in order Orion versions under 0.10.0 may
    //      work (Json content type only)
    //   2. replace all the white lines between tags with nothing; the regex ">[ ]*<" means "all the white spaces
    //      between '>' and '<', e.g. "<tag1>1</tag1>      <tag2>2</tag2>" becomes "<tag1>1</tag1><tag2>2</tag2>"

    if (contentType.equals("application/json")) {
        data = data.replaceAll("contextValue", "value");
    } // if

    data = data.replaceAll(">[ ]*<", "><");
    LOGGER.info("Received data (" + data + ")");

    // create the appropiate headers
    Map<String, String> eventHeaders = new HashMap<String, String>();
    eventHeaders.put(Constants.HEADER_CONTENT_TYPE, contentType);
    LOGGER.debug("Adding flume event header (name=" + Constants.HEADER_CONTENT_TYPE + ", value=" + contentType
            + ")");
    eventHeaders.put(Constants.HEADER_SERVICE, service == null ? defaultService : service);
    LOGGER.debug("Adding flume event header (name=" + Constants.HEADER_SERVICE + ", value="
            + (service == null ? defaultService : service) + ")");
    eventHeaders.put(Constants.HEADER_SERVICE_PATH, servicePath == null ? defaultServicePath : servicePath);
    LOGGER.debug("Adding flume event header (name=" + Constants.HEADER_SERVICE_PATH + ", value="
            + (servicePath == null ? defaultServicePath : servicePath) + ")");
    eventHeaders.put(Constants.HEADER_TRANSACTION_ID, transId);
    LOGGER.debug(
            "Adding flume event header (name=" + Constants.HEADER_TRANSACTION_ID + ", value=" + transId + ")");
    eventHeaders.put(Constants.HEADER_TTL, eventsTTL);
    LOGGER.debug("Adding flume event header (name=" + Constants.HEADER_TTL + ", value=" + eventsTTL + ")");

    // create the event list containing only one event
    ArrayList<Event> eventList = new ArrayList<Event>();
    Event event = EventBuilder.withBody(data.getBytes(), eventHeaders);
    eventList.add(event);
    LOGGER.info("Event put in the channel (id=" + event.hashCode() + ", ttl=" + eventsTTL + ")");
    return eventList;
}

From source file:de.tu_dortmund.ub.api.daia.DaiaOpenUrlEndpoint.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String ip = request.getHeader("X-Forwarded-For");

    boolean isTUintern = false;
    boolean isUBintern = false;
    boolean is52bIBA = false;

    try {/*w w  w  .j a  v a2  s  .  com*/
        if (ip != null) {

            String[] ranges = config.getProperty("service.iprange.tu").split("\\|");
            for (String range : ranges) {

                if (ip.matches(range)) {

                    isTUintern = true;
                    break;
                }
            }

            String[] exceptions = config.getProperty("service.iprange.tu.exceptions").split("\\|");
            if (isTUintern) {

                for (String exception : exceptions) {

                    if (ip.matches(exception)) {

                        isTUintern = false;
                        break;
                    }
                }
            }

            ranges = config.getProperty("service.iprange.ub").split("\\|");
            for (String range : ranges) {

                if (ip.matches(range)) {

                    isUBintern = true;
                    break;
                }
            }
            exceptions = config.getProperty("service.iprange.ub.exceptions").split("\\|");
            if (isUBintern) {

                for (String exception : exceptions) {

                    if (ip.matches(exception)) {

                        isUBintern = false;
                        break;
                    }
                }
            }

            ranges = config.getProperty("service.iprange.ub.52bIBAs").split("\\|");
            for (String range : ranges) {

                if (ip.matches(range)) {

                    is52bIBA = true;
                    break;
                }
            }
        }
    } catch (Exception e) {

        this.logger.error(e.getMessage(), e.getCause());
    }
    this.logger.debug("Where is it from? " + request.getHeader("X-Forwarded-For") + ", " + isTUintern + ", "
            + isUBintern);

    // read query
    StringBuffer jb = new StringBuffer();
    String line = null;
    try {
        BufferedReader reader = request.getReader();

        while ((line = reader.readLine()) != null) {

            jb.append(line);
        }

        this.logger.debug("POST-INPUT: \n\t" + jb);

    } catch (Exception e) {

        this.logger.error(e.getMessage(), e.getCause());
    }

    // format
    String format = "html";

    Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {

        String headerNameKey = headerNames.nextElement();

        if (headerNameKey.equals("Accept")) {

            if (request.getHeader(headerNameKey).contains("text/html")) {
                format = "html";
            } else if (request.getHeader(headerNameKey).contains("application/xml")) {
                format = "xml";
            } else if (request.getHeader(headerNameKey).contains("application/json")) {
                format = "json";
            }
        }
    }

    // read query
    String queryString = null;

    if (jb.length() == 0) {

        if (format.equals("html")) {

            try {

                JAXBContext context = JAXBContext.newInstance(Daia.class);
                Marshaller m = context.createMarshaller();
                m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

                // Write to HttpResponse
                org.jdom2.Document doc = new org.jdom2.Document();
                doc.setRootElement(new Element("daia"));

                HashMap<String, String> parameters = new HashMap<String, String>();
                parameters.put("lang", "de");
                parameters.put("isTUintern", Boolean.toString(isTUintern));
                parameters.put("isUBintern", Boolean.toString(isUBintern));
                parameters.put("is52bIBA", Boolean.toString(is52bIBA));

                String html = htmlOutputter(doc, this.config.getProperty("linkresolver.html.xslt"), parameters);

                response.setContentType("text/html;charset=UTF-8");
                response.setStatus(HttpServletResponse.SC_OK);
                response.getWriter().println(html);
            } catch (PropertyException e) {
                this.logger.error(e.getMessage(), e.getCause());
            } catch (JAXBException e) {
                this.logger.error(e.getMessage(), e.getCause());
            }
        } else {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Query is empty.");
        }
    } else {

        if (jb.toString().contains("__char_set=latin1") || jb.toString().contains("sid=semantics")
                || jb.toString().contains("sid=GBI:wiwi")) {
            this.logger.debug("TEST 'getQueryString': " + URLDecoder.decode(jb.toString(), "ISO-8859-1"));

            queryString = URLDecoder.decode(jb.toString(), "ISO-8859-1");

        } else {
            queryString = URLDecoder.decode(jb.toString(), "UTF-8");
        }

        HashMap<String, String> latinParameters = new HashMap<String, String>();

        for (String param : queryString.split("&")) {

            String[] tmp = param.split("=");
            try {
                latinParameters.put(tmp[0], tmp[1]);
            } catch (ArrayIndexOutOfBoundsException e) {
                latinParameters.put(tmp[0], "");
            }
        }

        if (latinParameters.get("format") != null && !latinParameters.get("format").equals("")) {

            format = latinParameters.get("format");
        }

        this.logger.debug("format = " + format);

        // build response
        response.setHeader("Access-Control-Allow-Origin", config.getProperty("Access-Control-Allow-Origin"));

        if (format.equals("")) {

            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No valid {FORMAT} requested.");
        } else {

            this.provideService(request, response, format, latinParameters, isTUintern, isUBintern, is52bIBA);
        }
    }
}

From source file:io.warp10.standalone.StandaloneIngressHandler.java

/**
 * Handle Metadata updating//from  ww  w .ja va  2  s .  c o m
 */
public void handleMeta(String target, Request baseRequest, HttpServletRequest request,
        HttpServletResponse response) throws IOException, ServletException {
    if (target.equals(Constants.API_ENDPOINT_META)) {
        baseRequest.setHandled(true);
    } else {
        return;
    }

    try {
        //
        // CORS header
        //

        response.setHeader("Access-Control-Allow-Origin", "*");

        //
        // Extract DatalogRequest if specified
        //

        String datalogHeader = request.getHeader(Constants.getHeader(Configuration.HTTP_HEADER_DATALOG));

        DatalogRequest dr = null;

        boolean forwarded = false;

        if (null != datalogHeader) {
            byte[] bytes = OrderPreservingBase64.decode(datalogHeader.getBytes(Charsets.US_ASCII));

            if (null != datalogPSK) {
                bytes = CryptoUtils.unwrap(datalogPSK, bytes);
            }

            if (null == bytes) {
                throw new IOException("Invalid Datalog header.");
            }

            TDeserializer deser = new TDeserializer(new TCompactProtocol.Factory());

            try {
                dr = new DatalogRequest();
                deser.deserialize(dr, bytes);
            } catch (TException te) {
                throw new IOException();
            }

            Map<String, String> labels = new HashMap<String, String>();
            labels.put(SensisionConstants.SENSISION_LABEL_ID, new String(
                    OrderPreservingBase64.decode(dr.getId().getBytes(Charsets.US_ASCII)), Charsets.UTF_8));
            labels.put(SensisionConstants.SENSISION_LABEL_TYPE, dr.getType());
            Sensision.update(SensisionConstants.CLASS_WARP_DATALOG_REQUESTS_RECEIVED, labels, 1);

            forwarded = true;
        }

        //
        // Loop over the input lines.
        // Each has the following format:
        //
        // class{labels}{attributes}
        //

        String token = null != dr ? dr.getToken()
                : request.getHeader(Constants.getHeader(Configuration.HTTP_HEADER_TOKENX));

        WriteToken wtoken;

        try {
            wtoken = Tokens.extractWriteToken(token);
        } catch (WarpScriptException ee) {
            throw new IOException(ee);
        }

        String application = wtoken.getAppName();
        String producer = Tokens.getUUID(wtoken.getProducerId());
        String owner = Tokens.getUUID(wtoken.getOwnerId());

        if (null == producer || null == owner) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN, "Invalid token.");
            return;
        }

        //
        // Determine if content if gzipped
        //

        boolean gzipped = false;

        if (null != request.getHeader("Content-Type")
                && "application/gzip".equals(request.getHeader("Content-Type"))) {
            gzipped = true;
        }

        BufferedReader br = null;

        if (gzipped) {
            GZIPInputStream is = new GZIPInputStream(request.getInputStream());
            br = new BufferedReader(new InputStreamReader(is));
        } else {
            br = request.getReader();
        }

        File loggingFile = null;
        PrintWriter loggingWriter = null;

        //
        // Open the logging file if logging is enabled
        //

        if (null != loggingDir) {
            long nanos = null != dr ? dr.getTimestamp() : TimeSource.getNanoTime();
            StringBuilder sb = new StringBuilder();
            sb.append(Long.toHexString(nanos));
            sb.insert(0, "0000000000000000", 0, 16 - sb.length());
            sb.append("-");
            if (null != dr) {
                sb.append(dr.getId());
            } else {
                sb.append(datalogId);
            }

            sb.append("-");
            sb.append(dtf.print(nanos / 1000000L));
            sb.append(Long.toString(1000000L + (nanos % 1000000L)).substring(1));
            sb.append("Z");

            if (null == dr) {
                dr = new DatalogRequest();
                dr.setTimestamp(nanos);
                dr.setType(Constants.DATALOG_META);
                dr.setId(datalogId);
                dr.setToken(token);
            }

            if (null != dr && (!forwarded || (forwarded && this.logforwarded))) {
                //
                // Serialize the request
                //

                TSerializer ser = new TSerializer(new TCompactProtocol.Factory());

                byte[] encoded;

                try {
                    encoded = ser.serialize(dr);
                } catch (TException te) {
                    throw new IOException(te);
                }

                if (null != this.datalogPSK) {
                    encoded = CryptoUtils.wrap(this.datalogPSK, encoded);
                }

                encoded = OrderPreservingBase64.encode(encoded);

                loggingFile = new File(loggingDir, sb.toString());
                loggingWriter = new PrintWriter(new FileWriterWithEncoding(loggingFile, Charsets.UTF_8));

                //
                // Write request
                //

                loggingWriter.println(new String(encoded, Charsets.US_ASCII));
            }
        }

        try {
            //
            // Loop on all lines
            //

            while (true) {
                String line = br.readLine();

                if (null == line) {
                    break;
                }

                // Ignore blank lines
                if ("".equals(line)) {
                    continue;
                }

                // Ignore comments
                if ('#' == line.charAt(0)) {
                    continue;
                }

                Metadata metadata = MetadataUtils.parseMetadata(line);

                // Add labels from the WriteToken if they exist
                if (wtoken.getLabelsSize() > 0) {
                    metadata.getLabels().putAll(wtoken.getLabels());
                }
                //
                // Force owner/producer
                //

                metadata.getLabels().put(Constants.PRODUCER_LABEL, producer);
                metadata.getLabels().put(Constants.OWNER_LABEL, owner);

                if (null != application) {
                    metadata.getLabels().put(Constants.APPLICATION_LABEL, application);
                } else {
                    // remove application label
                    metadata.getLabels().remove(Constants.APPLICATION_LABEL);
                }

                if (!MetadataUtils.validateMetadata(metadata)) {
                    response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid metadata " + line);
                    return;
                }

                metadata.setSource(Configuration.INGRESS_METADATA_UPDATE_ENDPOINT);
                this.directoryClient.register(metadata);

                //
                // Write the line last, so we do not write lines which triggered exceptions
                //

                if (null != loggingWriter) {
                    loggingWriter.println(line);
                }
            }
        } finally {
            if (null != loggingWriter) {
                Map<String, String> labels = new HashMap<String, String>();
                labels.put(SensisionConstants.SENSISION_LABEL_ID, new String(
                        OrderPreservingBase64.decode(dr.getId().getBytes(Charsets.US_ASCII)), Charsets.UTF_8));
                labels.put(SensisionConstants.SENSISION_LABEL_TYPE, dr.getType());
                Sensision.update(SensisionConstants.CLASS_WARP_DATALOG_REQUESTS_LOGGED, labels, 1);

                loggingWriter.close();
                loggingFile.renameTo(new File(loggingFile.getAbsolutePath() + DatalogForwarder.DATALOG_SUFFIX));
            }
        }

        response.setStatus(HttpServletResponse.SC_OK);
    } catch (Exception e) {
        if (!response.isCommitted()) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
            return;
        }
    }
}

From source file:io.warp10.standalone.StandaloneIngressHandler.java

@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    String token = null;/*from  w w  w. j  a v  a  2s.  c  o m*/

    if (target.equals(Constants.API_ENDPOINT_UPDATE)) {
        baseRequest.setHandled(true);
    } else if (target.startsWith(Constants.API_ENDPOINT_UPDATE + "/")) {
        baseRequest.setHandled(true);
        token = target.substring(Constants.API_ENDPOINT_UPDATE.length() + 1);
    } else if (target.equals(Constants.API_ENDPOINT_META)) {
        handleMeta(target, baseRequest, request, response);
        return;
    } else {
        return;
    }

    try {
        //
        // CORS header
        //

        response.setHeader("Access-Control-Allow-Origin", "*");

        long nano = System.nanoTime();

        //
        // Extract DatalogRequest if specified
        //

        String datalogHeader = request.getHeader(Constants.getHeader(Configuration.HTTP_HEADER_DATALOG));

        DatalogRequest dr = null;

        boolean forwarded = false;

        if (null != datalogHeader) {
            byte[] bytes = OrderPreservingBase64.decode(datalogHeader.getBytes(Charsets.US_ASCII));

            if (null != datalogPSK) {
                bytes = CryptoUtils.unwrap(datalogPSK, bytes);
            }

            if (null == bytes) {
                throw new IOException("Invalid Datalog header.");
            }

            TDeserializer deser = new TDeserializer(new TCompactProtocol.Factory());

            try {
                dr = new DatalogRequest();
                deser.deserialize(dr, bytes);
            } catch (TException te) {
                throw new IOException();
            }

            token = dr.getToken();

            Map<String, String> labels = new HashMap<String, String>();
            labels.put(SensisionConstants.SENSISION_LABEL_ID, new String(
                    OrderPreservingBase64.decode(dr.getId().getBytes(Charsets.US_ASCII)), Charsets.UTF_8));
            labels.put(SensisionConstants.SENSISION_LABEL_TYPE, dr.getType());
            Sensision.update(SensisionConstants.CLASS_WARP_DATALOG_REQUESTS_RECEIVED, labels, 1);
            forwarded = true;
        }

        //
        // TODO(hbs): Extract producer/owner from token
        //

        if (null == token) {
            token = request.getHeader(Constants.getHeader(Configuration.HTTP_HEADER_TOKENX));
        }

        WriteToken writeToken;

        try {
            writeToken = Tokens.extractWriteToken(token);
        } catch (WarpScriptException ee) {
            throw new IOException(ee);
        }

        String application = writeToken.getAppName();
        String producer = Tokens.getUUID(writeToken.getProducerId());
        String owner = Tokens.getUUID(writeToken.getOwnerId());

        Map<String, String> sensisionLabels = new HashMap<String, String>();
        sensisionLabels.put(SensisionConstants.SENSISION_LABEL_PRODUCER, producer);

        long count = 0;
        long total = 0;

        File loggingFile = null;
        PrintWriter loggingWriter = null;

        try {
            if (null == producer || null == owner) {
                response.sendError(HttpServletResponse.SC_FORBIDDEN, "Invalid token.");
                return;
            }

            //
            // Build extra labels
            //

            Map<String, String> extraLabels = new HashMap<String, String>();

            // Add labels from the WriteToken if they exist
            if (writeToken.getLabelsSize() > 0) {
                extraLabels.putAll(writeToken.getLabels());
            }

            // Force internal labels
            extraLabels.put(Constants.PRODUCER_LABEL, producer);
            extraLabels.put(Constants.OWNER_LABEL, owner);
            // FIXME(hbs): remove me, apps should be set in all tokens now...
            if (null != application) {
                extraLabels.put(Constants.APPLICATION_LABEL, application);
                sensisionLabels.put(SensisionConstants.SENSISION_LABEL_APPLICATION, application);
            } else {
                // remove application label
                extraLabels.remove(Constants.APPLICATION_LABEL);
            }

            //
            // Determine if content if gzipped
            //

            boolean gzipped = false;

            if (null != request.getHeader("Content-Type")
                    && "application/gzip".equals(request.getHeader("Content-Type"))) {
                gzipped = true;
            }

            BufferedReader br = null;

            if (gzipped) {
                GZIPInputStream is = new GZIPInputStream(request.getInputStream());
                br = new BufferedReader(new InputStreamReader(is));
            } else {
                br = request.getReader();
            }

            //
            // Get the present time
            //

            Long now = TimeSource.getTime();

            //
            // Check the value of the 'now' header
            //
            // The following values are supported:
            //
            // A number, which will be interpreted as an absolute time reference,
            // i.e. a number of time units since the Epoch.
            //
            // A number prefixed by '+' or '-' which will be interpreted as a
            // delta from the present time.
            //
            // A '*' which will mean to not set 'now', and to recompute its value
            // each time it's needed.
            //

            String nowstr = null != dr ? dr.getNow()
                    : request.getHeader(Constants.getHeader(Configuration.HTTP_HEADER_NOW_HEADERX));

            if (null != nowstr) {
                if ("*".equals(nowstr)) {
                    now = null;
                } else if (nowstr.startsWith("+")) {
                    try {
                        long delta = Long.parseLong(nowstr.substring(1));
                        now = now + delta;
                    } catch (Exception e) {
                        throw new IOException("Invalid base timestamp.");
                    }
                } else if (nowstr.startsWith("-")) {
                    try {
                        long delta = Long.parseLong(nowstr.substring(1));
                        now = now - delta;
                    } catch (Exception e) {
                        throw new IOException("Invalid base timestamp.");
                    }
                } else {
                    try {
                        now = Long.parseLong(nowstr);
                    } catch (Exception e) {
                        throw new IOException("Invalid base timestamp.");
                    }
                }
            }

            //
            // Open the logging file if logging is enabled
            //

            if (null != loggingDir) {
                long nanos = null != dr ? dr.getTimestamp() : TimeSource.getNanoTime();
                StringBuilder sb = new StringBuilder();
                sb.append(Long.toHexString(nanos));
                sb.insert(0, "0000000000000000", 0, 16 - sb.length());
                sb.append("-");
                if (null != dr) {
                    sb.append(dr.getId());
                } else {
                    sb.append(datalogId);
                }

                sb.append("-");
                sb.append(dtf.print(nanos / 1000000L));
                sb.append(Long.toString(1000000L + (nanos % 1000000L)).substring(1));
                sb.append("Z");

                if (null == dr) {
                    dr = new DatalogRequest();
                    dr.setTimestamp(nanos);
                    dr.setType(Constants.DATALOG_UPDATE);
                    dr.setId(datalogId);
                    dr.setToken(token);

                    if (null == now) {
                        //
                        // We MUST force 'now', otherwise forwarded metrics will not have a
                        // coherent time. This alters the semantics slightly but make it
                        // coherent across the board.
                        //
                        now = TimeSource.getTime();
                    }
                    dr.setNow(Long.toString(now));
                }

                if (null != dr && (!forwarded || (forwarded && this.logforwarded))) {

                    //
                    // Serialize the request
                    //

                    TSerializer ser = new TSerializer(new TCompactProtocol.Factory());

                    byte[] encoded;

                    try {
                        encoded = ser.serialize(dr);
                    } catch (TException te) {
                        throw new IOException(te);
                    }

                    if (null != this.datalogPSK) {
                        encoded = CryptoUtils.wrap(this.datalogPSK, encoded);
                    }

                    encoded = OrderPreservingBase64.encode(encoded);

                    loggingFile = new File(loggingDir, sb.toString());

                    loggingWriter = new PrintWriter(new FileWriterWithEncoding(loggingFile, Charsets.UTF_8));

                    //
                    // Write request
                    //

                    loggingWriter.println(new String(encoded, Charsets.US_ASCII));
                }

                //
                // Force 'now'
                //

                now = Long.parseLong(dr.getNow());
            }

            //
            // Loop on all lines
            //

            GTSEncoder lastencoder = null;
            GTSEncoder encoder = null;

            //
            // Chunk index when archiving
            //

            do {

                String line = br.readLine();

                if (null == line) {
                    break;
                }

                line = line.trim();

                if (0 == line.length()) {
                    continue;
                }

                //
                // Ignore comments
                //

                if ('#' == line.charAt(0)) {
                    continue;
                }

                //
                // Check for pushback
                // TODO(hbs): implement the actual push back if we are over the subscribed limit
                //

                if (count % PUSHBACK_CHECK_INTERVAL == 0) {
                    Sensision.update(
                            SensisionConstants.SENSISION_CLASS_CONTINUUM_STANDALONE_UPDATE_DATAPOINTS_RAW,
                            sensisionLabels, count);
                    total += count;
                    count = 0;
                }

                count++;

                try {
                    encoder = GTSHelper.parse(lastencoder, line, extraLabels, now, maxValueSize, false);
                    //nano2 += System.nanoTime() - nano0;
                } catch (ParseException pe) {
                    Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_STANDALONE_UPDATE_PARSEERRORS,
                            sensisionLabels, 1);
                    throw new IOException("Parse error at '" + line + "'", pe);
                }

                if (encoder != lastencoder || lastencoder.size() > ENCODER_SIZE_THRESHOLD) {

                    //
                    // Check throttling
                    //

                    if (null != lastencoder) {

                        // 128BITS
                        lastencoder.setClassId(GTSHelper.classId(classKeyLongs, lastencoder.getName()));
                        lastencoder.setLabelsId(
                                GTSHelper.labelsId(labelsKeyLongs, lastencoder.getMetadata().getLabels()));

                        ThrottlingManager.checkMADS(lastencoder.getMetadata(), producer, owner, application,
                                lastencoder.getClassId(), lastencoder.getLabelsId());
                        ThrottlingManager.checkDDP(lastencoder.getMetadata(), producer, owner, application,
                                (int) lastencoder.getCount());
                    }

                    //
                    // Build metadata object to push
                    //

                    if (encoder != lastencoder) {
                        Metadata metadata = new Metadata(encoder.getMetadata());
                        metadata.setSource(Configuration.INGRESS_METADATA_SOURCE);
                        //nano6 += System.nanoTime() - nano0;
                        this.directoryClient.register(metadata);
                        //nano5 += System.nanoTime() - nano0;
                    }

                    if (null != lastencoder) {
                        this.storeClient.store(lastencoder);
                    }

                    if (encoder != lastencoder) {
                        lastencoder = encoder;
                    } else {
                        //lastencoder = null
                        //
                        // Allocate a new GTSEncoder and reuse Metadata so we can
                        // correctly handle a continuation line if this is what occurs next
                        //
                        Metadata metadata = lastencoder.getMetadata();
                        lastencoder = new GTSEncoder(0L);
                        lastencoder.setMetadata(metadata);
                    }
                }

                //
                // Write the line last, so we do not write lines which triggered exceptions
                //

                if (null != loggingWriter) {
                    loggingWriter.println(line);
                }
            } while (true);

            br.close();

            if (null != lastencoder && lastencoder.size() > 0) {
                // 128BITS
                lastencoder.setClassId(GTSHelper.classId(classKeyLongs, lastencoder.getName()));
                lastencoder
                        .setLabelsId(GTSHelper.labelsId(labelsKeyLongs, lastencoder.getMetadata().getLabels()));

                ThrottlingManager.checkMADS(lastencoder.getMetadata(), producer, owner, application,
                        lastencoder.getClassId(), lastencoder.getLabelsId());
                ThrottlingManager.checkDDP(lastencoder.getMetadata(), producer, owner, application,
                        (int) lastencoder.getCount());
                this.storeClient.store(lastencoder);
            }

            //
            // TODO(hbs): should we update the count in Sensision periodically so you can't trick the throttling mechanism?
            //
        } catch (WarpException we) {
            throw new IOException(we);
        } finally {
            this.storeClient.store(null);
            this.directoryClient.register(null);
            Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_STANDALONE_UPDATE_DATAPOINTS_RAW,
                    sensisionLabels, count);
            Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_STANDALONE_UPDATE_REQUESTS,
                    sensisionLabels, 1);
            Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_STANDALONE_UPDATE_TIME_US,
                    sensisionLabels, (System.nanoTime() - nano) / 1000);

            if (null != loggingWriter) {
                Map<String, String> labels = new HashMap<String, String>();
                labels.put(SensisionConstants.SENSISION_LABEL_ID, new String(
                        OrderPreservingBase64.decode(dr.getId().getBytes(Charsets.US_ASCII)), Charsets.UTF_8));
                labels.put(SensisionConstants.SENSISION_LABEL_TYPE, dr.getType());
                Sensision.update(SensisionConstants.CLASS_WARP_DATALOG_REQUESTS_LOGGED, labels, 1);

                loggingWriter.close();
                loggingFile.renameTo(new File(loggingFile.getAbsolutePath() + DatalogForwarder.DATALOG_SUFFIX));
            }

            //
            // Update stats with CDN
            //

            String cdn = request.getHeader(Constants.OVH_CDN_GEO_HEADER);

            if (null != cdn) {
                sensisionLabels.put(SensisionConstants.SENSISION_LABEL_CDN, cdn);
                // Per CDN stat is updated at the end, so update with 'total' + 'count'
                Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_STANDALONE_UPDATE_DATAPOINTS_RAW,
                        sensisionLabels, count + total);
                Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_STANDALONE_UPDATE_REQUESTS,
                        sensisionLabels, 1);
                Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_STANDALONE_UPDATE_TIME_US,
                        sensisionLabels, (System.nanoTime() - nano) / 1000);
            }
        }

        response.setStatus(HttpServletResponse.SC_OK);
    } catch (Exception e) {
        if (!response.isCommitted()) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
            return;
        }
    }
}

From source file:de.tu_dortmund.ub.api.paia.core.PaiaCoreEndpoint.java

/**
 *
 * @param httpServletRequest/*from   www  .  j a  v a2  s.com*/
 * @param httpServletResponse
 * @throws ServletException
 * @throws IOException
 */
protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws ServletException, IOException {

    ObjectMapper mapper = new ObjectMapper();

    String format;
    String language;
    String redirect_url;

    this.logger.debug(
            "[" + config.getProperty("service.name") + "] " + "PathInfo = " + httpServletRequest.getPathInfo());
    this.logger.debug("[" + config.getProperty("service.name") + "] " + "QueryString = "
            + httpServletRequest.getQueryString());

    String patronid = "";
    String service = "";
    String accept = "";
    String authorization = "";

    String path = httpServletRequest.getPathInfo();
    if (path != null) {
        String[] params = path.substring(1, path.length()).split("/");

        if (params.length == 1) {
            patronid = params[0];
            service = "patron";
        } else if (params.length == 2) {
            patronid = params[0];
            service = params[1];
        } else if (params[1].equals("items") && params.length > 2) {
            patronid = params[0];
            for (int i = 1; i < params.length; i++) {

                service += params[i];
                if (i < params.length - 1) {
                    service += "/";
                }
            }
        }
    }

    if (patronid.equals("patronid")) {

        patronid = "";
    }

    this.logger.debug("[" + config.getProperty("service.name") + "] " + "Service: " + service);
    this.logger.debug("[" + config.getProperty("service.name") + "] " + "Patron: " + patronid);

    format = "html";

    if (httpServletRequest.getParameter("format") != null
            && !httpServletRequest.getParameter("format").equals("")) {

        format = httpServletRequest.getParameter("format");
    } else {

        Enumeration<String> headerNames = httpServletRequest.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerNameKey = headerNames.nextElement();

            if (headerNameKey.equals("Accept")) {

                this.logger.debug("headerNameKey = " + httpServletRequest.getHeader(headerNameKey));

                if (httpServletRequest.getHeader(headerNameKey).contains("text/html")) {
                    format = "html";
                } else if (httpServletRequest.getHeader(headerNameKey).contains("application/xml")) {
                    format = "xml";
                } else if (httpServletRequest.getHeader(headerNameKey).contains("application/json")) {
                    format = "json";
                }
            }
        }
    }

    this.logger.info("format = " + format);

    if (format.equals("html") && Lookup.lookupAll(ObjectToHtmlTransformation.class).size() == 0) {

        this.logger.error("[" + this.config.getProperty("service.name") + "] "
                + HttpServletResponse.SC_BAD_REQUEST + ": " + "html not implemented!");

        // Error handling mit suppress_response_codes=true
        if (httpServletRequest.getParameter("suppress_response_codes") != null) {
            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
        }
        // Error handling mit suppress_response_codes=false (=default)
        else {
            httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }

        // Json fr Response body
        RequestError requestError = new RequestError();
        requestError.setError(
                this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_BAD_REQUEST)));
        requestError.setCode(HttpServletResponse.SC_BAD_REQUEST);
        requestError.setDescription(this.config
                .getProperty("error." + Integer.toString(HttpServletResponse.SC_BAD_REQUEST) + ".description"));
        requestError.setErrorUri(this.config
                .getProperty("error." + Integer.toString(HttpServletResponse.SC_BAD_REQUEST) + ".uri"));

        this.sendRequestError(httpServletResponse, requestError, format, "", "");
    } else {

        // read requestBody
        StringBuffer jb = new StringBuffer();
        String line = null;
        try {
            BufferedReader reader = httpServletRequest.getReader();
            while ((line = reader.readLine()) != null)
                jb.append(line);
        } catch (Exception e) {
            /*report an error*/ }

        String requestBody = jb.toString();

        // read document list
        DocumentList documentList = null;

        try {

            // read DocumentList
            documentList = mapper.readValue(requestBody, DocumentList.class);
        } catch (Exception e) {

            if (!requestBody.equals("")) {

                String[] params = requestBody.split("&");

                if (params.length > 1) {

                    documentList = new DocumentList();
                    documentList.setDoc(new ArrayList<Document>());

                    for (String param : params) {

                        if (param.startsWith("document_id")) {
                            Document document = new Document();
                            document.setEdition(param.split("=")[1]);
                            documentList.getDoc().add(document);
                        }
                    }
                }
            } else if (httpServletRequest.getParameter("document_id") != null
                    && !httpServletRequest.getParameter("document_id").equals("")) {

                Document document = new Document();
                document.setEdition(httpServletRequest.getParameter("document_id"));

                if (httpServletRequest.getParameter("storage_id") != null
                        && !httpServletRequest.getParameter("storage_id").equals("")) {

                    document.setStorage_id(httpServletRequest.getParameter("storage_id"));
                }

                documentList = new DocumentList();
                documentList.setDoc(new ArrayList<Document>());
                documentList.getDoc().add(document);
            } else {

                // if exists cookie with name "PaiaServiceDocumentList": read it
                Cookie[] cookies = httpServletRequest.getCookies();

                if (cookies != null) {
                    for (Cookie cookie : cookies) {
                        if (cookie.getName().equals("PaiaServiceDocumentList")) {

                            if (cookie.getValue() != null && !cookie.getValue().equals("")
                                    && !cookie.getValue().equals("null")) {

                                String value = URLDecoder.decode(cookie.getValue(), "UTF-8");
                                this.logger.info(value);
                                documentList = mapper.readValue(value, DocumentList.class);
                            }

                            break;
                        }
                    }
                }
            }
        }

        if (patronid.equals("")) {

            // Authorization
            this.authorize(httpServletRequest, httpServletResponse, format, documentList);
        } else {

            redirect_url = "";

            if (httpServletRequest.getParameter("redirect_url") != null
                    && !httpServletRequest.getParameter("redirect_url").equals("")) {

                redirect_url = httpServletRequest.getParameter("redirect_url");
            }

            this.logger.info("redirect_url = " + redirect_url);

            language = "";

            // PAIA core - function
            if ((httpServletRequest.getMethod().equals("GET")
                    && (service.equals("patron") || service.equals("fullpatron") || service.equals("items")
                            || service.startsWith("items/ordered") || service.startsWith("items/reserved")
                            || service.startsWith("items/borrowed") || service.startsWith("items/borrowed/ill")
                            || service.startsWith("items/borrowed/renewed")
                            || service.startsWith("items/borrowed/recalled") || service.equals("fees")
                            || service.equals("request")))
                    || (httpServletRequest.getMethod().equals("POST") && (service.equals("request")
                            || service.equals("renew") || service.equals("cancel")))) {

                // get 'Accept' and 'Authorization' from Header
                Enumeration<String> headerNames = httpServletRequest.getHeaderNames();
                while (headerNames.hasMoreElements()) {

                    String headerNameKey = (String) headerNames.nextElement();
                    this.logger.debug(
                            "[" + config.getProperty("service.name") + "] " + "headerNameKey = " + headerNameKey
                                    + " / headerNameValue = " + httpServletRequest.getHeader(headerNameKey));

                    if (headerNameKey.equals("Accept-Language")) {
                        language = httpServletRequest.getHeader(headerNameKey);
                        this.logger.debug("[" + config.getProperty("service.name") + "] " + "Accept-Language: "
                                + language);
                    }
                    if (headerNameKey.equals("Accept")) {
                        accept = httpServletRequest.getHeader(headerNameKey);
                        this.logger
                                .debug("[" + config.getProperty("service.name") + "] " + "Accept: " + accept);
                    }
                    if (headerNameKey.equals("Authorization")) {
                        authorization = httpServletRequest.getHeader(headerNameKey);
                    }
                }

                // language
                if (language.startsWith("de")) {
                    language = "de";
                } else if (language.startsWith("en")) {
                    language = "en";
                } else if (httpServletRequest.getParameter("l") != null) {
                    language = httpServletRequest.getParameter("l");
                } else {
                    language = "de";
                }

                // if not exists token: read request parameter
                if ((authorization == null || authorization.equals(""))
                        && httpServletRequest.getParameter("access_token") != null
                        && !httpServletRequest.getParameter("access_token").equals("")) {
                    authorization = httpServletRequest.getParameter("access_token");
                }

                // if not exists token
                if (authorization == null || authorization.equals("")) {

                    // if exists PaiaService-Cookie: read content
                    Cookie[] cookies = httpServletRequest.getCookies();

                    if (cookies != null) {
                        for (Cookie cookie : cookies) {
                            if (cookie.getName().equals("PaiaService")) {

                                String value = URLDecoder.decode(cookie.getValue(), "UTF-8");
                                this.logger.info(value);
                                LoginResponse loginResponse = mapper.readValue(value, LoginResponse.class);

                                // A C H T U N G: ggf. andere patronID im Cookie als in Request (UniAccount vs. BibAccount)
                                if (loginResponse.getPatron().equals(patronid)) {
                                    authorization = loginResponse.getAccess_token();
                                }

                                break;
                            }
                        }

                        // if not exists token - search for Shibboleth-Token
                        if (authorization == null || authorization.equals("")) {

                            if (Lookup.lookupAll(AuthorizationInterface.class).size() > 0) {

                                AuthorizationInterface authorizationInterface = Lookup
                                        .lookup(AuthorizationInterface.class);
                                // init Authorization Service
                                authorizationInterface.init(this.config);

                                try {

                                    authorization = authorizationInterface.getAuthCookies(cookies);
                                } catch (AuthorizationException e) {

                                    // TODO correct error handling
                                    this.logger.error("[" + config.getProperty("service.name") + "] "
                                            + HttpServletResponse.SC_UNAUTHORIZED + "!");
                                }

                                this.logger.debug("[" + config.getProperty("service.name") + "] "
                                        + "Authorization: " + authorization);
                            }
                        }
                    }
                }

                httpServletResponse.setHeader("Access-Control-Allow-Origin",
                        config.getProperty("Access-Control-Allow-Origin"));
                httpServletResponse.setHeader("Cache-Control", config.getProperty("Cache-Control"));

                // check token ...
                boolean isAuthorized = false;

                if (authorization != null && !authorization.equals("")) {

                    if (Lookup.lookupAll(AuthorizationInterface.class).size() > 0) {

                        AuthorizationInterface authorizationInterface = Lookup
                                .lookup(AuthorizationInterface.class);
                        // init Authorization Service
                        authorizationInterface.init(this.config);

                        try {

                            isAuthorized = authorizationInterface.isTokenValid(httpServletResponse, service,
                                    patronid, authorization);
                        } catch (AuthorizationException e) {

                            // TODO correct error handling
                            this.logger.error("[" + config.getProperty("service.name") + "] "
                                    + HttpServletResponse.SC_UNAUTHORIZED + "!");
                        }
                    } else {

                        // TODO correct error handling
                        this.logger.error("[" + this.config.getProperty("service.name") + "] "
                                + HttpServletResponse.SC_INTERNAL_SERVER_ERROR + ": "
                                + "Authorization Interface not implemented!");
                    }
                }

                this.logger.debug("[" + config.getProperty("service.name") + "] " + "Authorization: "
                        + authorization + " - " + isAuthorized);

                if (isAuthorized) {

                    // execute query
                    this.provideService(httpServletRequest, httpServletResponse, patronid, service, format,
                            language, redirect_url, documentList);
                } else {

                    // Authorization
                    this.authorize(httpServletRequest, httpServletResponse, format, documentList);
                }
            } else {

                this.logger.error("[" + config.getProperty("service.name") + "] "
                        + HttpServletResponse.SC_METHOD_NOT_ALLOWED + ": " + httpServletRequest.getMethod()
                        + " for '" + service + "' not allowed!");

                // Error handling mit suppress_response_codes=true
                if (httpServletRequest.getParameter("suppress_response_codes") != null) {
                    httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                }
                // Error handling mit suppress_response_codes=false (=default)
                else {
                    httpServletResponse.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
                }

                RequestError requestError = new RequestError();
                requestError.setError(this.config
                        .getProperty("error." + Integer.toString(HttpServletResponse.SC_METHOD_NOT_ALLOWED)));
                requestError.setCode(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
                requestError.setDescription(this.config.getProperty("error."
                        + Integer.toString(HttpServletResponse.SC_METHOD_NOT_ALLOWED) + ".description"));
                requestError.setErrorUri(this.config.getProperty(
                        "error." + Integer.toString(HttpServletResponse.SC_METHOD_NOT_ALLOWED) + ".uri"));

                this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url);
            }
        }
    }
}