List of usage examples for com.google.gson JsonParser JsonParser
@Deprecated
public JsonParser()
From source file:apim.restful.importexport.utils.APIExportUtil.java
License:Open Source License
/** * Retrieve meta information of the API to export * URL template information are stored in swagger.json definition while rest of the required * data are in api.json/*www . ja v a 2 s. c o m*/ * * @param apiToReturn API to be exported * @param registry Current tenant registry * @throws APIExportException If an error occurs while exporting meta information */ private static void exportMetaInformation(API apiToReturn, Registry registry) throws APIExportException { APIDefinition definitionFromSwagger20 = new APIDefinitionFromSwagger20(); String archivePath = archiveBasePath .concat(File.separator + apiToReturn.getId().getApiName() + "-" + apiToReturn.getId().getVersion()); createDirectory(archivePath + File.separator + "Meta-information"); //Remove unnecessary data from exported Api cleanApiDataToExport(apiToReturn); Gson gson = new GsonBuilder().setPrettyPrinting().create(); String apiInJson = gson.toJson(apiToReturn); writeFile(archivePath + File.separator + "Meta-information" + File.separator + "api.json", apiInJson); try { String swaggerDefinition = definitionFromSwagger20.getAPIDefinition(apiToReturn.getId(), registry); JsonParser parser = new JsonParser(); JsonObject json = parser.parse(swaggerDefinition).getAsJsonObject(); String formattedSwaggerJson = gson.toJson(json); writeFile(archivePath + File.separator + "Meta-information" + File.separator + "swagger.json", formattedSwaggerJson); if (log.isDebugEnabled()) { log.debug("Meta information retrieved successfully"); } } catch (APIManagementException e) { log.error("Error while retrieving Swagger definition" + e.getMessage()); throw new APIExportException("Error while retrieving Swagger definition", e); } }
From source file:apim.restful.importexport.utils.APIImportUtil.java
License:Open Source License
/** * This method imports an API/*from w w w . ja va2s. co m*/ * * @param pathToArchive location of the extracted folder of the API * @param currentUser the current logged in user * @param isDefaultProviderAllowed decision to keep or replace the provider * @throws APIImportException if there is an error in importing an API */ public static void importAPI(String pathToArchive, String currentUser, boolean isDefaultProviderAllowed) throws APIImportException { API importedApi; // If the original provider is preserved, if (isDefaultProviderAllowed) { FileInputStream inputStream = null; BufferedReader bufferedReader = null; try { inputStream = new FileInputStream(pathToArchive + APIImportExportConstants.JSON_FILE_LOCATION); bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); importedApi = new Gson().fromJson(bufferedReader, API.class); } catch (FileNotFoundException e) { log.error("Error in locating api.json file. ", e); throw new APIImportException("Error in locating api.json file. " + e.getMessage()); } finally { IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(bufferedReader); } } else { String pathToJSONFile = pathToArchive + APIImportExportConstants.JSON_FILE_LOCATION; try { String jsonContent = FileUtils.readFileToString(new File(pathToJSONFile)); JsonElement configElement = new JsonParser().parse(jsonContent); JsonObject configObject = configElement.getAsJsonObject(); //locate the "providerName" within the "id" and set it as the current user JsonObject apiId = configObject.getAsJsonObject(APIImportExportConstants.ID_ELEMENT); apiId.addProperty(APIImportExportConstants.PROVIDER_ELEMENT, APIUtil.replaceEmailDomain(currentUser)); importedApi = new Gson().fromJson(configElement, API.class); } catch (IOException e) { log.error("Error in setting API provider to logged in user. ", e); throw new APIImportException("Error in setting API provider to logged in user. " + e.getMessage()); } } Set<Tier> allowedTiers; Set<Tier> unsupportedTiersList; try { allowedTiers = provider.getTiers(); } catch (APIManagementException e) { log.error("Error in retrieving tiers of the provider. ", e); throw new APIImportException("Error in retrieving tiers of the provider. " + e.getMessage()); } if (!(allowedTiers.isEmpty())) { unsupportedTiersList = Sets.difference(importedApi.getAvailableTiers(), allowedTiers); //If at least one unsupported tier is found, it should be removed before adding API if (!(unsupportedTiersList.isEmpty())) { for (Tier unsupportedTier : unsupportedTiersList) { //Process is continued with a warning and only supported tiers are added to the importer API log.warn("Tier name : " + unsupportedTier.getName() + " is not supported."); } //Remove the unsupported tiers before adding the API importedApi.removeAvailableTiers(unsupportedTiersList); } } try { int tenantId = APIUtil.getTenantId(currentUser); provider.addAPI(importedApi); addSwaggerDefinition(importedApi, pathToArchive, tenantId); } catch (APIManagementException e) { //Error is logged and APIImportException is thrown because adding API and swagger are mandatory steps log.error("Error in adding API to the provider. ", e); throw new APIImportException("Error in adding API to the provider. " + e.getMessage()); } //Since Image, documents, sequences and WSDL are optional, exceptions are logged and ignored in implementation addAPIImage(pathToArchive, importedApi); addAPIDocuments(pathToArchive, importedApi); addAPISequences(pathToArchive, importedApi, currentUser); addAPIWsdl(pathToArchive, importedApi, currentUser); }
From source file:app.abhijit.iter.data.source.StudentDataSource.java
License:Open Source License
public StudentDataSource(SharedPreferences localStore) { mLocalStore = localStore;/*from w w w . j a v a2s . co m*/ mJsonParser = new JsonParser(); mSubjectAvatars = new HashMap<>(); mSubjectAvatars.put("CHM1002", R.drawable.ic_subject_environmental_studies); mSubjectAvatars.put("CSE1002", R.drawable.ic_subject_maths); mSubjectAvatars.put("CSE1011", R.drawable.ic_subject_electrical); mSubjectAvatars.put("CSE2031", R.drawable.ic_subject_maths); mSubjectAvatars.put("CSE3151", R.drawable.ic_subject_database); mSubjectAvatars.put("CSE4042", R.drawable.ic_subject_network); mSubjectAvatars.put("CSE4043", R.drawable.ic_subject_security); mSubjectAvatars.put("CSE4044", R.drawable.ic_subject_security); mSubjectAvatars.put("CSE4051", R.drawable.ic_subject_database); mSubjectAvatars.put("CSE4052", R.drawable.ic_subject_database); mSubjectAvatars.put("CSE4053", R.drawable.ic_subject_database); mSubjectAvatars.put("CSE4054", R.drawable.ic_subject_database); mSubjectAvatars.put("CSE4102", R.drawable.ic_subject_html); mSubjectAvatars.put("CSE4141", R.drawable.ic_subject_android); mSubjectAvatars.put("CSE4151", R.drawable.ic_subject_server); mSubjectAvatars.put("CVL3071", R.drawable.ic_subject_traffic); mSubjectAvatars.put("CVL3241", R.drawable.ic_subject_water); mSubjectAvatars.put("CVL4031", R.drawable.ic_subject_earth); mSubjectAvatars.put("CVL4032", R.drawable.ic_subject_soil); mSubjectAvatars.put("CVL4041", R.drawable.ic_subject_water); mSubjectAvatars.put("CVL4042", R.drawable.ic_subject_water); mSubjectAvatars.put("EET1001", R.drawable.ic_subject_matlab); mSubjectAvatars.put("EET3041", R.drawable.ic_subject_electromagnetic_waves); mSubjectAvatars.put("EET3061", R.drawable.ic_subject_communication); mSubjectAvatars.put("EET3062", R.drawable.ic_subject_communication); mSubjectAvatars.put("EET4014", R.drawable.ic_subject_renewable_energy); mSubjectAvatars.put("EET4041", R.drawable.ic_subject_electromagnetic_waves); mSubjectAvatars.put("EET4061", R.drawable.ic_subject_wifi); mSubjectAvatars.put("EET4063", R.drawable.ic_subject_communication); mSubjectAvatars.put("EET4161", R.drawable.ic_subject_communication); mSubjectAvatars.put("HSS1001", R.drawable.ic_subject_effective_speech); mSubjectAvatars.put("HSS1021", R.drawable.ic_subject_economics); mSubjectAvatars.put("HSS2021", R.drawable.ic_subject_economics); mSubjectAvatars.put("MEL3211", R.drawable.ic_subject_water); mSubjectAvatars.put("MTH2002", R.drawable.ic_subject_probability_statistics); mSubjectAvatars.put("MTH4002", R.drawable.ic_subject_matlab); mSubjectAvatars.put("CHM", R.drawable.ic_subject_chemistry); mSubjectAvatars.put("CSE", R.drawable.ic_subject_computer); mSubjectAvatars.put("CVL", R.drawable.ic_subject_civil); mSubjectAvatars.put("EET", R.drawable.ic_subject_electrical); mSubjectAvatars.put("HSS", R.drawable.ic_subject_humanities); mSubjectAvatars.put("MEL", R.drawable.ic_subject_mechanical); mSubjectAvatars.put("MTH", R.drawable.ic_subject_maths); mSubjectAvatars.put("PHY", R.drawable.ic_subject_physics); mSubjectAvatars.put("generic", R.drawable.ic_subject_generic); }
From source file:app.abhijit.iter.data.source.TelemetryDataSource.java
License:Open Source License
public void processTelemetry(String response) { try {/*from ww w .j a v a 2s .c o m*/ JsonObject telemetry = new JsonParser().parse(response).getAsJsonObject(); boolean updateAvailable = telemetry.get("update").getAsBoolean(); boolean displayAds = telemetry.get("ads").getAsBoolean(); EventBus.getDefault().post(new Telemetry(updateAvailable, displayAds)); } catch (Exception ignored) { } }
From source file:application.Genius.java
License:Open Source License
public static ArrayList<Lyrics> search(String query) { ArrayList<Lyrics> results = new ArrayList<>(); query = Normalizer.normalize(query, Normalizer.Form.NFD).replaceAll("\\p{InCombiningDiacriticalMarks}+", "");//from w w w .ja va 2 s . c o m JsonObject response = null; try { URL queryURL = new URL( String.format("http://api.genius.com/search?q=%s", URLEncoder.encode(query, "UTF-8"))); Connection connection = Jsoup.connect(queryURL.toExternalForm()) .header("Authorization", "Bearer " + Keys.GENIUS).ignoreContentType(true); Document document = connection.userAgent(USER_AGENT).get(); response = new JsonParser().parse(document.text()).getAsJsonObject(); } catch (IOException e) { e.printStackTrace(); } if (response == null || response.getAsJsonObject("meta").get("status").getAsInt() != 200) return results; JsonArray hits = response.getAsJsonObject("response").getAsJsonArray("hits"); int processed = 0; while (processed < hits.size()) { JsonObject song = hits.get(processed).getAsJsonObject().getAsJsonObject("result"); String artist = song.getAsJsonObject("primary_artist").get("name").getAsString(); String title = song.get("title").getAsString(); String url = "http://genius.com/songs/" + song.get("id").getAsString(); Lyrics l = new Lyrics(); l.mArtist = artist; l.mTitle = title; l.mSourceUrl = url; l.mSource = "Genius"; results.add(l); processed++; } return results; }
From source file:application.rest.LibertyRestEndpoint.java
License:Apache License
@POST @Path("/text") @Produces("text/plain") // sends JSON public String hello(@FormParam("phrase") String phrase, @FormParam("language") String targetLang) { String decodePhrase = new String(Base64.getDecoder().decode(phrase.getBytes())); System.out.println(decodePhrase); LanguageDetection ld = new LanguageDetection(); com.ibm.watson.developer_cloud.alchemy.v1.model.Language sourceLang = ld.detect(decodePhrase); TranslateCredentials tc = new TranslateCredentials(); LanguageTranslator service = new LanguageTranslator(); service.setEndPoint(tc.getUrl());/* w ww .j a v a 2 s . c o m*/ service.setUsernameAndPassword(tc.getUser(), tc.getPass()); TranslationResult translationResult = null; Language lans = getLanguaje(sourceLang.getLanguage().toLowerCase()); Language lant = getLanguaje(targetLang.toLowerCase()); try { if (lans != null && lant != null) translationResult = service.translate(decodePhrase, lans, lant).execute(); else throw new Exception(); } catch (Exception e) { //return Base64.getEncoder().encode("Error detecting languaje or source/target translation is not implemented".getBytes()); return "Error detecting languaje or source/target translation is not implemented"; } JsonObject result = new JsonParser().parse(translationResult.toString()).getAsJsonObject(); System.out.println(result); JsonObject translations = result.getAsJsonArray("translations").get(0).getAsJsonObject(); System.out.println(translations); String translation = translations.get("translation").getAsString(); //return Base64.getEncoder().encode(translation.getBytes()); return translation; }
From source file:ar.com.wolox.wolmo.networking.retrofit.serializer.LocalDateSerializer.java
License:Open Source License
/** * Transforms and instance of {@link LocalDate} from the JodaTime library into a * {@link JsonElement}. This is useful for sending the data over the network. * * @param date an instance of {@link LocalDate} to be serialized into a {@link JsonElement} * * @return an instance of {@link JsonElement} representing a {@link LocalDate} *//*from ww w . ja v a 2s . com*/ @Override public JsonElement serialize(LocalDate date, Type type, JsonSerializationContext context) { initFormatter(); return new JsonParser().parse(mDateTimeFormatter.print(date)); }
From source file:ar.fiuba.jobify.JobifyChat.java
License:Open Source License
/** * Called when message is received.//from w w w. java 2 s . c o m * * @param remoteMessage Object representing the message received from Firebase Cloud Messaging. */ // [START receive_message] @Override public void onMessageReceived(RemoteMessage remoteMessage) { // [START_EXCLUDE] // There are two types of messages data messages and notification messages. Data messages are handled // here in onMessageReceived whether the app is in the foreground or background. Data messages are the type // traditionally used with GCM. Notification messages are only received here in onMessageReceived when the app // is in the foreground. When the app is in the background an automatically generated notification is displayed. // When the user taps on the notification they are returned to the app. Messages containing both notification // and data payloads are treated as notification messages. The Firebase console always sends notification // messages. For more see: https://firebase.google.com/docs/cloud-messaging/concept-options // [END_EXCLUDE] // Not getting messages here? See why this may be: https://goo.gl/39bRNJ Log.d(TAG, "From: " + remoteMessage.getFrom()); // Check if message contains a data payload. if (remoteMessage.getData().size() > 0) { String body = remoteMessage.getData() + ""; Log.d(TAG, "Message data payload: " + body); JsonParser parser = new JsonParser(); //JsonObject message = parser.parse(body).getAsJsonObject(); JSONObject message = null; try { message = new JSONObject(body); } catch (JSONException e) { e.printStackTrace(); } if (message.has("mensaje")) { long sender = 0, receiver = 0; try { receiver = message.getJSONObject("mensaje").getLong("to"); sender = message.getJSONObject("mensaje").getLong("from"); } catch (JSONException e) { e.printStackTrace(); } long currentId = getSharedPreferences(getString(R.string.shared_pref_connected_user), 0) .getLong(getString(R.string.stored_connected_user_id), -1); //Log.d("MYTAG", editor.g getLong( getString(R.string.stored_connected_user_id))); if (receiver != currentId) { // la app no esta abierta return; } if (!(ConversacionActivity.activityVisible && ConversacionActivity.corresponsalID == sender)) { NotificationCompat.Builder mBuilder = null; try { mBuilder = new NotificationCompat.Builder(this).setContentTitle("Nuevo mensaje") .setSmallIcon(R.drawable.common_google_signin_btn_icon_dark).setAutoCancel(true) .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.mensaje)) .setSmallIcon(R.drawable.logo_v2_j_square) .setContentText(message.getJSONObject("mensaje").getString("message")); } catch (JSONException e) { e.printStackTrace(); } //ConversacionActivity. Intent resultIntent = new Intent(this, ConversacionActivity.class); TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); stackBuilder.addParentStack(ConversacionActivity.class); // Adds the Intent that starts the Activity to the top of the stack stackBuilder.addNextIntent(resultIntent); resultIntent.putExtra(ConversacionActivity.CORRESPONSAL_ID_MESSAGE, (long) sender); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.setContentIntent(resultPendingIntent); NotificationManager mNotificationManager = (NotificationManager) getSystemService( Context.NOTIFICATION_SERVICE); Random r = new Random(); mNotificationManager.notify(r.nextInt(1000000000), mBuilder.build()); } // notify chat try { EventBus.getDefault().post(new MessageEvent(message.getJSONObject("mensaje"))); } catch (JSONException e) { e.printStackTrace(); } } else if (message.has("solicitud")) { long receiver = 0; try { receiver = message.getJSONObject("solicitud").getLong("toId"); } catch (JSONException e) { e.printStackTrace(); } long currentId = getSharedPreferences(getString(R.string.shared_pref_connected_user), 0) .getLong(getString(R.string.stored_connected_user_id), -1); //Log.d("MYTAG", editor.g getLong( getString(R.string.stored_connected_user_id))); if (receiver != currentId) { // la app no esta abierta return; } NotificationCompat.Builder mBuilder = null; try { mBuilder = new NotificationCompat.Builder(this).setContentTitle("Nueva solicitud") .setSmallIcon(R.drawable.common_google_signin_btn_icon_dark).setAutoCancel(true) .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.solicitud)) .setSmallIcon(R.drawable.logo_v2_j_square) .setContentText(message.getJSONObject("solicitud").getString("fromNombre")); } catch (JSONException e) { e.printStackTrace(); } Intent resultIntent = new Intent(this, UserListActivity.class); TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); stackBuilder.addParentStack(UserListActivity.class); // Adds the Intent that starts the Activity to the top of the stack stackBuilder.addNextIntent(resultIntent); resultIntent.putExtra(UserListActivity.LIST_MODE_MESSAGE, UserListActivity.MODE_SOLICITUDES); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.setContentIntent(resultPendingIntent); NotificationManager mNotificationManager = (NotificationManager) getSystemService( Context.NOTIFICATION_SERVICE); Random r = new Random(); mNotificationManager.notify(r.nextInt(1000000000), mBuilder.build()); } // if this is a notification: // TODO // here we call the callback to the activity // if this is a message: } // Check if message contains a notification payload. if (remoteMessage.getNotification() != null) { Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody()); } // Also if you intend on generating your own notifications as a result of a received FCM // message, here is where that should be initiated. See sendNotification method below. }
From source file:arces.unibo.SEPA.client.api.SPARQL11SEProtocol.java
License:Open Source License
/** * Parse SPARQL 1.1 Query and Update// w w w .j a v a 2 s . c om * * Update and error responses are serialized as JSON objects: * * {"code": HTTP Return Code, "body": "Message body"} */ @Override protected Response parseEndpointResponse(int token, String jsonResponse, SPARQLPrimitive op, QueryResultsFormat format) { if (token != -1) logger.debug("Parse endpoint response #" + token + " " + jsonResponse); else logger.debug("Parse endpoint response " + jsonResponse); JsonObject json = null; try { json = new JsonParser().parse(jsonResponse).getAsJsonObject(); } catch (JsonParseException | IllegalStateException e) { //An update response is not forced to be JSON if (op.equals(SPARQLPrimitive.UPDATE)) return new UpdateResponse(token, jsonResponse); logger.error(e.getMessage()); return new ErrorResponse(token, 500, e.getMessage()); } if (json.get("code") != null) { if (json.get("code").getAsInt() >= 400) return new ErrorResponse(token, json.get("code").getAsInt(), json.get("body").getAsString()); } if (op.equals(SPARQLPrimitive.UPDATE)) return new UpdateResponse(token, json.get("body").getAsString()); if (op.equals(SPARQLPrimitive.QUERY)) return new QueryResponse(token, json); return new ErrorResponse(token, 500, jsonResponse); }
From source file:arces.unibo.SEPA.client.api.SPARQL11SEProtocol.java
License:Open Source License
protected Response parseSPARQL11SEResponse(String response, SPARQL11SEPrimitive op) { if (response == null) return new ErrorResponse(0, 500, "Response is null"); JsonObject json = null;/*from w w w. j a v a 2s . c om*/ try { json = new JsonParser().parse(response).getAsJsonObject(); } catch (JsonParseException | IllegalStateException e) { //if (op == SPARQL11SEPrimitive.SECUREUPDATE) return new UpdateResponse(response); return new ErrorResponse(0, 500, "Unknown response: " + response); } //Error response if (json.get("code") != null) if (json.get("code").getAsInt() >= 400) return new ErrorResponse(0, json.get("code").getAsInt(), json.get("body").getAsString()); if (op == SPARQL11SEPrimitive.SECUREQUERY) return new QueryResponse(json); if (op == SPARQL11SEPrimitive.SECUREUPDATE) return new UpdateResponse(response); if (op == SPARQL11SEPrimitive.REGISTER) { if (json.get("client_id") != null && json.get("client_secret") != null) { try { properties.setCredentials(json.get("client_id").getAsString(), json.get("client_secret").getAsString()); } catch (IOException e) { return new ErrorResponse(ErrorResponse.NOT_FOUND, "Failed to save credentials"); } return new RegistrationResponse(json.get("client_id").getAsString(), json.get("client_secret").getAsString(), json.get("signature")); } return new ErrorResponse(0, 401, "Credentials not found in registration response"); } if (op == SPARQL11SEPrimitive.REQUESTTOKEN) { if (json.get("access_token") != null && json.get("expires_in") != null && json.get("token_type") != null) { int seconds = json.get("expires_in").getAsInt(); Date expires = new Date(); expires.setTime(expires.getTime() + (1000 * seconds)); try { properties.setJWT(json.get("access_token").getAsString(), expires, json.get("token_type").getAsString()); } catch (IOException e) { return new ErrorResponse(ErrorResponse.NOT_FOUND, "Failed to save JWT"); } return new JWTResponse(json.get("access_token").getAsString(), json.get("token_type").getAsString(), json.get("expires_in").getAsLong()); } else if (json.get("code") != null && json.get("body") != null) return new ErrorResponse(0, json.get("code").getAsInt(), json.get("body").getAsString()); else if (json.get("code") != null) return new ErrorResponse(0, json.get("code").getAsInt(), ""); return new ErrorResponse(0, 500, "Response not recognized: " + json.toString()); } return new ErrorResponse(0, 500, "Response unknown: " + response); }