Example usage for org.json.simple JSONObject toString

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

Introduction

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

Prototype

@Override
    public String toString() 

Source Link

Usage

From source file:com.availo.wms.plugin.vhostloadbalancer.HTTPLoadBalancerRedirector.java

public void onHTTPRequest(IVHost vhost, IHTTPRequest req, IHTTPResponse resp) {
    if (!doHTTPAuthentication(vhost, req, resp)) {
        return;/*  www. j  ava2s  .c o  m*/
    }

    String vhostName = vhost.getName();
    getRedirector();

    String retStr = null;

    String queryStr = req.getQueryString();
    boolean isServerInfoXML = queryStr == null || !enableServerInfo ? false
            : queryStr.indexOf("serverInfoXML") >= 0;
    boolean isServerInfoJSON = queryStr == null || !enableServerInfo ? false
            : queryStr.indexOf("serverInfoJSON") >= 0;
    boolean isServerInfo = queryStr == null || !enableServerInfo ? false : queryStr.indexOf("serverInfo") >= 0;

    if (isServerInfoXML) {
        List<Map<String, Object>> info = this.redirector == null ? null : this.redirector.getInfo(vhostName);
        retStr = LoadBalancerUtils.serverInfoToXMLStr(info);
        resp.setHeader("Content-Type", "text/xml");
    } else if (isServerInfoJSON) {
        List<Map<String, Object>> info = this.redirector == null ? null : this.redirector.getInfo(vhostName);
        JSONObject jsonOutput = new JSONObject();
        jsonOutput.put("LoadBalancerServerInfo", info);
        retStr = jsonOutput.toString();
        resp.setHeader("Content-Type", "application/json");
    } else if (isServerInfo) {
        /** @TODO Currently, the only difference between this and the JSON output, is the content-type. */
        List<Map<String, Object>> info = this.redirector == null ? null : this.redirector.getInfo(vhostName);
        JSONObject jsonOutput = new JSONObject();
        jsonOutput.put("LoadBalancerServerInfo", info);
        retStr = jsonOutput.toString();
        resp.setHeader("Content-Type", "text/plain");
    } else {
        LoadBalancerRedirect redirect = this.redirector == null ? null : this.redirector.getRedirect(vhostName);
        retStr = "redirect=" + (redirect == null ? "unknown" : redirect.getHost());
    }

    try {
        OutputStream out = resp.getOutputStream();
        byte[] outBytes = retStr.getBytes();
        out.write(outBytes);
    } catch (Exception e) {
        WMSLoggerFactory.getLogger(HTTPLoadBalancerRedirector.class)
                .error("HTTPLoadBalancerRedirector: " + e.toString());
    }

}

From source file:ca.fastenalcompany.order.OrderManager.java

public String report() {
    String report = "";
    if (!orderQueue.isEmpty() || !orderList.isEmpty()) {
        JSONObject obj = new JSONObject();
        List<Order> list = new ArrayList(orderQueue);
        list.addAll(orderList);//  w  ww.  j  a  v a  2s  .com
        obj.put("orders", list);
        report = obj.toString();
    }
    return report;
}

From source file:cloudworker.WorkerThread.java

@SuppressWarnings("unchecked")
@Override/* w w  w.  ja va  2s .c  o m*/
public void run() {
    //Get queue url   
    GetQueueUrlResult urlResult = sqs.getQueueUrl(responseQName);
    String QueueUrl = urlResult.getQueueUrl();
    JSONObject result = new JSONObject();

    try {
        Thread.sleep(sleepLength);

        result.put("task_id", task_id);
        result.put("result", "0");

        sqs.sendMessage(new SendMessageRequest(QueueUrl, result.toString()));
        //System.out.println(Thread.currentThread().getName()+" sleep done!");

    } catch (Exception e) {
        result.put("task_id", task_id);
        result.put("result", "1");
        sqs.sendMessage(new SendMessageRequest(QueueUrl, result.toString()));

    }
}

From source file:LicenseKeyAPI.java

/**
 * Registers a user with the server// www.java2 s  .  co  m
 *
 * @param   userName    The users name to register with the server.
 * @param   userEmail   The users email to register with the server.
 * @return              The status code returned from the server.
 **/
public int registerUser(String userName, String userEmail) {
    String URLpostFixEndpoint = "api/client/register_user";

    // Creates HTTP POST request
    HttpPost httppost = new HttpPost(baseServerURLAddress + URLpostFixEndpoint);
    httppost.addHeader("Content-Type", "application/json");
    httppost.setHeader("Content-Type", "application/json; charset= utf-8");
    httppost.setHeader("Accept", "application/json");

    JSONObject json = new JSONObject();
    json.put("username", userName);
    json.put("email", userEmail);

    StringEntity entity = new StringEntity(json.toString(), "utf-8");

    // Adds the POST params to the request
    httppost.setEntity(entity);

    return sendPOST(httppost);
}

From source file:identify.SendMessage.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from 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, ParseException {
    String sender = request.getParameter("sender");
    String receiver = request.getParameter("receiver");
    String message = request.getParameter("body");
    int index = SaveToken.storage.findUsername(receiver);
    System.out.println(index);
    String tokenTo = SaveToken.storage.getData().get(index).getToken();
    JSONObject obj = new JSONObject();
    obj.put("sender", sender);
    obj.put("receiver", receiver);
    obj.put("body", message);
    JSONObject arrayObj = new JSONObject();
    arrayObj.put("to", tokenTo);
    arrayObj.put("data", obj);
    System.out.println(arrayObj.toString());
    String USER_AGENT = "Mozilla/5.0";
    String authKey = "key=AIzaSyBPldzkpB5YtLm3N8cYbdoweqtn5Dk3IfQ";
    String contentType = "application/json";
    String url = "https://fcm.googleapis.com/fcm/send";
    URL connection = new URL(url);
    HttpURLConnection con = (HttpURLConnection) connection.openConnection();

    //add reuqest header
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", USER_AGENT);
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
    con.setRequestProperty("Content-Type", contentType);
    con.setRequestProperty("Authorization", authKey);

    String urlParameters = arrayObj.toString();
    // Send post request
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuilder resp = new StringBuilder();
    while ((inputLine = in.readLine()) != null) {
        resp.append(inputLine);
    }
    in.close();
    String acrHeaders = request.getHeader("Access-Control-Request-Headers");
    String acrMethod = request.getHeader("Access-Control-Request-Method");
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Headers", acrHeaders);
    response.setHeader("Access-Control-Allow-Methods", acrMethod);
    response.setContentType("application/json:charset=UTF-8");
    response.getWriter().write(resp.toString());
}

From source file:control.ParametrizacionServlets.EliminarTecnicos.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from   w w  w.j  ava 2  s .  c o  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {

        int codigo = Integer.parseInt(request.getParameter("codigo"));
        JSONObject respError = new JSONObject();

        Tecnicos manager = new Tecnicos();
        respError = manager.Eliminar(codigo);

        response.setContentType("application/json");

        response.getWriter().write(respError.toString());

    } catch (Exception e) {
    }

}

From source file:Controllers.ProfileController.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  ww  w .j  a  va2  s.  co  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, SQLException, ClassNotFoundException {
    if ("GET_PROFILE".equals(request.getParameter("TASK"))) {
        //Returns a user as a JSON string from a user ID
        String userID = request.getParameter("user_id");
        User user = new User();
        user.setFacebookID(userID);
        user = user.getUser();

        //GET RIDES TAKEN AND GIVEN HERE
        //user.updateGivenAndTaken();

        JSONObject jsonUser = user.toJSON();
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();
        out.append(jsonUser.toString()); //Might be toString instead
        out.flush();
    } else if ("UPDATE_CAR".equals(request.getParameter("TASK"))) {
        //Returns a user as a JSON string from a user ID
        String userID = request.getParameter("user_id");
        User user = new User();
        user.setFacebookID(userID);
        user = user.getUser();

        String newBrand = request.getParameter("car_brand");
        String newModel = request.getParameter("car_model");
        String newColour = request.getParameter("car_colour");
        String newLicence = request.getParameter("licence_plate");

        user.setCarBrand(newBrand);
        user.setCarModel(newModel);
        user.setCarColour(newColour);
        user.setLicencePlate(newLicence);
        user.updateDB();

        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.append("Profile Updated"); //Might be toString instead
        out.flush();
    }
}

From source file:anotadorderelacoes.model.UtilidadesPacotes.java

/**
 * Converte um arquivo de texto puro para o formato JSON aceito pela ARS.
 * O arquivo de texto deve conter uma sentena por linha.
 *
 * @param arquivoTexto Arquivo de texto puro
 * @param arquivoSaida Arquivo de texto convertido para o formato JSON
 *///from ww  w  .  ja v a  2  s .c o m
public static void converterTextoJson(File arquivoTexto, File arquivoSaida) {

    BufferedReader br;
    BufferedWriter bw;
    String linha;
    int contadorSentencas = 1;

    try {

        //br = new BufferedReader( new FileReader( arquivoTexto ) );
        br = new BufferedReader(new InputStreamReader(new FileInputStream(arquivoTexto), "UTF-8"));
        //bw = new BufferedWriter( new FileWriter( arquivoSaida ) );
        bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(arquivoSaida), "UTF-8"));

        bw.write("# Arquivo \"" + arquivoTexto.getName() + "\" convertido para o formato JSON\n");
        bw.write("===\n");

        // Uma sentena por linha
        while ((linha = br.readLine()) != null) {

            JSONObject sentenca = new JSONObject();
            JSONArray tokens = new JSONArray();

            sentenca.put("id", contadorSentencas++);
            sentenca.put("texto", linha);
            sentenca.put("comentarios", "");

            sentenca.put("termos", new JSONArray());
            sentenca.put("relacoes", new JSONArray());
            sentenca.put("anotadores", new JSONArray());

            sentenca.put("anotada", false);
            sentenca.put("ignorada", false);

            // Separao simples de tokens
            for (String token : linha.split(" "))
                tokens.add(novoToken(token, token, null, null));
            sentenca.put("tokens", tokens);

            bw.write(sentenca.toString() + "\n");

        }

        bw.close();
        br.close();

        Logger.getLogger("ARS logger").log(Level.INFO, "Arquivo JSON \"{0}\" gravado.",
                arquivoSaida.getAbsolutePath());

    } catch (FileNotFoundException ex) {
        Logger.getLogger("ARS logger").log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger("ARS logger").log(Level.SEVERE, null, ex);
    }

}

From source file:com.rackspacecloud.blueflood.outputs.handlers.HttpMultiRollupsQueryHandler.java

@Override
public void handle(ChannelHandlerContext ctx, HttpRequest request) {

    Tracker.track(request);/*from w w  w.j a  va2s  .  co  m*/

    final String tenantId = request.getHeader("tenantId");

    if (!(request instanceof HTTPRequestWithDecodedQueryParams)) {
        sendResponse(ctx, request, "Missing query params: from, to, points", HttpResponseStatus.BAD_REQUEST);
        return;
    }

    final String body = request.getContent().toString(Constants.DEFAULT_CHARSET);

    if (body == null || body.isEmpty()) {
        sendResponse(ctx, request, "Invalid body. Expected JSON array of metrics.",
                HttpResponseStatus.BAD_REQUEST);
        return;
    }

    List<String> locators = new ArrayList<String>();
    try {
        locators.addAll(getLocatorsFromJSONBody(tenantId, body));
    } catch (Exception ex) {
        log.debug(ex.getMessage(), ex);
        sendResponse(ctx, request, ex.getMessage(), HttpResponseStatus.BAD_REQUEST);
        return;
    }

    if (locators.size() > maxMetricsPerRequest) {
        sendResponse(ctx, request,
                "Too many metrics fetch in a single call. Max limit is " + maxMetricsPerRequest + ".",
                HttpResponseStatus.BAD_REQUEST);
        return;
    }

    HTTPRequestWithDecodedQueryParams requestWithParams = (HTTPRequestWithDecodedQueryParams) request;
    final Timer.Context httpBatchMetricsFetchTimerContext = httpBatchMetricsFetchTimer.time();
    try {
        RollupsQueryParams params = PlotRequestParser.parseParams(requestWithParams.getQueryParams());
        Map<Locator, MetricData> results = getRollupByGranularity(tenantId, locators,
                params.getRange().getStart(), params.getRange().getStop(), params.getGranularity(tenantId));
        JSONObject metrics = serializer.transformRollupData(results, params.getStats());
        final JsonElement element = parser.parse(metrics.toString());
        final String jsonStringRep = gson.toJson(element);
        sendResponse(ctx, request, jsonStringRep, HttpResponseStatus.OK);
    } catch (InvalidRequestException e) {
        log.debug(e.getMessage());
        sendResponse(ctx, request, e.getMessage(), HttpResponseStatus.BAD_REQUEST);
    } catch (SerializationException e) {
        log.debug(e.getMessage(), e);
        sendResponse(ctx, request, e.getMessage(), HttpResponseStatus.INTERNAL_SERVER_ERROR);
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        sendResponse(ctx, request, e.getMessage(), HttpResponseStatus.INTERNAL_SERVER_ERROR);
    } finally {
        httpBatchMetricsFetchTimerContext.stop();
    }
}

From source file:control.ProcesoVertimientosServlets.FinalizarProcesoVertimientos.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from   w w w .ja v a2s  .com*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        int codigoProceso = Integer.parseInt(request.getParameter("codigoProceso"));
        JSONObject respuesta = new JSONObject();

        ProcesoVertimientos manager = new ProcesoVertimientos();

        respuesta = manager.finalizarProceso(codigoProceso);

        response.setContentType("application/json");
        response.getWriter().write(respuesta.toString());

    } catch (Exception ex) {

    }

}