Example usage for org.json.simple JSONArray toJSONString

List of usage examples for org.json.simple JSONArray toJSONString

Introduction

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

Prototype

public String toJSONString() 

Source Link

Usage

From source file:sce.RESTAppMetricJob.java

@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
    Connection conn = null;/* w  w  w.j  a  v a 2 s. c o  m*/
    try {
        String url1 = prop.getProperty("kb_url");
        //required parameters #url
        JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
        String callUrl = jobDataMap.getString("#url"); // url to call when passing result data from SPARQL query
        if (callUrl == null) {
            throw new JobExecutionException("#url parameter must be not null");
        }
        String timeout = jobDataMap.getString("#timeout"); // timeout in ms to use when calling the #url
        if (timeout == null) {
            timeout = "5000";
        }

        //first SPARQL query to retrieve application related metrics and business configurations
        String url = url1 + "?query=" + URLEncoder.encode(getSPARQLQuery(), "UTF-8");
        URL u = new URL(url);
        final String usernamePassword = u.getUserInfo();
        if (usernamePassword != null) {
            Authenticator.setDefault(new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(usernamePassword.split(":")[0],
                            usernamePassword.split(":")[1].toCharArray());
                }
            });
        }
        this.urlConnection = u.openConnection();
        this.urlConnection.setRequestProperty("Accept", "application/sparql-results+json");
        HashMap<String, Object> res = new ObjectMapper().readValue(urlConnection.getInputStream(),
                HashMap.class);
        HashMap<String, Object> r = (HashMap<String, Object>) res.get("results");
        ArrayList<Object> list = (ArrayList<Object>) r.get("bindings");
        ArrayList<String[]> lst = new ArrayList<>();
        for (Object obj : list) {
            HashMap<String, Object> o = (HashMap<String, Object>) obj;
            String mn = (String) ((HashMap<String, Object>) o.get("mn")).get("value");
            String bc = (String) ((HashMap<String, Object>) o.get("bc")).get("value");
            lst.add(new String[] { mn, bc });
        }

        //second SPARQL query to retrieve alerts for SLA
        url = url1 + "?query=" + URLEncoder.encode(getValuesForMetrics(lst), "UTF-8");
        u = new URL(url);
        //java.io.FileWriter fstream = new java.io.FileWriter("/var/www/html/sce/log.txt", false);
        //java.io.BufferedWriter out = new java.io.BufferedWriter(fstream);
        //out.write(getAlertsForSLA(lst, slaTimestamp));
        //out.close();
        this.urlConnection = u.openConnection();
        this.urlConnection.setRequestProperty("Accept", "application/sparql-results+json");

        //format the result
        HashMap<String, Object> alerts = new ObjectMapper().readValue(urlConnection.getInputStream(),
                HashMap.class);
        HashMap<String, Object> r1 = (HashMap<String, Object>) alerts.get("results");
        ArrayList<Object> list1 = (ArrayList<Object>) r1.get("bindings");
        String result = "";

        //MYSQL CONNECTION
        conn = Main.getConnection();
        // conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); // use for transactions and at the end call conn.commit() conn.close()
        int counter = 0;

        //SET timestamp FOR MYSQL ROW
        Date dt = new java.util.Date();
        SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String timestamp = sdf.format(dt);

        // JSON to be sent to the SM
        JSONArray jsonArray = new JSONArray();

        for (Object obj : list1) {
            //JSON to insert into database
            //JSONArray jsonArray = new JSONArray();
            HashMap<String, Object> o = (HashMap<String, Object>) obj;
            String sm = (String) ((HashMap<String, Object>) o.get("sm")).get("value"); //metric
            String mn = (String) ((HashMap<String, Object>) o.get("mn")).get("value"); //metric_name
            String mu = (String) ((HashMap<String, Object>) o.get("mu")).get("value"); //metric_unit
            String v = (String) ((HashMap<String, Object>) o.get("v")).get("value"); //value
            String mt = (String) ((HashMap<String, Object>) o.get("mt")).get("value"); //metric_timestamp
            String bc = (String) ((HashMap<String, Object>) o.get("bc")).get("value"); //business_configuration

            // add these metric value to the json array
            JSONObject object = new JSONObject();
            object.put("business_configuration", bc);
            object.put("metric", sm);
            object.put("metric_name", mn);
            object.put("metric_unit", mu);
            object.put("value", v);
            object.put("metric_timestamp", mt);
            jsonArray.add(object);

            //INSERT THE DATA INTO DATABASE
            PreparedStatement preparedStatement = conn.prepareStatement(
                    "INSERT INTO quartz.QRTZ_APP_METRICS (timestamp, metric, metric_name, metric_unit, value, metric_timestamp, business_configuration) VALUES (?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE timestamp=?");
            preparedStatement.setString(1, timestamp); // date
            preparedStatement.setString(2, sm); // metric
            preparedStatement.setString(3, mn); // metric_name
            preparedStatement.setString(4, mu); // metric_unit
            preparedStatement.setString(5, v); // value
            preparedStatement.setString(6, mt); // metric_timestamp (e.g., 2014-12-01T16:14:00)
            preparedStatement.setString(7, bc); // business_configuration 
            preparedStatement.setString(8, timestamp); // date
            preparedStatement.executeUpdate();
            preparedStatement.close();

            result += "\nService Metric: " + sm + "\n";
            result += "\nMetric Name: " + mn + "\n";
            result += "\nMetric Unit: " + mu + "\n";
            result += "Timestamp: " + mt + "\n";
            result += "Business Configuration: " + bc + "\n";
            result += "Value" + (counter + 1) + ": " + v + "\n";
            result += "Call Url: " + callUrl + "\n";

            counter++;
        }

        // send the JSON to the CM
        URL tmp_u = new URL(callUrl);
        final String usr_pwd = tmp_u.getUserInfo();
        String usr = null;
        String pwd = null;
        if (usr_pwd != null) {
            usr = usr_pwd.split(":")[0];
            pwd = usr_pwd.split(":")[1];
        }
        sendPostRequest(jsonArray.toJSONString(), callUrl, usr, pwd, Integer.parseInt(timeout));

        //set the result to the job execution context, to be able to retrieve it later (e.g., with a job listener)
        context.setResult(result);

        if (jobDataMap.containsKey("#notificationEmail")) {
            sendEmail(context, jobDataMap.getString("#notificationEmail"));
        }
        jobChain(context);
    } catch (MalformedURLException ex) {
        Logger.getLogger(RESTCheckSLAJob.class.getName()).log(Level.SEVERE, null, ex);
        ex.printStackTrace();
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(RESTCheckSLAJob.class.getName()).log(Level.SEVERE, null, ex);
        ex.printStackTrace();
    } catch (IOException | SQLException ex) {
        Logger.getLogger(RESTCheckSLAJob.class.getName()).log(Level.SEVERE, null, ex);
        ex.printStackTrace();
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        try {
            if (!conn.isClosed()) {
                conn.close();
            }
        } catch (SQLException ex) {
            Logger.getLogger(RESTCheckSLAJob.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:semRewrite.CommonCNFUtil.java

/***********************************************************
 * save the intermediate parsing result to JSON file
 *///from   www.  j av a 2 s.  c om
public static String saveCNFMaptoFile(List<QAPair> list, String path) {

    File f = new File(path);
    if (!f.exists())
        try {
            f.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    System.out.println(f.getAbsolutePath());
    try (PrintWriter pw = new PrintWriter(f)) {
        JSONArray arr = new JSONArray();
        for (QAPair k : list) {
            JSONObject obj = new JSONObject();
            obj.put("file", k.file);
            obj.put("index", "" + k.index);
            obj.put("query", k.query);
            obj.put("queryCNF", k.queryCNF.toString());
            obj.put("answer", k.answer);
            obj.put("answerCNF", k.answerCNF.toString());
            arr.add(obj);
        }
        System.out.println(arr.toJSONString());
        pw.print(arr.toJSONString());
        pw.flush();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    return f.getAbsolutePath();
}

From source file:semRewrite.QAOutputGenerator.java

/************************************************************
 * save the record to a json file//ww w.j  ava2  s  .c  om
 */
public static void saveRecord(List<Record> list, String path) throws FileNotFoundException {

    if (list == null) {
        System.out.println("INFO in RewriteRuleUtil.saveRecord():  list is null");
        return;
    }
    try (PrintWriter pw = new PrintWriter(path)) {
        JSONArray arr = new JSONArray();
        for (Record k : list) {
            JSONObject obj = new JSONObject();
            obj.put("index", k.index + "");
            obj.put("sentence", k.sen);
            obj.put("CNF", k.CNF.toString());
            obj.put("KIF", k.KIF);
            obj.put("result", k.result);
            arr.add(obj);
        }
        pw.println(arr.toJSONString());
        pw.flush();
    }
}

From source file:Servelets.ShowAll.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//  w  w w .  j av  a  2 s.  c o  m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        int num = Integer.parseInt(request.getParameter("num"));
        SE.System_manage sys = System_manage.Get_System_manage();
        if (num == 1) //search Employee
        {
            String chars = request.getParameter("chars");
            ArrayList<User> users = sys.Search_user_by_name(chars);
            JSONObject jsonobj = null;
            JSONArray array = new JSONArray();
            for (User u : users) {
                if (u.getType_id() != 5) {
                    jsonobj = new JSONObject();
                    jsonobj.put("name", u.getF_name() + " " + u.getL_name());
                    jsonobj.put("email", u.getEmail());
                    jsonobj.put("id", u.getID());
                    if (u.getGander() == 1)
                        jsonobj.put("gander", "Mall");
                    else
                        jsonobj.put("gander", "femal");
                    jsonobj.put("type", sys.User_Types().get(u.getType_id()));
                    jsonobj.put("Block", u.getBlock());
                    array.add(jsonobj);
                }
            }
            response.getWriter().write(array.toString());
        } else if (num == 2) //search Customer
        {
            String chars = request.getParameter("chars");
            ArrayList<User> users = sys.Search_user_by_name(chars);
            JSONObject jsonobj = null;
            JSONArray array = new JSONArray();
            for (User u : users) {
                if (u.getType_id() == 5) {
                    jsonobj = new JSONObject();
                    jsonobj.put("name", u.getF_name() + " " + u.getL_name());
                    jsonobj.put("email", u.getEmail());
                    jsonobj.put("id", u.getID());

                    HashMap<Integer, String> aa = u.getAddresses();
                    if (aa.size() != 0) {
                        Map.Entry<Integer, String> oo = aa.entrySet().iterator().next();
                        jsonobj.put("address", oo.getValue());
                    } else {
                        jsonobj.put("address", "Nonsdadse");
                    }
                    aa = u.getPhones();
                    if (aa.size() != 0) {
                        Map.Entry<Integer, String> oo = aa.entrySet().iterator().next();
                        jsonobj.put("phone", oo.getValue());
                    } else {
                        jsonobj.put("phone", "None");
                    }
                    jsonobj.put("Block", u.getBlock());
                    array.add(jsonobj);
                }
            }
            response.getWriter().write(array.toString());
        } else if (num == 3) {
            HttpSession session = request.getSession();
            int chars = (int) session.getAttribute("chars");
            int id = (int) session.getAttribute("id");
            User E = (User) session.getAttribute("User");
            E.Load_inbox();
            General_massge g = null;
            if (E.getInbox().size() != 0) {
                g = (General_massge) E.getInbox().get(chars);
                E.Show_this_massage(chars);
            } else {
                g = (General_massge) Message_Controller.Get_Message_Controller().Search_Massage(id);
            }
            JSONObject json = new JSONObject();
            json.put("content", g.getContent());
            User sendeer = (User) sys.Search_user_by_id(g.getSender_id());
            json.put("sendername", sendeer.getF_name() + " " + sendeer.getL_name());
            json.put("date", sys.Get_this_date(g.getDate_id()));
            json.put("time", g.getTime());
            JSONArray jsarr = new JSONArray();
            jsarr.add(json);

            ArrayList<SE.Comment> Commints = g.getMy_Commint();
            for (SE.Comment c : Commints) {
                json = new JSONObject();
                User us = (User) sys.Search_user_by_id(c.getSender_id());
                json.put("sendername", us.getF_name() + " " + us.getL_name());
                json.put("date", sys.Get_this_date(c.getDate_id()));
                json.put("time", c.getTime());
                json.put("content", c.getContent());
                jsarr.add(json);
            }
            System.err.println(jsarr.toJSONString());
            response.getWriter().write(jsarr.toJSONString());
        }
        if (num == 4) {
            HttpSession s = request.getSession();
            int id = (int) s.getAttribute("id");
            User E = (User) s.getAttribute("User");
            int chars = (int) s.getAttribute("chars");
            E.Load_inbox();
            String content = request.getParameter("content");
            SE.Message_Controller con = Message_Controller.Get_Message_Controller();
            SE.Comment commint = new Comment();
            commint.setContent(content);
            commint.setDate_id(sys.Get_date_iD());
            commint.setMassage_type_id(3);
            commint.setSender_id(E.getID());
            commint.setState(5);
            commint.setTime(sys.Get_time());
            con.Reply_message(id, commint);
            response.sendRedirect("Show_my_profile.jsp");
        }
        if (num == 5) {
            int chars = Integer.parseInt(request.getParameter("chars"));
            HttpSession ses = request.getSession();
            User u = (User) ses.getAttribute("User");
            System.err.println("aaaaaaaaaaaaaaaaaaaaaaaa  :" + u.getEmail() + "   " + u.getID());
            u.Load_inbox();
            ArrayList<SE.General_massge> message = u.Show_my_massage(chars);
            JSONObject jsobj = null;
            JSONArray jsarr = new JSONArray();
            for (General_massge g : message) {
                jsobj = new JSONObject();
                jsobj.put("id", g.getId());
                User Sender = (User) sys.Search_user_by_id(g.getSender_id());
                jsobj.put("sendername", u.getF_name() + " " + u.getL_name());
                jsobj.put("date", sys.Get_this_date(g.getDate_id()));
                jsobj.put("time", g.getTime());
                jsobj.put("numofcommit", g.getMy_Commint().size());
                jsarr.add(jsobj);
            }
            System.err.println(jsarr.toString());
            response.getWriter().write(jsarr.toJSONString());
        }
        if (num == 6) {
            int chars = Integer.parseInt(request.getParameter("chars"));
            Service_Management serv = Service_Management.Get_Serive_Management();
            ArrayList<Order> ord = serv.Show_all_order(chars);
            JSONObject jsobj = null;
            JSONArray jsarr = new JSONArray();
            for (Order o : ord) {
                jsobj = new JSONObject();
                jsobj.put("id", o.getId());
                jsobj.put("startdate", sys.Get_this_date(o.getDate_start_id()));
                jsobj.put("enddate", o.getDate_end());
                jsobj.put("tecnicalid", o.getMy_Technical_id().get(0));
                jsarr.add(jsobj);
            }
            response.getWriter().write(jsarr.toJSONString());
        }
    }
}

From source file:Servelets.SHowAllSPare.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from ww  w. j a  v a  2  s . c o  m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        String s = request.getParameter("SpareName");
        Spare_parts namespare = Service_Management.Get_Serive_Management().Like_SpareParts(s);
        HashMap<String, Double> namecost = namespare.getNAmeMony();
        JSONObject json = null;
        JSONArray jsonArray = new JSONArray();
        for (Map.Entry<String, Double> entrySet : namecost.entrySet()) {
            String key = entrySet.getKey();
            Double value = entrySet.getValue();
            json = new JSONObject();
            json.put("SpareName", key);
            json.put("Cost", value);
            jsonArray.add(json);
        }
        response.getWriter().write(jsonArray.toJSONString());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:servlet.ProductServlet.java

@GET
@Produces("application/json; charset=UTF-8")
public String doGet() throws IOException, SQLException {
    JSONArray jArray = new JSONArray();
    Connection conn = DatabaseConnection.getConnection();
    String query = "SELECT * FROM products";
    PreparedStatement preparedStatement = conn.prepareStatement(query);
    ResultSet resultSet = preparedStatement.executeQuery();
    while (resultSet.next()) {
        int num_columns = resultSet.getMetaData().getColumnCount();
        JSONObject jObject = new JSONObject();
        for (int i = 0; i < num_columns; i++) {
            String columnName = resultSet.getMetaData().getColumnLabel(i + 1);
            Object columnValue = resultSet.getObject(i + 1);
            jObject.put(columnName, columnValue);
        }/*from   ww  w  .java2 s  .c  o  m*/
        jArray.add(jObject);
    }
    return jArray.toJSONString();
}

From source file:utils.JsonDatabase.java

/**
 * Fetches vm configurations from the web and populates a database with them
 * @return The different vm configurations available
 *///from   www. j  a  va  2  s.co  m
public String[] refreshDbContents() {
    JSONArray array = NetworkManager.getInstance().fetchVmConfigs();

    if (array != null) {
        String[] alternatives = digestAlternatives(array);
        try {
            //Writes the db
            FileWriter writer = new FileWriter(Preferences.getSavingDir() + "vmconfigs.json");
            writer.write(array.toJSONString());
            writer.close();
            return alternatives;

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    return null;
}

From source file:webrtc.server.WebRTCServer.java

public static void main(String[] args) {

    wsServer = WebSocketServer.createServer();

    db = new Database("127.0.0.1:3306", "webcamtest-db", "admin", "admin");

    db.getTable("rooms").findAll(row -> {
        try {// w w w. j av a  2 s.c  om
            wsServer.newRoom((String) row.get(RoomTable.RID), WebSocketRoom.TYPES.PERMANENT);
        } catch (SQLException ex) {
            LOG.log(Level.SEVERE, null, ex);
        }
    });

    HTTPServer httpServer = (HTTPServer) HTTPServer.createServer();
    httpServer.setRootPath("/Users/gaelph/NetBeansProjects/WebRTC Server/www/");

    httpServer.on("GET", "/api/user/:uid", (request, response) -> {

        Table users = db.getTable("users");
        JSONObject user = new JSONObject();
        response.status = HTTPStatusCodes.NOT_FOUND;

        users.find(UserTable.UID, request.params.get("uid"), row -> {
            try {
                user.put("sid", (String) row.get(UserTable.SID));
                user.put("firstname", (String) row.get(UserTable.FIRST_NAME));
                user.put("lastname", (String) row.get(UserTable.LAST_NAME));

                response.status = HTTPStatusCodes.OK;
                response.setBody(user.toJSONString());

            } catch (SQLException ex) {
                LOG.log(Level.SEVERE, null, ex);
            }
        });
        try {
            response.send();
        } catch (Exception ex) {
            LOG.log(Level.SEVERE, null, ex);
        }
    });

    httpServer.on("POST", "/api/user/:uid", (request, response) -> {
        UserTable users = UserTable.newInstance();

        users.find(UserTable.UID, request.formContent.get("UID"), row -> {
            try {
                row.set(UserTable.EMAIL, request.formContent.get("email"));
                row.set(UserTable.PASSWORD, request.formContent.get("password"));
                row.set(UserTable.FIRST_NAME, request.formContent.get("firstName"));
                row.set(UserTable.LAST_NAME, request.formContent.get("lastName"));

                row.commit();

                JSONObject jsonUser = new JSONObject();
                jsonUser.put("UID", request.formContent.get("UID"));
                jsonUser.put("firstname", request.formContent.get("firstName"));
                jsonUser.put("lastname", request.formContent.get("lastName"));
                response.setBody(jsonUser.toJSONString());

                response.status = HTTPStatusCodes.OK;
                response.send();
            } catch (SQLException ex) {
                LOG.log(Level.SEVERE, null, ex);
                response.status = HTTPStatusCodes.INTERNAL_SERVER_ERROR;
                try {
                    response.send();
                } catch (Exception ex1) {
                    LOG.log(Level.SEVERE, null, ex1);
                }
            } catch (Exception ex) {
                LOG.log(Level.SEVERE, null, ex);
            }
        });
    });

    httpServer.on("DELETE", "/api/user/:uid", (request, response) -> {
        UserTable users = UserTable.newInstance();

        users.delete(UserTable.UID, request.params.get("UID"));

        try {
            response.send();
        } catch (Exception ex) {
            LOG.log(Level.SEVERE, null, ex);
        }
    });

    httpServer.on("GET", "/api/rooms", (request, response) -> {
        JSONArray jRooms = new JSONArray();

        wsServer.getRooms().stream().forEach((room) -> {
            jRooms.add(room.toJSONString());
        });

        response.status = HTTPStatusCodes.OK;
        response.setBody(jRooms.toJSONString());

        try {
            response.send();
        } catch (Exception ex) {
            LOG.log(Level.SEVERE, null, ex);
        }
    });

    httpServer.on("GET", "/api/room/:rid/users", (request, response) -> {

        wsServer.getRooms().stream().filter((room) -> {
            return room.rid.equals(request.params.get("rid"));
        }).findFirst().ifPresent((room) -> {
            JSONArray users = new JSONArray();

            room.participants.forEach((participant) -> {
                JSONObject jP = new JSONObject();

                db.getTable("users").find(UserTable.SID, participant.sid, row -> {
                    try {
                        jP.put("firstname", row.get("first_name"));
                        jP.put("sid", row.get("SID"));
                    } catch (SQLException ex) {
                        LOG.log(Level.SEVERE, null, ex);
                    }
                });

                users.add(jP.toJSONString());
            });

            response.status = HTTPStatusCodes.OK;
            response.setContentType(HTTPMIMETypes.get(HTTPMIMETypes.TYPES.JSON) + "; charset=utf-8");
            response.setBody(users.toJSONString());
        });

        try {
            response.send();
        } catch (Exception ex) {
            LOG.log(Level.SEVERE, null, ex);
        }
    });

    httpServer.on("POST", "/api/login", (request, response) -> {
        UserTable userTable = UserTable.newInstance();

        Object[] params;

        String contentType = request.header.get("content-type").split(";")[0].trim();

        switch (contentType) {
        case "application/json":
            params = Arrays.asList(request.jsonContent.get("email"), request.jsonContent.get("password"))
                    .toArray();
            break;

        default:
            response.status = 415; {
            try {
                response.send();
            } catch (Exception ex) {
                LOG.log(Level.SEVERE, null, ex);
            }
        }
            return;
        }

        response.status = HTTPStatusCodes.UNAUTHORIZED;
        response.setBody("No user with such email or password");

        JSONObject message = new JSONObject();
        JSONObject user = new JSONObject();

        userTable.select(null, "`email`=? and `password`=?", params, null, false, row -> {
            try {
                user.put("UID", row.get(UserTable.UID));
                user.put("SID", row.get(UserTable.SID)); //Is this relevant?
                user.put("firstname", row.get(UserTable.FIRST_NAME));
                user.put("lastname", row.get(UserTable.LAST_NAME));
            } catch (SQLException ex) {
                LOG.log(Level.SEVERE, null, ex);
            }
        });

        if (!user.isEmpty()) {
            message.put("user", user);
            response.status = HTTPStatusCodes.OK;
            response.setBody(message.toJSONString());

            HTTPCookie cookie = new HTTPCookie("sid", (String) user.get("SID"), "127.0.0.1", "/");
            response.cookies.add(cookie);
            cookie = new HTTPCookie("sid", (String) user.get("SID"), "localhost", "/");
            response.cookies.add(cookie);
        }

        try {
            response.send();
        } catch (Exception ex) {
            LOG.log(Level.SEVERE, null, ex);
        }

    });

    httpServer.on("POST", "api/user/create", (request, response) -> {
        UserTable users = UserTable.newInstance();

        if (users.find(UserTable.EMAIL, request.formContent.get("email")).isPresent()) {
            response.status = HTTPStatusCodes.BAD_REQUEST;
            response.setBody(
                    "User with email already exists (" + (String) request.formContent.get("email") + ")");
            try {
                response.send();
            } catch (Exception ex) {
                LOG.log(Level.SEVERE, null, ex);
            }
            return;
        }

        String UID = Utils.makeRandomString(24);
        String apiToken = Utils.makeRandomString(32);

        try {
            users.newRow(row -> {
                try {
                    row.set(UserTable.UID, UID);
                    row.set(UserTable.API_TOKEN, apiToken);
                    row.set(UserTable.EMAIL, request.formContent.get("email"));
                    row.set(UserTable.PASSWORD, request.formContent.get("password"));
                    row.set(UserTable.FIRST_NAME, request.formContent.get("firstName"));
                    row.set(UserTable.LAST_NAME, request.formContent.get("lastName"));
                    row.set(UserTable.STATUS, 0);

                    row.commit();
                } catch (SQLException ex) {
                    LOG.log(Level.SEVERE, null, ex);

                    response.status = HTTPStatusCodes.INTERNAL_SERVER_ERROR;
                    try {
                        response.send();
                    } catch (Exception ex1) {
                        LOG.log(Level.SEVERE, null, ex1);
                    }
                }
            });
        } catch (SQLException ex) {
            LOG.log(Level.SEVERE, null, ex);

            response.status = HTTPStatusCodes.INTERNAL_SERVER_ERROR;
            try {
                response.send();
            } catch (Exception ex1) {
                LOG.log(Level.SEVERE, null, ex1);
            }

            return;
        }

        users.find(UserTable.UID, UID, row -> {
            try {
                JSONObject user = new JSONObject();

                user.put("UID", row.get(UserTable.UID));
                user.put("api_token", apiToken);
                user.put("SID", row.get(UserTable.SID)); //Is this relevant?
                user.put("firstname", row.get(UserTable.FIRST_NAME));
                user.put("lastname", row.get(UserTable.LAST_NAME));

                response.status = HTTPStatusCodes.CREATED;
                response.setBody(user.toJSONString());

                response.send();

            } catch (SQLException ex) {
                LOG.log(Level.SEVERE, null, ex);
                response.status = HTTPStatusCodes.INTERNAL_SERVER_ERROR;
                try {
                    response.send();
                } catch (Exception ex1) {
                    LOG.log(Level.SEVERE, null, ex1);
                }
            } catch (Exception ex) {
                LOG.log(Level.SEVERE, null, ex);
            }
        });
    });

    httpServer.listen(HTTP_PORT);

    wsServer.on("connect", (WebSocketConnection connection) -> {
        if (connection.request.cookies.stream().anyMatch(cookie -> cookie.name.equals("token"))) {
            String UID = connection.request.cookies.stream().filter(cookie -> cookie.name.equals("token"))
                    .findFirst().get().value;

            if (!db.getTable("users").find(UserTable.UID, UID).isPresent()) {
                try {
                    connection.close();
                } catch (IOException ex) {
                    LOG.log(Level.SEVERE, null, ex);
                }
                return;
            }

            db.getTable("users").find(UserTable.UID, UID, row -> {
                try {
                    row.set(UserTable.SID, connection.sid);
                    row.commit();
                    LOG.log(Level.INFO, "User {0} connected",
                            row.get(UserTable.UID) + ", " + row.get(UserTable.FIRST_NAME));
                } catch (SQLException ex) {
                    LOG.log(Level.SEVERE, null, ex);
                }

                connection.uid = UID;

            });

        }

        PeerConnection pConnection = new PeerConnection();

        pConnection.on("icecandidate", object -> connection.emit("icecandidate", (String) object));

        connection.on("joined", rid -> {
            connection.getJoinedRooms().forEach(room -> {
                JSONObject msg = new JSONObject();
                msg.put("sid", connection.sid);

                db.getTable("users").find(UserTable.SID, connection.sid, row -> {
                    try {
                        msg.put("firstname", row.get(UserTable.FIRST_NAME));

                        LOG.log(Level.INFO, "User {0}", row.get(UserTable.SID) + " joined room " + rid);
                    } catch (SQLException ex) {
                        LOG.log(Level.SEVERE, null, ex);
                    }
                });

                room.emit("user_joined", msg.toJSONString());
            });
        });

        connection.on("left", rid -> {
            connection.getJoinedRooms().forEach(room -> {
                JSONObject msg = new JSONObject();
                msg.put("sid", connection.sid);

                LOG.log(Level.INFO, "User {0}", connection.sid + " left room " + rid);

                room.emit("user_left", msg.toJSONString());
            });
        });

        connection.on("disconnect", data -> {
            wsServer.getRooms().stream().filter(room -> room.participants.contains(connection))
                    .forEach(room -> room.leave(connection));

            db.getTable("users").find(UserTable.SID, connection.sid, row -> {
                try {
                    LOG.log(Level.INFO, "User {0} disconnected",
                            row.get(UserTable.UID) + ", " + row.get(UserTable.FIRST_NAME));
                } catch (SQLException ex) {
                    LOG.log(Level.SEVERE, null, ex);
                }
            });

        });

        connection.on("message", data -> {

        });

        connection.on("offer", data -> {
            try {
                JSONParser parser = new JSONParser();
                String string = (String) parser.parse(data);
                JSONObject offer = (JSONObject) parser.parse(string);

                JSONObject body = (JSONObject) ((JSONObject) offer).get("body");

                pConnection.setRemoteDescription(body);

                body = pConnection.createAnswer();
                body.put("sid", connection.sid);

                connection.emit("answer", body.toJSONString());

                pConnection.setLocalDescription(body);
            } catch (ParseException ex) {
                LOG.log(Level.SEVERE, null, ex);
            } catch (Exception ex) {
                Logger.getLogger(WebRTCServer.class.getName()).log(Level.SEVERE, null, ex);
            }
        });

        connection.on("answer", data -> {
            try {
                JSONParser parser = new JSONParser();
                String string = (String) parser.parse(data);
                JSONObject offer = (JSONObject) parser.parse(string);

                JSONObject body = (JSONObject) ((JSONObject) offer).get("body");

                pConnection.setRemoteDescription(body);
            } catch (ParseException ex) {
                LOG.log(Level.SEVERE, null, ex);
            }
        });

        connection.on("icecandidate", (String data) -> {
            try {
                JSONParser parser = new JSONParser();
                JSONObject message = (JSONObject) parser.parse((String) parser.parse(data));
                JSONObject candidateDict = (JSONObject) message.get("body");
                pConnection.addCandidate(candidateDict);
            } catch (ParseException ex) {
                LOG.log(Level.SEVERE, null, ex);
            }
        });

        connection.on("hangup", data -> {
            try {
                JSONObject offer = (JSONObject) new JSONParser().parse(data);
            } catch (ParseException ex) {
                LOG.log(Level.SEVERE, null, ex);
            }
        });
    });

    wsServer.listen(WS_PORT);

}

From source file:webscrap.WebScrap.java

/**
 * @param args the command line arguments
 *///from  ww w.  ja  v a 2 s .com
public static void main(String[] args) {
    // TODO code application logic here
    Document doc;
    try {
        doc = Jsoup.connect(
                "http://www.metmuseum.org/collection/the-collection-online/search/15538?pos=1&rpp=30&pg=1&rndkey=20150122&ft=*&deptids=2")
                .get();

        File jsonFile = new File("Records.json");
        FileWriter output = new FileWriter(jsonFile);
        JSONArray store = new JSONArray();
        //Declarations for JSON output
        String nameTag = "Name";
        String name;
        String artistTag = "Artist";
        String artistName;
        String imgURLTag = "imgURL";
        String imgsrc;
        String dateTag = "Date";
        String date;
        String geoTag = "Geography";
        String geoVal;
        String cultureTag = "Culture";
        String culture;
        String mediumTag = "Medium";
        String medium;
        String dimTag = "Dimension";
        String dim;
        String classTag = "Classification";
        String classification;
        String credit_line_tag = "Credit_Line";
        String credit_line;
        String accessNumTag = "Accession_Number";
        String accessNum;
        String RnRTag = "Rights_and_Reproduction";
        String RnR;

        //trying to load the next urls
        String next = "http://www.metmuseum.org/collection/the-collection-online/search/11432?pos=1&rpp=30&pg=1&rndkey=20150123&ft=*&deptids=2";
        int i = 500;
        while (i != 0) {

            name = "";
            artistName = "";
            imgsrc = "";
            date = "";
            //geoVal = "not available";
            //culture = "not available";
            medium = "";
            dim = "";
            classification = "";
            credit_line = "";
            accessNum = "";
            //RnR = "not available";

            doc = Jsoup.connect(next).get();
            String o_title = doc.getElementsByTag("h2").text();
            String[] part_o = o_title.split("Email");
            String part_o1 = part_o[0];
            String part_o2 = part_o[1];
            //System.out.println(o_title);
            name = part_o1;
            //String artist = doc.getElementsByTag("h3").text();
            //System.out.println(artist);
            //artistName = artist;
            Elements imgdiv = doc.select("div#inner-image-container img");
            for (Element e : imgdiv) {
                imgsrc = e.absUrl("src");
            }

            Elements divs;
            divs = doc.select("div.tombstone");
            Elements divchild;
            divchild = divs.select("div");
            int count = 0;
            for (Element div : divchild) {
                String info = div.text();
                if (count != 0) {
                    String[] parts = info.split(":");
                    String part1 = parts[0];
                    String part2 = parts[1];

                    switch (part1) {
                    case "Artist":
                        artistName = part2;
                        break;
                    case "Date":
                        date = part2;
                        break;
                    case "Geography":
                        geoVal = part2;
                        break;
                    case "Culture":
                        culture = part2;
                        break;
                    case "Medium":
                        medium = part2;
                        break;
                    case "Dimensions":
                        dim = part2;
                        break;
                    case "Classification":
                        classification = part2;
                        break;
                    case "Credit Line":
                        credit_line = part2;
                        break;
                    case "Accession Number":
                        accessNum = part2;
                        break;
                    case "Rights and Reproduction":
                        RnR = part2;
                        break;
                    }
                }
                count++;
            }
            if (classification.equals(" Paintings")) {
                //System.out.println(nameTag+name);
                //System.out.println(artistTag+artistName);
                //System.out.println(imgURLTag+imgsrc);
                //System.out.println(dateTag+date);
                //System.out.println(mediumTag+medium);
                //System.out.println(dimTag+dim);
                //System.out.println(classTag+classification);
                //System.out.println(credit_line_tag+credit_line);
                //System.out.println(accessNumTag+accessNum);
                //System.out.println(i);
                //json writing
                JSONObject jsonObj = new JSONObject();
                jsonObj.put(nameTag, name);
                jsonObj.put(artistTag, artistName);
                jsonObj.put(imgURLTag, imgsrc);
                jsonObj.put(dateTag, date);
                jsonObj.put(mediumTag, medium);
                jsonObj.put(dimTag, dim);
                jsonObj.put(classTag, classification);
                jsonObj.put(credit_line_tag, credit_line);
                jsonObj.put(accessNumTag, accessNum);

                store.add(jsonObj);
                i--;
            }
            //going to next page      
            Element link = doc.select("a.next").first();
            next = link.attr("abs:href");

        }
        output.write(store.toJSONString());
        output.write("\n");
        output.flush();
        output.close();

    } catch (IOException e) {
    }

}

From source file:zebrinho.controller.TweetController.java

@RequestMapping(value = "/getTweetsAsync", method = RequestMethod.GET)
@ResponseBody//from  ww w .  j  ava  2s  . co m
public String getTweetsAsync(HttpServletRequest request, HttpServletResponse response) {

    User user = getLoggedUser(request);
    if (user == null) {
        return "ERROR";
    } else {
        List<Tweet> wall = Tweet.forUserWall(user);
        JSONArray list = new JSONArray();
        for (Tweet tweet : wall) {
            JSONObject obj = new JSONObject();
            obj.put("content", tweet.getContent());
            obj.put("date", tweet.getFormatedDate());
            obj.put("user", tweet.getUser().getUsername());
            list.add(obj);
        }
        return list.toJSONString();
    }
}