List of usage examples for com.fasterxml.jackson.core JsonParser getCurrentName
public abstract String getCurrentName() throws IOException, JsonParseException;
From source file:org.apache.cxf.cwiki.SiteExporter.java
private String renderPage(AbstractPage p) throws ParserConfigurationException, IOException { ContentResource content = getContentResource(); InputStream ins = content.getContentById(p.getId(), null, null, "body.export_view") .readEntity(InputStream.class); JsonParser parser = new JsonFactory().createParser(ins); JsonToken tok = parser.nextToken();/*w w w.j a v a 2s. c o m*/ boolean inExportView = false; while (tok != null) { if (tok == JsonToken.FIELD_NAME) { if (parser.getCurrentName().equals("export_view")) { inExportView = true; } } else if (tok == JsonToken.VALUE_STRING && inExportView && parser.getCurrentName().equals("value")) { return "<div id='ConfluenceContent'>" + parser.getText() + "</div>"; } tok = parser.nextToken(); } System.out.println("No text for page \"" + p.getTitle() + "\""); return ""; }
From source file:com.github.heuermh.personalgenome.client.converter.JacksonPersonalGenomeConverter.java
@Override public UserName parseNames(final InputStream inputStream) { checkNotNull(inputStream);/*from w w w .j a va2 s . c o m*/ JsonParser parser = null; try { parser = jsonFactory.createParser(inputStream); parser.nextToken(); String id = null; String firstName = null; String lastName = null; String profileId = null; String profileFirstName = null; String profileLastName = null; List<ProfileName> profileNames = new ArrayList<ProfileName>(); while (parser.nextToken() != JsonToken.END_OBJECT) { String field = parser.getCurrentName(); parser.nextToken(); if ("id".equals(field)) { id = parser.getText(); } else if ("first_name".equals(field)) { firstName = parser.getText(); } else if ("last_name".equals(field)) { lastName = parser.getText(); } else if ("profiles".equals(field)) { while (parser.nextToken() != JsonToken.END_ARRAY) { while (parser.nextToken() != JsonToken.END_OBJECT) { String profileNameField = parser.getCurrentName(); parser.nextToken(); if ("id".equals(profileNameField)) { profileId = parser.getText(); } else if ("first_name".equals(profileNameField)) { profileFirstName = parser.getText(); } else if ("last_name".equals(profileNameField)) { profileLastName = parser.getText(); } } profileNames.add(new ProfileName(profileId, profileFirstName, profileLastName)); } } } return new UserName(id, firstName, lastName, profileNames); } catch (IOException e) { logger.warn("could not parse names", e); } finally { try { inputStream.close(); } catch (Exception e) { // ignored } try { parser.close(); } catch (Exception e) { // ignored } } return null; }
From source file:org.messic.server.api.musicinfo.youtube.MusicInfoYoutubePlugin.java
private String search(Locale locale, String search) throws IOException { // http://ctrlq.org/code/19608-youtube-search-api // Based con code writted by Amit Agarwal // YouTube Data API base URL (JSON response) String surl = "v=2&alt=jsonc"; // set paid-content as false to hide movie rentals surl = surl + "&paid-content=false"; // set duration as long to filter partial uploads // url = url + "&duration=long"; // order search results by view count surl = surl + "&orderby=viewCount"; // we can request a maximum of 50 search results in a batch surl = surl + "&max-results=50"; surl = surl + "&q=" + search; URI uri = null;/*from ww w . j a v a 2 s .c o m*/ try { uri = new URI("http", "gdata.youtube.com", "/feeds/api/videos", surl, null); } catch (URISyntaxException e) { log.error("failed!", e); } URL url = new URL(uri.toASCIIString()); log.info(surl); Proxy proxy = getProxy(); URLConnection connection = (proxy != null ? url.openConnection(proxy) : url.openConnection()); InputStream is = connection.getInputStream(); JsonFactory jsonFactory = new JsonFactory(); // or, for data binding, // org.codehaus.jackson.mapper.MappingJsonFactory JsonParser jParser = jsonFactory.createParser(is); String htmlCode = "<script type=\"text/javascript\">"; htmlCode = htmlCode + " function musicInfoYoutubeDestroy(){"; htmlCode = htmlCode + " $('.messic-musicinfo-youtube-overlay').remove();"; htmlCode = htmlCode + " $('.messic-musicinfo-youtube-iframe').remove();"; htmlCode = htmlCode + " }"; htmlCode = htmlCode + " function musicInfoYoutubePlay(id){"; htmlCode = htmlCode + " var code='<div class=\"messic-musicinfo-youtube-overlay\" onclick=\"musicInfoYoutubeDestroy()\"></div>';"; htmlCode = htmlCode + " code=code+'<iframe class=\"messic-musicinfo-youtube-iframe\" src=\"http://www.youtube.com/embed/'+id+'\" frameborder=\"0\" allowfullscreen></iframe>';"; htmlCode = htmlCode + " $(code).hide().appendTo('body').fadeIn();"; htmlCode = htmlCode + " }"; htmlCode = htmlCode + "</script>"; // loop until token equal to "}" while (jParser.nextToken() != null) { String fieldname = jParser.getCurrentName(); if ("items".equals(fieldname)) { jParser.nextToken(); while (jParser.nextToken() != JsonToken.END_OBJECT) { YoutubeItem yi = new YoutubeItem(); while (jParser.nextToken() != JsonToken.END_OBJECT) { if (jParser.getCurrentToken() == JsonToken.START_OBJECT) { jParser.skipChildren(); } fieldname = jParser.getCurrentName(); if ("id".equals(fieldname)) { jParser.nextToken(); yi.id = jParser.getText(); } if ("category".equals(fieldname)) { jParser.nextToken(); yi.category = jParser.getText(); } if ("title".equals(fieldname)) { jParser.nextToken(); yi.title = jParser.getText(); } if ("description".equals(fieldname)) { jParser.nextToken(); yi.description = jParser.getText(); } if ("thumbnail".equals(fieldname)) { jParser.nextToken(); jParser.nextToken(); jParser.nextToken(); jParser.nextToken(); fieldname = jParser.getCurrentName(); if ("hqDefault".equals(fieldname)) { jParser.nextToken(); yi.thumbnail = jParser.getText(); } jParser.nextToken(); } } if (yi.category != null && "MUSIC".equals(yi.category.toUpperCase()) || (yi.category == null)) { if (yi.title != null) { htmlCode = htmlCode + "<div class=\"messic-musicinfo-youtube-item\"><img src=\"" + yi.thumbnail + "\"/><div class=\"messic-musicinfo-youtube-item-play\" onclick=\"musicInfoYoutubePlay('" + yi.id + "')\"></div>" + "<div class=\"messic-musicinfo-youtube-description\">" + " <div class=\"messic-musicinfo-youtube-item-title\">" + yi.title + "</div>" + " <div class=\"messic-musicinfo-youtube-item-description\">" + yi.description + "</div>" + "</div>" + "</div>"; } } } } } return htmlCode; }
From source file:com.adobe.communities.ugc.migration.importer.UGCImportHelper.java
protected void extractTopic(final JsonParser jsonParser, final Resource resource, final ResourceResolver resolver, final CommentOperations operations) throws IOException, ServletException { if (jsonParser.getCurrentToken().equals(JsonToken.END_OBJECT)) { return; // replies could just be an empty object (i.e. "ugc:replies":{} ) in which case, do nothing }// w w w . j a va 2 s .c o m final Map<String, Object> properties = new HashMap<String, Object>(); properties.put("social:key", jsonParser.getCurrentName()); Resource post = null; jsonParser.nextToken(); if (jsonParser.getCurrentToken().equals(JsonToken.START_OBJECT)) { jsonParser.nextToken(); String author = null; List<DataSource> attachments = new ArrayList<DataSource>(); while (!jsonParser.getCurrentToken().equals(JsonToken.END_OBJECT)) { final String label = jsonParser.getCurrentName(); JsonToken token = jsonParser.nextToken(); if (jsonParser.getCurrentToken().isScalarValue()) { // either a string, boolean, or long value if (token.isNumeric()) { properties.put(label, jsonParser.getValueAsLong()); } else { final String value = jsonParser.getValueAsString(); if (value.equals("true") || value.equals("false")) { properties.put(label, jsonParser.getValueAsBoolean()); } else { final String decodedValue = URLDecoder.decode(value, "UTF-8"); if (label.equals("language")) { properties.put("mtlanguage", decodedValue); } else { properties.put(label, decodedValue); if (label.equals("userIdentifier")) { author = decodedValue; } else if (label.equals("jcr:description")) { properties.put("message", decodedValue); } } } } } else if (label.equals(ContentTypeDefinitions.LABEL_ATTACHMENTS)) { attachments = getAttachments(jsonParser); } else if (label.equals(ContentTypeDefinitions.LABEL_REPLIES) || label.equals(ContentTypeDefinitions.LABEL_TALLY) || label.equals(ContentTypeDefinitions.LABEL_TRANSLATION) || label.equals(ContentTypeDefinitions.LABEL_SUBNODES)) { // replies and sub-nodes ALWAYS come after all other properties and attachments have been listed, // so we can create the post now if we haven't already, and then dive in if (post == null) { try { post = createPost(resource, author, properties, attachments, resolver.adaptTo(Session.class), operations); resProvider = SocialResourceUtils.getSocialResource(post).getResourceProvider(); } catch (Exception e) { throw new ServletException(e.getMessage(), e); } } if (label.equals(ContentTypeDefinitions.LABEL_REPLIES)) { if (token.equals(JsonToken.START_OBJECT)) { jsonParser.nextToken(); while (!token.equals(JsonToken.END_OBJECT)) { extractTopic(jsonParser, post, resolver, operations); token = jsonParser.nextToken(); } } else { throw new IOException("Expected an object for the subnodes"); } } else if (label.equals(ContentTypeDefinitions.LABEL_SUBNODES)) { if (token.equals(JsonToken.START_OBJECT)) { token = jsonParser.nextToken(); try { while (!token.equals(JsonToken.END_OBJECT)) { final String subnodeType = jsonParser.getCurrentName(); token = jsonParser.nextToken(); if (token.equals(JsonToken.START_OBJECT)) { jsonParser.skipChildren(); token = jsonParser.nextToken(); } } } catch (final IOException e) { throw new IOException("unable to skip child of sub-nodes", e); } } else { final String field = jsonParser.getValueAsString(); throw new IOException("Expected an object for the subnodes. Instead: " + field); } } else if (label.equals(ContentTypeDefinitions.LABEL_TALLY)) { UGCImportHelper.extractTally(post, jsonParser, resProvider, tallyOperationsService); } else if (label.equals(ContentTypeDefinitions.LABEL_TRANSLATION)) { importTranslation(jsonParser, post); resProvider.commit(post.getResourceResolver()); } } else if (jsonParser.getCurrentToken().equals(JsonToken.START_OBJECT)) { properties.put(label, UGCImportHelper.extractSubmap(jsonParser)); } else if (jsonParser.getCurrentToken().equals(JsonToken.START_ARRAY)) { jsonParser.nextToken(); // skip the START_ARRAY token if (label.equals(ContentTypeDefinitions.LABEL_TIMESTAMP_FIELDS)) { while (!jsonParser.getCurrentToken().equals(JsonToken.END_ARRAY)) { final String timestampLabel = jsonParser.getValueAsString(); if (properties.containsKey(timestampLabel) && properties.get(timestampLabel) instanceof Long) { final Calendar calendar = new GregorianCalendar(); calendar.setTimeInMillis((Long) properties.get(timestampLabel)); properties.put(timestampLabel, calendar.getTime()); } jsonParser.nextToken(); } } else { final List<String> subArray = new ArrayList<String>(); while (!jsonParser.getCurrentToken().equals(JsonToken.END_ARRAY)) { subArray.add(jsonParser.getValueAsString()); jsonParser.nextToken(); } String[] strings = new String[subArray.size()]; for (int i = 0; i < subArray.size(); i++) { strings[i] = subArray.get(i); } properties.put(label, strings); } } jsonParser.nextToken(); } if (post == null) { try { post = createPost(resource, author, properties, attachments, resolver.adaptTo(Session.class), operations); if (null == resProvider) { resProvider = SocialResourceUtils.getSocialResource(post).getResourceProvider(); } // resProvider.commit(resolver); } catch (Exception e) { throw new ServletException(e.getMessage(), e); } } } else { throw new IOException("Improperly formed JSON - expected an OBJECT_START token, but got " + jsonParser.getCurrentToken().toString()); } }
From source file:org.seedstack.seed.core.internal.data.DataManagerImpl.java
@Override public void importData(InputStream inputStream, String acceptGroup, String acceptName, boolean clear) { Set<DataImporter<Object>> usedDataImporters = new HashSet<>(); try {/* w w w . j ava 2s .com*/ ParsingState state = ParsingState.START; String group = null; String name = null; JsonParser jsonParser = this.jsonFactory .createParser(new InputStreamReader(inputStream, Charset.forName(UTF_8))); JsonToken jsonToken = jsonParser.nextToken(); while (jsonToken != null) { switch (state) { case START: if (jsonToken == JsonToken.START_ARRAY) { state = ParsingState.DEFINITION_START; } else { throwParsingError(jsonParser.getCurrentLocation(), "start array expected"); } break; case DEFINITION_START: if (jsonToken == JsonToken.START_OBJECT) { state = ParsingState.DEFINITION_GROUP; } else { throwParsingError(jsonParser.getCurrentLocation(), "start object expected"); } break; case DEFINITION_GROUP: if (jsonToken == JsonToken.FIELD_NAME && GROUP.equals(jsonParser.getCurrentName())) { group = jsonParser.nextTextValue(); state = ParsingState.DEFINITION_NAME; } else { throwParsingError(jsonParser.getCurrentLocation(), "group field expected"); } break; case DEFINITION_NAME: if (jsonToken == JsonToken.FIELD_NAME && NAME.equals(jsonParser.getCurrentName())) { name = jsonParser.nextTextValue(); state = ParsingState.DEFINITION_ITEMS; } else { throwParsingError(jsonParser.getCurrentLocation(), "name field expected"); } break; case DEFINITION_ITEMS: if (jsonToken == JsonToken.FIELD_NAME && ITEMS.equals(jsonParser.getCurrentName())) { usedDataImporters.add(consumeItems(jsonParser, group, name, acceptGroup, acceptName)); state = ParsingState.DEFINITION_END; } else { throwParsingError(jsonParser.getCurrentLocation(), "items field expected"); } break; case DEFINITION_END: if (jsonToken == JsonToken.END_OBJECT) { group = null; name = null; state = ParsingState.END; } else { throwParsingError(jsonParser.getCurrentLocation(), "end object expected"); } break; case END: if (jsonToken == JsonToken.START_OBJECT) { state = ParsingState.DEFINITION_GROUP; } else if (jsonToken == JsonToken.END_ARRAY) { state = ParsingState.START; } else { throwParsingError(jsonParser.getCurrentLocation(), "start object or end array expected"); } break; default: throwParsingError(jsonParser.getCurrentLocation(), "unexpected parser state"); } jsonToken = jsonParser.nextToken(); } } catch (Exception e1) { for (DataImporter<Object> usedDataImporter : usedDataImporters) { try { usedDataImporter.rollback(); } catch (Exception e2) { e2.initCause(e1); throw SeedException.wrap(e2, DataErrorCode.FAILED_TO_ROLLBACK_IMPORT).put(IMPORTER_CLASS, usedDataImporter.getClass().getName()); } } throw SeedException.wrap(e1, DataErrorCode.IMPORT_FAILED); } for (DataImporter<Object> usedDataImporter : usedDataImporters) { try { usedDataImporter.commit(clear); } catch (Exception e) { throw SeedException.wrap(e, DataErrorCode.FAILED_TO_COMMIT_IMPORT).put(IMPORTER_CLASS, usedDataImporter.getClass().getName()); } } }
From source file:pl.selvin.android.syncframework.content.BaseContentProvider.java
protected boolean Sync(String service, String scope, String params) { final Date start = new Date(); boolean hasError = false; if (params == null) params = ""; final SQLiteDatabase db = mDB.getWritableDatabase(); final ArrayList<TableInfo> notifyTableInfo = new ArrayList<TableInfo>(); final String download = String.format(contentHelper.DOWNLOAD_SERVICE_URI, service, scope, params); final String upload = String.format(contentHelper.UPLOAD_SERVICE_URI, service, scope, params); final String scopeServerBlob = String.format("%s.%s.%s", service, scope, _.serverBlob); String serverBlob = null;//from w ww . j a v a2 s .c om Cursor cur = db.query(BlobsTable.NAME, new String[] { BlobsTable.C_VALUE }, BlobsTable.C_NAME + "=?", new String[] { scopeServerBlob }, null, null, null); final String originalBlob; if (cur.moveToFirst()) { originalBlob = serverBlob = cur.getString(0); } else { originalBlob = null; } cur.close(); db.beginTransaction(); try { boolean nochanges = false; if (serverBlob != null) { nochanges = !contentHelper.hasDirtTable(db, scope); } boolean resolve = false; final Metadata meta = new Metadata(); final HashMap<String, Object> vals = new HashMap<String, Object>(); final ContentValues cv = new ContentValues(2); JsonFactory jsonFactory = new JsonFactory(); JsonToken current = null; String name = null; boolean moreChanges = false; boolean forceMoreChanges = false; do { final int requestMethod; final String serviceRequestUrl; final ContentProducer contentProducer; if (serverBlob != null) { requestMethod = HTTP_POST; if (nochanges) { serviceRequestUrl = download; } else { serviceRequestUrl = upload; forceMoreChanges = true; } contentProducer = new SyncContentProducer(jsonFactory, db, scope, serverBlob, !nochanges, notifyTableInfo, contentHelper); nochanges = true; } else { requestMethod = HTTP_GET; serviceRequestUrl = download; contentProducer = null; } if (moreChanges) { db.beginTransaction(); } Result result = executeRequest(requestMethod, serviceRequestUrl, contentProducer); if (result.getStatus() == HttpStatus.SC_OK) { final JsonParser jp = jsonFactory.createParser(result.getInputStream()); jp.nextToken(); // skip ("START_OBJECT(d) expected"); jp.nextToken(); // skip ("FIELD_NAME(d) expected"); if (jp.nextToken() != JsonToken.START_OBJECT) throw new Exception("START_OBJECT(d - object) expected"); while (jp.nextToken() != JsonToken.END_OBJECT) { name = jp.getCurrentName(); if (_.__sync.equals(name)) { current = jp.nextToken(); while (jp.nextToken() != JsonToken.END_OBJECT) { name = jp.getCurrentName(); current = jp.nextToken(); if (_.serverBlob.equals(name)) { serverBlob = jp.getText(); } else if (_.moreChangesAvailable.equals(name)) { moreChanges = jp.getBooleanValue() || forceMoreChanges; forceMoreChanges = false; } else if (_.resolveConflicts.equals(name)) { resolve = jp.getBooleanValue(); } } } else if (_.results.equals(name)) { if (jp.nextToken() != JsonToken.START_ARRAY) throw new Exception("START_ARRAY(results) expected"); while (jp.nextToken() != JsonToken.END_ARRAY) { meta.isDeleted = false; meta.tempId = null; vals.clear(); while (jp.nextToken() != JsonToken.END_OBJECT) { name = jp.getCurrentName(); current = jp.nextToken(); if (current == JsonToken.VALUE_STRING) { vals.put(name, jp.getText()); } else if (current == JsonToken.VALUE_NUMBER_INT) { vals.put(name, jp.getLongValue()); } else if (current == JsonToken.VALUE_NUMBER_FLOAT) { vals.put(name, jp.getDoubleValue()); } else if (current == JsonToken.VALUE_FALSE) { vals.put(name, 0L); } else if (current == JsonToken.VALUE_TRUE) { vals.put(name, 1L); } else if (current == JsonToken.VALUE_NULL) { vals.put(name, null); } else { if (current == JsonToken.START_OBJECT) { if (_.__metadata.equals(name)) { while (jp.nextToken() != JsonToken.END_OBJECT) { name = jp.getCurrentName(); jp.nextToken(); if (_.uri.equals(name)) { meta.uri = jp.getText(); } else if (_.type.equals(name)) { meta.type = jp.getText(); } else if (_.isDeleted.equals(name)) { meta.isDeleted = jp.getBooleanValue(); } else if (_.tempId.equals(name)) { meta.tempId = jp.getText(); } } } else if (_.__syncConflict.equals(name)) { while (jp.nextToken() != JsonToken.END_OBJECT) { name = jp.getCurrentName(); jp.nextToken(); if (_.isResolved.equals(name)) { } else if (_.conflictResolution.equals(name)) { } else if (_.conflictingChange.equals(name)) { while (jp.nextToken() != JsonToken.END_OBJECT) { name = jp.getCurrentName(); current = jp.nextToken(); if (current == JsonToken.START_OBJECT) { if (_.__metadata.equals(name)) { while (jp.nextToken() != JsonToken.END_OBJECT) { } } } } } } // resolve conf } else if (_.__syncError.equals(name)) { while (jp.nextToken() != JsonToken.END_OBJECT) { name = jp.getCurrentName(); jp.nextToken(); } } } } } TableInfo tab = contentHelper.getTableFromType(meta.type); if (meta.isDeleted) { tab.DeleteWithUri(meta.uri, db); } else { tab.SyncJSON(vals, meta, db); } if (!notifyTableInfo.contains(tab)) notifyTableInfo.add(tab); } } } jp.close(); if (!hasError) { cv.clear(); cv.put(BlobsTable.C_NAME, scopeServerBlob); cv.put(BlobsTable.C_VALUE, serverBlob); cv.put(BlobsTable.C_DATE, Calendar.getInstance().getTimeInMillis()); cv.put(BlobsTable.C_STATE, 0); db.replace(BlobsTable.NAME, null, cv); db.setTransactionSuccessful(); db.endTransaction(); if (DEBUG) { Log.d(TAG, "CP-Sync: commit changes"); } final ContentResolver cr = getContext().getContentResolver(); for (TableInfo t : notifyTableInfo) { final Uri nu = contentHelper.getDirUri(t.name, false); cr.notifyChange(nu, null, false); // false - do not force sync cause we are in sync if (DEBUG) { Log.d(TAG, "CP-Sync: notifyChange table: " + t.name + ", uri: " + nu); } for (String n : t.notifyUris) { cr.notifyChange(Uri.parse(n), null, false); if (DEBUG) { Log.d(TAG, "+uri: " + n); } } } notifyTableInfo.clear(); } } else { if (DEBUG) { Log.e(TAG, "Server error in fetching remote contacts: " + result.getStatus()); } hasError = true; break; } } while (moreChanges); } catch (final ConnectTimeoutException e) { hasError = true; if (DEBUG) { Log.e(TAG, "ConnectTimeoutException", e); } } catch (final IOException e) { hasError = true; if (DEBUG) { Log.e(TAG, Log.getStackTraceString(e)); } } catch (final ParseException e) { hasError = true; if (DEBUG) { Log.e(TAG, "ParseException", e); } } catch (final Exception e) { hasError = true; if (DEBUG) { Log.e(TAG, "ParseException", e); } } if (hasError) { db.endTransaction(); ContentValues cv = new ContentValues(); cv.put(BlobsTable.C_NAME, scopeServerBlob); cv.put(BlobsTable.C_VALUE, originalBlob); cv.put(BlobsTable.C_DATE, Calendar.getInstance().getTimeInMillis()); cv.put(BlobsTable.C_STATE, -1); db.replace(BlobsTable.NAME, null, cv); } /*-if (!hasError) { final ContentValues cv = new ContentValues(2); cv.put(BlobsTable.C_NAME, scopeServerBlob); cv.put(BlobsTable.C_VALUE, serverBlob); db.replace(BlobsTable.NAME, null, cv); db.setTransactionSuccessful(); } db.endTransaction(); if (!hasError) { for (String t : notifyTableInfo) { getContext().getContentResolver().notifyChange(getDirUri(t), null); } }*/ if (DEBUG) { Helpers.LogInfo(start); } return !hasError; }
From source file:org.mongojack.internal.DBRefDeserializer.java
@Override public DBRef deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { // First of all, make sure that we can get a copy of the DBCollection if (jp instanceof JacksonDBCollectionProvider) { K id = null;/* w w w . j av a2 s.c o m*/ String collectionName = null; JsonToken token = jp.getCurrentToken(); if (token == JsonToken.VALUE_NULL) { return null; } if (token == JsonToken.VALUE_EMBEDDED_OBJECT) { // Someones already kindly decoded it for us Object object = jp.getEmbeddedObject(); if (object instanceof com.mongodb.DBRef) { if (keyDeserializer != null) { id = keyDeserializer.deserialize(jp, ctxt); } else { id = (K) ((com.mongodb.DBRef) object).getId(); } collectionName = ((com.mongodb.DBRef) object).getRef(); } else { throw ctxt.instantiationException(DBRef.class, "Don't know what to do with embedded object: " + object); } } else if (token == JsonToken.START_OBJECT) { token = jp.nextValue(); while (token != JsonToken.END_OBJECT) { if (jp.getCurrentName().equals("$id")) { if (keyDeserializer != null) { id = keyDeserializer.deserialize(jp, ctxt); } else { id = (K) jp.getEmbeddedObject(); } } else if (jp.getCurrentName().equals("$ref")) { collectionName = jp.getText(); } else { // Ignore the rest } token = jp.nextValue(); } } if (id == null) { return null; } if (collectionName == null) { throw ctxt.instantiationException(DBRef.class, "DBRef contains no collection name"); } JacksonDBCollection coll = ((JacksonDBCollectionProvider) jp).getDBCollection(); JacksonDBCollection<T, K> refColl = coll.getReferenceCollection(collectionName, type, keyType); return new FetchableDBRef<T, K>(id, refColl); } else { throw ctxt.instantiationException(DBRef.class, "DBRef can only be deserialised by this deserializer if parser implements " + JacksonDBCollectionProvider.class.getName() + " parser is actually " + jp.getClass().getName()); } }
From source file:org.commonjava.maven.atlas.graph.jackson.ProjectRelationshipDeserializer.java
@Override public T deserialize(final JsonParser jp, final DeserializationContext ctx) throws JsonProcessingException, IOException { Map<String, Object> ast = new HashMap<String, Object>(); Map<String, JsonLocation> locations = new HashMap<String, JsonLocation>(); JsonToken token = jp.getCurrentToken(); String currentField = null;/*from w w w.j av a 2s. c o m*/ List<String> currentArry = null; Logger logger = LoggerFactory.getLogger(getClass()); do { // logger.info( "Token: {}", token ); switch (token) { case START_ARRAY: { // logger.info( "Starting array for field: {}", currentField ); currentArry = new ArrayList<String>(); break; } case END_ARRAY: // logger.info( "Ending array for field: {}", currentField ); locations.put(currentField, jp.getCurrentLocation()); ast.put(currentField, currentArry); currentArry = null; break; case FIELD_NAME: currentField = jp.getCurrentName(); break; case VALUE_STRING: if (currentArry != null) { currentArry.add(jp.getText()); } else { locations.put(currentField, jp.getCurrentLocation()); ast.put(currentField, jp.getText()); } break; case VALUE_NUMBER_INT: locations.put(currentField, jp.getCurrentLocation()); ast.put(currentField, jp.getIntValue()); break; case VALUE_NUMBER_FLOAT: locations.put(currentField, jp.getCurrentLocation()); ast.put(currentField, jp.getFloatValue()); break; case VALUE_TRUE: locations.put(currentField, jp.getCurrentLocation()); ast.put(currentField, Boolean.TRUE); break; case VALUE_FALSE: locations.put(currentField, jp.getCurrentLocation()); ast.put(currentField, Boolean.FALSE); break; } token = jp.nextToken(); } while (token != JsonToken.END_OBJECT); StringBuilder sb = new StringBuilder(); sb.append("AST is:"); for (String field : ast.keySet()) { Object value = ast.get(field); sb.append("\n ").append(field).append(" = "); if (value == null) { sb.append("null"); } else { sb.append(value).append(" (type: ").append(value.getClass().getSimpleName()).append(")"); } } logger.debug(sb.toString()); final RelationshipType type = RelationshipType.getType((String) ast.get(RELATIONSHIP_TYPE)); final String uri = (String) ast.get(POM_LOCATION_URI); URI pomLocation; if (uri == null) { pomLocation = RelationshipUtils.POM_ROOT_URI; } else { try { pomLocation = new URI(uri); } catch (final URISyntaxException e) { throw new JsonParseException("Invalid " + POM_LOCATION_URI + ": '" + uri + "': " + e.getMessage(), locations.get(POM_LOCATION_URI), e); } } Collection<URI> sources = new HashSet<URI>(); List<String> srcs = (List<String>) ast.get(SOURCE_URIS); if (srcs != null) { for (String u : srcs) { try { sources.add(new URI(u)); } catch (URISyntaxException e) { throw new JsonParseException("Failed to parse source URI: " + u, locations.get(SOURCE_URIS)); } } } String decl = (String) ast.get(DECLARING_REF); final ProjectVersionRef declaring = SimpleProjectVersionRef.parse(decl); String tgt = (String) ast.get(TARGET_REF); Integer index = (Integer) ast.get(INDEX); if (index == null) { index = 0; } // handle null implicitly by comparing to true. boolean managed = Boolean.TRUE.equals(ast.get(MANAGED)); boolean inherited = Boolean.TRUE.equals(ast.get(INHERITED)); boolean mixin = Boolean.TRUE.equals(ast.get(MIXIN)); boolean optional = Boolean.TRUE.equals(ast.get(OPTIONAL)); ProjectRelationship<?, ?> rel = null; switch (type) { case DEPENDENCY: { final ArtifactRef target = SimpleArtifactRef.parse(tgt); String scp = (String) ast.get(SCOPE); final DependencyScope scope; if (scp == null) { scope = DependencyScope.compile; } else { scope = DependencyScope.getScope(scp); } rel = new SimpleDependencyRelationship(sources, pomLocation, declaring, target, scope, index, managed, inherited, optional); break; } case EXTENSION: { final ProjectVersionRef target = SimpleProjectVersionRef.parse(tgt); rel = new SimpleExtensionRelationship(sources, pomLocation, declaring, target, index, inherited); break; } case PARENT: { final ProjectVersionRef target = SimpleProjectVersionRef.parse(tgt); rel = new SimpleParentRelationship(sources, declaring, target); break; } case PLUGIN: { final ProjectVersionRef target = SimpleProjectVersionRef.parse(tgt); Boolean report = (Boolean) ast.get(REPORTING); rel = new SimplePluginRelationship(sources, pomLocation, declaring, target, index, managed, Boolean.TRUE.equals(report), inherited); break; } case PLUGIN_DEP: { String plug = (String) ast.get(PLUGIN_REF); if (plug == null) { throw new JsonParseException( "No plugin reference (field: " + PLUGIN_REF + ") found in plugin-dependency relationship!", jp.getCurrentLocation()); } final ProjectRef plugin = SimpleProjectRef.parse(plug); final ArtifactRef target = SimpleArtifactRef.parse(tgt); rel = new SimplePluginDependencyRelationship(sources, pomLocation, declaring, plugin, target, index, managed, inherited); break; } case BOM: { final ProjectVersionRef target = SimpleProjectVersionRef.parse(tgt); rel = new SimpleBomRelationship(sources, pomLocation, declaring, target, index, inherited, mixin); break; } } return (T) rel; }
From source file:com.microsoft.windowsazure.storage.table.TableParser.java
/** * Reserved for internal use. Parses the operation response as a collection of entities. Reads entity data from the * specified input stream using the specified class type and optionally projects each entity result with the * specified resolver into an {@link ODataPayload} containing a collection of {@link TableResult} objects. * /*from w w w . j a v a 2 s .co m*/ * @param inStream * The <code>InputStream</code> to read the data to parse from. * @param clazzType * The class type <code>T</code> implementing {@link TableEntity} for the entities returned. Set to * <code>null</code> to ignore the returned entities and copy only response properties into the * {@link TableResult} objects. * @param resolver * An {@link EntityResolver} instance to project the entities into instances of type <code>R</code>. Set * to <code>null</code> to return the entities as instances of the class type <code>T</code>. * @param opContext * An {@link OperationContext} object used to track the execution of the operation. * @return * An {@link ODataPayload} containing a collection of {@link TableResult} objects with the parsed operation * response. * @throws ParseException * if an error occurs while parsing the stream. * @throws InstantiationException * if an error occurs while constructing the result. * @throws IllegalAccessException * if an error occurs in reflection while parsing the result. * @throws StorageException * if a storage service error occurs. * @throws IOException * if an error occurs while accessing the stream. * @throws JsonParseException * if an error occurs while parsing the stream. */ @SuppressWarnings("unchecked") private static <T extends TableEntity, R> ODataPayload<?> parseJsonQueryResponse(final InputStream inStream, final Class<T> clazzType, final EntityResolver<R> resolver, final TableRequestOptions options, final OperationContext opContext) throws ParseException, InstantiationException, IllegalAccessException, StorageException, JsonParseException, IOException { ODataPayload<T> corePayload = null; ODataPayload<R> resolvedPayload = null; ODataPayload<?> commonPayload = null; JsonParser parser = createJsonParserFromStream(inStream); try { if (resolver != null) { resolvedPayload = new ODataPayload<R>(); commonPayload = resolvedPayload; } else { corePayload = new ODataPayload<T>(); commonPayload = corePayload; } if (!parser.hasCurrentToken()) { parser.nextToken(); } ODataUtilities.assertIsStartObjectJsonToken(parser); // move into data parser.nextToken(); // if there is a clazz type and if JsonNoMetadata, create a classProperties dictionary to use for type inference once // instead of querying the cache many times HashMap<String, PropertyPair> classProperties = null; if (options.getTablePayloadFormat() == TablePayloadFormat.JsonNoMetadata && clazzType != null) { classProperties = PropertyPair.generatePropertyPairs(clazzType); } while (parser.getCurrentToken() != null) { if (parser.getCurrentToken() == JsonToken.FIELD_NAME && parser.getCurrentName().equals(ODataConstants.VALUE)) { // move to start of array parser.nextToken(); ODataUtilities.assertIsStartArrayJsonToken(parser); // go to properties parser.nextToken(); while (parser.getCurrentToken() == JsonToken.START_OBJECT) { final TableResult res = parseJsonEntity(parser, clazzType, classProperties, resolver, options, opContext); if (corePayload != null) { corePayload.tableResults.add(res); } if (resolver != null) { resolvedPayload.results.add((R) res.getResult()); } else { corePayload.results.add((T) res.getResult()); } parser.nextToken(); } ODataUtilities.assertIsEndArrayJsonToken(parser); } parser.nextToken(); } } finally { parser.close(); } return commonPayload; }
From source file:com.github.heuermh.personalgenome.client.converter.JacksonPersonalGenomeConverter.java
@Override public List<Relative> parseRelatives(final InputStream inputStream) { checkNotNull(inputStream);/*from w w w. j ava 2s . co m*/ JsonParser parser = null; try { parser = jsonFactory.createParser(inputStream); parser.nextToken(); List<Relative> relatives = new ArrayList<Relative>(); String profileId = null; String matchId = null; double similarity = 0.0d; int sharedSegments = 0; Relationship relationship = null; Relationship userRelationship = null; Set<Relationship> range = new HashSet<Relationship>(); while (parser.nextToken() != JsonToken.END_OBJECT) { String field = parser.getCurrentName(); parser.nextToken(); if ("id".equals(field)) { profileId = parser.getText(); } else if ("relatives".equals(field)) { while (parser.nextToken() != JsonToken.END_ARRAY) { while (parser.nextToken() != JsonToken.END_OBJECT) { String relativeField = parser.getCurrentName(); parser.nextToken(); if ("match_id".equals(relativeField)) { matchId = parser.getText(); } else if ("similarity".equals(relativeField)) { similarity = Double.parseDouble(parser.getText()); } else if ("shared_segments".equals(relativeField)) { sharedSegments = parser.getIntValue(); } else if ("relationship".equals(relativeField)) { relationship = Relationship.fromDescription(parser.getText()); } else if ("user_relationship_code".equals(relativeField)) { String code = parser.getText(); userRelationship = code == "null" ? null : Relationship.fromCode(Integer.parseInt(code)); } else if ("predicted_relationship_code".equals(relativeField)) { if (relationship == null) { String code = parser.getText(); relationship = code == "null" ? null : Relationship.fromCode(Integer.parseInt(code)); } } else if ("range".equals(relativeField)) { while (parser.nextToken() != JsonToken.END_ARRAY) { range.add(Relationship.fromDescription(parser.getText())); } } // ignored nested fields else if ("family_locations".equals(relativeField)) { while (parser.nextToken() != JsonToken.END_ARRAY) { // ignore } } else if ("family_surnames".equals(relativeField)) { while (parser.nextToken() != JsonToken.END_ARRAY) { // ignore } } else if ("profile_picture_urls".equals(relativeField)) { while (parser.nextToken() != JsonToken.END_OBJECT) { // ignore } } } } relatives.add(new Relative(profileId, matchId, similarity, sharedSegments, relationship, userRelationship, range)); matchId = null; similarity = 0.0d; sharedSegments = 0; relationship = null; userRelationship = null; range.clear(); } } return relatives; } catch (IOException e) { logger.warn("could not parse relatives", e); } finally { try { inputStream.close(); } catch (Exception e) { // ignored } try { parser.close(); } catch (Exception e) { // ignored } } return null; }