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:au.edu.ausstage.networks.LookupManager.java

/**
 * A method to lookup the export options
 *
 * @return a JSON encoded object listing the options
 *///from   w  w w . ja v  a2  s.  c  o  m
@SuppressWarnings("unchecked")
public String getExportOptions() {

    // define helper variables
    JSONObject object = new JSONObject();
    JSONArray list = new JSONArray();

    for (int i = 0; i < ExportServlet.EXPORT_TYPES_UI.length; i++) {
        list.add(ExportServlet.EXPORT_TYPES_UI[i]);
    }

    object.put("tasks", list);

    list = new JSONArray();

    for (int i = 0; i < ExportServlet.FORMAT_TYPES.length; i++) {
        list.add(ExportServlet.FORMAT_TYPES[i]);
    }

    object.put("formats", list);

    list = new JSONArray();

    String[] radius = new String[ExportServlet.MAX_DEGREES];

    for (int i = 0; i < ExportServlet.MAX_DEGREES; i++) {
        list.add(Integer.toString(i + 1));
    }

    object.put("radius", list);

    return object.toString();

}

From source file:com.photon.phresco.util.Utility.java

public static void killProcess(String baseDir, String actionType) throws PhrescoException {
    File do_not_checkin = new File(baseDir + File.separator + DO_NOT_CHECKIN_DIRY);
    File jsonFile = new File(do_not_checkin.getPath() + File.separator + "process.json");
    if (!jsonFile.exists()) {
        return;/* w w  w  . j a  va2  s. c om*/
    }
    try {
        JSONObject jsonObject = new JSONObject();
        JSONParser parser = new JSONParser();
        FileReader reader = new FileReader(jsonFile);
        jsonObject = (JSONObject) parser.parse(reader);
        Object processId = jsonObject.get(actionType);
        if (processId == null) {
            return;
        }
        if (System.getProperty(Constants.OS_NAME).startsWith(Constants.WINDOWS_PLATFORM)) {
            Runtime.getRuntime().exec("cmd /X /C taskkill /F /T /PID " + processId.toString());
        } else {
            Runtime.getRuntime().exec(Constants.JAVA_UNIX_PROCESS_KILL_CMD + processId.toString());
        }
        jsonObject.remove(actionType);
        FileWriter writer = new FileWriter(jsonFile);
        writer.write(jsonObject.toString());
        writer.close();
        reader.close();
        if (jsonObject.size() <= 0) {
            FileUtil.delete(jsonFile);
        }
    } catch (IOException e) {
        throw new PhrescoException(e);
    } catch (ParseException e) {
        throw new PhrescoException(e);
    }
}

From source file:jp.aegif.nemaki.rest.GroupResource.java

@SuppressWarnings("unchecked")
@POST/*from ww  w  .  j  a v  a 2s. c om*/
@Path("/create/{id}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public String create(@PathParam("repositoryId") String repositoryId, @PathParam("id") String groupId,
        @FormParam(FORM_GROUPNAME) String name, @FormParam("users") String users,
        @FormParam("groups") String groups, @Context HttpServletRequest httpRequest) {

    boolean status = true;
    JSONObject result = new JSONObject();
    JSONArray errMsg = new JSONArray();

    //Validation
    status = validateNewGroup(repositoryId, status, errMsg, groupId, name);

    //Edit group info
    JSONArray _users = parseJsonArray(users);
    JSONArray _groups = parseJsonArray(groups);
    Group group = new Group(groupId, name, _users, _groups);
    setFirstSignature(httpRequest, group);

    //Create a group
    if (status) {
        try {
            principalService.createGroup(repositoryId, group);
        } catch (Exception ex) {
            ex.printStackTrace();
            status = false;
            addErrMsg(errMsg, ITEM_GROUP, ErrorCode.ERR_CREATE);
        }
    }
    result = makeResult(status, result, errMsg);
    return result.toString();
}

From source file:com.onarandombox.MultiverseCore.MVWorld.java

@Override
public String toString() {
    final JSONObject jsonData = new JSONObject();
    jsonData.put("Name", getName());
    jsonData.put("Env", getEnvironment().toString());
    jsonData.put("Type", getWorldType().toString());
    jsonData.put("Gen", getGenerator());
    final JSONObject topLevel = new JSONObject();
    topLevel.put(getClass().getSimpleName() + "@" + hashCode(), jsonData);
    return topLevel.toString();
}

From source file:dbProcs.Getter.java

/**
 * Use to return the current progress of a class in JSON format with information like user name, score and completed modules
 * @param applicationRoot The current running context of the application
 * @param classId The identifier of the class to use in lookup
 * @return A JSON representation of a class's progress in the application
 *//*from  ww w .  ja  va 2 s .  c  o m*/
@SuppressWarnings("unchecked")
public static String getProgressJSON(String applicationRoot, String classId) {
    log.debug("*** Getter.getProgressJSON ***");

    String result = new String();
    Encoder encoder = ESAPI.encoder();
    Connection conn = Database.getCoreConnection(applicationRoot);
    try {
        log.debug("Preparing userProgress call");
        //Returns User's: Name, # of Completed modules and Score
        CallableStatement callstmnt = conn.prepareCall("call userProgress(?)");
        callstmnt.setString(1, classId);
        log.debug("Executing userProgress");
        ResultSet resultSet = callstmnt.executeQuery();
        JSONArray json = new JSONArray();
        JSONObject jsonInner = new JSONObject();
        int resultAmount = 0;
        while (resultSet.next()) //For each user in a class
        {
            resultAmount++;
            jsonInner = new JSONObject();
            if (resultSet.getString(1) != null) {
                jsonInner.put("userName", new String(encoder.encodeForHTML(resultSet.getString(1)))); //User Name
                jsonInner.put("progressBar", new Integer(resultSet.getInt(2) * widthOfUnitBar)); //Progress Bar Width
                jsonInner.put("score", new Integer(resultSet.getInt(3))); //Score
                log.debug("Adding: " + jsonInner.toString());
                json.add(jsonInner);
            }
        }
        if (resultAmount > 0)
            result = json.toString();
        else
            result = new String();
    } catch (SQLException e) {
        log.error("getProgressJSON Failure: " + e.toString());
        result = null;
    } catch (Exception e) {
        log.error("getProgressJSON Unexpected Failure: " + e.toString());
        result = null;
    }
    Database.closeConnection(conn);
    log.debug("*** END getProgressJSON ***");
    return result;
}

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

private void computeNewPrices() {
    if (SessionManager.sessionInterrupted())
        return; //external interruption

    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, Settings.DEFAULT_PRECISION);
        buyPricePEG_new = Utils.round(buyPriceUSD * Global.conversion, Settings.DEFAULT_PRECISION);
    } else {/*from ww  w.j a v  a2s  . com*/
        //convert sell price to PEG
        sellPricePEG_new = Utils.round(sellPriceUSD / peg_price, Settings.DEFAULT_PRECISION);
        buyPricePEG_new = Utils.round(buyPriceUSD / peg_price, Settings.DEFAULT_PRECISION);
    }

    BidAskPair newPrice = new BidAskPair(buyPricePEG_new, sellPricePEG_new);

    //check if the price increased or decreased compared to last
    if ((newPrice.getAsk() - this.bidask.getAsk()) > 0) {
        this.pegPriceDirection = Constant.UP;
    } else {
        this.pegPriceDirection = Constant.DOWN;
    }

    //Store new value
    this.bidask = newPrice;

    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 and notify the price change

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

    Global.conversion = price;

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

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

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

    LOG.info("New price computed [" + row + "]");
    if (SessionManager.sessionInterrupted())
        return; //external interruption

    row += otherPricesAtThisTime.toString() + "\n";
    backup_feeds.add(otherPricesAtThisTime);
    logrow(row, wallshiftsFilePathCSV, 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_info = new JSONObject();
    JSONArray wall_shifts = new JSONArray();
    try { //object already exists in file
        wall_shift_info = (JSONObject) parser.parse(FilesystemUtils.readFromFile(this.wallshiftsFilePathJSON));
        wall_shifts = (JSONArray) wall_shift_info.get("wall_shifts");
    } catch (ParseException pe) {
        LOG.error("Unable to parse order_history.json");
    }
    //add the latest orders to the orders array
    wall_shifts.add(wall_shift);
    wall_shift_info.put("wall_shifts", wall_shifts);
    //then save

    logWallShift(wall_shift_info.toJSONString());
    if (SessionManager.sessionInterrupted())
        return; //external interruption

    if (Global.options.sendMails()) {
        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";

        if (!Global.options.isMultipleCustodians()) {
            MailNotifications.send(Global.options.getMailRecipient(), title, tldr + emailHistory);
        }
    }
}

From source file:net.mybox.mybox.ClientStatus.java

/**
 * Attempt to connect to the server port and attach the user
 * @param pollInterval The amount of seconds between socket connection retries
 *///from w ww  .  j  a  v  a  2  s .  c  o m
public void attemptConnection(int pollInterval) {

    if (account.serverName == null)
        printErrorExit("Client not configured");

    setStatus(ClientStatus.CONNECTING);

    printMessage("Establishing connection to " + account.serverName + ":" + account.serverPort + " ...");

    // repeatedly attempt to connect to the server
    while (true) {
        try {
            serverConnectionSocket = new Socket(account.serverName, account.serverPort);

            outStream = serverConnectionSocket.getOutputStream();
            inStream = serverConnectionSocket.getInputStream();

            dataOutStream = new DataOutputStream(outStream);
            dataInStream = new DataInputStream(inStream);

            break; // reachable if there is no exception thrown
        } catch (IOException ioe) {
            printMessage(
                    "There was an error reaching server. Will try again in " + pollInterval + " seconds...");
            try {
                Thread.sleep(1000 * pollInterval);
            } catch (Exception ee) {
            }
        }
    }

    printMessage("Connected: " + serverConnectionSocket);

    startClientInputListenerThread();

    JSONObject jsonOut = new JSONObject();
    jsonOut.put("email", account.email);
    //    jsonOut.put("password", password);

    // TODO: make sure if the attachAccount fails, no files can be transfered

    if (!serverDiscussion(Common.Signal.attachaccount, Common.Signal.attachaccount_response,
            jsonOut.toString()))
        printErrorExit("Unable to attach account");

    // checking that the mybox versions are the same happens in handleMessageFromServer

    loadNativeLibs();

    getLastSync(); // TODO: handle false case

    enableDirListener();

    printMessage("Client ready. Startup sync.");
    setStatus(ClientStatus.READY);

    // perform an initial sync to catch all the files that have changed while the client was off
    FullSync();
}

From source file:edu.illinois.cs.cogcomp.wikifier.utils.freebase.QueryMQL.java

public String lookupMidFromTitle(MQLQueryWrapper mql) throws Exception {
    JSONObject response;
    String mqlQuery = mql.MQLquery;
    logger.debug("QUERY IS " + mqlQuery);
    String title = mql.value;/*ww w. ja  va  2  s. c  om*/
    String checksum = getMD5Checksum(title);
    // first check mid in cache
    if (IOUtils.exists(typeCacheLocation + "/" + checksum + ".cached")) {
        found++;
        logger.info("Found! " + found);
        JSONParser jsonParser = new JSONParser();
        response = (JSONObject) jsonParser.parse(
                FileUtils.readFileToString(new File(typeCacheLocation + "/" + checksum + ".cached"), "UTF-8"));
    } else {
        response = getResponse(mqlQuery);
        if (response == null)
            return null;
        cacheMiss++;
        logger.info("Caching " + cacheMiss);
        FileUtils.writeStringToFile(new File(typeCacheLocation + "/" + checksum + ".cached"),
                response.toString(), "UTF-8");
    }

    JSONObject result = (JSONObject) response.get("result");

    if (result != null) {
        return (String) result.get("mid");
    }
    return null;
}

From source file:edu.illinois.cs.cogcomp.wikifier.utils.freebase.QueryMQL.java

public List<String> lookupTypeFromTitle(MQLQueryWrapper mql) throws Exception {
    List<String> ans = new ArrayList<String>();
    JSONObject response;
    String mqlQuery = mql.MQLquery;
    logger.debug("QUERY IS " + mqlQuery);
    String title = mql.value;//from w  w w .  j  a  v a 2s  .c o  m
    String checksum = getMD5Checksum(title);
    // first check mid in cache
    if (IOUtils.exists(typeCacheLocation + "/" + checksum + ".cached")) {
        found++;
        logger.info("Found! " + found);
        JSONParser jsonParser = new JSONParser();
        response = (JSONObject) jsonParser.parse(
                FileUtils.readFileToString(new File(typeCacheLocation + "/" + checksum + ".cached"), "UTF-8"));
    } else {
        response = getResponse(mqlQuery);
        if (response == null)
            return ans;
        cacheMiss++;
        logger.info("Caching " + cacheMiss);
        FileUtils.writeStringToFile(new File(typeCacheLocation + "/" + checksum + ".cached"),
                response.toString(), "UTF-8");
    }

    JSONObject result = (JSONObject) response.get("result");

    if (result != null) {
        JSONArray types = (JSONArray) result.get("type");
        for (Object value : types) {
            ans.add(value.toString());
        }
    }
    return ans;
}

From source file:controller.ISAuth.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/json");
    try (PrintWriter out = response.getWriter()) {
        String token = request.getParameter("token");
        String sql = "SELECT * FROM token WHERE access_token = ?";

        JSONObject object = new JSONObject();

        try (PreparedStatement statement = conn.prepareStatement(sql)) {
            statement.setString(1, token);

            ResultSet result = statement.executeQuery();

            if (result.next()) {
                Date now = new Date();
                DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                try {
                    Date expiry_date = format.parse(result.getString("expiry_date"));
                    if (now.after(expiry_date)) {
                        object.put("error", "Expired Token");
                        String deleteQuery = "DELETE FROM token WHERE access_token = ?";
                        try (PreparedStatement deleteStatement = conn.prepareStatement(deleteQuery)) {
                            deleteStatement.setString(1, token);
                            deleteStatement.execute();
                        }//from  w  w  w.  j av  a2 s  .  c o m
                    } else {
                        object.put("id", result.getInt("u_id"));

                    }
                } catch (SQLException | ParseException e) {

                }

            }
        } catch (SQLException e) {
        }
        out.println(object.toString());
    }

}