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:jp.aegif.nemaki.rest.GroupResource.java

@SuppressWarnings("unchecked")
@GET//from   w w w .  jav  a 2 s.  c o  m
@Path("/search")
@Produces(MediaType.APPLICATION_JSON)
public String search(@PathParam("repositoryId") String repositoryId, @QueryParam("query") String query) {
    boolean status = true;
    JSONObject result = new JSONObject();
    JSONArray errMsg = new JSONArray();

    List<Group> groups = this.principalService.getGroups(repositoryId);
    JSONArray queriedGroups = new JSONArray();

    for (Group g : groups) {
        if (g.getGroupId().startsWith(query) || g.getName().startsWith(query)) {
            queriedGroups.add(this.convertGroupToJson(g));
        }
    }

    if (queriedGroups.size() == 0) {
        status = false;
        addErrMsg(errMsg, ITEM_GROUP, ErrorCode.ERR_NOTFOUND);
    } else {
        result.put("result", queriedGroups);
    }

    result = makeResult(status, result, errMsg);
    return result.toString();
}

From source file:com.nubits.nubot.tasks.strategy.PriceMonitorTriggerTask.java

private void computeNewPrices() {

    //Sell-side custodian sell-wall

    double peg_price = lastPrice.getPrice().getQuantity();

    double sellPricePEG_new;
    double buyPricePEG_new;

    if (Global.swappedPair) { //NBT as paymentCurrency
        sellPricePEG_new = Utils.round(sellPriceUSD * Global.conversion, 8);
        buyPricePEG_new = Utils.round(buyPriceUSD * Global.conversion, 8);
    } else {//  ww w  . j a  v a2  s .  c  om
        //convert sell price to PEG
        sellPricePEG_new = Utils.round(sellPriceUSD / peg_price, 8);
        buyPricePEG_new = Utils.round(buyPriceUSD / peg_price, 8);
    }

    //check if the price increased or decreased
    if ((sellPricePEG_new - sellPricePEG_old) > 0) {
        this.pegPriceDirection = Constant.UP;
    } else {
        this.pegPriceDirection = Constant.DOWN;
    }

    LOG.info("Sell Price " + sellPricePEG_new + "  | " + "Buy Price  " + buyPricePEG_new);

    //------------ here for output csv

    String source = currentWallPEGPrice.getSource();
    double price = currentWallPEGPrice.getPrice().getQuantity();
    String currency = currentWallPEGPrice.getPrice().getCurrency().getCode();
    String crypto = pfm.getPair().getOrderCurrency().getCode();

    //Call

    strategy.notifyPriceChanged(sellPricePEG_new, buyPricePEG_new, price, pegPriceDirection);

    Global.conversion = price;
    //Store values in class variable
    sellPricePEG_old = sellPricePEG_new;

    Date currentDate = new Date();
    String row = currentDate + "," + source + "," + crypto + "," + price + "," + currency + ","
            + sellPricePEG_new + "," + buyPricePEG_new + ",";

    JSONArray backup_feeds = new JSONArray();
    JSONObject otherPricesAtThisTime = new JSONObject();

    ArrayList<LastPrice> priceList = pfm.getLastPrices().getPrices();

    for (int i = 0; i < priceList.size(); i++) {
        LastPrice tempPrice = priceList.get(i);
        otherPricesAtThisTime.put("feed", tempPrice.getSource());
        otherPricesAtThisTime.put("price", tempPrice.getPrice().getQuantity());
    }
    LOG.warning(row);

    row += otherPricesAtThisTime.toString() + "\n";
    backup_feeds.add(otherPricesAtThisTime);
    FileSystem.writeToFile(row, outputPath, true);

    //Also update a json version of the output file
    //build the latest data into a JSONObject
    JSONObject wall_shift = new JSONObject();
    wall_shift.put("timestamp", currentDate.getTime());
    wall_shift.put("feed", source);
    wall_shift.put("crypto", crypto);
    wall_shift.put("price", price);
    wall_shift.put("currency", currency);
    wall_shift.put("sell_price", sellPricePEG_new);
    wall_shift.put("buy_price", buyPricePEG_new);
    wall_shift.put("backup_feed", backup_feeds);
    //now read the existing object if one exists
    JSONParser parser = new JSONParser();
    JSONObject wall_shift_file = new JSONObject();
    JSONArray wall_shifts = new JSONArray();
    try { //object already exists in file
        wall_shift_file = (JSONObject) parser.parse(FileSystem.readFromFile(this.jsonFile));
        wall_shifts = (JSONArray) wall_shift_file.get("wall_shifts");
    } catch (ParseException pe) {
        LOG.severe("Unable to parse order_history.json");
    }
    //add the latest orders to the orders array
    wall_shifts.add(wall_shift);
    wall_shift_file.put("wall_shifts", wall_shifts);
    //then save
    FileSystem.writeToFile(wall_shift_file.toJSONString(), jsonFile, false);

    if (Global.options.isSendMails()) {
        String title = " production (" + Global.options.getExchangeName() + ") [" + pfm.getPair().toString()
                + "] price changed more than " + wallchangeThreshold + "%";

        String messageNow = row;
        emailHistory += messageNow;

        String tldr = pfm.getPair().toString() + " price changed more than " + wallchangeThreshold
                + "% since last notification: " + "now is " + price + " "
                + pfm.getPair().getPaymentCurrency().getCode().toUpperCase() + ".\n"
                + "Here are the prices the bot used in the new orders : \n" + "Sell at " + sellPricePEG_new
                + " " + pfm.getPair().getOrderCurrency().getCode().toUpperCase() + " " + "and buy at "
                + buyPricePEG_new + " " + pfm.getPair().getOrderCurrency().getCode().toUpperCase() + "\n"
                + "\n#########\n"
                + "Below you can see the history of price changes. You can copy paste to create a csv report."
                + "For each row the bot should have shifted the sell/buy walls.\n\n";

        MailNotifications.send(Global.options.getMailRecipient(), title, tldr + emailHistory);
    }
}

From source file:com.ba.forms.foodBill.BAFoodBillAction.java

public ActionForward baGet(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    JSONObject json = new JSONObject();
    BAFoodBillDTO vo = new BAFoodBillDTO();

    try {/*from   w ww  .j a  v  a 2  s  .co  m*/
        logger.info(" get method starts here");
        String foodId = request.getParameter("search");
        HashMap hashMpFoodBillDet = BAFoodBillFactory.getInstanceOfBAFoodBillFactory().getFoodBillDtls(foodId);
        json.put("exception", "");
        json.put("FoodBillDets", hashMpFoodBillDet);
        json.put("FoodBillExit", hashMpFoodBillDet.size());

        logger.warn("strCurrent PageNo ------------->" + objPageCount);
    } catch (Exception ex) {
        logger.error("The Exception is  :" + ex);
        ex.printStackTrace();
        json.put("exception", BAHandleAllException.exceptionHandler(ex));
    }
    response.getWriter().write(json.toString());
    return null;

}

From source file:control.ParametrizacionServlets.ActualizarActParamfisicoquimicos.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*w ww  . ja  va 2s .  c om*/
 * @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 {

    JSONObject respError = new JSONObject();
    try {
        String mayorInicial = request.getParameter("mayorInicial");
        String mayorFinal = request.getParameter("mayorFinal");
        Double rangoFinal = Double.parseDouble(request.getParameter("rangoFinal"));
        Double rangoInicial = Double.parseDouble(request.getParameter("rangoInicial"));
        Integer parametro = Integer.parseInt(request.getParameter("parametro"));
        Integer actividad = Integer.parseInt(request.getParameter("actividad"));
        int codigo = Integer.parseInt(request.getParameter("codigo"));
        String mostrarRango = request.getParameter("mostrarRango");

        //Creamos el manager para registrar la informacion
        ActParamFisicoquimicos manager = new ActParamFisicoquimicos();

        respError = manager.actualizar(codigo, actividad, parametro, rangoInicial, rangoFinal, mayorInicial,
                mayorFinal, mostrarRango);

        //Armamos la respuesta JSON y la enviamos
        response.setContentType("application/json");
        response.getWriter().write(respError.toString());

    } catch (Exception ex) {
        //Armamos la respuesta JSON y la enviamos
        response.setContentType("application/json");
        respError.put("error", 0);
        response.getWriter().write(respError.toString());
    }

}

From source file:com.ba.forms.serviceBillForm.BAServiceBillAction.java

public ActionForward baGet(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    logger.info(" get method starts here");
    JSONObject json = new JSONObject();
    BAServiceBillDTO vo = new BAServiceBillDTO();
    try {//  www.j a  v  a2s . c o m
        logger.info(" get method starts here");
        String serviceId = request.getParameter("search");
        HashMap hashMpServiceBillfItemDet = BAServiceBillFactory.getInstanceOfBAServiceBillFactory()
                .getServiceBillItemDtls(serviceId);
        json.put("exception", "");
        json.put("ServiceBillDets", hashMpServiceBillfItemDet);
        json.put("ServiceBillExit", hashMpServiceBillfItemDet.size());

        //                 logger.warn("strCurrent PageNo ------------->"+objPageCount);

    } catch (Exception ex) {
        logger.error("The Exception is  :" + ex);
        ex.printStackTrace();
        json.put("exception", BAHandleAllException.exceptionHandler(ex));
    }
    response.getWriter().write(json.toString());
    return null;

}

From source file:com.eatthepath.gtfs.realtime.Vehicle.java

@SuppressWarnings("unchecked")
@Override//  w  ww  .  j a v a2  s .c  om
public String toJSONString() {
    final JSONObject json = new JSONObject();

    json.put("id", this.id);
    json.put("label", this.label);
    json.put("licensePlate", this.licensePlate);
    json.put("latitude", this.position != null ? this.position.getLatitude() : null);
    json.put("longitude", this.position != null ? this.position.getLongitude() : null);
    json.put("bearing", this.bearing);
    json.put("inferredBearing", this.getInferredBearing());
    json.put("odometer", this.odometer);
    json.put("speed", this.speed);
    json.put("currentTripId", this.trip != null ? this.trip.getId() : null);
    json.put("currentRouteId", this.getRoute() != null ? this.getRoute().getId() : null);
    json.put("currentStopId", this.currentStop != null ? this.currentStop.getId() : null);
    json.put("stopStatus", this.stopStatus != null ? this.stopStatus.toString() : null);
    json.put("congestionLevel", this.congestionLevel != null ? this.congestionLevel.toString() : null);

    return json.toString();
}

From source file:com.photon.phresco.framework.rest.api.LoginService.java

/**
 * Authenticate User for login./*from   ww w  . j a v a2  s  .  co m*/
 *
 * @param credentials the credentials
 * @return the response
 */
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response authenticate(@Context HttpServletRequest request, @Context HttpServletResponse response,
        Credentials credentials) {
    User user = null;
    ResponseInfo<User> responseData = new ResponseInfo<User>();

    try {
        user = doLogin(credentials);
        if (user == null) {
            status = RESPONSE_STATUS_FAILURE;
            errorCode = PHR110001;
            ResponseInfo<User> finalOuptut = responseDataEvaluation(responseData, null, null, status,
                    errorCode);
            return Response.status(Status.OK).entity(finalOuptut).header("Access-Control-Allow-Origin", "*")
                    .build();
        }
        if (!user.isPhrescoEnabled()) {
            status = RESPONSE_STATUS_FAILURE;
            errorCode = PHR110002;
            ResponseInfo<User> finalOuptut = responseDataEvaluation(responseData, null, null, status,
                    errorCode);
            return Response.status(Status.OK).entity(finalOuptut).header("Access-Control-Allow-Origin", "*")
                    .build();
        }

        List<Customer> customers = user.getCustomers();
        //Collections.sort(customers, sortCusNameInAlphaOrder());

        File tempPath = new File(Utility.getPhrescoTemp() + File.separator + "user.json");
        String userId = user.getId();
        JSONObject userjson = new JSONObject();
        JSONParser parser = new JSONParser();
        String customerId = "photon";
        if (tempPath.exists()) {
            FileReader reader = new FileReader(tempPath);
            userjson = (JSONObject) parser.parse(reader);
            customerId = (String) userjson.get(userId);
            reader.close();
        }
        userjson.put(userId, customerId);

        List<String> customerList = new ArrayList<String>();
        for (Customer c : customers) {
            customerList.add(c.getId());
        }

        if ((StringUtils.isEmpty(customerId) || "photon".equals(customerId))
                && customerList.contains("photon")) {
            customerId = "photon";
        }

        FileWriter writer = new FileWriter(tempPath);
        writer.write(userjson.toString());
        writer.close();

        ServiceManager serviceManager = CONTEXT_MANAGER_MAP.get(credentials.getUsername());
        UserPermissions userPermissions = FrameworkUtil.getUserPermissions(serviceManager, user);
        user.setPermissions(userPermissions);

        status = RESPONSE_STATUS_SUCCESS;
        successCode = PHR100001;
        ResponseInfo<User> finalOuptut = responseDataEvaluation(responseData, null, user, status, successCode);
        request.getSession().setAttribute("user", user);
        return Response.ok(finalOuptut).header("Access-Control-Allow-Origin", "*").build();
    } catch (PhrescoWebServiceException e) {
        if (e.getResponse().getStatus() == 204) {
            status = RESPONSE_STATUS_ERROR;
            errorCode = PHR110003;
            ResponseInfo<User> finalOuptut = responseDataEvaluation(responseData, e, null, status, errorCode);
            return Response.status(Status.OK).entity(finalOuptut).header("Access-Control-Allow-Origin", "*")
                    .build();
        } else {
            status = RESPONSE_STATUS_ERROR;
            errorCode = PHR110004;
            ResponseInfo<User> finalOuptut = responseDataEvaluation(responseData, e, null, status, errorCode);
            return Response.status(Status.OK).entity(finalOuptut).header("Access-Control-Allow-Origin", "*")
                    .build();
        }
    } catch (IOException e) {
        status = RESPONSE_STATUS_ERROR;
        errorCode = PHR110005;
        ResponseInfo<User> finalOuptut = responseDataEvaluation(responseData, e, null, status, errorCode);
        return Response.status(Status.OK).entity(finalOuptut).header("Access-Control-Allow-Origin", "*")
                .build();
    } catch (ParseException e) {
        status = RESPONSE_STATUS_ERROR;
        errorCode = PHR110006;
        ResponseInfo<User> finalOuptut = responseDataEvaluation(responseData, e, null, status, errorCode);
        return Response.status(Status.OK).entity(finalOuptut).header("Access-Control-Allow-Origin", "*")
                .build();
    } catch (PhrescoException e) {
        status = RESPONSE_STATUS_ERROR;
        errorCode = PHR110007;
        ResponseInfo<User> finalOuptut = responseDataEvaluation(responseData, e, null, status, errorCode);
        return Response.status(Status.OK).entity(finalOuptut).header("Access-Control-Allow-Origin", "*")
                .build();
    }
}

From source file:MainFrame.HttpCommunicator.java

public boolean removeLessons(JSONObject jsObj) throws MalformedURLException, IOException {
    String response = null;//w  w  w .j a va  2 s . c  om
    if (SingleDataHolder.getInstance().isProxyActivated) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                SingleDataHolder.getInstance().proxyLogin, SingleDataHolder.getInstance().proxyPassword));
        HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider)
                .build();

        HttpHost proxy = new HttpHost(SingleDataHolder.getInstance().proxyIpAdress,
                SingleDataHolder.getInstance().proxyPort);
        RequestConfig config = RequestConfig.custom().setProxy(proxy).build();

        HttpPost post = new HttpPost(SingleDataHolder.getInstance().hostAdress + "index.php");
        post.setConfig(config);

        StringBody head = new StringBody(jsObj.toString(), ContentType.TEXT_PLAIN);

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addPart("apideskviewer.getAllLessons", head);

        HttpEntity entity = builder.build();
        post.setEntity(entity);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        response = client.execute(post, responseHandler);
        System.out.println("responseBody : " + response);
    } else {
        HttpClient client = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(SingleDataHolder.getInstance().hostAdress + "index.php");

        StringBody head = new StringBody(jsObj.toString(), ContentType.TEXT_PLAIN);

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addPart("apiDeskViewer.removeLesson", head);

        HttpEntity entity = builder.build();
        post.setEntity(entity);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        response = client.execute(post, responseHandler);
        System.out.println("responseBody : " + response);
    }

    if (response.equals(new String("\"success\"")))
        return true;
    else
        return false;
}

From source file:com.nubits.nubot.utils.FrozenBalancesManager.java

private void updateFrozenFilesystem() {
    String toWrite = "";
    JSONObject toWriteJ = new JSONObject();

    toWriteJ.put("frozen-quantity-total", Utils.formatNumber(getFrozenAmount().getAmount().getQuantity(), 10));
    toWriteJ.put("frozen-currency", getFrozenAmount().getAmount().getCurrency().getCode());
    JSONArray historyListJ = new JSONArray();
    for (int i = 0; i < history.size(); i++) {
        JSONObject tempRow = new JSONObject();
        HistoryRow tempHistory = history.get(i);

        if (tempHistory.getFreezedQuantity() > 0.00000001) {

            tempRow.put("timestamp", tempHistory.getTimestamp().toString());
            tempRow.put("froze-quantity", Utils.formatNumber(tempHistory.getFreezedQuantity(), 10));
            tempRow.put("currency-code", tempHistory.getCurrencyCode());

            historyListJ.add(tempRow);//w  w  w.j av a  2 s.  co m
        }
    }

    toWriteJ.put("history", historyListJ);

    toWrite += toWriteJ.toString();

    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    JsonParser jp = new JsonParser();
    JsonElement je = jp.parse(toWrite);
    String toWritePretty = gson.toJson(je);

    try {
        FileUtils.writeStringToFile(new File(pathToFrozenBalancesFiles), toWritePretty);
        LOG.info("Updated Froozen Balances file (" + pathToFrozenBalancesFiles + ") : "
                + Utils.formatNumber(getFrozenAmount().getAmount().getQuantity(), 10) + " "
                + toFreezeCurrency.getCode());
    } catch (IOException ex) {
        LOG.error(ex.toString());
    }

}

From source file:MainFrame.HttpCommunicator.java

public boolean setPassword(String password, String group) throws IOException {
    String response = null;/*from   w  w  w . j av  a 2s .com*/
    String hashPassword = md5Custom(password);
    JSONObject jsObj = new JSONObject();
    jsObj.put("group", group);
    jsObj.put("newHash", hashPassword);

    if (SingleDataHolder.getInstance().isProxyActivated) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                SingleDataHolder.getInstance().proxyLogin, SingleDataHolder.getInstance().proxyPassword));
        HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider)
                .build();

        HttpHost proxy = new HttpHost(SingleDataHolder.getInstance().proxyIpAdress,
                SingleDataHolder.getInstance().proxyPort);
        RequestConfig config = RequestConfig.custom().setProxy(proxy).build();

        HttpPost post = new HttpPost(SingleDataHolder.getInstance().hostAdress + "index.php");
        post.setConfig(config);

        StringBody head = new StringBody(jsObj.toString(), ContentType.TEXT_PLAIN);

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addPart("apideskviewer.getAllLessons", head);

        HttpEntity entity = builder.build();
        post.setEntity(entity);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        response = client.execute(post, responseHandler);
        System.out.println("responseBody : " + response);
    } else {
        HttpClient client = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(SingleDataHolder.getInstance().hostAdress + "index.php");

        StringBody head = new StringBody(jsObj.toString(), ContentType.TEXT_PLAIN);

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addPart("apiDeskViewer.updateGroupAccess", head);

        HttpEntity entity = builder.build();
        post.setEntity(entity);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        response = client.execute(post, responseHandler);
        System.out.println("responseBody : " + response);
    }

    if (response.equals(new String("\"success\"")))
        return true;
    else
        return false;
}