List of usage examples for com.fasterxml.jackson.core JsonParser getText
public abstract String getText() throws IOException, JsonParseException;
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;// ww w . ja va2 s. c o m 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.hyperledger.dropwizard.hocon.HoconDeserializer.java
protected ConfigObject deserializeObject(JsonParser jp, DeserializationContext ctxt) throws IOException { HashMap<String, Object> mapping = new HashMap<>(); while (jp.nextToken() != JsonToken.END_OBJECT) { String name = jp.getCurrentName(); JsonToken t = jp.nextToken();/*from ww w. j a v a 2 s . c om*/ switch (t) { case START_ARRAY: mapping.put(name, deserializeArray(jp, ctxt).unwrapped()); break; case START_OBJECT: mapping.put(name, deserializeObject(jp, ctxt).unwrapped()); break; case VALUE_FALSE: mapping.put(name, false); break; case VALUE_TRUE: mapping.put(name, true); break; case VALUE_NULL: mapping.put(name, null); break; case VALUE_NUMBER_FLOAT: if (jp.getNumberType() == JsonParser.NumberType.BIG_DECIMAL) { mapping.put(name, jp.getDecimalValue()); } else { mapping.put(name, jp.getDoubleValue()); } break; case VALUE_NUMBER_INT: // very cumbersome... but has to be done switch (jp.getNumberType()) { case LONG: mapping.put(name, jp.getLongValue()); break; case INT: mapping.put(name, jp.getIntValue()); break; default: mapping.put(name, jp.getBigIntegerValue()); } break; case VALUE_STRING: mapping.put(name, jp.getText()); break; case VALUE_EMBEDDED_OBJECT: { Object ob = jp.getEmbeddedObject(); if (ob instanceof byte[]) { String b64 = ctxt.getBase64Variant().encode((byte[]) ob, false); mapping.put(name, b64); break; } } default: throw ctxt.mappingException(_valueClass); } } return ConfigValueFactory.fromMap(mapping); }
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 w w . j a v a 2 s. c om * * <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.google.openrtb.json.OpenRtbJsonReader.java
protected void readSeatBidField(JsonParser par, SeatBid.Builder seatbid, String fieldName) throws IOException { switch (fieldName) { case "bid": for (startArray(par); endArray(par); par.nextToken()) { seatbid.addBid(readBid(par)); }/*from www.ja v a2 s . co m*/ break; case "seat": seatbid.setSeat(par.getText()); break; case "group": seatbid.setGroup(par.getValueAsBoolean()); break; default: readOther(seatbid, par, fieldName); } }
From source file:com.google.openrtb.json.OpenRtbJsonReader.java
@SuppressWarnings("deprecation") protected void readVideoField(JsonParser par, Video.Builder video, String fieldName) throws IOException { switch (fieldName) { case "mimes": for (startArray(par); endArray(par); par.nextToken()) { video.addMimes(par.getText()); }/*from ww w . j a v a 2s . c o m*/ break; case "minduration": video.setMinduration(par.getIntValue()); break; case "maxduration": video.setMaxduration(par.getIntValue()); break; case "protocol": { Protocol value = Protocol.valueOf(par.getIntValue()); if (checkEnum(value)) { video.setProtocol(value); } } break; case "protocols": for (startArray(par); endArray(par); par.nextToken()) { Protocol value = Protocol.valueOf(par.getIntValue()); if (checkEnum(value)) { video.addProtocols(value); } } break; case "w": video.setW(par.getIntValue()); break; case "h": video.setH(par.getIntValue()); break; case "startdelay": video.setStartdelay(par.getIntValue()); break; case "linearity": { VideoLinearity value = VideoLinearity.valueOf(par.getIntValue()); if (checkEnum(value)) { video.setLinearity(value); } } break; case "sequence": video.setSequence(par.getIntValue()); break; case "battr": for (startArray(par); endArray(par); par.nextToken()) { CreativeAttribute value = CreativeAttribute.valueOf(par.getIntValue()); if (checkEnum(value)) { video.addBattr(value); } } break; case "maxextended": video.setMaxextended(par.getIntValue()); break; case "minbitrate": video.setMinbitrate(par.getIntValue()); break; case "maxbitrate": video.setMaxbitrate(par.getIntValue()); break; case "boxingallowed": video.setBoxingallowed(par.getValueAsBoolean()); break; case "playbackmethod": for (startArray(par); endArray(par); par.nextToken()) { PlaybackMethod value = PlaybackMethod.valueOf(par.getIntValue()); if (checkEnum(value)) { video.addPlaybackmethod(value); } } break; case "delivery": for (startArray(par); endArray(par); par.nextToken()) { ContentDeliveryMethod value = ContentDeliveryMethod.valueOf(par.getIntValue()); if (checkEnum(value)) { video.addDelivery(value); } } break; case "pos": { AdPosition value = AdPosition.valueOf(par.getIntValue()); if (checkEnum(value)) { video.setPos(value); } } break; case "companionad": if (peekStructStart(par) == JsonToken.START_ARRAY) { // OpenRTB 2.2+ for (startArray(par); endArray(par); par.nextToken()) { video.addCompanionad(readBanner(par)); } } else { // START_OBJECT // OpenRTB 2.1- video.setCompanionad21(readCompanionAd(par)); } break; case "api": for (startArray(par); endArray(par); par.nextToken()) { APIFramework value = APIFramework.valueOf(par.getIntValue()); if (checkEnum(value)) { video.addApi(value); } } break; case "companiontype": for (startArray(par); endArray(par); par.nextToken()) { CompanionType value = CompanionType.valueOf(par.getIntValue()); if (checkEnum(value)) { video.addCompaniontype(value); } } break; case "skip": video.setSkip(par.getValueAsBoolean()); break; case "skipmin": video.setSkipmin(par.getIntValue()); break; case "skipafter": video.setSkipafter(par.getIntValue()); break; default: readOther(video, par, fieldName); } }
From source file:org.gvnix.web.json.DataBinderDeserializer.java
/** * Deserializes JSON property into Map<String, String> format to use it in a * Spring {@link DataBinder}.//from w w w . j a v a 2 s. c o m * <p/> * Check token's type to perform an action: * <ul> * <li>If it's a property, stores it in map</li> * <li>If it's an object, calls to * {@link #readObject(JsonParser, DeserializationContext, String)}</li> * <li>If it's an array, calls to * {@link #readArray(JsonParser, DeserializationContext, String)}</li> * </ul> * * @param parser * @param ctxt * @param token current token * @param prefix property dataBinder path * @return * @throws IOException * @throws JsonProcessingException */ protected Map<String, String> readField(JsonParser parser, DeserializationContext ctxt, JsonToken token, String prefix) throws IOException, JsonProcessingException { String fieldName = null; String fieldValue = null; // Read the field name fieldName = parser.getCurrentName(); // If current token contains a field name if (!isEmptyString(fieldName)) { // Append the prefix if given if (isEmptyString(prefix)) { fieldName = parser.getCurrentName(); } else { fieldName = prefix.concat(parser.getCurrentName()); } } // If current token contains mark array or object start markers. // Note it cannot be a field value because it will be read below and // then the token is advanced to the next else { // Use the prefix in recursive calls if (!isEmptyString(prefix)) { fieldName = prefix; } } // If current token has been used to read the field name, advance // stream to the next token that contains the field value if (token == JsonToken.FIELD_NAME) { token = parser.nextToken(); } // Field value switch (token) { case VALUE_STRING: case VALUE_NUMBER_INT: case VALUE_NUMBER_FLOAT: case VALUE_EMBEDDED_OBJECT: case VALUE_TRUE: case VALUE_FALSE: // Plain field: Store value Map<String, String> field = new HashMap<String, String>(); fieldValue = parser.getText(); field.put(fieldName, fieldValue); return field; case START_ARRAY: // Read array items return readArray(parser, ctxt, fieldName); case START_OBJECT: // Read object properties return readObject(parser, ctxt, fieldName); case END_ARRAY: case END_OBJECT: // Skip array and object end markers parser.nextToken(); break; default: throw ctxt.mappingException(getBeanClass()); } return Collections.emptyMap(); }
From source file:com.google.openrtb.json.OpenRtbJsonReader.java
protected void readAudioField(JsonParser par, Audio.Builder audio, String fieldName) throws IOException { // Video & Audio common switch (fieldName) { case "mimes": for (startArray(par); endArray(par); par.nextToken()) { audio.addMimes(par.getText()); }/* w ww .jav a2 s. co m*/ break; case "minduration": audio.setMinduration(par.getIntValue()); break; case "maxduration": audio.setMaxduration(par.getIntValue()); break; case "protocols": for (startArray(par); endArray(par); par.nextToken()) { Protocol value = Protocol.valueOf(par.getIntValue()); if (checkEnum(value)) { audio.addProtocols(value); } } break; case "startdelay": audio.setStartdelay(par.getIntValue()); break; case "sequence": audio.setSequence(par.getIntValue()); break; case "battr": for (startArray(par); endArray(par); par.nextToken()) { CreativeAttribute value = CreativeAttribute.valueOf(par.getIntValue()); if (checkEnum(value)) { audio.addBattr(value); } } break; case "maxextended": audio.setMaxextended(par.getIntValue()); break; case "minbitrate": audio.setMinbitrate(par.getIntValue()); break; case "maxbitrate": audio.setMaxbitrate(par.getIntValue()); break; case "delivery": for (startArray(par); endArray(par); par.nextToken()) { ContentDeliveryMethod value = ContentDeliveryMethod.valueOf(par.getIntValue()); if (checkEnum(value)) { audio.addDelivery(value); } } break; case "companionad": if (peekStructStart(par) == JsonToken.START_ARRAY) { // OpenRTB 2.2+ for (startArray(par); endArray(par); par.nextToken()) { audio.addCompanionad(readBanner(par)); } } break; case "api": for (startArray(par); endArray(par); par.nextToken()) { APIFramework value = APIFramework.valueOf(par.getIntValue()); if (checkEnum(value)) { audio.addApi(value); } } break; case "companiontype": for (startArray(par); endArray(par); par.nextToken()) { CompanionType value = CompanionType.valueOf(par.getIntValue()); if (checkEnum(value)) { audio.addCompaniontype(value); } } break; // Audio only case "maxseq": audio.setMaxseq(par.getIntValue()); break; case "feed": { FeedType feed = FeedType.valueOf(par.getIntValue()); if (checkEnum(feed)) { audio.setFeed(feed); } } break; case "stitched": audio.setStitched(par.getValueAsBoolean()); break; case "nvol": { VolumeNormalizationMode value = VolumeNormalizationMode.valueOf(par.getIntValue()); if (checkEnum(value)) { audio.setNvol(value); } } break; default: readOther(audio, par, fieldName); } }
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 w ww. j a va 2 s . co 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.tage.calcite.adapter.druid.DruidConnectionImpl.java
private void parseField(List<String> fieldNames, List<Primitive> fieldTypes, Row.RowBuilder rowBuilder, JsonParser parser) throws IOException { final String fieldName = parser.getCurrentName(); // Move to next token, which is name's value JsonToken token = parser.nextToken(); int i = fieldNames.indexOf(fieldName); if (i < 0) { return;//w ww. j a va2s . co m } switch (token) { case VALUE_NUMBER_INT: case VALUE_NUMBER_FLOAT: Primitive type = fieldTypes.get(i); if (type == null) { if (token == JsonToken.VALUE_NUMBER_INT) { type = Primitive.INT; } else { type = Primitive.FLOAT; } } switch (type) { case BYTE: rowBuilder.set(i, parser.getIntValue()); break; case SHORT: rowBuilder.set(i, parser.getShortValue()); break; case INT: rowBuilder.set(i, parser.getIntValue()); break; case LONG: rowBuilder.set(i, parser.getLongValue()); break; case FLOAT: rowBuilder.set(i, parser.getFloatValue()); break; case DOUBLE: rowBuilder.set(i, parser.getDoubleValue()); break; } break; case VALUE_TRUE: rowBuilder.set(i, true); break; case VALUE_FALSE: rowBuilder.set(i, false); break; case VALUE_NULL: break; default: rowBuilder.set(i, parser.getText()); } }
From source file:com.google.openrtb.json.OpenRtbJsonReader.java
protected void readGeoField(JsonParser par, Geo.Builder geo, String fieldName) throws IOException { switch (fieldName) { case "lat": geo.setLat(par.getValueAsDouble()); break;/* w w w. j a v a 2 s .co m*/ case "lon": geo.setLon(par.getValueAsDouble()); break; case "type": { LocationType value = LocationType.valueOf(par.getIntValue()); if (checkEnum(value)) { geo.setType(value); } } break; case "country": geo.setCountry(par.getText()); break; case "region": geo.setRegion(par.getText()); break; case "regionfips104": geo.setRegionfips104(par.getText()); break; case "metro": geo.setMetro(par.getText()); break; case "city": geo.setCity(par.getText()); break; case "zip": geo.setZip(par.getText()); break; case "utcoffset": geo.setUtcoffset(par.getIntValue()); break; case "accuracy": geo.setAccuracy(par.getIntValue()); break; case "lastfix": geo.setLastfix(par.getIntValue()); break; case "ipservice": { LocationService value = LocationService.valueOf(par.getIntValue()); if (checkEnum(value)) { geo.setIpservice(value); } } break; default: readOther(geo, par, fieldName); } }