Example usage for org.json.simple JSONObject put

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

Introduction

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

Prototype

V put(K key, V value);

Source Link

Document

Associates the specified value with the specified key in this map (optional operation).

Usage

From source file:com.raphfrk.craftproxyclient.net.auth.AuthManager.java

@SuppressWarnings("unchecked")
public static void authServer17(String hash) throws IOException {
    URL url;/*from  w w w .  jav  a  2s  .  c  o m*/
    String username;
    String accessToken;
    try {
        if (loginDetails == null) {
            throw new IOException("Not logged in");
        }

        try {
            username = URLEncoder.encode(getUsername(), "UTF-8");
            accessToken = URLEncoder.encode(getAccessToken(), "UTF-8");
            hash = URLEncoder.encode(hash, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new IOException("Username/password encoding error", e);
        }

        String urlString;
        urlString = sessionServer17;
        url = new URL(urlString);
    } catch (MalformedURLException e) {
        throw new IOException("Auth server URL error", e);
    }
    HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
    con.setDoOutput(true);
    con.setInstanceFollowRedirects(false);
    con.setReadTimeout(5000);
    con.setConnectTimeout(5000);
    con.setRequestMethod("POST");
    con.setRequestProperty("Content-Type", "application/json");
    con.connect();

    JSONObject obj = new JSONObject();
    obj.put("accessToken", accessToken);
    obj.put("selectedProfile", loginDetails.get("selectedProfile"));
    obj.put("serverId", hash);
    BufferedWriter writer = new BufferedWriter(
            new OutputStreamWriter(con.getOutputStream(), StandardCharsets.UTF_8));
    try {
        obj.writeJSONString(writer);
        writer.flush();
        writer.close();
    } catch (IOException e) {
        if (writer != null) {
            writer.close();
            con.disconnect();
            return;
        }
    }
    if (con.getResponseCode() != 200) {
        throw new IOException("Unable to verify username, please restart proxy");
    }
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8));
    try {
        String reply = reader.readLine();
        if (reply != null) {
            throw new IOException("Auth server replied (" + reply + ")");
        }
    } finally {
        reader.close();
        con.disconnect();
    }
}

From source file:agileinterop.AgileInterop.java

private static JSONObject createRelatedPSRs(String body)
        throws UnsupportedOperationException, ParseException, APIException {
    // Parse body as JSON
    JSONParser parser = new JSONParser();
    JSONObject jsonBody = (JSONObject) parser.parse(body);

    Map<String, List<String>> data = new HashMap<>();

    for (Iterator it = jsonBody.entrySet().iterator(); it.hasNext();) {
        Map.Entry pair = (Map.Entry) it.next();

        String psrNumber = (String) pair.getKey();
        JSONArray relatedPSRTypes = (JSONArray) pair.getValue();

        List<String> relatedPSRNumbers = new ArrayList<>();
        for (Object relatedPSRType : relatedPSRTypes) {
            String relatedPSRNumber = Agile.createRelatedPSR(psrNumber, (String) relatedPSRType);
            relatedPSRNumbers.add(relatedPSRNumber);
        }//w ww .  j ava 2 s  .  c  o m

        data.put(psrNumber, relatedPSRNumbers);
    }

    JSONObject obj = new JSONObject();
    obj.put("data", data);
    return obj;
}

From source file:com.jilk.ros.rosbridge.implementation.JSON.java

private static JSONObject wrap(JSONObject jo, Class c) {
    JSONObject result = new JSONObject();
    String indicatorName = Indication.getIndicatorName(c);
    String indicatedName = Indication.getIndicatedName(c);
    result.put(indicatorName, jo.get(indicatorName));
    result.put(indicatedName, jo);//from w ww.j  av a2 s . c o m
    return result;
}

From source file:com.google.android.gcm.demo.server.Datastore.java

/**
 * Gets the number of total devices./*from  w  w w .j  a v  a2s.com*/
 */
public static JSONArray getAllAlertsFromDataStore(int offset, int limit) {
    JSONArray alerts = null;

    Transaction txn = datastore.beginTransaction();
    try {
        alerts = new JSONArray();
        Query query = new Query(ALERTS).addSort(ALERT_TIME, SortDirection.DESCENDING);
        Iterable<Entity> entities = datastore.prepare(query)
                .asIterable(FetchOptions.Builder.withOffset(offset).limit(limit));
        for (Entity entity : entities) {
            JSONObject alert = new JSONObject();
            alert.put(ALERT_FROM, (String) entity.getProperty(ALERT_FROM));
            alert.put(ALERT_MESSAGE, (String) entity.getProperty(ALERT_MESSAGE));
            Date date = (Date) entity.getProperty(ALERT_TIME);
            SimpleDateFormat sd = new SimpleDateFormat("HH:mm:ss dd/MM/yyyy");
            sd.setTimeZone(TimeZone.getTimeZone("IST"));
            alert.put(ALERT_TIME, sd.format(date));
            alerts.add(alert);
        }
        txn.commit();
    } finally {
        if (txn.isActive()) {
            txn.rollback();
        }
    }
    return alerts;
}

From source file:br.bireme.mlts.utils.Document2JSON.java

public static JSONObject getJSON(final Map<String, List<Fieldable>> map) {
    if (map == null) {
        throw new NullPointerException("map");
    }/*from   ww w.jav  a 2  s  .  c om*/

    final JSONObject jobj = new JSONObject();

    for (Map.Entry<String, List<Fieldable>> entry : map.entrySet()) {
        final String key = entry.getKey();
        final List<Fieldable> value = entry.getValue();
        final boolean multivalue = value.size() > 1;

        if (multivalue) {
            final JSONArray array = new JSONArray();
            jobj.put(key, array);
            for (Fieldable fld : value) {
                array.add(getObject(fld));
            }
        } else {
            jobj.put(key, getObject(value.get(0)));
        }
    }
    return jobj;
}

From source file:com.avatarproject.core.storage.UserCache.java

/**
 * Adds a player into the custom UserCache.
 * @param player Player to add to the cache.
 *//*w w  w. j a  v  a 2 s. com*/
@SuppressWarnings("unchecked")
public static void addUser(Player player) {
    String name = player.getName();
    UUID uuid = player.getUniqueId();
    JSONArray array = getUserCache();
    try {
        for (int n = 0; n < array.size(); n++) { //Loop through all the objects in the array.
            JSONObject object = (JSONObject) array.get(n);
            if (object.get("id").equals(uuid.toString())) { //Check if the player's UUID exists in the cache.
                if (String.valueOf(object.get("name")).equalsIgnoreCase(name)) {
                    return;
                } else {
                    object.put("name", name); //Update the user.
                    FileWriter fileOut = new FileWriter(usercache);
                    fileOut.write(array.toJSONString()); //Write the JSON array to the file.
                    fileOut.close();
                    return;
                }
            }
        }
        JSONObject newEntry = new JSONObject();
        newEntry.put("id", uuid.toString());
        newEntry.put("name", name);
        array.add(newEntry); //Add a new player into the cache.
        FileWriter fileOut = new FileWriter(usercache);
        fileOut.write(array.toJSONString()); //Write the JSON array to the file.
        fileOut.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.splunk.logging.HttpEventCollectorSender.java

@SuppressWarnings("unchecked")
private static void putIfPresent(JSONObject collection, String tag, String value) {
    if (value != null && value.length() > 0) {
        collection.put(tag, value);
    }//from   w  w  w .  ja  v  a  2 s .  co m
}

From source file:agileinterop.AgileInterop.java

private static JSONObject getPSRCellValues(String body)
        throws UnsupportedOperationException, YamlException, APIException {
    String[] psrNumbers = body.split(",");

    // Trim and upper case all PSR numbers
    for (int i = 0; i < psrNumbers.length; i++) {
        psrNumbers[i] = psrNumbers[i].trim().toUpperCase();
    }//  w w  w  .  j  a  v  a  2  s .  co  m

    Map<String, Map<String, String>> data = new HashMap<>();
    for (String psrNumber : psrNumbers) {
        Map<String, String> psrData = new HashMap<>();

        IServiceRequest psr = (IServiceRequest) Agile.session.getObject(IServiceRequest.OBJECT_TYPE, psrNumber);

        ICell[] cells = psr.getCells();
        for (ICell cell : cells) {
            String cellName = cell.getName();

            if (cell.getDataType() == DataTypeConstants.TYPE_DATE) {
                if (cell.getValue() != null) {
                    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a zz");
                    sdf.setTimeZone(TimeZone.getTimeZone("Europe/London"));
                    psrData.put(cell.getName(), sdf.format((Date) cell.getValue()));
                } else {
                    psrData.put(cell.getName(), cell.toString());
                }
            } else {
                psrData.put(cell.getName(), cell.toString());
            }
        }

        data.put(psrNumber, psrData);
    }

    JSONObject obj = new JSONObject();
    obj.put("data", data);
    return obj;
}

From source file:gov.nih.nci.rembrandt.web.ajax.DynamicListHelper.java

public static String getGeneAliases(String gene) {
    JSONArray aliases = new JSONArray();
    try {//from  w  ww  .j av  a  2 s.  c o m
        if (!DataValidator.isGeneSymbolFound(gene)) {
            AllGeneAliasLookup[] allGeneAlias = DataValidator.searchGeneKeyWord(gene);
            // if there are aliases , set the array to be displayed in the form and return the showAlias warning
            if (allGeneAlias != null) {
                for (int i = 0; i < allGeneAlias.length; i++) {
                    JSONObject a = new JSONObject();

                    AllGeneAliasLookup alias = allGeneAlias[i];
                    a.put("alias", (alias.getAlias() != null) ? alias.getAlias() : "N/A");
                    a.put("symbol", (alias.getApprovedSymbol() != null) ? alias.getApprovedSymbol() : "N/A");
                    a.put("name", (alias.getApprovedName() != null) ? alias.getApprovedName() : "N/A");
                    //alias.getAlias()+"\t"+alias.getApprovedSymbol()+"\t"+alias.getApprovedName()
                    aliases.add(a);
                }
            } else {
                aliases.add("invalid");
            }
        } else {
            aliases.add("valid");
        }

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return aliases.toString();
}

From source file:net.amigocraft.mpt.command.InstallCommand.java

public static void installPackage(String id) throws MPTException {
    if (Thread.currentThread().getId() == Main.mainThreadId)
        throw new MPTException(ERROR_COLOR + "Packages may not be installed from the main thread!");
    id = id.toLowerCase();/*  ww w.  j  ava  2 s  .  c o m*/
    try {
        File file = new File(Main.plugin.getDataFolder(), "cache" + File.separator + id + ".zip");
        if (!file.exists())
            downloadPackage(id);
        if (!Main.packageStore.containsKey("packages")
                && ((JSONObject) Main.packageStore.get("packages")).containsKey(id))
            throw new MPTException(
                    ERROR_COLOR + "Cannot find package by id " + ID_COLOR + id + ERROR_COLOR + "!");
        JSONObject pack = (JSONObject) ((JSONObject) Main.packageStore.get("packages")).get(id);
        List<String> files = new ArrayList<>();
        lockStores();
        boolean success = MiscUtil.unzip(new ZipFile(file), Bukkit.getWorldContainer(), files);
        if (!KEEP_ARCHIVES)
            file.delete();
        pack.put("installed", pack.get("version").toString());
        JSONArray fileArray = new JSONArray();
        for (String str : files)
            fileArray.add(str);
        pack.put("files", fileArray);
        try {
            writePackageStore();
        } catch (IOException ex) {
            ex.printStackTrace();
            unlockStores();
            throw new MPTException(ERROR_COLOR + "Failed to write package store to disk!");
        }
        unlockStores();
        if (!success)
            throw new MPTException(
                    ERROR_COLOR + "Some files were not extracted. Use verbose logging for details.");
    } catch (IOException ex) {
        throw new MPTException(ERROR_COLOR + "Failed to access archive!");
    }
}