List of usage examples for com.google.gson JsonArray size
public int size()
From source file:com.goodow.realtime.server.presence.PresenceHandler.java
License:Apache License
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { boolean isConnect; if (req.getRequestURI().endsWith(Services.PRESENCE_CONNECT)) { isConnect = true;/*from w ww . j a v a2 s .co m*/ } else if (req.getRequestURI().endsWith(Services.PRESENCE_DISCONNECT)) { isConnect = false; } else { throw new IllegalArgumentException( "Can't determine the type of channel presence from the path: " + req.getRequestURI()); } String sessionId = req.getParameter(Params.SESSION_ID); String json = RpcUtil.readRequestBody(req); if (json == null || json.isEmpty()) { assert !isConnect; presenceEndpoint.get().disconnect(sessionId, null); return; } JsonObject payload = new JsonParser().parse(json).getAsJsonObject(); JsonArray ids = payload.get(Params.IDS).getAsJsonArray(); List<String> docIds = new ArrayList<String>(ids.size()); int i = 0; for (JsonElement e : ids) { docIds.add(i++, e.getAsString()); } if (isConnect) { presenceEndpoint.get().connect(sessionId, docIds); } else { presenceEndpoint.get().disconnect(sessionId, docIds); } super.doPost(req, resp); }
From source file:com.goodow.realtime.server.rpc.PollHandler.java
License:Apache License
private JsonArray fetchDeltas(JsonArray ids, String sessionId) throws IOException, SlobNotFoundException, AccessDeniedException { JsonArray msgs = new JsonArray(); SlobStore store = slobFacilities.getSlobStore(); String token = null;// w w w .jav a2 s .com for (JsonElement elem : ids) { JsonArray array = elem.getAsJsonArray(); ObjectId key = new ObjectId(array.get(0).getAsString()); long startRev = array.get(1).getAsLong(); Long endVersion = array.size() >= 3 ? array.get(2).getAsLong() : null; ConnectResult r = null; try { r = store.reconnect(key, new Session(context.get().getAccountInfo().getUserId(), sessionId)); } catch (SlobNotFoundException e) { if (startRev == 1) { continue; } throw e; } if (r.getChannelToken() != null) { assert token == null || token.equals(r.getChannelToken()); token = r.getChannelToken(); } JsonObject msg = new JsonObject(); msg.addProperty(Params.ID, key.toString()); boolean isEmpty = deltaHandler.fetchDeltas(msg, key, startRev - 1, endVersion); if (!isEmpty) { msgs.add(msg); } } if (token != null) { JsonObject tokenMsg = new JsonObject(); tokenMsg.addProperty(Params.ID, Params.TOKEN); tokenMsg.addProperty(Params.TOKEN, token); msgs.add(tokenMsg); } return msgs; }
From source file:com.goodow.realtime.server.rpc.SaveHandler.java
License:Apache License
@Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { String sid = requireParameter(req, Constants.Params.SESSION_ID); String key = requireParameter(req, Constants.Params.ID); JsonObject payload = new JsonParser().parse(RpcUtil.readRequestBody(req)).getAsJsonObject(); long version = payload.get(Params.REVISION).getAsLong(); String changes = payload.get(Params.CHANGES).toString(); ObjectId id = new ObjectId(key); Session session = new Session(context.get().getAccountInfo().getUserId(), sid); long resultingVersion; if (version == 0) { JsonArray jsonArray = new JsonParser().parse(changes).getAsJsonArray(); List<Delta<String>> deltas = new ArrayList<Delta<String>>(jsonArray.size()); for (JsonElement e : jsonArray) { deltas.add(new Delta<String>(session, e.toString())); }// ww w . j av a 2s. c o m loader.create(id, deltas); resultingVersion = deltas.size(); } else { ServerMutateRequest mutateRequest = new ServerMutateRequest(); mutateRequest.setSession(new ObjectSession(id, session)); mutateRequest.setVersion(version); mutateRequest.setDeltas(changes); MutateResult res; try { res = slobFacilities.getSlobStore().mutateObject(mutateRequest); } catch (SlobNotFoundException e) { throw new BadRequestException("Object not found or access denied", e); } catch (AccessDeniedException e) { throw new BadRequestException("Object not found or access denied", e); } resultingVersion = res.getResultingVersion(); } JsonObject json = new JsonObject(); json.addProperty(Constants.Params.REVISION, resultingVersion); RpcUtil.writeJsonResult(req, resp, json.toString()); }
From source file:com.google.api.ads.adwords.awalerting.processor.AlertActionsProcessor.java
License:Open Source License
/** * @param configs the JSON array of alert actions configurations * @param numThreads the number of threads to use */// w w w .j a v a 2 s. com public AlertActionsProcessor(JsonArray configs, int numThreads) { this.numThreads = numThreads; actions = new ArrayList<AlertAction>(configs.size()); for (JsonElement config : configs) { try { AlertAction action = getActionObject(config.getAsJsonObject()); actions.add(action); } catch (Exception e) { LOGGER.error("Error constructing alert action.", e); LOGGER.error("Problemetic config: {}", config); throw new IllegalArgumentException("Wrong AlertAction config.", e); } } }
From source file:com.google.api.ads.adwords.awalerting.processor.AlertRulesProcessor.java
License:Open Source License
/** * @param configs the JSON array of alert rules configurations, could be null * @param alertMessage the alert message template string * @param numThreads the number of threads to use *//*from w ww. j a v a 2 s . c o m*/ public AlertRulesProcessor(JsonArray configs, String alertMessage, int numThreads) { this.rules = new ArrayList<AlertRule>(configs == null ? 0 : configs.size()); this.alertMessage = alertMessage; this.numThreads = numThreads; if (configs != null) { for (JsonElement config : configs) { try { AlertRule rule = getRuleObject(config.getAsJsonObject()); rules.add(rule); } catch (AlertConfigLoadException e) { // Skip this rule, and try next one LOGGER.error(e.toString()); } } } }
From source file:com.google.api.ads.adwords.awalerting.sampleimpl.downloader.SqlDbReportDownloader.java
License:Open Source License
/** * Get SQL query string according to config, and build column names list. * * @return the sql query string// w w w . ja v a2 s . c o m */ private String getSqlQueryWithReportColumnNames() { JsonObject queryConfig = getQueryConfig(); StringBuilder sqlQueryBuilder = new StringBuilder(); sqlQueryBuilder.append("SELECT "); Preconditions.checkArgument(queryConfig.has(COLUMN_MAPPINGS_TAG), "Missing compulsory property: %s - %s", REPORT_QUERY_TAG, COLUMN_MAPPINGS_TAG); JsonArray columnMappings = queryConfig.getAsJsonArray(COLUMN_MAPPINGS_TAG); // Use LinkedHashMap to preserve order (SQL query and result parsing must have matched order). Map<String, String> fieldsMapping = new LinkedHashMap<String, String>(columnMappings.size()); // Process database column -> report column mapping String dbColumnName; String reportColumnName; for (JsonElement columnMapping : columnMappings) { JsonObject mapping = columnMapping.getAsJsonObject(); Preconditions.checkArgument(mapping.has(DATABASE_COLUMN_NAME_TAG), "Missing compulsory property: %s - %s - %s", REPORT_QUERY_TAG, COLUMN_MAPPINGS_TAG, DATABASE_COLUMN_NAME_TAG); Preconditions.checkArgument(mapping.has(REPORT_COLUMN_NAME_TAG), "Missing compulsory property: %s - %s - %s", REPORT_QUERY_TAG, COLUMN_MAPPINGS_TAG, REPORT_COLUMN_NAME_TAG); dbColumnName = mapping.get(DATABASE_COLUMN_NAME_TAG).getAsString(); reportColumnName = mapping.get(REPORT_COLUMN_NAME_TAG).getAsString(); fieldsMapping.put(dbColumnName, reportColumnName); } sqlQueryBuilder.append(Joiner.on(", ").withKeyValueSeparator(" AS ").join(fieldsMapping)); Preconditions.checkArgument(queryConfig.has(TABLE_TAG), "Missing compulsory property: %s - %s", REPORT_QUERY_TAG, TABLE_TAG); sqlQueryBuilder.append(" FROM ").append(queryConfig.get(TABLE_TAG).getAsString()); boolean hasWhereClause = false; if (queryConfig.has(DATE_RANGE_TAG)) { DateRange dateRange = DateRange.fromString(queryConfig.get(DATE_RANGE_TAG).getAsString()); String dateRangeCondition = String.format(DATA_RANGE_CONDITION_FORMAT, DATE_COLUMN_NAME, dateRange.getStartDate(), dateRange.getEndDate()); sqlQueryBuilder.append(" WHERE ").append(dateRangeCondition); hasWhereClause = true; } if (queryConfig.has(CONDITIONS_TAG)) { sqlQueryBuilder.append(hasWhereClause ? " AND " : " WHERR ") .append(queryConfig.get(CONDITIONS_TAG).getAsString()); } String sqlQuery = sqlQueryBuilder.toString(); LOGGER.info("SQL query: {}", sqlQuery); return sqlQuery; }
From source file:com.google.api.ads.adwords.awalerting.sampleimpl.rule.ConvertMoneyValue.java
License:Open Source License
public ConvertMoneyValue(JsonObject config) { if (config.has(MONEY_FIELD_TAG) && config.has(MONEY_FIELDS_TAG)) { String errorMsg = String.format( "Error in ConvertMoneyValue constructor: cannot have both \"%s\" and \"%s\" in config.", MONEY_FIELD_TAG, MONEY_FIELDS_TAG); throw new IllegalArgumentException(errorMsg); }//from w w w . j a va 2 s . c om moneyFields = new HashSet<String>(); if (config.has(MONEY_FIELD_TAG)) { moneyFields.add(config.get(MONEY_FIELD_TAG).getAsString()); } else if (config.has(MONEY_FIELDS_TAG)) { JsonArray array = config.get(MONEY_FIELDS_TAG).getAsJsonArray(); for (int i = 0; i < array.size(); i++) { moneyFields.add(array.get(i).getAsString()); } } else { // Use default moneyFields.add(DEFAULT_MONEY_FIELD); } }
From source file:com.google.appinventor.components.runtime.Survey.java
License:Open Source License
/** * Creates a new Survey component./*from w ww .j av a 2 s . com*/ * * @param container * container the component will be placed in * @throws IOException */ public Survey(ComponentContainer container) throws IOException { super(container); mainUI = container.$form(); exportRoot = new java.io.File(Environment.getExternalStorageDirectory(), mainUI.getPackageName()) + java.io.File.separator + "export"; JsonParser parse = new JsonParser(); webview = new WebView(container.$context()); webview.getSettings().setJavaScriptEnabled(true); webview.setFocusable(true); webview.setVerticalScrollBarEnabled(true); container.$add(this); webview.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_UP: if (!v.hasFocus()) { v.requestFocus(); } break; } return false; } }); // set the initial default properties. Height and Width // will be fill-parent, which will be the default for the web viewer. Width(LENGTH_FILL_PARENT); Height(LENGTH_FILL_PARENT); //set default survey style style = TEXTBOX; //default style // see if the Survey is created by someone tapping on a notification! // create the Survey and load it in the webviewer /* e.g. * value = { * "style": "multipleChoice", * "question": "What is your favorite food" * "options": ["apple", "banana", "strawberry", "orange"], * "surveyGroup": "MIT-food-survey" * } * */ initValues = container.$form().getSurveyStartValues(); Log.i(TAG, "startVal Suvey:" + initValues.toString()); if (initValues != "") { JsonObject values = (JsonObject) parse.parse(initValues); this.style = values.get("style").getAsString(); this.question = values.get("question").getAsString(); this.surveyGroup = values.get("surveyGroup").getAsString(); ArrayList<String> arrOptions = new ArrayList<String>(); JsonArray _options = values.get("options").getAsJsonArray(); for (int i = 0; i < _options.size(); i++) { arrOptions.add(_options.get(i).getAsString()); } this.options = arrOptions; this.styleFromIntent = values.get("style").getAsString(); Log.i(TAG, "Survey component got created"); } }
From source file:com.google.cloud.das.languagecheck.Translate.java
License:Apache License
public Hashtable<String, String> getLanguagesFromAPI() { String response;/* www . j a v a 2 s .com*/ String path = "/languages"; String query = "?target=" + target + "&key=" + key; String url = baseurl + path + query; Hashtable<String, String> hash = new Hashtable<String, String>(); try { response = sendGet(url); //System.out.println(response); } catch (Exception e) { //do something clever with the exception response = "{}"; System.out.println(e.getMessage()); } JsonParser jsonParser = new JsonParser(); JsonArray arr = jsonParser.parse(response).getAsJsonObject().getAsJsonObject("data") .getAsJsonArray("languages"); for (int i = 0; i < arr.size(); i++) { JsonElement el = arr.get(i).getAsJsonObject(); hash.put(el.getAsJsonObject().get("language").getAsString(), el.getAsJsonObject().get("name").getAsString()); } return hash; }
From source file:com.google.cloud.solutions.sampleapps.orchestration.orchestrator.server.GceInstanceRetriever.java
License:Open Source License
/** * Parses the response, which contains all information about the running VMs. Extracts only the * IPs and names, as they are all that the orchstrator needs. Adjust this implementation to suit * your needs if necessary./*from w w w . j a v a 2 s .c o m*/ * * @param instanceResponse the string containing the response from queriying "instances" for the * given project. * @param instancePrefix returns only instances with name that starts with the prefix as specified * in the configuration properties. * @return the extracted IP, or null if it can't be found. */ static Map<String, String> extractIpsAndInstanceNames(String instanceResponse, String instancePrefix) { JsonParser parser = new JsonParser(); JsonObject jsonObject = (JsonObject) parser.parse(instanceResponse); Map<String, String> gceIpsAndInstanceNames = new HashMap<String, String>(); JsonArray items = jsonObject.getAsJsonArray("items"); if (items != null) { for (int i = 0; i < items.size(); i++) { String natIp = items.get(i).getAsJsonObject().getAsJsonArray("networkInterfaces").get(0) .getAsJsonObject().getAsJsonArray("accessConfigs").get(0).getAsJsonObject().get("natIP") .getAsString(); String name = items.get(i).getAsJsonObject().get("name").getAsString(); if (name.startsWith(instancePrefix)) { gceIpsAndInstanceNames.put(natIp, name); } } } return gceIpsAndInstanceNames; }