List of usage examples for com.google.gson JsonArray get
public JsonElement get(int i)
From source file:com.birbit.jsonapi.JsonApiResourceDeserializer.java
License:Apache License
private List<String> parseIds(JsonArray jsonArray) { List<String> result = new ArrayList<String>(jsonArray.size()); for (int i = 0; i < jsonArray.size(); i++) { JsonElement item = jsonArray.get(i); if (item.isJsonObject()) { JsonElement idField = item.getAsJsonObject().get("id"); if (idField != null && idField.isJsonPrimitive()) { result.add(idField.getAsString()); }//from w w w . ja v a2 s .c om } } return result; }
From source file:com.bizosys.dataservice.sql.SqlSensorInputParser.java
License:Apache License
private static void addQuery(List<UnitStep> queryUnits, JsonObject queryObj, String queryId) throws ErrorCodeExp { AppConfig queryObject = QueryDefinationFactory.queryM.get(queryId); if (queryObject == null) { QueryDefinationFactory.refreshQueries(); queryObject = QueryDefinationFactory.queryM.get(queryId); }// w w w. ja v a2 s . c om if (queryObject == null) { throw new ErrorCodeExp(queryId, ErrorCodes.QUERY_NOT_FOUND, "Query Id " + queryId + " is not configured.", ErrorCodes.QUERY_KEY); } queryObject = queryObject.clone(); /** * Parameters */ List<Object> paramL = new ArrayList<Object>(); if (queryObj.has("params")) { JsonArray paramsArray = queryObj.get("params").getAsJsonArray(); int totalParam = paramsArray.size(); for (int i = 0; i < totalParam; i++) { String paramVal = paramsArray.get(i).getAsString(); if (paramVal.length() > 0) { if (paramVal.equals("__null") || paramVal.equals("null")) paramVal = null; } paramL.add(paramVal); } } /** * where, sort, offset, limit */ String where = (queryObj.has("where")) ? queryObj.get("where").getAsString() : null; String sort = (queryObj.has("sort")) ? queryObj.get("sort").getAsString() : null; int offset = (queryObj.has("offset")) ? queryObj.get("offset").getAsInt() : -1; int limit = (queryObj.has("limit")) ? queryObj.get("limit").getAsInt() : -1; /** * If there are any sequence ids to be generated then generate the ids * and add the generated sequenceids to the variables string. */ String variables = (queryObj.has("variables")) ? "{variables:" + queryObj.get("variables").getAsJsonArray().toString() + "}" : null; if (DEBUG_ENABLED && variables != null) LOG.debug("String variables are : " + variables); Boolean isRecursive = (queryObj.has("isRecursive")) ? queryObj.get("isRecursive").getAsBoolean() : false; /** * Single Expression */ UnitExpr expr = extractExpr(queryObj); /** * Boolean Expression */ List<UnitExpr> andExprs = booleanExprs(queryObj, true); List<UnitExpr> orExprs = booleanExprs(queryObj, false); JsonElement sequenceElem = null; if (queryObj.has("sequences")) sequenceElem = queryObj.get("sequences"); UnitQuery uq = new UnitQuery(queryObject, paramL, expr, andExprs, orExprs, where, sort, offset, limit, variables, isRecursive, sequenceElem); uq.isFunc = false; uq.stepId = queryId; queryUnits.add(uq); }
From source file:com.bizosys.dataservice.sql.SqlSensorInputParser.java
License:Apache License
public static Map<String, String> generateSequences(JsonElement sequenceElem) throws SQLException { JsonArray sequenceArray = sequenceElem.getAsJsonArray(); int totalSequence = sequenceArray.size(); Map<String, String> ids = new HashMap<String, String>(totalSequence); for (int i = 0; i < totalSequence; i++) { JsonObject sequenceKeyName = sequenceArray.get(i).getAsJsonObject(); String sequenceKey = sequenceKeyName.get("sequenceKey").getAsString(); String sequenceName = sequenceKeyName.get("sequenceName").getAsString(); int id = CachedIdGenerator.getInstance().generateId(sequenceKey); ids.put(sequenceName, Integer.toString(id)); }//from w ww . ja v a2 s . c o m return ids; }
From source file:com.blackducksoftware.integration.hub.api.report.ReportRestService.java
License:Apache License
/** * Gets the content of the report/*from www. jav a 2 s. c o m*/ * */ public VersionReport getReportContent(final String reportContentUrl) throws IOException, BDRestException, URISyntaxException { final HubRequest hubRequest = new HubRequest(getRestConnection()); hubRequest.setMethod(Method.GET); hubRequest.setLimit(HubRequest.EXCLUDE_INTEGER_QUERY_PARAMETER); hubRequest.setUrl(reportContentUrl); final JsonObject json = hubRequest.executeForResponseJson(); final JsonElement content = json.get("reportContent"); final JsonArray reportConentArray = content.getAsJsonArray(); final JsonObject reportFile = reportConentArray.get(0).getAsJsonObject(); final VersionReport report = getRestConnection().getGson().fromJson(reportFile.get("fileContent"), VersionReport.class); return report; }
From source file:com.blackducksoftware.integration.hub.HubIntRestService.java
License:Apache License
/** * Gets the content of the report/*from w w w . j a va2s. co m*/ * */ public VersionReport getReportContent(final String reportContentUrl) throws IOException, BDRestException, URISyntaxException { final ClientResource resource = hubServicesFactory.getRestConnection() .createClientResource(reportContentUrl); try { resource.setMethod(Method.GET); hubServicesFactory.getRestConnection().handleRequest(resource); final int responseCode = resource.getResponse().getStatus().getCode(); if (hubServicesFactory.getRestConnection().isSuccess(responseCode)) { final String response = hubServicesFactory.getRestConnection() .readResponseAsString(resource.getResponse()); final JsonObject json = hubServicesFactory.getRestConnection().getJsonParser().parse(response) .getAsJsonObject(); final JsonElement content = json.get("reportContent"); final JsonArray reportConentArray = content.getAsJsonArray(); final JsonObject reportFile = reportConentArray.get(0).getAsJsonObject(); final VersionReport report = hubServicesFactory.getRestConnection().getGson() .fromJson(reportFile.get("fileContent"), VersionReport.class); return report; } else if (responseCode == 412) { final String response = hubServicesFactory.getRestConnection() .readResponseAsString(resource.getResponse()); final JsonObject json = hubServicesFactory.getRestConnection().getJsonParser().parse(response) .getAsJsonObject(); final String errorMessage = json.get("errorMessage").getAsString(); throw new BDRestException(errorMessage + " Error Code: " + responseCode, resource); } else { throw new BDRestException( "There was a problem getting the content of this Report. Error Code: " + responseCode, resource); } } finally { releaseResource(resource); } }
From source file:com.blackypaw.mc.i18n.chat.ChatComponentDeserializer.java
License:Open Source License
/** * Deserializes a JSON formatted component array, e.g. '["Hey, ",{extra:["there!"]}]' * * @param json The JSON array to be deserialized into a chat component * * @return The deserialized chat component *//* www. ja v a2s . c o m*/ private ChatComponent deserializeComponentArray(JsonArray json) { // Each and every element inside a component array is a text component // The first element of the array is considered to be the parent component: if (json.size() <= 0) { return new TextComponent(""); } final TextComponent parent = this.deserializeTextComponent(json.get(0)); for (int i = 1; i < json.size(); ++i) { parent.addChild(this.deserializeTextComponent(json.get(i))); } return parent; }
From source file:com.blackypaw.mc.i18n.chat.ChatComponentDeserializer.java
License:Open Source License
/** * Creates a text component given its JSON representation. Both the shorthand notation as * a raw string as well as the notation as a full-blown JSON object are supported. * * @param json The JSON element to be deserialized into a text component * * @return The deserialized TextComponent */// w w w . j a va2s.c o m private TextComponent deserializeTextComponent(JsonElement json) { final TextComponent component = new TextComponent(""); if (json.isJsonPrimitive()) { JsonPrimitive primitive = json.getAsJsonPrimitive(); if (primitive.isString()) { component.setText(primitive.getAsString()); } } else if (json.isJsonObject()) { JsonObject object = json.getAsJsonObject(); if (object.has("text")) { JsonElement textElement = object.get("text"); if (textElement.isJsonPrimitive()) { JsonPrimitive textPrimitive = textElement.getAsJsonPrimitive(); if (textPrimitive.isString()) { component.setText(textPrimitive.getAsString()); } } } if (object.has("extra")) { JsonElement extraElement = object.get("extra"); if (extraElement.isJsonArray()) { JsonArray extraArray = extraElement.getAsJsonArray(); for (int i = 0; i < extraArray.size(); ++i) { JsonElement fieldElement = extraArray.get(i); component.addChild(this.deserializeComponent(fieldElement)); } } } } return component; }
From source file:com.brainardphotography.gravatar.contact.PCContactLoader.java
License:Apache License
@Override public PCContact loadContact(Reader reader) throws IOException { JsonElement element = jsonParser.parse(reader); JsonObject object = element.getAsJsonObject(); JsonArray entries = object.getAsJsonArray("entry"); if (entries.size() > 0) return gson.fromJson(entries.get(0), PCContact.class); return null;/*from w w w. jav a 2 s . c o m*/ }
From source file:com.buddycloud.channeldirectory.cli.Main.java
License:Apache License
@SuppressWarnings("static-access") public static void main(String[] args) throws Exception { JsonElement rootElement = new JsonParser().parse(new FileReader(QUERIES_FILE)); JsonArray rootArray = rootElement.getAsJsonArray(); Map<String, Query> queries = new HashMap<String, Query>(); for (int i = 0; i < rootArray.size(); i++) { JsonObject queryElement = rootArray.get(i).getAsJsonObject(); String queryName = queryElement.get("name").getAsString(); String type = queryElement.get("type").getAsString(); Query query = null;//from w ww . j a v a 2 s .c o m if (type.equals("solr")) { query = new QueryToSolr(queryElement.get("agg").getAsString(), queryElement.get("core").getAsString(), queryElement.get("q").getAsString()); } else if (type.equals("dbms")) { query = new QueryToDBMS(queryElement.get("q").getAsString()); } queries.put(queryName, query); } LinkedList<String> queriesNames = new LinkedList<String>(queries.keySet()); Collections.sort(queriesNames); Options options = new Options(); options.addOption(OptionBuilder.isRequired(true).withLongOpt("query").hasArg(true) .withDescription("The name of the query. Possible queries are: " + queriesNames).create('q')); options.addOption(OptionBuilder.isRequired(false).withLongOpt("args").hasArg(true) .withDescription("Arguments for the query").create('a')); options.addOption(new Option("?", "help", false, "Print this message")); CommandLineParser parser = new PosixParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (ParseException e) { printHelpAndExit(options); } if (cmd.hasOption("help")) { printHelpAndExit(options); } String queryName = cmd.getOptionValue("q"); String argsCmd = cmd.getOptionValue("a"); Properties configuration = ConfigurationUtils.loadConfiguration(); Query query = queries.get(queryName); if (query == null) { printHelpAndExit(options); } System.out.println(query.exec(argsCmd, configuration)); }
From source file:com.buddycloud.channeldirectory.crawler.node.ActivityHelper.java
License:Apache License
/** * @param postData//from w w w . j av a2 s . c om * @param dataSource * @param configuration * @throws ParseException */ public static void updateActivity(PostData postData, ChannelDirectoryDataSource dataSource, Properties properties) { String channelJid = postData.getParentSimpleId(); try { if (!isChannelRegistered(channelJid, properties)) { return; } } catch (Exception e1) { LOGGER.error("Could not retrieve channel info.", e1); return; } Long published = postData.getPublished().getTime(); long thisPostPublishedInHours = published / ONE_HOUR; ChannelActivity oldChannelActivity = null; try { oldChannelActivity = retrieveActivityFromDB(channelJid, dataSource); } catch (SQLException e) { return; } JsonArray newChannelHistory = new JsonArray(); long summarizedActivity = 0; boolean newActivity = true; if (oldChannelActivity != null) { newActivity = false; JsonArray oldChannelHistory = oldChannelActivity.activity; JsonObject firstActivityInWindow = oldChannelHistory.get(0).getAsJsonObject(); long firstActivityPublishedInHours = firstActivityInWindow.get(PUBLISHED_LABEL).getAsLong(); int hoursToAppend = (int) (firstActivityPublishedInHours - thisPostPublishedInHours); // Too old if (hoursToAppend + oldChannelHistory.size() >= DAY_IN_HOURS) { return; } // Crawled already if (postData.getPublished().compareTo(oldChannelActivity.earliest) >= 0 && postData.getPublished().compareTo(oldChannelActivity.updated) <= 0) { return; } for (int i = 0; i < hoursToAppend; i++) { JsonObject activityobject = new JsonObject(); activityobject.addProperty(PUBLISHED_LABEL, thisPostPublishedInHours + i); activityobject.addProperty(ACTIVITY_LABEL, 0); newChannelHistory.add(activityobject); } for (int i = 0; i < oldChannelHistory.size(); i++) { JsonObject activityObject = oldChannelHistory.get(i).getAsJsonObject(); summarizedActivity += activityObject.get(ACTIVITY_LABEL).getAsLong(); newChannelHistory.add(activityObject); } } else { JsonObject activityobject = new JsonObject(); activityobject.addProperty(PUBLISHED_LABEL, thisPostPublishedInHours); activityobject.addProperty(ACTIVITY_LABEL, 0); newChannelHistory.add(activityobject); } // Update first activity JsonObject firstActivity = newChannelHistory.get(0).getAsJsonObject(); firstActivity.addProperty(ACTIVITY_LABEL, firstActivity.get(ACTIVITY_LABEL).getAsLong() + 1); summarizedActivity += 1; if (newActivity) { insertActivityInDB(channelJid, newChannelHistory, summarizedActivity, postData.getPublished(), dataSource); } else { updateActivityInDB(channelJid, newChannelHistory, summarizedActivity, postData.getPublished(), dataSource); } }