Example usage for org.json JSONObject get

List of usage examples for org.json JSONObject get

Introduction

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

Prototype

public Object get(String key) throws JSONException 

Source Link

Document

Get the value object associated with a key.

Usage

From source file:com.orange.oidc.secproxy_service.Token.java

public void fromToken(String token) {
    reset();/*from  www  .java 2  s. c o m*/
    if (token == null)
        return;

    try {
        JSONObject jObject = null;

        // try token as is
        try {
            jObject = new JSONObject(token);
        } catch (Exception e) {
        }

        // try to decode JWT
        if (jObject == null) {
            String ds = getJSON(token);
            if (ds != null)
                jObject = new JSONObject(ds);
        }

        if (jObject != null) {
            JSONArray names = jObject.names();
            if (names != null) {
                for (int j = 0; j < names.length(); j++) {
                    String name = names.getString(j);
                    // Log.d("Token",name);
                    setField(name, jObject.get(name));
                }
            }
        }
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.hueemulator.lighting.utils.TestUtils.java

@SuppressWarnings("unchecked")
private static Object convertJsonElement(Object elem) throws JSONException {
    if (elem instanceof JSONObject) {
        JSONObject obj = (JSONObject) elem;
        Iterator<String> keys = obj.keys();
        Map<String, Object> jsonMap = new HashMap<String, Object>();
        while (keys.hasNext()) {
            String key = keys.next();
            jsonMap.put(key, convertJsonElement(obj.get(key)));
        }/*ww  w.jav a  2  s. co  m*/
        return jsonMap;
    } else if (elem instanceof JSONArray) {
        JSONArray arr = (JSONArray) elem;
        Set<Object> jsonSet = new HashSet<Object>();
        for (int i = 0; i < arr.length(); i++) {
            jsonSet.add(convertJsonElement(arr.get(i)));
        }
        return jsonSet;
    } else {
        return elem;
    }
}

From source file:actuatorapp.ActuatorApp.java

public void commandFromApi(JSONObject command) throws JSONException {
    //Takes the command and processes it
    try {/*from w  w w.ja va  2  s  .  c  o m*/
        String type = (String) command.get("type");
        if (type.equals("control") == true) {
            System.out.println(command);
            String yocto_addr = (String) command.get("yocto_addr");
            JSONObject payload = command.getJSONObject("payload");
            boolean value = (Boolean) payload.getBoolean("value");

            setActuatorState(yocto_addr, value);
        } else {
            System.out.println("Wrong command recieved");
        }
    } catch (Exception e) {
        System.out.println("Error on command SEND");
    }

}

From source file:nl.b3p.viewer.stripes.IbisMergeFeaturesActionBean.java

/**
 * Force the workflow status attribute on the feature. This will handle the
 * case where the {@code extraData} attribute is a piecs of json with the
 * workflow, eg//from   w  ww . j a  va2 s.co  m
 * {@code {workflow_status:'afgevoerd',datum_mutatie:'2015-12-01Z00:00'}}.
 *
 * @param features A list of features to be modified
 * @return the list of modified features that are about to be committed to
 * the datastore
 *
 * @throws JSONException if json parsing failed
 */
@Override
protected List<SimpleFeature> handleExtraData(List<SimpleFeature> features) throws JSONException {
    JSONObject json = new JSONObject(this.getExtraData());
    Iterator items = json.keys();
    while (items.hasNext()) {
        String key = (String) items.next();
        for (SimpleFeature f : features) {
            log.debug(String.format("Setting value: %s for attribute: %s on feature %s", json.get(key), key,
                    f.getID()));
            f.setAttribute(key, json.get(key));
            if (key.equalsIgnoreCase(WORKFLOW_FIELDNAME)) {
                newWorkflowStatus = WorkflowStatus.valueOf(json.getString(key));
            }
        }
    }
    return features;
}

From source file:com.joyfulmongo.db.JFCommand.java

protected List<ContainerObject> findChildObject(JSONObject parentObj) {
    List<ContainerObject> childs = new ArrayList<ContainerObject>(0);
    Iterator<String> keys = parentObj.keys();
    while (keys.hasNext()) {
        String key = keys.next();
        Object obj = parentObj.get(key);
        if (obj instanceof JSONObject) {
            ContainerObject typedObj = ContainerObjectFactory.getChildObject(key, (JSONObject) obj);
            if (typedObj != null) {
                childs.add(typedObj);/*w  ww .j  ava 2s . c o  m*/
            }
        }
    }

    return childs;
}

From source file:eu.codeplumbers.cosi.services.CosiLoyaltyCardService.java

/**
 * Make remote request to get all loyalty cards stored in Cozy
 *//*from  w w  w  .j  a  v a2s. c om*/
public String getRemoteLoyaltyCards() {
    URL urlO = null;
    try {
        urlO = new URL(designUrl);
        HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        conn.setRequestProperty("Authorization", authHeader);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");

        // read the response
        int status = conn.getResponseCode();
        InputStream in = null;

        if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
            in = conn.getErrorStream();
        } else {
            in = conn.getInputStream();
        }

        StringWriter writer = new StringWriter();
        IOUtils.copy(in, writer, "UTF-8");
        String result = writer.toString();

        JSONArray jsonArray = new JSONArray(result);

        if (jsonArray != null) {
            if (jsonArray.length() == 0) {
                EventBus.getDefault()
                        .post(new LoyaltyCardSyncEvent(SYNC_MESSAGE, "Your Cozy has no calls stored."));
                LoyaltyCard.setAllUnsynced();
            } else {
                for (int i = 0; i < jsonArray.length(); i++) {
                    try {

                        EventBus.getDefault().post(new LoyaltyCardSyncEvent(SYNC_MESSAGE,
                                "Reading loyalty cards on Cozy " + i + "/" + jsonArray.length() + "..."));
                        JSONObject loyaltyCardJson = jsonArray.getJSONObject(i).getJSONObject("value");
                        LoyaltyCard loyaltyCard = LoyaltyCard
                                .getByRemoteId(loyaltyCardJson.get("_id").toString());
                        if (loyaltyCard == null) {
                            loyaltyCard = new LoyaltyCard(loyaltyCardJson);
                        } else {
                            loyaltyCard.setRemoteId(loyaltyCardJson.getString("_id"));
                            loyaltyCard.setRawValue(loyaltyCardJson.getString("rawValue"));
                            loyaltyCard.setCode(loyaltyCardJson.getInt("code"));
                            loyaltyCard.setLabel(loyaltyCardJson.getString("label"));
                            loyaltyCard.setCreationDate(loyaltyCardJson.getString("creationDate"));
                        }

                        loyaltyCard.save();
                    } catch (JSONException e) {
                        EventBus.getDefault()
                                .post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
                        stopSelf();
                    }
                }
            }
        } else {
            errorMessage = new JSONObject(result).getString("error");
            EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, errorMessage));
            stopSelf();
        }

        in.close();
        conn.disconnect();

    } catch (MalformedURLException e) {
        EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (ProtocolException e) {
        EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (IOException e) {
        EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (JSONException e) {
        EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    }
    return errorMessage;
}

From source file:org.academia.servlet.SRegistrarTutor.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*  w  w  w  . j a 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 {
    StringBuffer jb = new StringBuffer();
    String line = null;
    try {
        BufferedReader reader = request.getReader();
        while ((line = reader.readLine()) != null) {
            jb.append(line);
        }
        //System.out.println(jb.toString());
        String datt = String.valueOf(jb.toString());

        JSONObject jsonObj = new JSONObject(datt);

        BTutor oTutor = new BTutor();
        String value = (String) jsonObj.get("nombre");
        oTutor.setNombre(value);

        value = (String) jsonObj.get("apellidoPaterno");
        oTutor.setApellidoPaterno(value);

        value = (String) jsonObj.get("apellidoMaterno");
        oTutor.setApellidoMaterno(value);

        value = (String) jsonObj.get("dni");
        oTutor.setDni(value);

        value = (String) jsonObj.get("direccion");
        oTutor.setDireccion(value);

        //Valores por defecto
        oTutor.setEstado(true);
        oTutor.setIdTutor(1);//no interesa el numero de id

        int idTutor = new DAOTutor().registrarTutor(oTutor);

        BTelefono oBTelefono = new BTelefono();

        value = (String) jsonObj.get("telefono");
        oBTelefono.setNumero(value);
        //valores predetemindas
        oBTelefono.setIdTelefono(1);
        oBTelefono.setIdTitular(idTutor);
        oBTelefono.setTipoTelefono("Claro");
        oBTelefono.setEstado(true);

        boolean flag = new DAOTelefono().insertarTelefono(oBTelefono);

        if ((idTutor != 0) && flag == true) {
            String json1 = new Gson().toJson("Tutor Registrado!");
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().write(json1);
        } else {
            String json1 = new Gson().toJson("Error al registrar Tutor");
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().write(json1);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:org.wso2.carbon.identity.authenticator.office365.Office365Authenticator.java

/**
 * Process the response of the office365 end-point
 *///from  w  w  w  . j  ava  2 s  . c o m
@Override
protected void processAuthenticationResponse(HttpServletRequest request, HttpServletResponse response,
        AuthenticationContext context) throws AuthenticationFailedException {
    try {
        Map<String, String> authenticatorProperties = context.getAuthenticatorProperties();
        String clientId = authenticatorProperties.get(OIDCAuthenticatorConstants.CLIENT_ID);
        String clientSecret = authenticatorProperties.get(OIDCAuthenticatorConstants.CLIENT_SECRET);
        String tokenEndPoint = getTokenEndpoint(authenticatorProperties);
        String callbackUrl = getCallbackUrl(authenticatorProperties);
        OAuthAuthzResponse authorizationResponse = OAuthAuthzResponse.oauthCodeAuthzResponse(request);
        String code = authorizationResponse.getCode();
        OAuthClientRequest accessRequest = getAccessRequest(tokenEndPoint, clientId, code, clientSecret,
                callbackUrl);
        OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
        OAuthClientResponse oAuthResponse = getOauthResponse(oAuthClient, accessRequest);
        String accessToken = oAuthResponse.getParam(OIDCAuthenticatorConstants.ACCESS_TOKEN);
        if (StringUtils.isBlank(accessToken)) {
            throw new AuthenticationFailedException("Access token is empty or null");
        }
        context.setProperty(OIDCAuthenticatorConstants.ACCESS_TOKEN, accessToken);
        String json = sendRequest(Office365AuthenticatorConstants.office365_USERINFO_ENDPOINT,
                oAuthResponse.getParam(OIDCAuthenticatorConstants.ACCESS_TOKEN));
        JSONObject obj = new JSONObject(json);
        Map<ClaimMapping, String> claims = getSubjectAttributes(oAuthResponse, authenticatorProperties);
        String id = claims.get(ClaimMapping.build(Office365AuthenticatorConstants.ID,
                Office365AuthenticatorConstants.ID, null, false));
        AuthenticatedUser authenticatedUserObj = AuthenticatedUser
                .createFederateAuthenticatedUserFromSubjectIdentifier(
                        (String) obj.get(Office365AuthenticatorConstants.ID));
        authenticatedUserObj.setAuthenticatedSubjectIdentifier(id);
        authenticatedUserObj.setUserAttributes(claims);
        context.setSubject(authenticatedUserObj);
    } catch (OAuthProblemException | IOException e) {
        throw new AuthenticationFailedException("Authentication process failed", e);
    }
}

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

@POST
@Path("/")
@Consumes(MediaType.APPLICATION_JSON)//from  w  w w.  ja  v a2s.c o  m
@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: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;/*from   ww  w.  jav  a2s.  c  om*/
    }

    // 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();
}