List of usage examples for com.google.gson JsonElement getAsString
public String getAsString()
From source file:at.ac.uniklu.mobile.sportal.api.GsonNotificationTypeDeserializer.java
License:Open Source License
@Override public Type deserialize(JsonElement json, java.lang.reflect.Type classOfT, JsonDeserializationContext context) throws JsonParseException { try {//from w ww .ja v a 2 s . c o m return Type.valueOf(json.getAsString()); } catch (IllegalArgumentException e) { return Type.UNKNOWN; } }
From source file:at.pcgamingfreaks.Message.MessageComponent.java
License:Open Source License
/** * Generates a MessageComponent list from a given {@link JsonArray} object. * * @param componentArray The {@link JsonArray} containing all the components, from the deserializer. * @return A list of MessageComponent objects. An empty list if there are no components in the given {@link JsonArray}. *///w ww . j a v a 2 s .co m protected List<T> fromJsonArrayWorker(JsonArray componentArray) { List<T> components = new LinkedList<>(); for (JsonElement component : componentArray) { if (component instanceof JsonPrimitive) { try { T messageComponent = (T) messageComponentConstructor.newInstance(); messageComponent.setText(component.getAsString()); components.add(messageComponent); } catch (Exception e) { e.printStackTrace(); } } else if (component instanceof JsonObject) { components.add((T) GSON.fromJson(component, messageComponentClass)); } else if (component instanceof JsonArray) { components.addAll(fromJsonArrayWorker((JsonArray) component)); } } return components; }
From source file:au.edu.ausstage.tweetgatherer.MessageProcessor.java
License:Open Source License
/** * A method that is run in the thread//from w ww . ja v a 2 s . com * Takes a tweet from the queue and processes it */ public void run() { STweet tweet = null; try { // infinite loop to keep the thread running while (true) { // take a tweet from the queue tweet = newTweets.take(); // get the tweet id number String tweetId = Long.toString(tweet.getStatusId()); // get a hash of the tweet id String tweetIdHash = HashUtils.hashValue(tweetId); // get the user STweetUser user = tweet.getUser(); // get the user id String userId = Long.toString(user.getUserId()); // get a hash of the user id String userIdHash = HashUtils.hashValue(userId); // get the JSON value of the tweet JsonObject jsonTweetObject = sanitiseMessage(tweet.getJSON(), tweetIdHash); // get the JSON value of the user JsonObject jsonUserObject = sanitiseUser(user.getJSON(), userIdHash); // replace the user with the sanitised version jsonTweetObject.remove("user"); jsonTweetObject.addProperty("user", ""); /* * Write the file */ if (FileUtils.writeNewFile(logFiles + "/" + tweetIdHash, jsonTweetObject.toString() + "\n" + jsonUserObject.toString()) == false) { System.err.println("ERROR: Unable to write file to the specified log file"); System.err.println(" twitter message with id '" + tweetId + "' is now lost"); } else { System.out.println("INFO: New Message written to the log directory:"); System.out.println(" " + tweetIdHash); } /* * get the hash tags from this message */ // get the list of hash tags from the tweet JsonElement elem = jsonTweetObject.get("text"); List<String> hashtags = extractHashTags.extractHashtags(elem.getAsString()); // convert all of the found hash tags to lower case ListIterator<String> hashtagsIterator = hashtags.listIterator(); while (hashtagsIterator.hasNext() == true) { // get the next tage in the list String tmp = (String) hashtagsIterator.next(); tmp = tmp.toLowerCase(); // replace the value we retrieved with this updated one hashtagsIterator.set(tmp); } // see if this is a company performance if (isCompanyPerformance(hashtags, jsonTweetObject, jsonUserObject, tweetIdHash) == false) { // this isn't a company performance // is it using a performance specific id? if (isPerformance(hashtags, jsonTweetObject, jsonUserObject, tweetIdHash) == false) { //this isn't a valid performance System.err.println("ERROR: Unable to find a matching performance for this message"); // send an exception report if (emailManager.sendMessageWithAttachment(EMAIL_SUBJECT, EMAIL_MESSAGE, logFiles + "/" + tweetIdHash) == false) { System.err.println("ERROR: Unable to send the exception report"); } } } } } catch (InterruptedException ex) { // thread has been interrupted System.out.println("INFO: The Message processing thread has stopped"); } }
From source file:au.edu.ausstage.tweetgatherer.MessageProcessor.java
License:Open Source License
/** * A private method to sanitise the message * * @param jsonTweetObject the original message object * @param idHash the hash of the message id * * @return the sanitised message object *//* w w w .j a va2 s . c o m*/ private JsonObject sanitiseMessage(JsonObject jsonTweetObject, String idHash) { // remove the id and replace it with the hash jsonTweetObject.remove("id"); jsonTweetObject.addProperty("id", idHash); // replace the "in_reply_to_user_id" field with a hash if present if (jsonTweetObject.has("in_reply_to_user_id") == true) { // get a hash of the value JsonElement elem = jsonTweetObject.get("in_reply_to_user_id"); if (elem.isJsonNull() == false) { String hash = HashUtils.hashValue(elem.getAsString()); // update the value jsonTweetObject.remove("in_reply_to_user_id"); jsonTweetObject.addProperty("in_reply_to_user_id", hash); } } // replace the "in_reply_to_status_id" field with a hash if present if (jsonTweetObject.has("in_reply_to_status_id") == true) { // get a hash of the value JsonElement elem = jsonTweetObject.get("in_reply_to_status_id"); if (elem.isJsonNull() == false) { String hash = HashUtils.hashValue(elem.getAsString()); // update the value jsonTweetObject.remove("in_reply_to_status_id"); jsonTweetObject.addProperty("in_reply_to_status_id", hash); } } // replace the "retweeted_status" field with a hash if present if (jsonTweetObject.has("retweeted_status") == true) { // get a hash of the value JsonElement elem = jsonTweetObject.get("retweeted_status"); if (elem.isJsonNull() == false) { String hash = HashUtils.hashValue(elem.getAsString()); // update the value jsonTweetObject.remove("retweeted_status"); jsonTweetObject.addProperty("retweeted_status", hash); } } // return the sanitised object return jsonTweetObject; }
From source file:au.edu.ausstage.tweetgatherer.MessageProcessor.java
License:Open Source License
/** * A private method to process a message containing a company hash tag * * @param hashtags a list of hashtags associated with this message * @param jsonTweetObject the message/* ww w . j a v a2 s . c o m*/ * @param jsonUserObject the user object * @param tweetIdHash the hash of the message id * * @return true if, and only if, the message was processed successfully */ private boolean isPerformance(List<String> hashtags, JsonObject jsonTweetObject, JsonObject jsonUserObject, String tweetIdHash) { /* * get the performance and question id */ String performanceId = null; String questionId = null; JsonElement elem = jsonTweetObject.get("created_at"); DateTime messageCreated = inputDateTimeFormat.parseDateTime(elem.getAsString()); String selectSql = "SELECT performance_id, question_id, SUBSTR(hash_tag, 2) " + "FROM mob_performances " + "WHERE deprecated_hash_tag = 'N'"; // get the data DbObjects results = database.executeStatement(selectSql); // double check the results if (results == null) { System.err.println("ERROR: Unable to execute the SQL to lookup performance specific hashtags"); // send an exception report if (emailManager.sendMessageWithAttachment(EMAIL_SUBJECT, EMAIL_MESSAGE, logFiles + "/" + tweetIdHash) == false) { System.err.println("ERROR: Unable to send the exception report"); } return false; } else { // look for performances matching the hash tag from the message ResultSet resultSet = results.getResultSet(); // loop through the resultset boolean found = false; // exit the loop early String[] sqlParameters = new String[7]; // store the parameters try { while (resultSet.next() && found == false) { // see if the hashtags in the message match one in the DB if (hashtags.contains(resultSet.getString(3)) == true) { // yep sqlParameters[0] = resultSet.getString(1); sqlParameters[1] = resultSet.getString(2); found = true; } } } catch (java.sql.SQLException ex) { found = false; } if (found == false) { // no performance with a matching company id was found return false; } else { /* * write the message to the database */ // define the sql String insertSql = "INSERT INTO mob_feedback " + "(performance_id, question_id, source_type, received_date_time, received_from, source_id, short_content) " + "VALUES (?,?,?, TO_DATE(?, '" + DB_DATE_TIME_FORMAT + "'),?,?,?)"; // use the source id from the constant sqlParameters[2] = SOURCE_ID; // add the date and time sqlParameters[3] = dateTimeFormat.print(messageCreated); // add the user id elem = jsonUserObject.get("id"); sqlParameters[4] = elem.getAsString(); // add the source id elem = jsonTweetObject.get("id"); sqlParameters[5] = elem.getAsString(); // add the message elem = jsonUserObject.get("text"); sqlParameters[6] = elem.getAsString(); // insert the data if (database.executePreparedInsertStatement(insertSql, sqlParameters) == false) { System.err.println("ERROR: Unable to add the message to the database"); // send an exception report if (emailManager.sendMessageWithAttachment(EMAIL_SUBJECT, "Exception Report: The Tweet Gatherer was unable to store this message in the database", logFiles + "/" + tweetIdHash) == false) { System.err.println("ERROR: Unable to send the exception report"); } } else { System.out.println("INFO: Successfully added the message to the database"); return true; } } } // end performance check // if we get this far, something bad happend return false; }
From source file:au.edu.ausstage.tweetgatherer.MessageProcessor.java
License:Open Source License
/** * A private method to process a message containing a company hash tag * * @param hashtags a list of hashtags associated with this message * @param jsonTweetObject the message/* w ww.java 2 s . co m*/ * @param jsonUserObject the user object * @param tweetIdHash the hash of the message id * * @return true if, and only if, the message was processed successfully */ private boolean isCompanyPerformance(List<String> hashtags, JsonObject jsonTweetObject, JsonObject jsonUserObject, String tweetIdHash) { /* * get the date & time that the message was received */ JsonElement elem = jsonTweetObject.get("created_at"); DateTime messageCreated = inputDateTimeFormat.parseDateTime(elem.getAsString()); LocalDateTime localMessageCreated = messageCreated.toLocalDateTime(); /* * get the performance and question id */ String performanceId = null; String questionId = null; // define the sql String selectSql = "SELECT performance_id, question_id, SUBSTR(twitter_hash_tag, 2) " + "FROM mob_performances, mob_organisations, orgevlink " + "WHERE mob_performances.event_id = orgevlink.eventid " + "AND mob_organisations.organisation_id = orgevlink.organisationid " + "AND start_date_time < TO_DATE(?, '" + DB_DATE_TIME_FORMAT + "') " + "AND end_date_time + 1/12 > TO_DATE(?, '" + DB_DATE_TIME_FORMAT + "') "; // define the parameters array String[] sqlParameters = new String[2]; sqlParameters[0] = dateTimeFormat.print(messageCreated); sqlParameters[1] = dateTimeFormat.print(messageCreated); // get the data DbObjects results = database.executePreparedStatement(selectSql, sqlParameters); // double check the results if (results == null) { System.err.println("ERROR: Unable to execute the SQL to lookup performances"); // send an exception report if (emailManager.sendMessageWithAttachment(EMAIL_SUBJECT, EMAIL_MESSAGE, logFiles + "/" + tweetIdHash) == false) { System.err.println("ERROR: Unable to send the exception report"); } return false; } else { // look for performances matching the hash tag from the message ResultSet resultSet = results.getResultSet(); // loop through the resultset boolean found = false; // exit the loop early sqlParameters = new String[7]; // store the parameters try { while (resultSet.next() && found == false) { // see if the hashtags in the message match one in the DB if (hashtags.contains(resultSet.getString(3)) == true) { // yep sqlParameters[0] = resultSet.getString(1); sqlParameters[1] = resultSet.getString(2); found = true; } } } catch (java.sql.SQLException ex) { found = false; } if (found == false) { // no performance with a matching company id was found return false; } else { /* * write the message to the database */ // define the sql String insertSql = "INSERT INTO mob_feedback " + "(performance_id, question_id, source_type, received_date_time, received_from, source_id, short_content) " + "VALUES (?,?,?, TO_DATE(?, '" + DB_DATE_TIME_FORMAT + "'),?,?,?)"; // use the source id from the constant sqlParameters[2] = SOURCE_ID; // add the date and time sqlParameters[3] = dateTimeFormat.print(messageCreated); // add the user id elem = jsonUserObject.get("id"); sqlParameters[4] = elem.getAsString(); // add the source id elem = jsonTweetObject.get("id"); sqlParameters[5] = elem.getAsString(); // add the message elem = jsonUserObject.get("text"); sqlParameters[6] = elem.getAsString(); // insert the data if (database.executePreparedInsertStatement(insertSql, sqlParameters) == false) { System.err.println("ERROR: Unable to add the message to the database"); // send an exception report if (emailManager.sendMessageWithAttachment(EMAIL_SUBJECT, "Exception Report: The Tweet Gatherer was unable to store this message in the database", logFiles + "/" + tweetIdHash) == false) { System.err.println("ERROR: Unable to send the exception report"); } } else { System.out.println("INFO: Successfully added the message to the database"); return true; } } } // end performance check // if we get this far, something bad happend return false; }
From source file:augsburg.se.alltagsguide.utilities.Helper.java
License:Open Source License
@NonNull public static String getStringOrDefault(JsonElement elem, String defaultValue) { try {//ww w. ja v a 2 s . c om return elem.getAsString(); } catch (Exception e) { Ln.d(e); return defaultValue; } }
From source file:be.iminds.iot.dianne.nn.util.DianneJSONConverter.java
License:Open Source License
private static ModuleDTO parseModuleJSON(JsonObject jsonModule) { UUID id = UUID.fromString(jsonModule.get("id").getAsString()); String type = jsonModule.get("type").getAsString(); UUID[] next = null, prev = null; Map<String, String> properties = new HashMap<String, String>(); if (jsonModule.has("next")) { if (jsonModule.get("next").isJsonArray()) { JsonArray jsonNext = jsonModule.get("next").getAsJsonArray(); next = new UUID[jsonNext.size()]; int i = 0; Iterator<JsonElement> it = jsonNext.iterator(); while (it.hasNext()) { JsonElement e = it.next(); next[i++] = UUID.fromString(e.getAsString()); }// w w w . j a va 2 s . c o m } else { next = new UUID[1]; next[0] = UUID.fromString(jsonModule.get("next").getAsString()); } } if (jsonModule.has("prev")) { if (jsonModule.get("prev").isJsonArray()) { JsonArray jsonPrev = jsonModule.get("prev").getAsJsonArray(); prev = new UUID[jsonPrev.size()]; int i = 0; Iterator<JsonElement> it = jsonPrev.iterator(); while (it.hasNext()) { JsonElement e = it.next(); prev[i++] = UUID.fromString(e.getAsString()); } } else { prev = new UUID[1]; prev[0] = UUID.fromString(jsonModule.get("prev").getAsString()); } } // TODO this uses the old model where properties where just stored as flatmap for (Entry<String, JsonElement> property : jsonModule.entrySet()) { String key = property.getKey(); if (key.equals("id") || key.equals("type") || key.equals("prev") || key.equals("next")) { continue; // this is only for module-specific properties } properties.put(property.getKey(), property.getValue().getAsString()); } // TODO evolve to a separate "properties" item if (jsonModule.has("properties")) { JsonObject jsonProperties = jsonModule.get("properties").getAsJsonObject(); for (Entry<String, JsonElement> jsonProperty : jsonProperties.entrySet()) { String key = jsonProperty.getKey(); String value = jsonProperty.getValue().getAsString(); properties.put(key, value); } } ModuleDTO dto = new ModuleDTO(id, type, next, prev, properties); return dto; }
From source file:br.com.caelum.vraptor.serialization.gson.CalendarGsonConverter.java
License:Open Source License
@Override public Calendar deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { return DatatypeConverter.parseDate(json.getAsString()); }
From source file:br.com.caelum.vraptor.serialization.gson.DateGsonConverter.java
License:Open Source License
@Override public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { try {//from w w w .ja v a2s .c o m return iso8601Format.parse(json.getAsString()); } catch (ParseException e) { throw new JsonSyntaxException(json.getAsString(), e); } }