Example usage for org.json JSONArray JSONArray

List of usage examples for org.json JSONArray JSONArray

Introduction

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

Prototype

public JSONArray(Object array) throws JSONException 

Source Link

Document

Construct a JSONArray from an array

Usage

From source file:com.endofhope.neurasthenia.bayeux.BayeuxMessage.java

public BayeuxMessage(String jsonMessage) throws JSONException {
    JSONTokener jsont = new JSONTokener(jsonMessage);
    JSONArray jsona = new JSONArray(jsont);
    // FIXME ? msg   .
    JSONObject jsono = jsona.getJSONObject(0);
    // channel /*  w ww  .java  2 s .c o  m*/
    channel = jsono.getString("channel");
    if (channel != null && channel.startsWith("/meta/")) {
        if ("/meta/handshake".equals(channel)) {
            // type 
            type = BayeuxMessage.HANDSHAKE_REQ;
            // version 
            version = jsono.getString("version");
            JSONArray jsonaSupportedConnectionTypes = jsono.getJSONArray("supportedConnectionTypes");
            supportedConnectionTypesList = new ArrayList<String>();
            // supportedConnectionTypes 
            for (int i = 0; i < jsonaSupportedConnectionTypes.length(); i++) {
                supportedConnectionTypesList.add(jsonaSupportedConnectionTypes.getString(i));
            }
            // Handshake req ?  mandatory ? ? ?.
        } else if ("/meta/connect".equals(channel)) {
            type = BayeuxMessage.CONNECT_REQ;
            clientId = jsono.getString("clientId");
            connectionType = jsono.getString("connectionType");
        } else if ("/meta/disconnect".equals(channel)) {
            type = BayeuxMessage.DISCONNECT_REQ;
            clientId = jsono.getString("clientId");
        } else if ("/meta/subscribe".equals(channel)) {
            type = BayeuxMessage.SUBSCRIBE_REQ;
            clientId = jsono.getString("clientId");
            subscription = jsono.getString("subscription");
        } else if ("/meta/unsubscribe".equals(channel)) {
            type = BayeuxMessage.UNSUBSCRIBE_REQ;
            clientId = jsono.getString("clientId");
            subscription = jsono.getString("subscription");
        }
    } else {
        type = BayeuxMessage.PUBLISH_REQ;
        data = jsono.getString("data");
    }
}

From source file:io.s4.client.Driver.java

/**
 * Establish a connection to the adapter. Upon success, this enables the
 * client to send and receive events. The client must first be initialized.
 * Otherwise, this operation will fail.//from   w  w w  .j a v a 2s  .c o  m
 * 
 * @see #init()
 * 
 * @return true if and only if a connection was successfully established.
 * @throws IOException
 *             if the underlying TCP/IP socket throws an exception.
 */
public boolean connect() throws IOException {
    if (!state.isInitialized()) {
        // must first be initialized
        if (debug) {
            System.err.println("Not initialized.");
        }
        return false;
    } else if (state.isConnected()) {
        // nothing to do if already connected.
        return true;
    }

    String message = null;

    try {
        // constructing connect message
        JSONObject json = new JSONObject();

        json.put("uuid", uuid);
        json.put("readMode", readMode.toString());
        json.put("writeMode", writeMode.toString());

        if (readInclude != null) {
            // stream inclusion
            json.put("readInclude", new JSONArray(readInclude));
        }

        if (readExclude != null) {
            // stream exclusion
            json.put("readExclude", new JSONArray(readExclude));
        }

        message = json.toString();

    } catch (JSONException e) {
        if (debug) {
            System.err.println("error constructing connect message: " + e);
        }
        return false;
    }

    try {
        // send the message
        this.sock = new Socket(hostname, port);
        this.io = new ByteArrayIOChannel(sock);

        io.send(message.getBytes());

        // get a response
        byte[] b = io.recv();

        if (b == null || b.length == 0) {
            if (debug) {
                System.err.println("empty response from adapter during connect.");
            }
            return false;
        }

        String response = new String(b);

        JSONObject json = new JSONObject(response);
        String s = json.optString("status", "unknown");

        // does it look OK?
        if (s.equalsIgnoreCase("ok")) {
            // done connecting
            state = State.Connected;
            return true;
        } else if (s.equalsIgnoreCase("failed")) {
            // server has failed the connect attempt
            if (debug) {
                System.err.println("connect failed by adapter. reason: " + json.optString("reason", "unknown"));
            }
            return false;
        } else {
            // unknown response.
            if (debug) {
                System.err.println("connect failed by adapter. unrecongnized response: " + response);
            }
            return false;
        }

    } catch (Exception e) {
        // clean up after error...
        if (debug) {
            System.err.println("error during connect: " + e);
            e.printStackTrace();
        }

        if (this.sock.isConnected()) {
            this.sock.close();

        }

        return false;
    }
}

From source file:com.sublimis.urgentcallfilter.MyPreference.java

public static JSONArray getData() {
    String input = getStringPref(R.string.pref_database_key, null);

    JSONArray obj = null;//www  . ja va  2 s.c om

    try {
        obj = new JSONArray(input);
    } catch (Exception e) {
    }

    return obj;
}

From source file:com.google.enterprise.connector.ldap.LdapConnectorConfig.java

/**
 * Gets the attribute which has the appended schema attributes and splits them
 * to add individual items in the provided set.
 * @param config Config of user entered entries
 * @param tempSchema Set which holds the schema attributes.
 *///  www .j av  a  2s  .co m
private void addSchemaFromConfig(Map<String, String> config, Set<String> tempSchema) {

    String schemaValues = getJsonStringForSelectedAttributes(config);
    if (schemaValues != null && schemaValues.trim().length() != 0) {
        JSONArray arr;
        try {
            arr = new JSONArray(schemaValues);
            for (int i = 0; i < arr.length(); i++) {
                tempSchema.add(arr.getString(i));
            }
        } catch (JSONException e) {
            LOG.warning("Did not get any selected attributes...");
        }
    }
    LOG.fine("Selected attributes: " + tempSchema);
}

From source file:com.google.enterprise.connector.ldap.LdapConnectorConfig.java

/**
 * Assigns value to schemavalue from config form. Adds DN_ATTRIBUTE if not
 * present already./*from  w  w w  .  j  a v a  2  s.co  m*/
 * 
 * @param config Config values entered on the form
 * @return SchemaValue in as String
 */
static String getSchemaValueFromConfig(Map<String, String> config) {

    String configSchemaValue = null;
    LOG.fine("Original SchemaValue - " + config.get(ConfigName.SCHEMAVALUE.toString()));

    Set<String> schemaValue = new TreeSet<String>();
    LOG.fine("Trying to recover attributes from schema checkboxes");
    StringBuffer schemaKey = new StringBuffer();
    schemaKey.append(ConfigName.SCHEMA.toString()).append("_").append("\\d");
    Pattern keyPattern = Pattern.compile(schemaKey.toString());
    Set<String> configKeySet = config.keySet();

    for (String configKey : configKeySet) {
        Matcher matcher = keyPattern.matcher(configKey);
        if (matcher.find()) {
            String schemaAttribute = config.get(configKey);
            if (schemaAttribute != null && schemaAttribute.trim().length() != 0) {
                schemaValue.add(config.get(configKey));
            }
        }
    }

    // always add dn attribute to schema. 'dn' checkbox is hidden so can't be 
    // read and added to schemaValue in the code above.
    schemaValue.add(LdapHandler.DN_ATTRIBUTE);

    try {
        configSchemaValue = (new JSONArray(schemaValue.toString())).toString();
        LOG.fine("From config SchemaValue - " + configSchemaValue);

    } catch (JSONException e) {
        LOG.log(Level.WARNING, "JSONException trace:", e);
    }

    return configSchemaValue;
}

From source file:nl.hnogames.domoticzapi.Parsers.NotificationsParser.java

@Override
public void parseResult(String result) {
    try {/*from   w  ww  .  j a v  a 2  s .c  o  m*/
        JSONArray jsonArray = new JSONArray(result);
        ArrayList<NotificationInfo> mNotificationInfo = new ArrayList<>();

        if (jsonArray.length() > 0) {
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject row = jsonArray.getJSONObject(i);
                mNotificationInfo.add(new NotificationInfo(row));
            }
        }
        notificationsReceiver.onReceiveNotifications(mNotificationInfo);

    } catch (JSONException e) {
        Log.e(TAG, "JSON exception");
        e.printStackTrace();
        notificationsReceiver.onError(e);
    }
}

From source file:no.ntnu.wifimanager.ServerUtilities.java

public static JSONArray getJSONArray(String url, String userId) {

    InputStream is = null;//from   w  w w .  j a  v a2s. c  o m
    JSONArray jArray = null;
    String json = "";

    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
        nameValuePairs.add(new BasicNameValuePair("user_id", userId));
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jArray = new JSONArray(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jArray;
}

From source file:com.soomla.cocos2dx.profile.ProfileEventHandlerBridge.java

/**
 * Called when a get feed process from a provider has finished
 *
 * @param getFeedFinishedEvent The event information
 *///from  w  ww.j ava  2s. c o  m
@Subscribe
public void onGetFeedFinishedEvent(final GetFeedFinishedEvent getFeedFinishedEvent) {
    mGLThread.queueEvent(new Runnable() {
        @Override
        public void run() {
            try {
                JSONObject parameters = new JSONObject();
                parameters.put("method", ProfileConsts.EVENT_GET_FEED_FINISHED);
                parameters.put("provider", getFeedFinishedEvent.Provider.getValue());
                parameters.put("socialActionType", getFeedFinishedEvent.SocialActionType.getValue());
                parameters.put("feed", new JSONArray(getFeedFinishedEvent.Posts));
                parameters.put("payload", getFeedFinishedEvent.Payload);
                parameters.put("hasMore", getFeedFinishedEvent.HasMore);
                NdkGlue.getInstance().sendMessageWithParameters(parameters);
            } catch (JSONException e) {
                throw new IllegalStateException(e);
            }
        }
    });
}

From source file:com.corumgaz.mobilsayac.VoiceRecognizer.LanguageDetailsChecker.java

@Override
public void onReceive(Context context, Intent intent) {
    Bundle results = getResultExtras(true);

    // get the list of supported languages
    if (results.containsKey(RecognizerIntent.EXTRA_SUPPORTED_LANGUAGES)) {
        // Convert the map to json
        supportedLanguages = results.getStringArrayList(RecognizerIntent.EXTRA_SUPPORTED_LANGUAGES);
        JSONArray jsonLanguages = new JSONArray(supportedLanguages);
        callbackContext.success(jsonLanguages);
    } else {/*w  ww  .j  ava 2s.co m*/
        callbackContext.error("Could not retrieve the list of supported languages");
    }
}

From source file:nl.hnogames.domoticz.Domoticz.SwitchLogParser.java

@Override
public void parseResult(String result) {
    try {/*  w w  w.ja  va 2s. co m*/
        JSONArray jsonArray = new JSONArray(result);
        ArrayList<SwitchLogInfo> mSwitcheLogs = new ArrayList<>();

        if (jsonArray.length() > 0) {
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject row = jsonArray.getJSONObject(i);
                mSwitcheLogs.add(new SwitchLogInfo(row));
            }
        }
        switcheLogsReceiver.onReceiveSwitches(mSwitcheLogs);

    } catch (JSONException e) {
        Log.e(TAG, "ScenesParser JSON exception");
        e.printStackTrace();
        switcheLogsReceiver.onError(e);
    }
}