Example usage for com.fasterxml.jackson.core JsonFactory createJsonParser

List of usage examples for com.fasterxml.jackson.core JsonFactory createJsonParser

Introduction

In this page you can find the example usage for com.fasterxml.jackson.core JsonFactory createJsonParser.

Prototype

@Deprecated
public JsonParser createJsonParser(String content) throws IOException, JsonParseException 

Source Link

Document

Method for constructing parser for parsing contents of given String.

Usage

From source file:mobile.tiis.appv2.LoginActivity.java

/**
 * This method will take the url built to use the webservice
 * and will try to parse JSON from the webservice stream to get
 * the user and password if they are correct or not. In case correct, fills
 * the Android Account Manager.//from  w ww . j  ava 2 s.c  o  m
 *
 * <p>This method will throw a Toast message when user and password
 * are not valid
 *
 */

protected void startWebService(final CharSequence loginURL, final String username, final String password) {
    client.setBasicAuth(username, password, true);

    //new handler in case of login error in the thread
    handler = new Handler();

    Thread thread = new Thread(new Runnable() {
        public void run() {
            try {
                int balanceCounter = 0;
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpGet httpGet = new HttpGet(loginURL.toString());
                Utils.writeNetworkLogFileOnSD(
                        Utils.returnDeviceIdAndTimestamp(getApplicationContext()) + loginURL.toString());
                httpGet.setHeader("Authorization", "Basic "
                        + Base64.encodeToString((username + ":" + password).getBytes(), Base64.NO_WRAP));
                HttpResponse httpResponse = httpClient.execute(httpGet);
                InputStream inputStream = httpResponse.getEntity().getContent();
                Log.d("", loginURL.toString());

                ByteArrayInputStream bais = Utils.getMultiReadInputStream(inputStream);
                Utils.writeNetworkLogFileOnSD(Utils.returnDeviceIdAndTimestamp(getApplicationContext())
                        + Utils.getStringFromInputStreamAndLeaveStreamOpen(bais));
                bais.reset();
                JsonFactory factory = new JsonFactory();
                JsonParser jsonParser = factory.createJsonParser(bais);
                JsonToken token = jsonParser.nextToken();

                if (token == JsonToken.START_OBJECT) {
                    balanceCounter++;
                    boolean idNextToHfId = false;
                    while (!(balanceCounter == 0)) {
                        token = jsonParser.nextToken();

                        if (token == JsonToken.START_OBJECT) {
                            balanceCounter++;
                        } else if (token == JsonToken.END_OBJECT) {
                            balanceCounter--;
                        } else if (token == JsonToken.FIELD_NAME) {
                            String object = jsonParser.getCurrentName();
                            switch (object) {
                            case "HealthFacilityId":
                                token = jsonParser.nextToken();
                                app.setLoggedInUserHealthFacilityId(jsonParser.getText());
                                Log.d("", "healthFacilityId is: " + jsonParser.getText());
                                idNextToHfId = true;
                                break;
                            case "Firstname":
                                token = jsonParser.nextToken();
                                app.setLoggedInFirstname(jsonParser.getText());
                                Log.d("", "firstname is: " + jsonParser.getText());
                                break;
                            case "Lastname":
                                token = jsonParser.nextToken();
                                app.setLoggedInLastname(jsonParser.getText());
                                Log.d("", "lastname is: " + jsonParser.getText());
                                break;
                            case "Username":
                                token = jsonParser.nextToken();
                                app.setLoggedInUsername(jsonParser.getText());
                                Log.d("", "username is: " + jsonParser.getText());
                                break;
                            case "Lastlogin":
                                token = jsonParser.nextToken();
                                Log.d("", "lastlogin is: " + jsonParser.getText());
                                break;
                            case "Id":
                                if (idNextToHfId) {
                                    token = jsonParser.nextToken();
                                    app.setLoggedInUserId(jsonParser.getText());
                                    Log.d("", "Id is: " + jsonParser.getText());
                                }
                                break;
                            default:
                                break;
                            }
                        }
                    }

                    Account account = new Account(username, ACCOUNT_TYPE);
                    AccountManager accountManager = AccountManager.get(LoginActivity.this);
                    //                        boolean accountCreated = accountManager.addAccountExplicitly(account, LoginActivity.this.password, null);
                    boolean accountCreated = accountManager.addAccountExplicitly(account, password, null);

                    Bundle extras = LoginActivity.this.getIntent().getExtras();
                    if (extras != null) {
                        if (accountCreated) { //Pass the new account back to the account manager
                            AccountAuthenticatorResponse response = extras
                                    .getParcelable(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE);
                            Bundle res = new Bundle();
                            res.putString(AccountManager.KEY_ACCOUNT_NAME, username);
                            res.putString(AccountManager.KEY_ACCOUNT_TYPE, ACCOUNT_TYPE);
                            res.putString(AccountManager.KEY_PASSWORD, password);
                            response.onResult(res);
                        }
                    }

                    SharedPreferences prefs = PreferenceManager
                            .getDefaultSharedPreferences(getApplicationContext());
                    SharedPreferences.Editor editor = prefs.edit();
                    editor.putBoolean("secondSyncNeeded", true);
                    editor.commit();

                    ContentValues values = new ContentValues();
                    values.put(SQLHandler.SyncColumns.UPDATED, 1);
                    values.put(SQLHandler.UserColumns.FIRSTNAME, app.getLOGGED_IN_FIRSTNAME());
                    values.put(SQLHandler.UserColumns.LASTNAME, app.getLOGGED_IN_LASTNAME());
                    values.put(SQLHandler.UserColumns.HEALTH_FACILITY_ID, app.getLOGGED_IN_USER_HF_ID());
                    values.put(SQLHandler.UserColumns.ID, app.getLOGGED_IN_USER_ID());
                    values.put(SQLHandler.UserColumns.USERNAME, app.getLOGGED_IN_USERNAME());
                    values.put(SQLHandler.UserColumns.PASSWORD, password);
                    databaseHandler.addUser(values);

                    Log.d(TAG, "initiating offline for " + username + " password = " + password);
                    app.initializeOffline(username, password);

                    Intent intent;
                    if (prefs.getBoolean("synchronization_needed", true)) {
                        Log.d("supportLog", "call the loggin second time before the account was found");
                        intent = new Intent(LoginActivity.this, LotSettingsActivity.class);
                    } else {
                        Log.d("supportLog", "call the loggin second time before the account was found");
                        intent = new Intent(LoginActivity.this, LotSettingsActivity.class);
                        evaluateIfFirstLogin(app.getLOGGED_IN_USER_ID());
                    }
                    app.setUsername(username);

                    startActivity(intent);
                }
                //if login failed show error
                else {
                    handler.post(new Runnable() {
                        public void run() {
                            progressDialog.show();
                            progressDialog.dismiss();
                            toastMessage("Login failed.\nPlease check your details!");
                            loginButton.setEnabled(true);
                        }
                    });
                }
            } catch (Exception e) {
                handler.post(new Runnable() {
                    public void run() {
                        progressDialog.show();
                        progressDialog.dismiss();
                        toastMessage("Login failed Login failed.\n"
                                + "Please check your details or your web connectivity");
                        loginButton.setEnabled(true);

                    }
                });
                e.printStackTrace();
            }
        }
    });
    thread.start();

}

From source file:org.jmxtrans.embedded.output.CopperEggWriter.java

public String groupFind(String findName, String findIndex, Integer ExpectInt) throws Exception {
    JsonFactory f = new MappingJsonFactory();
    JsonParser jp = f.createJsonParser(findIndex);

    int count = 0;
    int foundit = 0;
    String Result = null;//  www  .  j  a va 2s. c om

    JsonToken current = jp.nextToken();
    if (current != JsonToken.START_ARRAY) {
        logger.warn("groupFind: Error: START_ARRAY expected, not found : quiting.");
        return (Result);
    }
    current = jp.nextToken();
    while (current != JsonToken.END_ARRAY) {
        if (current != JsonToken.START_OBJECT) {
            logger.warn("groupFind: Error: START_OBJECT expected, not found : quiting.");
            return (Result);
        }
        current = jp.nextToken();
        JsonNode node = jp.readValueAsTree();
        String tmpStr = node.get("name").asText().toString();
        if (findName.equals(node.get("name").asText().toString())) {
            if (ExpectInt != 0) {
                foundit = node.get("id").asInt();
                Result = String.valueOf(foundit);
            } else {
                Result = node.get("id").asText().toString();
            }
            break;
        }
        current = jp.nextToken();
        count = count + 1;
    }
    return (Result);
}

From source file:com.parworks.androidlibrary.ar.ARSites.java

private List<AugmentedData> getAugmentedImageGroupResult(final List<String> sites, String imageId) {
    Log.d("PARWORKS ANDROID LIBRARY", "getAugmentedImageGroupResult");
    Map<String, String> params = new HashMap<String, String>();
    params.put("imgId", imageId);
    HttpUtils httpUtils = new HttpUtils(mApiKey, mTime, mSignature);
    HttpResponse serverResponse = httpUtils.doGetWithSiteArray(
            HttpUtils.PARWORKS_API_BASE_URL + HttpUtils.AUGMENT_IMAGE_GROUP_RESULT_PATH, sites, params);
    HttpUtils.handleStatusCode(serverResponse.getStatusLine().getStatusCode());
    List<AugmentImageResultResponse> augmentedImageResults = new ArrayList<AugmentImageResultResponse>();
    try {//from  www  .j av  a 2  s . c  o  m
        JsonFactory f = new JsonFactory();
        JsonParser jp = f.createJsonParser(ARResponseUtils.convertHttpResponseToString(serverResponse));
        // advance stream to START_ARRAY first:
        jp.nextToken();
        // and then each time, advance to opening START_OBJECT
        while (jp.nextToken() == JsonToken.START_OBJECT) {
            Log.d(TAG, "Parsing json token");
            ARResponseHandler responseHandler = new ARResponseHandlerImpl();
            AugmentImageResultResponse augmentImageResult = responseHandler.handleResponse(jp,
                    AugmentImageResultResponse.class);
            augmentedImageResults.add(augmentImageResult);
        }
    } catch (Exception e) {
        throw new ARException("Failed to parse json.", e);
    }

    List<AugmentedData> allAugmentedData = new ArrayList<AugmentedData>();
    for (AugmentImageResultResponse response : augmentedImageResults) {
        allAugmentedData.add(convertAugmentResultResponse(imageId, response));
    }
    return allAugmentedData;
}

From source file:org.jmxtrans.embedded.output.CopperEggWriter.java

/**
 * read_config()/*from  w w w . ja  v  a2s.  co  m*/
 * The copperegg_config.json file contains a specification for the metric groups and dashboards to be created / or updated.
 * Mandatory
 */
public void read_config(InputStream in) throws Exception {

    JsonFactory f = new MappingJsonFactory();
    JsonParser jp = f.createJsonParser(in);

    JsonToken current;

    current = jp.nextToken();
    if (current != JsonToken.START_OBJECT) {
        logger.warn("read_config: Error:  START_OBJECT not found : quiting.");
        return;
    }
    current = jp.nextToken();
    String fieldName = jp.getCurrentName();
    current = jp.nextToken();
    if (fieldName.equals("config")) {
        if (current != JsonToken.START_OBJECT) {
            logger.warn("read_config: Error:  START_OBJECT not found after config : quiting.");
            return;
        }
        current = jp.nextToken();
        String fieldName2 = jp.getCurrentName();
        if (fieldName2.equals("metric_groups")) {
            current = jp.nextToken();
            if (current != JsonToken.START_ARRAY) {
                logger.warn("read_config: Error:  START_ARRAY not found after metric_groups : quiting.");
                return;
            }

            current = jp.nextToken();
            while (current != JsonToken.END_ARRAY) {
                if (current != JsonToken.START_OBJECT) {
                    logger.warn(
                            "read_config: Error:  START_OBJECT not found after metric_groups START_ARRAY : quiting.");
                    return;
                }
                current = jp.nextToken();
                JsonNode node1 = jp.readValueAsTree();
                String node1string = write_tostring(node1);
                metricgroupMap.put(node1.get("name").asText(), node1string);
                current = jp.nextToken();
            }

            current = jp.nextToken();
            String fieldName3 = jp.getCurrentName();

            if (fieldName3.equals("dashboards")) {
                current = jp.nextToken();
                if (current != JsonToken.START_ARRAY) {
                    logger.warn("read_config: Error:  START_ARRAY not found after dashboards : quiting.");
                    return;
                }
                current = jp.nextToken();
                while (current != JsonToken.END_ARRAY) {
                    if (current != JsonToken.START_OBJECT) {
                        logger.warn(
                                "read_config: Error:  START_OBJECT not found after dashboards START_ARRAY : quiting.");
                        return;
                    }
                    current = jp.nextToken();
                    JsonNode node = jp.readValueAsTree();
                    String nodestring = write_tostring(node);
                    dashMap.put(node.get("name").asText(), nodestring);
                    current = jp.nextToken();

                }
                if (jp.nextToken() != JsonToken.END_OBJECT) {
                    logger.warn("read_config: Error:  END_OBJECT expected, not found (1): quiting.");
                    return;
                }
                if (jp.nextToken() != JsonToken.END_OBJECT) {
                    logger.warn("read_config: Error:  END_OBJECT expected, not found (2): quiting.");
                    return;
                }
            } else {
                logger.warn("read_config: Error:  Expected dashboards : quiting.");
                return;
            }
        } else {
            logger.warn("read_config: Error:  Expected metric_groups : quiting.");
            return;
        }
    }
}

From source file:com.marklogic.client.functionaltest.BasicJavaClientREST.java

/**
 * Get the expected JSON document//from   w w  w .  j av a  2  s  .c o m
 * @param filename
 * @return
 * @throws JsonParseException
 * @throws IOException
 */
public JsonNode expectedJSONDocument(String filename) throws JsonParseException, IOException {
    // get json document for expected result
    ObjectMapper mapper = new ObjectMapper();
    JsonFactory jfactory = new JsonFactory();
    JsonParser jParser = jfactory
            .createJsonParser(new File("src/test/java/com/marklogic/client/functionaltest/data/" + filename));
    JsonNode expectedDoc = mapper.readTree(jParser);
    return expectedDoc;
}

From source file:com.marklogic.client.functionaltest.BasicJavaClientREST.java

/**
 * Get the expected JSON query option// w w  w . j  a v  a 2s . co m
 * @param filename
 * @return
 * @throws JsonParseException
 * @throws IOException
 */
public JsonNode expectedJSONQueryOption(String filename) throws JsonParseException, IOException {
    // get json document for expected result
    ObjectMapper mapper = new ObjectMapper();
    JsonFactory jfactory = new JsonFactory();
    JsonParser jParser = jfactory.createJsonParser(
            new File("src/test/java/com/marklogic/client/functionaltest/queryoptions/" + filename));
    JsonNode expectedDoc = mapper.readTree(jParser);
    return expectedDoc;
}