Example usage for org.json JSONObject put

List of usage examples for org.json JSONObject put

Introduction

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

Prototype

public JSONObject put(String key, Object value) throws JSONException 

Source Link

Document

Put a key/value pair in the JSONObject.

Usage

From source file:org.seadpdt.impl.PeopleServicesImpl.java

@POST
@Path("/")
@Consumes(MediaType.APPLICATION_JSON)/*from   w  w w .  j  a  v a2s .c om*/
@Produces(MediaType.APPLICATION_JSON)
public Response registerPerson(String personString) {

    JSONObject person = new JSONObject(personString);
    Provider p = null;

    if (person.has(provider)) {
        p = Provider.getProvider((String) person.get(provider));

    }

    if (!person.has(identifier)) {
        return Response.status(Status.BAD_REQUEST)
                .entity(new BasicDBObject("Failure", "Invalid request format: missing identifier")).build();
    }
    String rawID = (String) person.get(identifier);

    String newID;
    if (p != null) {
        //Know which provider the ID is from (as claimed by the client) so go direct to get its canonical form
        newID = p.getCanonicalId(rawID);
    } else {
        //Don't know the provider, so find it and the canonical ID together
        Profile profile = Provider.findCanonicalId(rawID);
        if (profile != null) {

            p = Provider.getProvider(profile.getProvider());
        } //else no provider recognized the id (e.g. it's a string), so we'll just fail with a null Provier
        if (p == null) {
            return Response.status(Status.BAD_REQUEST)
                    .entity(new BasicDBObject("Failure", "Invalid request format:identifier not recognized"))
                    .build();
        }
        newID = profile.getIdentifier();
    }

    person.put(identifier, newID);

    FindIterable<Document> iter = peopleCollection.find(new Document("@id", newID));
    if (iter.iterator().hasNext()) {
        return Response.status(Status.CONFLICT)
                .entity(new BasicDBObject("Failure", "Person with Identifier " + newID + " already exists"))
                .build();
    } else {
        URI resource = null;
        try {

            Document profileDocument = p.getExternalProfile(person);
            peopleCollection.insertOne(profileDocument);
            resource = new URI("./" + profileDocument.getString("@id"));
        } catch (Exception r) {
            return Response.serverError()
                    .entity(new BasicDBObject("failure", "Provider call failed with status: " + r.getMessage()))
                    .build();
        }

        try {
            resource = new URI("./" + newID);
        } catch (URISyntaxException e) {
            // Should not happen given simple ids
            e.printStackTrace();
        }
        return Response.created(resource).entity(new Document("identifier", newID)).build();
    }
}

From source file:CNCEntities.ResponseTopup.java

@Override
public JSONObject getJsonEntity() {
    JSONObject jo = new JSONObject();
    try {/*from  ww w . jav  a 2s.co  m*/
        jo.put("code", code);
        jo.put("msg", msg);
        jo.put("tranid", tranid);
    } catch (JSONException ex) {
        Logger.getLogger(ResponseTopup.class.getName()).log(Level.SEVERE, null, ex);
    }
    return jo;
}

From source file:Servlet.AjaxRestockIngredientServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  w w  w  . j  ava  2s. 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");
    PrintWriter out = response.getWriter();
    try {
        /* TODO output your page here. You may use following sample code. */
        JSONObject obj = new JSONObject();
        String ingredientID = request.getParameter("restockingredientID");
        IngredientInterface ingredientDAO = new IngredientImplementation();
        IngredientBean ingredientBean = ingredientDAO.getIngredient(Integer.parseInt(ingredientID));
        // System.out.println("pumasok sa ajaxrestockingredient servlet");
        System.out.println("it's this " + ingredientID);
        // System.out.println(ingredientBean.getIngredient_id());
        try {
            obj.put("RestockIngredientID", ingredientBean.getIngredient_id());

        } catch (JSONException ex) {
            Logger.getLogger(AjaxEditIngredientServlet.class.getName()).log(Level.SEVERE, null, ex);
        }

        out.print(obj);
        out.flush();
    } finally {
        out.close();
    }
}

From source file:net.jmhertlein.mcanalytics.console.gui.HostEntry.java

public JSONObject toJSON() {
    JSONObject ret = new JSONObject();
    ret.put("nick", displayName);
    ret.put("url", url);
    ret.put("port", port);
    return ret;/*ww  w  .  jav  a 2 s  .co m*/
}

From source file:com.jsonstore.util.JSONStoreLogger.java

public static void logAnalytics(Long startTime, Long endTime, String username, String collection,
        String operation) {//from  w  w w .  ja v a  2 s. c  o  m
    if (!analyticsEnabled) {
        return;
    }

    String analyticsMessage = ""; //$NON-NLS-1$
    JSONObject metadata = new JSONObject();

    try {
        metadata.put(ANALYTICS_SOURCE_KEY, ANALYTICS_SOURCE);

        metadata.put(ANALYTICS_START_TIME, startTime);
        metadata.put(ANALYTICS_END_TIME, endTime);

        metadata.put(ANALYTICS_USERNAME, username);
        metadata.put(ANALYTICS_COLLECTION, collection);
        metadata.put(ANALYTICS_OPERATION, operation);

        metadata.put(ANALYTICS_RETURN_CODE, 0);
    } catch (JSONException e) {
        // Will not happen, only adding properties to a JSONObject created in this method

        logger.error("Error logging JSONStore analytics.", e);
    }

    logger.info(analyticsMessage, metadata);
}

From source file:com.jsonstore.util.JSONStoreLogger.java

public static void logFileInfo(List<JSONStoreFileInfo> fileInfoList) {
    if (!analyticsEnabled) {
        return;/*  w  w  w .j a va 2  s  .  c  o  m*/
    }

    for (JSONStoreFileInfo fileInfo : fileInfoList) {
        String analyticsMessage = ""; //$NON-NLS-1$
        JSONObject metadata = new JSONObject();

        try {
            metadata.put(ANALYTICS_SOURCE_KEY, ANALYTICS_SOURCE);

            metadata.put(ANALYTICS_USERNAME, fileInfo.getUsername());
            metadata.put(ANALYTICS_SIZE, fileInfo.getFileSizeBytes());
            metadata.put(ANALYTICS_IS_ENCRYPTED, fileInfo.isEncrypted());

            metadata.put(ANALYTICS_RETURN_CODE, 0);
        } catch (JSONException e) {
            // Will not happen, only adding properties to a JSONObject created in this method

            logger.error("Error logging JSONStore analytics.", e);
        }

        logger.info(analyticsMessage, metadata);
    }

}

From source file:com.facebook.login.LoginLogger.java

public void logStartLogin(LoginClient.Request pendingLoginRequest) {
    Bundle bundle = newAuthorizationLoggingBundle(pendingLoginRequest.getAuthId());

    // Log what we already know about the call in start event
    try {/* w  w  w  . j  a v  a 2s .  c  o m*/
        JSONObject extras = new JSONObject();
        extras.put(EVENT_EXTRAS_LOGIN_BEHAVIOR, pendingLoginRequest.getLoginBehavior().toString());
        extras.put(EVENT_EXTRAS_REQUEST_CODE, LoginClient.getLoginRequestCode());
        extras.put(EVENT_EXTRAS_PERMISSIONS, TextUtils.join(",", pendingLoginRequest.getPermissions()));
        extras.put(EVENT_EXTRAS_DEFAULT_AUDIENCE, pendingLoginRequest.getDefaultAudience().toString());
        extras.put(EVENT_EXTRAS_IS_REAUTHORIZE, pendingLoginRequest.isRerequest());
        bundle.putString(EVENT_PARAM_EXTRAS, extras.toString());
    } catch (JSONException e) {
    }

    appEventsLogger.logSdkEvent(EVENT_NAME_LOGIN_START, null, bundle);
}

From source file:com.facebook.login.LoginLogger.java

public void logCompleteLogin(String loginRequestId, Map<String, String> loggingExtras,
        LoginClient.Result.Code result, Map<String, String> resultExtras, Exception exception) {

    Bundle bundle = newAuthorizationLoggingBundle(loginRequestId);
    if (result != null) {
        bundle.putString(EVENT_PARAM_LOGIN_RESULT, result.getLoggingValue());
    }/* w w  w.  j  av a2  s . c om*/
    if (exception != null && exception.getMessage() != null) {
        bundle.putString(EVENT_PARAM_ERROR_MESSAGE, exception.getMessage());
    }

    // Combine extras from the request and from the result.
    JSONObject jsonObject = null;
    if (loggingExtras.isEmpty() == false) {
        jsonObject = new JSONObject(loggingExtras);
    }
    if (resultExtras != null) {
        if (jsonObject == null) {
            jsonObject = new JSONObject();
        }
        try {
            for (Map.Entry<String, String> entry : resultExtras.entrySet()) {
                jsonObject.put(entry.getKey(), entry.getValue());
            }
        } catch (JSONException e) {
        }
    }
    if (jsonObject != null) {
        bundle.putString(EVENT_PARAM_EXTRAS, jsonObject.toString());
    }

    appEventsLogger.logSdkEvent(EVENT_NAME_LOGIN_COMPLETE, null, bundle);
}

From source file:org.loklak.api.geo.GeocodeServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Query post = RemoteAccess.evaluate(request);

    // manage DoS
    if (post.isDoS_blackout()) {
        response.sendError(503, "your request frequency is too high");
        return;// w  ww  .  jav  a2  s . c o  m
    }

    // parameters
    String callback = post.get("callback", "");
    boolean jsonp = callback != null && callback.length() > 0;
    boolean minified = post.get("minified", false);
    String data = post.get("data", "");
    String places = post.get("places", "");
    if (places.length() == 0 && data.length() == 0) {
        response.sendError(503,
                "you must submit a data attribut with a json containing the property 'places' with a list of place names");
        return;
    }

    String[] place = new String[0];
    if (places.length() > 0) {
        place = places.split(",");
    } else {
        // parse the json data
        try {
            JSONObject json = new JSONObject(data);
            if (json.has("places") && json.get("places") instanceof JSONArray) {
                JSONArray p = json.getJSONArray("places");
                place = new String[p.length()];
                int i = 0;
                for (Object o : p)
                    place[i++] = (String) o;
            } else {
                response.sendError(400, "submitted data is not well-formed: expected a list of strings");
                return;
            }
        } catch (IOException e) {
            Log.getLog().warn(e);
        }
    }

    // find locations for places
    JSONObject locations = new JSONObject(true);
    for (String p : place) {
        GeoMark loc = DAO.geoNames.analyse(p, null, 5, Long.toString(System.currentTimeMillis()));
        if (loc != null) {
            locations.put(p, loc.toJSON(minified));
        } else {
            locations.put(p, new JSONObject());
        }
    }

    post.setResponse(response, "application/javascript");

    // generate json
    JSONObject m = new JSONObject(true);
    m.put("locations", locations);

    // write json
    response.setCharacterEncoding("UTF-8");
    PrintWriter sos = response.getWriter();
    if (jsonp)
        sos.print(callback + "(");
    sos.print(m.toString(minified ? 0 : 2));
    if (jsonp)
        sos.println(");");
    sos.println();
    post.finalize();
}

From source file:com.basetechnology.s0.agentserver.field.LocationField.java

public JSONObject toJson() throws JSONException {
    JSONObject json = new JSONObject();
    json.put("type", "location");
    if (symbol.name != null)
        json.put("name", symbol.name);
    if (label != null)
        json.put("label", label);
    if (description != null)
        json.put("description", description);
    if (defaultValue != null)
        json.put("default_value", defaultValue);
    if (minValue != null)
        json.put("min_value", minValue);
    if (maxValue != null)
        json.put("max_value", maxValue);
    if (nominalWidth != 0)
        json.put("nominal_width", nominalWidth);
    if (compute != null)
        json.put("compute", compute);
    return json;/*w ww  .ja  v a2s . c  o  m*/
}