List of usage examples for com.fasterxml.jackson.core JsonToken END_OBJECT
JsonToken END_OBJECT
To view the source code for com.fasterxml.jackson.core JsonToken END_OBJECT.
Click Source Link
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.//ww w.j av a2s. co 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:com.github.shyiko.jackson.module.advice.AdvisedBeanDeserializer.java
protected Object deserializeWithExternalTypeId(JsonParser jp, DeserializationContext ctxt, Object bean) throws IOException { final Class<?> activeView = _needViewProcesing ? ctxt.getActiveView() : null; final ExternalTypeHandler ext = _externalTypeIdHandler.start(); beanDeserializerAdvice.before(bean, jp, ctxt); for (; jp.getCurrentToken() != JsonToken.END_OBJECT; jp.nextToken()) { String propName = jp.getCurrentName(); jp.nextToken();/*from ww w . java2 s.c om*/ if (beanDeserializerAdvice.intercept(bean, propName, jp, ctxt)) { continue; } SettableBeanProperty prop = _beanProperties.find(propName); if (prop != null) { // normal case // [JACKSON-831]: may have property AND be used as external type id: if (jp.getCurrentToken().isScalarValue()) { ext.handleTypePropertyValue(jp, ctxt, propName, bean); } if (activeView != null && !prop.visibleInView(activeView)) { jp.skipChildren(); continue; } try { prop.deserializeAndSet(jp, ctxt, bean); } catch (Exception e) { wrapAndThrow(e, bean, propName, ctxt); } continue; } // ignorable things should be ignored if (_ignorableProps != null && _ignorableProps.contains(propName)) { handleIgnoredProperty(jp, ctxt, bean, propName); continue; } // but others are likely to be part of external type id thingy... if (ext.handlePropertyValue(jp, ctxt, propName, bean)) { continue; } // if not, the usual fallback handling: if (_anySetter != null) { try { _anySetter.deserializeAndSet(jp, ctxt, bean, propName); } catch (Exception e) { wrapAndThrow(e, bean, propName, ctxt); } continue; } // Unknown: let's call handler method handleUnknownProperty(jp, ctxt, bean, propName); } // and when we get this far, let's try finalizing the deal: ext.complete(jp, ctxt, bean); beanDeserializerAdvice.after(bean, jp, ctxt); return bean; }
From source file:com.github.heuermh.personalgenome.client.converter.JacksonPersonalGenomeConverter.java
@Override public List<Carrier> parseCarriers(final InputStream inputStream) { checkNotNull(inputStream);// w ww . j a v a 2s . c o m JsonParser parser = null; try { parser = jsonFactory.createParser(inputStream); parser.nextToken(); String id = null; String reportId = null; String description = null; int mutations = 0; List<Carrier> carriers = new ArrayList<Carrier>(); while (parser.nextToken() != JsonToken.END_OBJECT) { String field = parser.getCurrentName(); parser.nextToken(); if ("id".equals(field)) { id = parser.getText(); } else if ("carriers".equals(field)) { while (parser.nextToken() != JsonToken.END_ARRAY) { while (parser.nextToken() != JsonToken.END_OBJECT) { String carrierField = parser.getCurrentName(); parser.nextToken(); if ("report_id".equals(carrierField)) { reportId = parser.getText(); } else if ("description".equals(carrierField)) { description = parser.getText(); } else if ("mutations".equals(carrierField)) { mutations = Integer.parseInt(parser.getText()); } } carriers.add(new Carrier(id, reportId, description, mutations)); reportId = null; description = null; mutations = 0; } } } return carriers; } catch (IOException e) { logger.warn("could not parse carriers", e); } finally { try { inputStream.close(); } catch (Exception e) { // ignored } try { parser.close(); } catch (Exception e) { // ignored } } return null; }
From source file:com.zenesis.qx.remote.RequestHandler.java
/** * Handles creating a server object to match one created on the client; expects className, * clientId, properties/* ww w .j a v a 2 s .co m*/ * @param jp * @throws ServletException * @throws IOException */ protected void cmdNewObject(JsonParser jp) throws ServletException, IOException { // Get the basics String className = getFieldValue(jp, "className", String.class); int clientId = getFieldValue(jp, "clientId", Integer.class); // Get the class Class<? extends Proxied> clazz; try { clazz = (Class<? extends Proxied>) Class.forName(className); } catch (ClassNotFoundException e) { throw new ServletException("Unknown class " + className); } ProxyType type = ProxyTypeManager.INSTANCE.getProxyType(clazz); // Create the instance Proxied proxied; try { proxied = type.newInstance(clazz); } catch (InstantiationException e) { throw new ServletException("Cannot create class " + className + ": " + e.getMessage(), e); } catch (InvocationTargetException e) { throw new ServletException("Cannot create class " + className + ": " + e.getMessage(), e); } catch (IllegalAccessException e) { throw new ServletException("Cannot create class " + className + ": " + e.getMessage(), e); } // Get the server ID int serverId = tracker.addClientObject(proxied); // Remember the client ID, in case there are subsequent commands which refer to it if (clientObjects == null) clientObjects = new HashMap<Integer, Proxied>(); clientObjects.put(clientId, proxied); // Tell the client about the new ID - do this before changing properties tracker.invalidateCache(proxied); tracker.getQueue().queueCommand(CommandId.CommandType.MAP_CLIENT_ID, proxied, null, new MapClientId(serverId, clientId)); // Set property values if (jp.nextToken() == JsonToken.FIELD_NAME) { if (jp.nextToken() != JsonToken.START_OBJECT) throw new ServletException("Unexpected properties definiton for 'new' command"); while (jp.nextToken() != JsonToken.END_OBJECT) { String propertyName = jp.getCurrentName(); jp.nextToken(); // Read a Proxied object? ProxyProperty prop = getProperty(type, propertyName); MetaClass propClass = prop.getPropertyClass(); Object value = null; if (propClass.isSubclassOf(Proxied.class)) { if (propClass.isArray() || propClass.isCollection()) { value = readArray(jp, propClass.getJavaType()); } else if (propClass.isMap()) { value = readMap(jp, propClass.getKeyClass(), propClass.getJavaType()); } else { Integer id = jp.readValueAs(Integer.class); if (id != null) value = getProxied(id); } } else { value = jp.readValueAs(Object.class); if (value != null && Enum.class.isAssignableFrom(propClass.getJavaType())) { String str = Helpers.camelCaseToEnum(value.toString()); value = Enum.valueOf(propClass.getJavaType(), str); } } setPropertyValue(type, proxied, propertyName, value); } } // Done jp.nextToken(); }
From source file:com.github.heuermh.personalgenome.client.converter.JacksonPersonalGenomeConverter.java
@Override public List<DrugResponse> parseDrugResponses(final InputStream inputStream) { checkNotNull(inputStream);//from w w w .j a v a 2 s . c o m JsonParser parser = null; try { parser = jsonFactory.createParser(inputStream); parser.nextToken(); String id = null; String reportId = null; String description = null; String status = null; List<DrugResponse> drugResponses = new ArrayList<DrugResponse>(); while (parser.nextToken() != JsonToken.END_OBJECT) { String field = parser.getCurrentName(); parser.nextToken(); if ("id".equals(field)) { id = parser.getText(); } else if ("drug_responses".equals(field)) { while (parser.nextToken() != JsonToken.END_ARRAY) { while (parser.nextToken() != JsonToken.END_OBJECT) { String drugResponseField = parser.getCurrentName(); parser.nextToken(); if ("report_id".equals(drugResponseField)) { reportId = parser.getText(); } else if ("description".equals(drugResponseField)) { description = parser.getText(); } else if ("status".equals(drugResponseField)) { status = parser.getText(); } } drugResponses.add(new DrugResponse(id, reportId, description, status)); reportId = null; description = null; status = null; } } } return drugResponses; } catch (IOException e) { logger.warn("could not parse drug responses", e); } finally { try { inputStream.close(); } catch (Exception e) { // ignored } try { parser.close(); } catch (Exception e) { // ignored } } return null; }
From source file:com.ntsync.shared.RawContact.java
private static RawOrganizationData readOrg(String rowId, JsonParser jp) throws IOException { String orgname = null;/* w w w . ja va 2s. c o m*/ OrganizationType orgtype = null; String orgLabel = null; String department = null; String jobTitle = null; String title = null; boolean isSuperPrimary = false; boolean isPrimary = false; while (jp.nextToken() != JsonToken.END_OBJECT) { String namefield = jp.getCurrentName(); // move to value if (jp.nextToken() == null) { throw new JsonParseException("Invalid JSON-Structure. End of Object missing.", jp.getCurrentLocation()); } if (ContactConstants.DATA.equals(namefield)) { orgname = jp.getValueAsString(); } else if (ContactConstants.TYPE.equals(namefield)) { orgtype = OrganizationType.fromVal(jp.getValueAsInt()); } else if (ContactConstants.PRIMARY.equals(namefield)) { isPrimary = jp.getValueAsBoolean(); } else if (ContactConstants.SUPERPRIMARY.equals(namefield)) { isSuperPrimary = jp.getValueAsBoolean(); } else if (ContactConstants.LABEL.equals(namefield)) { orgLabel = jp.getValueAsString(); } else if (ContactConstants.ORGANIZATION_DEPARTMENT.equals(namefield)) { department = jp.getValueAsString(); } else if (ContactConstants.ORGANIZATION_TITLE.equals(namefield)) { title = jp.getValueAsString(); } else if (ContactConstants.ORGANIZATION_JOB.equals(namefield)) { jobTitle = jp.getValueAsString(); } else { LOG.error("Unrecognized Organization-field for row with Id:" + rowId + " Fieldname:" + namefield); } } if (orgtype == null) { orgtype = OrganizationType.TYPE_OTHER; } return new RawOrganizationData(orgname, orgtype, orgLabel, isPrimary, isSuperPrimary, title, department, jobTitle); }
From source file:com.github.heuermh.personalgenome.client.converter.JacksonPersonalGenomeConverter.java
@Override public List<Trait> parseTraits(final InputStream inputStream) { checkNotNull(inputStream);/*from w w w .ja v a 2 s .c o m*/ JsonParser parser = null; try { parser = jsonFactory.createParser(inputStream); parser.nextToken(); String id = null; String reportId = null; String description = null; String trait = null; Set<String> possibleTraits = new HashSet<String>(); List<Trait> traits = new ArrayList<Trait>(); while (parser.nextToken() != JsonToken.END_OBJECT) { String field = parser.getCurrentName(); parser.nextToken(); if ("id".equals(field)) { id = parser.getText(); } else if ("traits".equals(field)) { while (parser.nextToken() != JsonToken.END_ARRAY) { while (parser.nextToken() != JsonToken.END_OBJECT) { String traitField = parser.getCurrentName(); parser.nextToken(); if ("report_id".equals(traitField)) { reportId = parser.getText(); } else if ("description".equals(traitField)) { description = parser.getText(); } else if ("trait".equals(traitField)) { trait = parser.getText(); } else if ("possible_traits".equals(traitField)) { while (parser.nextToken() != JsonToken.END_ARRAY) { possibleTraits.add(parser.getText()); } } } traits.add(new Trait(id, reportId, description, trait, possibleTraits)); reportId = null; description = null; trait = null; possibleTraits.clear(); } } } return traits; } catch (IOException e) { logger.warn("could not parse traits", e); } finally { try { inputStream.close(); } catch (Exception e) { // ignored } try { parser.close(); } catch (Exception e) { // ignored } } return null; }
From source file:com.cedarsoft.serialization.test.performance.XmlParserPerformance.java
private void benchParse(@Nonnull JsonFactory factory, @Nonnull String contentSample) throws XMLStreamException, IOException { for (int i = 0; i < BIG; i++) { JsonParser parser = factory.createParser(new StringReader(contentSample)); assertEquals(JsonToken.START_OBJECT, parser.nextToken()); assertEquals(JsonToken.FIELD_NAME, parser.nextToken()); assertEquals("dependent", parser.getCurrentName()); assertEquals(JsonToken.VALUE_FALSE, parser.nextToken()); boolean dependent = parser.getBooleanValue(); assertFalse(dependent);/*ww w . j av a 2 s.c o m*/ assertEquals(JsonToken.FIELD_NAME, parser.nextToken()); assertEquals("id", parser.getCurrentName()); assertEquals(JsonToken.VALUE_STRING, parser.nextToken()); String id = parser.getText(); assertEquals("Canon Raw", id); assertEquals(JsonToken.FIELD_NAME, parser.nextToken()); assertEquals("extension", parser.getCurrentName()); assertEquals(JsonToken.START_OBJECT, parser.nextToken()); assertEquals(JsonToken.FIELD_NAME, parser.nextToken()); assertEquals("isDefault", parser.getCurrentName()); assertEquals(JsonToken.VALUE_TRUE, parser.nextToken()); boolean isDefault = parser.getBooleanValue(); assertTrue(isDefault); assertEquals(JsonToken.FIELD_NAME, parser.nextToken()); assertEquals("delimiter", parser.getCurrentName()); assertEquals(JsonToken.VALUE_STRING, parser.nextToken()); String delimiter = parser.getText(); assertEquals(".", delimiter); assertEquals(JsonToken.FIELD_NAME, parser.nextToken()); assertEquals("extension", parser.getCurrentName()); assertEquals(JsonToken.VALUE_STRING, parser.nextToken()); String extension = parser.getText(); assertEquals("cr2", extension); assertEquals(JsonToken.END_OBJECT, parser.nextToken()); assertEquals(JsonToken.END_OBJECT, parser.nextToken()); assertNull(parser.nextToken()); parser.close(); FileType type = new FileType(id, new Extension(delimiter, extension, isDefault), dependent); assertNotNull(type); } }
From source file:com.ntsync.shared.RawContact.java
private static List<RawImData> readImList(String rowId, List<RawImData> imAddresses, JsonParser jp) throws IOException { List<RawImData> newImAddresses = imAddresses; while (jp.nextToken() != JsonToken.END_ARRAY) { ImType type = null;/*www.ja va 2 s. c om*/ ImProtocolType proType = null; String customProctocolName = null; String imAddress = null; String imTypeLabel = null; boolean isSuperPrimary = false; boolean isPrimary = false; while (jp.nextToken() != JsonToken.END_OBJECT) { String namefield = jp.getCurrentName(); // move to value if (jp.nextToken() == null) { throw new JsonParseException("Invalid JSON-Structure. End of Object missing.", jp.getCurrentLocation()); } if (ContactConstants.DATA.equals(namefield)) { imAddress = jp.getValueAsString(); } else if (ContactConstants.TYPE.equals(namefield)) { type = ImType.fromVal(jp.getValueAsInt()); } else if (ContactConstants.SUPERPRIMARY.equals(namefield)) { isSuperPrimary = jp.getValueAsBoolean(); } else if (ContactConstants.PRIMARY.equals(namefield)) { isPrimary = jp.getValueAsBoolean(); } else if (ContactConstants.LABEL.equals(namefield)) { imTypeLabel = jp.getValueAsString(); } else if (ContactConstants.PROTOCOL_TYPE.equals(namefield)) { proType = ImProtocolType.fromVal(jp.getValueAsInt()); } else if (ContactConstants.PROTOCOL_CUSTOM_PROT.equals(namefield)) { customProctocolName = jp.getValueAsString(); } else { LOG.error(JSON_FIELDNOTRECOGNIZED + rowId + " Fieldname:" + namefield); } } if (newImAddresses == null) { newImAddresses = new ArrayList<RawImData>(); } if (type == null) { type = ImType.TYPE_OTHER; } newImAddresses.add(new RawImData(imAddress, type, imTypeLabel, isPrimary, isSuperPrimary, proType, customProctocolName)); } return newImAddresses; }
From source file:com.adobe.communities.ugc.migration.importer.UGCImportHelper.java
protected static void getAttachments(final JsonParser jsonParser, final List attachments) throws IOException { JsonToken token = jsonParser.nextToken(); // skip START_ARRAY token String filename;//from ww w . j a v a2 s. c om String mimeType; InputStream inputStream; while (token.equals(JsonToken.START_OBJECT)) { filename = null; mimeType = null; inputStream = null; byte[] databytes = null; token = jsonParser.nextToken(); while (!token.equals(JsonToken.END_OBJECT)) { final String label = jsonParser.getCurrentName(); jsonParser.nextToken(); if (label.equals("filename")) { filename = URLDecoder.decode(jsonParser.getValueAsString(), "UTF-8"); } else if (label.equals("jcr:mimeType")) { mimeType = jsonParser.getValueAsString(); } else if (label.equals("jcr:data")) { databytes = Base64.decodeBase64(jsonParser.getValueAsString()); inputStream = new ByteArrayInputStream(databytes); } token = jsonParser.nextToken(); } if (filename != null && mimeType != null && inputStream != null) { attachments.add( new UGCImportHelper.AttachmentStruct(filename, inputStream, mimeType, databytes.length)); } else { // log an error LOG.error( "We expected to import an attachment, but information was missing and nothing was imported"); } token = jsonParser.nextToken(); } }