List of usage examples for com.google.gson JsonArray get
public JsonElement get(int i)
From source file:com.adobe.acs.commons.remoteassets.impl.RemoteAssetsNodeSyncImpl.java
License:Apache License
/** * Set generic array property for a resource, based on an array found in the retrieved JSON. * * @param jsonArray JsonArray/* w ww. j av a2s .com*/ * @param key String * @param resource Resource * @throws RepositoryException exception */ private void setNodeSimpleArrayProperty(final JsonArray jsonArray, final String key, final Resource resource) throws RepositoryException { JsonPrimitive firstVal = jsonArray.get(0).getAsJsonPrimitive(); try { Object[] values; if (firstVal.isBoolean()) { values = new Boolean[jsonArray.size()]; for (int i = 0; i < jsonArray.size(); i++) { values[i] = jsonArray.get(i).getAsBoolean(); } } else if (DECIMAL_REGEX.matcher(firstVal.getAsString()).matches()) { values = new BigDecimal[jsonArray.size()]; for (int i = 0; i < jsonArray.size(); i++) { values[i] = jsonArray.get(i).getAsBigDecimal(); } } else if (firstVal.isNumber()) { values = new Long[jsonArray.size()]; for (int i = 0; i < jsonArray.size(); i++) { values[i] = jsonArray.get(i).getAsLong(); } } else { values = new String[jsonArray.size()]; for (int i = 0; i < jsonArray.size(); i++) { values[i] = jsonArray.get(i).getAsString(); } } ValueMap resourceProperties = resource.adaptTo(ModifiableValueMap.class); resourceProperties.put(key, values); LOG.trace("Array property '{}' added for resource '{}'", key, resource.getPath()); } catch (Exception e) { LOG.error("Unable to assign property '{}' to resource '{}'", key, resource.getPath(), e); } }
From source file:com.adobe.acs.commons.workflow.bulk.removal.impl.servlets.RemoveServlet.java
License:Apache License
@Override public final void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); List<String> statuses = new ArrayList<>(); List<String> models = new ArrayList<>(); List<Pattern> payloads = new ArrayList<>(); Calendar olderThan = null;/*from ww w . j av a 2 s . c o m*/ try { JsonObject params = toJsonObject(request.getParameter("params")); JsonArray jsonArray = params.getAsJsonArray(PARAM_WORKFLOW_STATUSES); for (int i = 0; i < jsonArray.size(); i++) { statuses.add(jsonArray.get(i).getAsString()); } jsonArray = params.getAsJsonArray(PARAM_WORKFLOW_MODELS); for (int i = 0; i < jsonArray.size(); i++) { models.add(jsonArray.get(i).getAsString()); } jsonArray = params.getAsJsonArray(PARAM_WORKFLOW_PAYLOADS); for (int i = 0; i < jsonArray.size(); i++) { final JsonObject tmp = jsonArray.get(i).getAsJsonObject(); final String pattern = getString(tmp, "pattern"); if (StringUtils.isNotBlank(pattern)) { payloads.add(Pattern.compile(pattern)); } } final Long ts = getLong(params, PARAM_OLDER_THAN); if (ts != null && ts > 0) { olderThan = Calendar.getInstance(); olderThan.setTimeInMillis(ts * MS_IN_SECOND); } int batchSize = getInteger(params, PARAM_BATCH_SIZE); if (batchSize < 1) { batchSize = DEFAULT_BATCH_SIZE; } int maxDuration = getInteger(params, PARAM_MAX_DURATION); if (maxDuration < 1) { maxDuration = DEFAULT_MAX_DURATION; } workflowInstanceRemover.removeWorkflowInstances(request.getResourceResolver(), models, statuses, payloads, olderThan, batchSize, maxDuration); } catch (WorkflowRemovalForceQuitException e) { response.setStatus(599); response.getWriter().write("Workflow removal force quit"); } catch (Exception e) { log.error("An error occurred while attempting to remove workflow instances.", e); response.setStatus(SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR); if (response.getWriter() != null) { response.getWriter().write(e.getMessage()); } } }
From source file:com.adssets.ejb.DataAccess.java
@Override public String buildFeedForMarket(String marketId, String lazyLoad) { JsonArray jsonArray = new JsonArray(); JsonParser parser = new JsonParser(); // Feed feed = feedFacade.find(marketId); Market market = marketFacade.find(Integer.valueOf(marketId)); List<Feed> feeds = em.createNamedQuery("Feed.findByMarketId").setParameter("marketId", market) .getResultList();//from w ww . j av a 2s. c o m if (feeds.size() > 0) { for (Feed feed : feeds) { JsonObject obj = new JsonObject(); obj.addProperty("id", feed.getId()); obj.addProperty("marketId", feed.getIdmarket().getId()); obj.addProperty("json", feed.getJson()); jsonArray.add(obj); } JsonObject obj = jsonArray.get(0).getAsJsonObject(); String objArray = obj.get("json").getAsString(); JsonArray objArrayParsed = parser.parse(objArray).getAsJsonArray(); JsonArray objData = new JsonArray(); for (JsonElement objId : objArrayParsed) { JsonObject objElmParsed = parser.parse(objId.toString()).getAsJsonObject(); System.out.println(objElmParsed); // try{ // isInteger(objId.getAsString()); String value = objElmParsed.get("type").getAsString(); System.out.println(value); //CHANGE ADPICTURE TO THE PICTURE STORED IN THE DATABASE if (value.equals("object")) { String result = scout24.getApartments(objElmParsed.get("objectid").getAsString()); if (!result.equals("{\"error\":1}")) { JsonObject resultObj = parser.parse(result).getAsJsonObject(); String link = "{\"link\": \"https://www.immobilienscout24.de/expose/" + objElmParsed.get("objectid").getAsInt() + "?referrer=\"}"; JsonObject clickLink = parser.parse(link).getAsJsonObject(); resultObj.add("clickLink", clickLink); resultObj.add("objectId", objElmParsed.get("objectid")); resultObj.add("marketId", parser.parse(marketId)); // Use the selected image as ad image JsonObject objHref = new JsonObject(); objHref.add("href", objElmParsed.get("url")); resultObj.add("adpicture", objHref); //If lazyLoad = yes dont return "allpictures" LazyLoad=yes is the parameter the ad will send so it does not get unneccesary data if (lazyLoad.equals("yes")) { resultObj.remove("allpictures"); } objData.add(resultObj); } } else { objData.add(objId); } // }catch(UnsupportedOperationException ex){ // objData.add(objId); // } } return objData.toString(); } else { return new JsonArray().toString(); } }
From source file:com.aliyun.odps.udf.utils.CounterUtils.java
License:Apache License
private static void fromJson(CounterGroup group, JsonObject obj) { JsonArray counterArray = obj.get("counters").getAsJsonArray(); for (int i = 0; i < counterArray.size(); i++) { JsonObject subObj = counterArray.get(i).getAsJsonObject(); String counterName = subObj.get("name").getAsString(); Counter counter = group.findCounter(counterName); long value = subObj.get("value").getAsLong(); counter.increment(value);//from ww w.ja va 2 s .c o m } }
From source file:com.amsterdam.marktbureau.makkelijkemarkt.DagvergunningFragment.java
License:Mozilla Public License
/** * Populate overzicht fragment from local member vars *///from w ww . j av a2 s . c om private void populateOverzichtFragment() { if (mOverzichtFragmentReady) { // TODO: show the changes in case we are editing an existing dagvergunning // koopman if (mKoopmanId > 0) { mOverzichtFragment.mKoopmanLinearLayout.setVisibility(View.VISIBLE); mOverzichtFragment.mKoopmanEmptyTextView.setVisibility(View.GONE); // koopman details mOverzichtFragment.setKoopman(mKoopmanId); // dagvergunning registratie tijd if (mRegistratieDatumtijd != null) { try { Date registratieDate = new SimpleDateFormat(getString(R.string.date_format_datumtijd), Locale.getDefault()).parse(mRegistratieDatumtijd); SimpleDateFormat sdf = new SimpleDateFormat(getString(R.string.date_format_tijd)); String registratieTijd = sdf.format(registratieDate); mOverzichtFragment.mRegistratieDatumtijdText.setText(registratieTijd); } catch (java.text.ParseException e) { Utility.log(getContext(), LOG_TAG, "Format registratie tijd failed: " + e.getMessage()); } } else { mOverzichtFragment.mRegistratieDatumtijdText.setText(""); } // dagvergunning notitie if (mNotitie != null && !mNotitie.equals("")) { mOverzichtFragment.mNotitieText.setText(getString(R.string.label_notitie) + ": " + mNotitie); Utility.collapseView(mOverzichtFragment.mNotitieText, false); } else { Utility.collapseView(mOverzichtFragment.mNotitieText, true); } // dagvergunning totale lengte if (mTotaleLengte != -1) { mOverzichtFragment.mTotaleLengte .setText(mTotaleLengte + " " + getString(R.string.length_meter)); } // registratie account naam if (mRegistratieAccountNaam != null) { mOverzichtFragment.mAccountNaam.setText(mRegistratieAccountNaam); } else { mOverzichtFragment.mAccountNaam.setText(""); } // koopman aanwezig status if (mKoopmanAanwezig != null) { // get the corresponding aanwezig title from the resource array based on the aanwezig key String[] aanwezigKeys = getResources().getStringArray(R.array.array_aanwezig_key); String[] aanwezigTitles = getResources().getStringArray(R.array.array_aanwezig_title); String aanwezigTitle = ""; for (int i = 0; i < aanwezigKeys.length; i++) { if (aanwezigKeys[i].equals(mKoopmanAanwezig)) { aanwezigTitle = aanwezigTitles[i]; } } mOverzichtFragment.mAanwezigText.setText(aanwezigTitle); } // vervanger if (mVervangerId > 0) { // hide the aanwezig status and populate and show the vervanger details mOverzichtFragment.mAanwezigText.setVisibility(View.GONE); mOverzichtFragment.mVervangerDetail.setVisibility(View.VISIBLE); mOverzichtFragment.setVervanger(mVervangerId); } else { // show the aanwezig status and hide the vervanger details mOverzichtFragment.mAanwezigText.setVisibility(View.VISIBLE); mOverzichtFragment.mVervangerDetail.setVisibility(View.GONE); } } else { mOverzichtFragment.mKoopmanEmptyTextView.setVisibility(View.VISIBLE); mOverzichtFragment.mKoopmanLinearLayout.setVisibility(View.GONE); } // product if (mErkenningsnummer != null && isProductSelected()) { // show progress bar mProgressbar.setVisibility(View.VISIBLE); // disable save function until we have a response from the api for a concept factuur mConceptFactuurDownloaded = false; // post the dagvergunning details to the api and retrieve a concept 'factuur' ApiPostDagvergunningConcept postDagvergunningConcept = new ApiPostDagvergunningConcept( getContext()); postDagvergunningConcept.setPayload(dagvergunningToJson()); postDagvergunningConcept.enqueue(new Callback<JsonObject>() { @Override public void onResponse(Response<JsonObject> response) { // hide progress bar mProgressbar.setVisibility(View.GONE); if (response.isSuccess() && response.body() != null) { mOverzichtFragment.mProductenLinearLayout.setVisibility(View.VISIBLE); mOverzichtFragment.mProductenEmptyTextView.setVisibility(View.GONE); // enable save function and give wizard next button background enabled color mConceptFactuurDownloaded = true; mWizardNextButton .setBackgroundColor(ContextCompat.getColor(getContext(), R.color.accent)); // from the response, populate the product section of the overzicht fragment View overzichtView = mOverzichtFragment.getView(); if (overzichtView != null) { // find placeholder table layout view TableLayout placeholderLayout = (TableLayout) overzichtView .findViewById(R.id.producten_placeholder); if (placeholderLayout != null) { placeholderLayout.removeAllViews(); LayoutInflater layoutInflater = (LayoutInflater) getActivity() .getSystemService(Context.LAYOUT_INFLATER_SERVICE); // get the producten array JsonArray producten = response.body().getAsJsonArray(getString( R.string.makkelijkemarkt_api_dagvergunning_concept_producten)); if (producten != null) { int rowCount = 0; // table header View headerLayout = layoutInflater .inflate(R.layout.dagvergunning_overzicht_product_item, null); TextView btwHeaderText = (TextView) headerLayout .findViewById(R.id.btw_totaal); btwHeaderText.setText("BTW"); TextView exclusiefHeaderText = (TextView) headerLayout .findViewById(R.id.bedrag_totaal); exclusiefHeaderText.setText("Ex. BTW"); placeholderLayout.addView(headerLayout, rowCount++); for (int i = 0; i < producten.size(); i++) { JsonObject product = producten.get(i).getAsJsonObject(); // get the product item layout View childLayout = layoutInflater .inflate(R.layout.dagvergunning_overzicht_product_item, null); // aantal if (product.get("aantal") != null && !product.get("aantal").isJsonNull()) { TextView aantalText = (TextView) childLayout .findViewById(R.id.product_aantal); aantalText.setText(product.get("aantal").getAsInt() + " x "); } // naam if (product.get("naam") != null && !product.get("naam").isJsonNull()) { TextView naamText = (TextView) childLayout .findViewById(R.id.product_naam); naamText.setText( Utility.capitalize(product.get("naam").getAsString())); } // btw % if (product.get("btw_percentage") != null && !product.get("btw_percentage").isJsonNull()) { long btwPercentage = Math.round(Double .parseDouble(product.get("btw_percentage").getAsString())); if (btwPercentage != 0) { TextView btwPercentageText = (TextView) childLayout .findViewById(R.id.btw_percentage); btwPercentageText.setText(btwPercentage + "%"); } } // btw totaal if (product.get("btw_totaal") != null && !product.get("btw_totaal").isJsonNull()) { double btwTotaalProduct = Double .parseDouble(product.get("btw_totaal").getAsString()); TextView btwTotaalText = (TextView) childLayout .findViewById(R.id.btw_totaal); if (Math.round(btwTotaalProduct) != 0) { btwTotaalText .setText(String.format(" %.2f", btwTotaalProduct)); } else { btwTotaalText.setText("-"); } } // bedrag totaal if (product.get("totaal") != null && !product.get("totaal").isJsonNull()) { double bedragTotaal = Double .parseDouble(product.get("totaal").getAsString()); TextView bedragTotaalText = (TextView) childLayout .findViewById(R.id.bedrag_totaal); bedragTotaalText.setText(String.format(" %.2f", bedragTotaal)); } // add child view placeholderLayout.addView(childLayout, rowCount++); } // exclusief double exclusief = 0; if (response.body().get("exclusief") != null && !response.body().get("exclusief").isJsonNull()) { exclusief = Double .parseDouble(response.body().get("exclusief").getAsString()); } // totaal double totaal = 0; if (response.body().get("totaal") != null && !response.body().get("totaal").isJsonNull()) { totaal = response.body().get("totaal").getAsDouble(); } // totaal btw en ex. btw View totaalLayout = layoutInflater .inflate(R.layout.dagvergunning_overzicht_product_item, null); TextView naamText = (TextView) totaalLayout.findViewById(R.id.product_naam); naamText.setText("Totaal"); TextView btwTotaalText = (TextView) totaalLayout .findViewById(R.id.btw_totaal); if (Math.round(totaal - exclusief) != 0) { btwTotaalText.setText(String.format(" %.2f", (totaal - exclusief))); } TextView exclusiefText = (TextView) totaalLayout .findViewById(R.id.bedrag_totaal); exclusiefText.setText(String.format(" %.2f", exclusief)); placeholderLayout.addView(totaalLayout, rowCount++); // separator View emptyLayout = layoutInflater .inflate(R.layout.dagvergunning_overzicht_product_item, null); placeholderLayout.addView(emptyLayout, rowCount++); // totaal inc. btw View totaalIncLayout = layoutInflater .inflate(R.layout.dagvergunning_overzicht_product_item, null); TextView totaalNaamText = (TextView) totaalIncLayout .findViewById(R.id.product_naam); totaalNaamText.setText("Totaal inc. BTW"); TextView totaalIncText = (TextView) totaalIncLayout .findViewById(R.id.bedrag_totaal); totaalIncText.setText(String.format(" %.2f", totaal)); placeholderLayout.addView(totaalIncLayout, rowCount); } } } } } @Override public void onFailure(Throwable t) { mProgressbar.setVisibility(View.GONE); } }); } else { mOverzichtFragment.mProductenLinearLayout.setVisibility(View.GONE); if (mKoopmanId > 0) { mOverzichtFragment.mProductenEmptyTextView.setVisibility(View.VISIBLE); } } } }
From source file:com.android.tools.idea.gradle.structure.model.repositories.search.JCenterRepository.java
License:Apache License
SearchResult parse(@NotNull Reader response) { /*/*from w w w .j a v a2 s. c om*/ Sample response: [ { "name": "com.atlassian.guava:guava", "repo": "jcenter", "owner": "bintray", "desc": null, "system_ids": [ "com.atlassian.guava:guava" ], "versions": [ "15.0" ], "latest_version": "15.0" }, { "name": "com.atlassian.bundles:guava", "repo": "jcenter", "owner": "bintray", "desc": null, "system_ids": [ "com.atlassian.bundles:guava" ], "versions": [ "8.1", "8.0", "1.0-actually-8.1" ], "latest_version": "8.1" }, { "name": "io.janusproject.guava:guava", "repo": "jcenter", "owner": "bintray", "desc": null, "system_ids": [ "io.janusproject.guava:guava" ], "versions": [ "19.0.0", "17.0.2", "17.0" ], "latest_version": "19.0.0" }, { "name": "com.google.guava:guava", "repo": "jcenter", "owner": "bintray", "desc": "Guava is a suite of core and expanded libraries that include\n utility classes, google's collections, io classes, and much\n much more.\n\n Guava has two code dependencies - javax.annotation\n per the JSR-305 spec and javax.inject per the JSR-330 spec.", "system_ids": [ "com.google.guava:guava" ], "versions": [ "19.0", "19.0-rc3", "19.0-rc2", "19.0-rc1", "18.0", "18.0-rc2", "18.0-rc1", "11.0.2-atlassian-02", "17.0", "17.0-rc2", "17.0-rc1", "16.0.1", "16.0", "16.0-rc1", "15.0", "15.0-rc1", "14.0.1", "14.0", "14.0-rc3", "14.0-rc2", "14.0-rc1", "13.0.1", "13.0", "13.0-final", "13.0-rc2", "13.0-rc1", "12.0.1", "12.0", "12.0-rc2", "12.0-rc1", "11.0.2-atlassian-01", "11.0.2", "11.0.1", "11.0", "11.0-rc1", "10.0.1", "10.0", "10.0-rc3", "10.0-rc2", "10.0-rc1", "r09", "r08", "r07", "r06", "r05", "r03" ], "latest_version": "19.0" } ] */ JsonParser parser = new JsonParser(); JsonArray array = parser.parse(response).getAsJsonArray(); int totalFound = array.size(); List<FoundArtifact> artifacts = Lists.newArrayListWithExpectedSize(totalFound); for (int i = 0; i < totalFound; i++) { JsonObject root = array.get(i).getAsJsonObject(); String name = root.getAsJsonPrimitive("name").getAsString(); List<GradleVersion> availableVersions = Lists.newArrayList(); JsonArray versions = root.getAsJsonArray("versions"); versions.forEach(element -> { String version = element.getAsString(); availableVersions.add(GradleVersion.parse(version)); }); List<String> coordinate = Splitter.on(GRADLE_PATH_SEPARATOR).splitToList(name); assert coordinate.size() == 2; artifacts.add(new FoundArtifact(getName(), coordinate.get(0), coordinate.get(1), availableVersions)); } return new SearchResult(getName(), artifacts, totalFound); }
From source file:com.android.tools.lint.checks.AppLinksAutoVerifyDetector.java
License:Apache License
/** * Gets the package names of all the apps from the Digital Asset Links JSON file. * * @param element The JsonElement of the json file. * @return All the package names.//ww w. j a va 2 s. co m */ private static List<String> getPackageNameFromJson(JsonElement element) { List<String> packageNames = Lists.newArrayList(); if (element instanceof JsonArray) { JsonArray jsonArray = (JsonArray) element; for (int i = 0; i < jsonArray.size(); i++) { JsonElement app = jsonArray.get(i); if (app instanceof JsonObject) { JsonObject target = ((JsonObject) app).getAsJsonObject("target"); if (target != null) { // Checks namespace to ensure it is an app statement. JsonElement namespace = target.get("namespace"); JsonElement packageName = target.get("package_name"); if (namespace != null && namespace.getAsString().equals("android_app") && packageName != null) { packageNames.add(packageName.getAsString()); } } } } } return packageNames; }
From source file:com.apcb.utils.utils.HtmlTemplateReader.java
private SectionMatch readJson(JsonElement jsonElement, String from, SectionMatch sectionMatch) { //log.info(jsonElement.toString()); //SectionMatch sectionMatchChild = new SectionMatch(from); if (jsonElement.isJsonArray()) { //log.info("JsonArray"); JsonArray jsonArray = jsonElement.getAsJsonArray(); for (int i = 0; i < jsonArray.size(); i++) { SectionMatch sectionMatchArrayLevel = new SectionMatch(sectionMatch.getName()); sectionMatchArrayLevel.setIndex(i); sectionMatch.putChildens(readJson(jsonArray.get(i), from + "[" + i + "]", sectionMatchArrayLevel)); }/* w w w . j av a 2s. co m*/ } else if (jsonElement.isJsonObject()) { //log.info("JsonObject"); JsonObject jsonObject = jsonElement.getAsJsonObject(); //since you know it's a JsonObject Set<Map.Entry<String, JsonElement>> entries = jsonObject.entrySet();//will return members of your object for (Map.Entry<String, JsonElement> entry : entries) { //log.info(entry.getKey()); sectionMatch.putChildens(readJson(jsonObject.get(entry.getKey()), from + "." + entry.getKey(), new SectionMatch(entry.getKey()))); } } else if (jsonElement.isJsonNull()) { log.info("JsonNull"); } else if (jsonElement.isJsonPrimitive()) { //log.info("JsonPrimitive"); String jsonVal = jsonElement.getAsString(); //from+= "."+entry.getKey(); sectionMatch.setValue(jsonVal); log.info(from + "=" + jsonVal); } return sectionMatch; }
From source file:com.appdynamics.monitors.boundary.BoundaryWrapper.java
License:Apache License
/** * Constructs a metrics map based on the Json response data retrieved from the REST API * @param responseData The extracted 'data' field from the Json response * @param metricsMap Map that is to be populated with metrics parsed from the responseData * @param meterName Name of the Boundary application node *///w w w . j av a 2s.com private void populateMetricsMap(JsonArray responseData, Map metricsMap, String meterName) throws Exception { for (int i = 0; i < responseData.size(); i++) { JsonArray ipMetricsArray = responseData.get(i).getAsJsonArray(); HashMap<String, Long> ipMetrics = new HashMap<String, Long>(); for (int j = 1; j < ipMetricsArray.size(); j++) { ipMetrics.put(metricNames.get(j - 1), ipMetricsArray.get(j).getAsLong()); } metricsMap.put(meterName, ipMetrics); } }
From source file:com.appdynamics.monitors.boundary.BoundaryWrapper.java
License:Apache License
/** * Retrieves observation domain ids from the /meters REST request * @return Map A map containing the name of the meter and it's corresponding observationDomainId *///w ww. j a v a 2s.c om private void populateObservationDomainIds() throws Exception { HttpGet httpGet = new HttpGet(constructMetersURL()); httpGet.addHeader(BasicScheme.authenticate(new UsernamePasswordCredentials(apiKey, ""), "UTF-8", false)); HttpClient httpClient = new DefaultHttpClient(); HttpResponse response = httpClient.execute(httpGet); HttpEntity entity = response.getEntity(); BufferedReader bufferedReader2 = new BufferedReader(new InputStreamReader(entity.getContent())); StringBuilder responseString = new StringBuilder(); String line = ""; while ((line = bufferedReader2.readLine()) != null) { responseString.append(line); } JsonArray responseArray = new JsonParser().parse(responseString.toString()).getAsJsonArray(); for (int i = 0; i < responseArray.size(); i++) { JsonObject obj = responseArray.get(i).getAsJsonObject(); meterIds.put(obj.get("name").getAsString(), obj.get("obs_domain_id").getAsString()); } }