Example usage for org.json JSONObject getJSONObject

List of usage examples for org.json JSONObject getJSONObject

Introduction

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

Prototype

public JSONObject getJSONObject(String key) throws JSONException 

Source Link

Document

Get the JSONObject value associated with a key.

Usage

From source file:org.mapsforge.poi.exchange.GeoJsonPoiReader.java

PointOfInterest fromFeature(JSONObject feature) throws JSONException {
    String type = feature.getString("type").toString();
    PointOfInterest point;//  w w  w .ja  v a  2s  . c  o m
    String name = null;
    String url = null;
    Long id = null;

    if (type.equals("Feature")) {
        point = fromPoint(feature.getJSONObject("geometry"));

        if (feature.has("properties")) {
            JSONObject properties = feature.getJSONObject("properties");
            if (properties.has("name")) {
                name = properties.getString("name");
            }
            if (properties.has("url")) {
                url = properties.getString("url");
            }
            if (properties.has("id")) {
                id = properties.getLong("id");
            }
        }

    } else {
        throw new IllegalArgumentException();
    }

    return new PoiBuilder(id, point.getLatitude(), point.getLongitude(), this.category).setName(name)
            .setUrl(url).build();
}

From source file:org.restcomm.app.utillib.Reporters.WebReporter.WebReporter.java

public static String geocode(Context context, double latitude, double longitude) {
    String addressString = String.format("%.4f, %.4f", latitude, longitude);
    try {/*www.jav  a 2  s  .c  o m*/
        String apiKey = Global.getApiKey(context);
        String server = Global.getApiUrl(context);
        String url = server + "/api/osm/location?apiKey=" + apiKey + "&location=" + latitude + "&location="
                + longitude;
        String response = WebReporter.getHttpURLResponse(url, false);

        JSONObject json = null;
        JSONArray jsonArray = null;

        if (response == null)
            return addressString;

        try {
            jsonArray = new JSONArray(response);
        } catch (JSONException e) {
            return addressString;
        }
        try {
            for (int i = 0; i < jsonArray.length(); i++) {
                json = jsonArray.getJSONObject(i);
                if (json.has("error")) {
                    String error = json.getString("error");
                    return null;
                } else {
                    addressString = "";
                    json = json.getJSONObject("address");
                    String number = "";
                    if (json.has("house_number")) {
                        number = json.getString("house_number");
                        addressString += number + " ";
                    }
                    String road = json.getString("road");
                    addressString += road;// + suburb;
                    return addressString;
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    } catch (Exception e) {
    }

    return addressString;
}

From source file:com.jaspersoft.jasperserver.ps.OAuth.JSONUtils.java

private static Map<String, String> parse(JSONObject json, Map<String, String> out) throws JSONException {
    Iterator<String> keys = json.keys();
    while (keys.hasNext()) {
        String key = keys.next();
        String val = null;
        try {/*from w  ww. j a  v a2 s .  c  o  m*/
            JSONObject value = json.getJSONObject(key);
            parse(value, out);
        } catch (Exception e) {
            val = json.getString(key);
        }

        if (val != null) {
            out.put(key, val);
        }
    }
    return out;
}

From source file:com.nextgis.maplib.datasource.ngw.Connection.java

protected void fillCapabilities() {
    mSupportedTypes.clear();/*from   w w w . ja va2 s . com*/
    try {
        String sURL = mURL + "/resource/schema";
        HttpGet get = new HttpGet(sURL);
        get.setHeader("Cookie", getCookie());
        get.setHeader("Accept", "*/*");
        HttpResponse response = getHttpClient().execute(get);
        HttpEntity entity = response.getEntity();

        JSONObject schema = new JSONObject(EntityUtils.toString(entity));
        JSONObject resources = schema.getJSONObject("resources");
        if (null != resources) {
            Iterator<String> keys = resources.keys();
            while (keys.hasNext()) {
                int type = getType(keys.next());
                if (type != NGWResourceTypeNone) {
                    if (mSupportedTypes.isEmpty())
                        mSupportedTypes.add(type);
                    else if (!isTypeSupported(type))
                        mSupportedTypes.add(type);
                }
            }
        }
    } catch (IOException | JSONException e) {
        e.printStackTrace();
    }
}

From source file:net.dv8tion.jda.core.handle.GuildBanHandler.java

@Override
protected Long handleInternally(JSONObject content) {
    final long id = content.getLong("guild_id");
    if (api.getGuildLock().isLocked(id))
        return id;

    JSONObject userJson = content.getJSONObject("user");
    GuildImpl guild = (GuildImpl) api.getGuildMap().get(id);
    if (guild == null) {
        api.getEventCache().cache(EventCache.Type.GUILD, id, () -> {
            handle(responseNumber, allContent);
        });/*from  w  ww . ja  v a2s .co m*/
        EventCache.LOG.debug(
                "Received Guild Member " + (banned ? "Ban" : "Unban") + " event for a Guild not yet cached.");
        return null;
    }

    User user = api.getEntityBuilder().createFakeUser(userJson, false);

    if (banned) {
        api.getEventManager().handle(new GuildBanEvent(api, responseNumber, guild, user));
    } else {
        api.getEventManager().handle(new GuildUnbanEvent(api, responseNumber, guild, user));
    }
    return null;
}

From source file:org.immopoly.android.api.IS24ApiService.java

/**
 * Runs an IS2 search with the given lat,lon,r
 * Returns at most 'max' Flats or null if there are less than 'min' flats.   
 * @param lat Latitude//from   w  w  w .jav a  2 s  .c om
 * @param lon Longitude
 * @param r Radius
 * @param min minimum nuber of flats
 * @param max maximum nuber of flats
 * @return Flats or null
 * @throws JSONException. MalformedURLException, NullPointerException 
 */
private Flats loadFlats(double lat, double lon, float r, int min, int max)
        throws JSONException, MalformedURLException {
    Log.d(Const.LOG_TAG,
            "IS24 search: Lat: " + lat + " Lon: " + lon + " R: " + r + " min: " + min + " max: " + max);
    // get the first result page and extract paging info
    JSONObject json = loadPage(lat, lon, r, 1); // IS24 page nr starts at 1
    JSONObject resultList = json.getJSONObject("resultlist.resultlist");
    JSONObject pagingInfo = resultList.getJSONObject("paging");
    int numPages = pagingInfo.getInt("numberOfPages");
    int results = pagingInfo.getInt("numberOfHits");
    int pageSize = pagingInfo.getInt("pageSize");

    Log.d(Const.LOG_TAG, "IS24 search got first page, numPages: " + numPages + " results: " + results
            + " pageSize: " + pageSize);
    // return if there aren't enough results
    if (results < min || numPages * pageSize < min || results <= 0)
        return null;

    // parse flats from 1st result page
    Flats flats = new Flats(max);
    flats.parse(json);

    // calc pages to get
    int pages = max / pageSize;
    if (pages >= 0 && max % pageSize > 0)
        pages++;
    if (pages > numPages) // if this happens theres something wrong here or in the json
        pages = numPages;

    // evtly get more pages
    for (int i = 2; i <= pages; i++) {
        json = loadPage(lat, lon, r, i);
        flats.parse(json);
        Log.d(Const.LOG_TAG, "IS24 search got page " + i + "/" + pages + " #flats: " + flats.size());
    }

    // restrict number of results
    if (flats.size() > max) {
        Flats lessFlats = new Flats(max);
        lessFlats.addAll(flats.subList(0, max));
        flats = lessFlats;
    }
    return flats;
}

From source file:io.sponges.dubtrack4j.internal.subscription.callback.UserJoinCall.java

@Override
public void run(JSONObject json) throws IOException {
    String username = json.getJSONObject("user").getString("username");
    String userId = json.getJSONObject("user").getString("_id");
    String roomId = json.getJSONObject("roomUser").getString("roomid");

    RoomImpl room = dubtrack.loadRoom(roomId);
    User user = room.getOrLoadUser(userId);

    dubtrack.getEventBus().post(new UserJoinEvent(user, room));
}

From source file:com.example.wmgps.MainActivity.java

/** Called when the user clicks the Send button */
public void sendMessage(View view) {
    /*Intent intent = new Intent(this, DisplayMessageActivity.class);
    EditText editText = (EditText) findViewById(R.id.edit_message);
    String message = editText.getText().toString();
    intent.putExtra(EXTRA_MESSAGE, message);
    startActivity(intent);*///from www .j  ava 2 s. co m

    /*EditText editText = (EditText) findViewById(R.id.edit_message);
    String message = editText.getText().toString();
            
    TextView output = (TextView) findViewById(R.id.welcome);
    output.setText(message);*/

    /*Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(URL));
    startActivity(browserIntent);
            
    */
    TextView hiddenText = (TextView) findViewById(R.id.Hidden11);
    if (Misc.isNullTrimmedString(hiddenText.getText().toString())) {
        TextView output = (TextView) findViewById(R.id.welcome1);
        boolean without_connection = true;
        Map<String, ArrayList<String>> typeAndValueOfTag = new LinkedHashMap<String, ArrayList<String>>(); // Insertion order must be followed

        String response = Misc.EMPTY_STRING;
        String welcome1String = "*******************Connected*************************";
        try {

            response = new RetrieveFeedTask().execute(new String[] {}).get();

        } catch (Exception e) {
            response = Misc.EMPTY_STRING;
            Log.e("Exception ", e.getMessage());

            Log.e("Exception ", e.getLocalizedMessage());

            Log.e("Exception ", e.getStackTrace().toString());

        }

        if (Misc.isNullTrimmedString(response)) {
            // welcome1String = "***Loading Static, couldn't connect***";

            response = "{\"window\":{\"elements\":[{\"type\":\"hidden\",\"name\":\"sourceAction\"},{\"type\":\"label\",\"value\":\"Warehouse Management\"},"
                    + "{\"type\":\"break\"},{\"type\":\"label\",\"value\":\"--------- ----------\"},{\"type\":\"break\"}, {\"type\":\"label\",\"value\":\" User ID: \"},"
                    + "{\"type\":\"entry\",\"name\":\"j_username\",\"value\":\"\",\"maxLength\":15,\"dispLength\":10,"
                    + "\"setHidden\":[{\"hiddenName\":\"sourceAction\",\"hiddenValue\":\"username\"}],\"focus\":true},"
                    + "{\"type\":\"break\"},{\"type\":\"label\",\"value\":\"Password: \"},"
                    + "{\"type\":\"entry\",\"name\":\"j_password\",\"value\":\"\",\"hideInput\":true,\"maxLength\":14,\"dispLength\":10,\"focus\":false},"
                    + "{\"type\":\"keybinding\",\"value\":\"CTRL-X\",\"URL\":\"\",\"keyDescription\":\"CTRL-X Exit\"},"
                    + "{\"type\":\"keybinding\",\"value\":\"CTRL-L\",\"URL\":\"/scopeRF/RFLogin/RFLegal.jsp\",\"keyDescription\":\"CTRL-L License Agreement\"}]"
                    + ",\"submit\":\"/scopeRF/RFLogin/ProcessLogin.jsp\"}}";
        }

        StringBuffer finalEncodedString = new StringBuffer(Misc.EMPTY_STRING);

        int currentOutputTag = R.id.Hidden1;
        int currentInputTag = R.id.edit_message;

        // Renderer::decodeConfig()
        if (!Misc.isNullTrimmedString(response)) {
            try {
                JSONObject jsonObj = new JSONObject(response);

                for (Iterator iterator = jsonObj.keys(); iterator.hasNext();) {
                    String name = (String) iterator.next();

                    JSONObject jsonObj1 = jsonObj.getJSONObject(name);

                    for (Iterator iterator1 = jsonObj1.keys(); iterator1.hasNext();) {
                        String name1 = (String) iterator1.next();

                        if ("elements".equals(name1)) {
                            JSONArray jsonArr = jsonObj1.getJSONArray(name1);
                            boolean userName = false;
                            boolean password = false;
                            for (int i = 0; i < jsonArr.length(); i++) {
                                JSONObject temp = jsonArr.getJSONObject(i);
                                String initialValue = null;
                                String initialName = null;
                                String initialLabel = null;

                                if (!temp.isNull("name") && temp.getString("name").equals("j_password")) {
                                    initialName = "j_password";
                                } else if (!temp.isNull("name")
                                        && temp.getString("name").equals("j_username")) {
                                    initialName = "j_username";
                                }

                                for (Iterator iterator2 = temp.keys(); iterator2.hasNext();) {
                                    String tempName = (String) iterator2.next();
                                    String tempValue = (String) temp.getString(tempName);

                                    if (tempName.equals("type")) {
                                        if (tempValue.equals("label") || tempValue.equals("entry")) {
                                            initialLabel = tempValue;
                                        }
                                    } else if (tempName.equals("value")) {
                                        initialValue = tempValue;
                                    }

                                    /* if(tempName.equals("label"))
                                     {
                                        if(Misc.isNullTrimmedString(initialValue))
                                     initialLabel = tempName;
                                        else
                                        {
                                     typeAndValueOfTag.put("output",initialValue);
                                     initialValue = Misc.EMPTY_STRING;
                                     continue;
                                        }
                                     }
                                     else if(tempName.equals("value"))
                                     {
                                        if(Misc.isNullTrimmedString(initialName) && Misc.isNullTrimmedString(initialLabel))
                                        {
                                     initialValue = tempValue;
                                        }
                                        else if(!Misc.isNullTrimmedString(initialLabel) && initialLabel.equals("label"))
                                        {
                                     typeAndValueOfTag.put("output",tempValue);
                                     initialValue = Misc.EMPTY_STRING;
                                     continue;
                                        }
                                        else if(!Misc.isNullTrimmedString(initialLabel) && initialLabel.equals("entry"))
                                        {
                                     if(!Misc.isNullTrimmedString(initialName) && initialName.equals("name"))
                                        typeAndValueOfTag.put("input",tempValue);
                                     else
                                        initialValue = tempValue;
                                        }
                                     }
                                     else if(tempName.equals("entry"))
                                     {
                                        if(Misc.isNullTrimmedString(initialValue) || Misc.isNullTrimmedString(initialLabel))
                                        {
                                     initialName = tempName;
                                        }
                                        else
                                     typeAndValueOfTag.put("input",initialValue);
                                                
                                        finalEncodedString.append("  " + tempName + "  " + tempValue + " ----- ");
                                     }*/
                                }

                                if (initialLabel != null) {
                                    if (initialLabel.equals("label")) {
                                        if (initialValue.equals(" User ID: ")) {
                                            TextView output1 = (TextView) findViewById(R.id.userNameText);
                                            output1.setText(initialValue);
                                            output1.setVisibility(View.VISIBLE);
                                            userName = true;
                                            password = false;
                                        } else if (initialValue.equals("Password: ")) {
                                            TextView output1 = (TextView) findViewById(R.id.passwordText);
                                            output1.setText(initialValue);
                                            output1.setVisibility(View.VISIBLE);
                                            password = true;
                                            userName = false;
                                        } else {
                                            TextView output1 = (TextView) findViewById(currentOutputTag++);
                                            output1.setText(initialValue);
                                            output1.setVisibility(View.VISIBLE);
                                            userName = false;
                                            password = false;
                                        }
                                    } else if (initialLabel.equals("entry")) {
                                        if ("j_password".equals(initialName)) {
                                            EditText input = ((EditText) findViewById(R.id.passwordEdit));
                                            input.setVisibility(View.VISIBLE);
                                            if (Misc.isNullTrimmedString(initialValue)) {
                                                input.setText("");
                                                input.setHint("Please enter password");
                                            }
                                        } else if ("j_username".equals(initialName)) {
                                            EditText input = ((EditText) findViewById(R.id.userNameEdit));
                                            input.setVisibility(View.VISIBLE);
                                            if (Misc.isNullTrimmedString(initialValue)) {
                                                input.setText("");
                                                input.setHint("Please enter username");
                                            }
                                        } else {
                                            EditText input = ((EditText) findViewById(currentInputTag++));
                                            input.setVisibility(View.VISIBLE);
                                            if (Misc.isNullTrimmedString(initialValue)) {
                                                input.setText("");
                                                input.setHint("Please enter value");
                                            } else
                                                input.setText(initialValue);
                                        }
                                    }
                                }
                                /*if(initialLabel != null)
                                {
                                   List<String> listOfValues;
                                   if(typeAndValueOfTag.containsKey(initialLabel))
                                   {
                                  listOfValues = typeAndValueOfTag.get(initialLabel);
                                  listOfValues.add(initialValue);
                                   }
                                   typeAndValueOfTag.put(initialLabel,initialValue);
                                }*/
                            }
                        } else {
                            // Here, just the URL would get processed. So don't use.
                            // output.setText("  " + name + "  " + jsonObj1.getString(name1));
                        }
                    }
                }

                TextView welcome1 = (TextView) findViewById(R.id.welcome1);
                welcome1.setText(welcome1String);

                // processUIDisplay(typeAndValueOfTag);

                /*if(finalEncodedString.length() == 0)
                   finalEncodedString.append("Could not process");
                        
                output.setText(finalEncodedString.toString());
                        
                TextView output2 = (TextView) findViewById(R.id.Hidden1);
                output2.setText("Hidden one is enabled");
                output2.setVisibility(View.VISIBLE);*/

            } catch (JSONException e) {
                Log.e("Exception ", e.getMessage());

                Log.e("Exception ", e.getLocalizedMessage());

                Log.e("Exception ", e.getStackTrace().toString());
            }
        }

        hiddenText.setText("validated user");

        /* {"window":{"elements":[{"type":"hidden","name":"sourceAction"},{"type":"label","value":"Warehouse Management"},
                  {"type":"break"},{"type":"label","value":"--------- ----------"},{"type":"break"}, {"type":"label","value":" User ID: "},
                  {"type":"entry","name":"j_username","value":"","maxLength":15,"dispLength":10,
                  "setHidden":[{"hiddenName":"sourceAction","hiddenValue":"username"}],"focus":true},
                  {"type":"break"},{"type":"label","value":"Password: "},
                  {"type":"entry","name":"j_password","value":"","hideInput":true,"maxLength":14,"dispLength":10,"focus":false},
                  {"type":"keybinding","value":"CTRL-X","URL":"","keyDescription":"CTRL-X Exit"},
                  {"type":"keybinding","value":"CTRL-L","URL":"/scopeRF/RFLogin/RFLegal.jsp","keyDescription":"CTRL-L License Agreement"}]
           ,"submit":"/scopeRF/RFLogin/ProcessLogin.jsp"}}*/
    } else {
        List outputList = verifyUser();

        if (!Misc.isNullList(outputList)) {
            String sessionId = (String) outputList.get(0);
            String userType = (String) outputList.get(1);

            Intent intent = new Intent(this, MenuActivity.class);
            if (!Misc.isNullTrimmedString(sessionId) && !Misc.isNullTrimmedString(userType)
                    && Integer.parseInt(sessionId) > 0) {
                if (userType.equals(Constants.WORKER)) {
                    MenuActivity.sessionId = Misc.EMPTY_STRING;
                    TextView error = (TextView) findViewById(R.id.ErrorText);
                    error.setText(Misc.EMPTY_STRING);
                    error.setVisibility(View.GONE);
                    intent.putExtra(Constants.USER_TYPE, Constants.WORKER);
                    intent.putExtra(Constants.SESSION_ID, sessionId);
                } else {
                    TextView error = (TextView) findViewById(R.id.ErrorText);
                    error.setText(Misc.EMPTY_STRING);
                    error.setVisibility(View.GONE);
                    intent.putExtra(Constants.USER_TYPE, Constants.SUPERVISOR);
                    intent.putExtra(Constants.SESSION_ID, sessionId);
                }
            }
            // goto Maps screen
            // Get the message from the intent
            startActivity(intent);
        } else {

            TextView error = (TextView) findViewById(R.id.ErrorText);
            error.setText("Invalid Username/Password");
            error.setVisibility(View.VISIBLE);
        }
    }
    return;

}

From source file:org.springframework.extensions.webscripts.connector.AlfrescoAuthenticator.java

public ConnectorSession authenticate(String endpoint, Credentials credentials,
        ConnectorSession connectorSession) throws AuthenticationException {
    ConnectorSession cs = null;/*from  www  .j  a  va2s .co m*/

    String user, pass;
    if (credentials != null
            && (user = (String) credentials.getProperty(Credentials.CREDENTIAL_USERNAME)) != null
            && (pass = (String) credentials.getProperty(Credentials.CREDENTIAL_PASSWORD)) != null) {
        // build a new remote client

        // Take endpointId from credentials as the endpoint may be remapped to allow an endpoint to credentials from
        // a parent endpoint - for the purposes of authentication, we want to use the parent endpoint URL.
        // @see ConnectorService.getConnectorSession()
        // @see SimpleCredentialVault.retrieve()
        final String endpointId = credentials.getEndpointId();
        final RemoteConfigElement config = getConnectorService().getRemoteConfig();
        final EndpointDescriptor desc = config.getEndpointDescriptor(endpointId);
        if (desc == null) {
            throw new IllegalArgumentException("Unknown endpoint ID: " + endpointId);
        }
        final RemoteClient remoteClient = buildRemoteClient(
                config.getEndpointDescriptor(endpointId).getEndpointUrl());

        if (logger.isDebugEnabled())
            logger.debug("Authenticating user: " + user);

        // POST to the Alfresco login WebScript
        remoteClient.setRequestContentType(MIMETYPE_APPLICATION_JSON);
        String body = MessageFormat.format(JSON_LOGIN, JSONWriter.encodeJSONString(user),
                JSONWriter.encodeJSONString(pass));
        Response response = remoteClient.call(getLoginURL(), body);

        // read back the ticket
        if (response.getStatus().getCode() == 200) {
            String ticket;
            try {
                JSONObject json = new JSONObject(response.getResponse());
                ticket = json.getJSONObject("data").getString("ticket");
            } catch (JSONException jErr) {
                // the ticket that came back could not be parsed
                // this will cause the entire handshake to fail
                throw new AuthenticationException("Unable to retrieve login ticket from Alfresco", jErr);
            }

            if (logger.isDebugEnabled())
                logger.debug("Parsed ticket: " + ticket);

            // place the ticket back into the connector session
            if (connectorSession != null) {
                connectorSession.setParameter(CS_PARAM_ALF_TICKET, ticket);

                // signal that this succeeded
                cs = connectorSession;
            }
        } else if (response.getStatus().getCode() == Status.STATUS_NO_CONTENT) {
            if (logger.isDebugEnabled())
                logger.debug("SC_NO_CONTENT(204) status received - retreiving auth cookies...");

            // The login created an empty response, probably with cookies in the connectorSession. We succeeded.
            processResponse(response, connectorSession);
            cs = connectorSession;
        } else {
            if (logger.isDebugEnabled())
                logger.debug(
                        "Authentication failed, received response code: " + response.getStatus().getCode());
        }
    } else if (logger.isDebugEnabled()) {
        logger.debug("No user credentials available - cannot authenticate.");
    }

    return cs;
}

From source file:com.sonoport.freesound.response.mapping.Mapper.java

/**
 * Extract a named value from a {@link JSONObject}. This method checks whether the value exists and is not an
 * instance of <code>JSONObject.NULL</code>.
 *
 * @param jsonObject The {@link JSONObject} being processed
 * @param field The field to retrieve// w ww .  j a va  2  s  .c om
 * @param fieldType The data type of the field
 * @return The field value (or null if not found)
 *
 * @param <T> The data type to return
 */
@SuppressWarnings("unchecked")
protected <T extends Object> T extractFieldValue(final JSONObject jsonObject, final String field,
        final Class<T> fieldType) {
    T fieldValue = null;
    if ((jsonObject != null) && jsonObject.has(field) && !jsonObject.isNull(field)) {
        try {
            if (fieldType == String.class) {
                fieldValue = (T) jsonObject.getString(field);
            } else if (fieldType == Integer.class) {
                fieldValue = (T) Integer.valueOf(jsonObject.getInt(field));
            } else if (fieldType == Long.class) {
                fieldValue = (T) Long.valueOf(jsonObject.getLong(field));
            } else if (fieldType == Float.class) {
                fieldValue = (T) Float.valueOf(Double.toString(jsonObject.getDouble(field)));
            } else if (fieldType == JSONArray.class) {
                fieldValue = (T) jsonObject.getJSONArray(field);
            } else if (fieldType == JSONObject.class) {
                fieldValue = (T) jsonObject.getJSONObject(field);
            } else {
                fieldValue = (T) jsonObject.get(field);
            }
        } catch (final JSONException | ClassCastException e) {
            // TODO Log a warning
        }
    }

    return fieldValue;
}