List of usage examples for com.google.gson JsonObject toString
@Override
public String toString()
From source file:br.edu.ifc.fraiburgo.rubble.servlets.StatusServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("utf8"); String start = request.getParameter("start"); String limit = request.getParameter("limit"); PrintWriter out = response.getWriter(); response.setContentType("application/json"); response.setHeader("Cache-control", "no-cache, no-store"); response.setHeader("Pragma", "no-cache"); response.setHeader("Expires", "-1"); response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "GET,POST"); response.setHeader("Access-Control-Allow-Headers", "Content-Type"); response.setHeader("Access-Control-Max-Age", "86400"); boolean sucess = false; JsonArray arrayObj = new JsonArray(); JsonObject myObj = new JsonObject(); List<Comentario> comments = new ArrayList(); if (request.getParameter("action").equals("change")) { try {/*from ww w . jav a 2s. c o m*/ Postagem p = new PostagemController() .getPostagemById(Integer.parseInt(request.getParameter("idPostagem"))); Usuario u = new UsuarioController() .getUsuarioById(Integer.parseInt(request.getParameter("idUsuario"))); Status s = new Status(); s.setAtivo(true); s.setData(new Date()); s.setIdPostagem(p); s.setIdUsuario(u); s.setStatus(request.getParameter("status")); s = new StatusController().mergeStatus(s); new StatusController().setAllStatusInactive(s.getIdStatus(), p); s.setIdPostagem(null); s.setIdUsuario(null); Gson gson = new Gson(); JsonElement statusObj = gson.toJsonTree(s); myObj.add("status", statusObj); sucess = true; } catch (Exception e) { e.printStackTrace(); } } myObj.addProperty("success", sucess); out.println(myObj.toString()); out.close(); }
From source file:br.org.cesar.knot.lib.connection.KnotSocketIo.java
License:Open Source License
/** * This method returns a instance of the device * * @param typeClass The specific genericized type of src. * @param uuid The device identification to find a device on server * @param callbackResult Callback for this method * @param <T> the type of the desired object * @throws JSONException/*from w w w .ja va2 s.c o m*/ */ public <T extends AbstractThingDevice> void getDevice(final T typeClass, String uuid, final Event<T> callbackResult) throws JSONException, InvalidParametersException, SocketNotConnected { if (isSocketConnected() && isSocketRegistered()) { if (typeClass != null && callbackResult != null && uuid != null) { JSONObject uuidDevice = new JSONObject(); uuidDevice.put(UUID, uuid); mSocket.emit(EVENT_GET_DEVICE, uuidDevice, new Ack() { @Override public void call(Object... args) { if (args != null && args.length > 0) { JsonElement jsonElement = new JsonParser().parse(args[FIRST_EVENT_RECEIVED].toString()); JsonObject jsonObject = jsonElement.getAsJsonObject(); if (jsonObject.get(ERROR) != null && !jsonObject.get(ERROR).isJsonNull()) { callbackResult.onEventError(new KnotException(jsonObject.get(ERROR).toString())); } else if (jsonObject.get(FROM) != null) { JsonObject json = jsonObject.get(DEVICE).getAsJsonObject(); try { T result = (T) mGson.fromJson(json.toString(), typeClass.getClass()); callbackResult.onEventFinish(result); } catch (Exception e) { callbackResult.onEventError(new KnotException("Error in reading the result")); } } else { callbackResult.onEventError(new KnotException("Unknown error")); } } else { callbackResult.onEventError(new KnotException("Error in reading the result")); } } }); } else { throw new InvalidParametersException("Invalid parameters"); } } else { throw new SocketNotConnected("Socket not ready or connected"); } }
From source file:br.unicamp.cst.bindings.soar.SOARPlugin.java
License:Open Source License
public JsonObject getOutputLinkJSON() { JsonObject json = new JsonObject(); try {//from ww w . j a v a2s .c o m if (getAgent() != null) { List<Wme> Commands = getOutputLink_WME(); setOutputLinkAsString(getWMEStringOutput()); for (Wme command : Commands) { String commandType = command.getAttribute().toString(); json.add(commandType, new JsonObject()); String parameter = command.getAttribute().toString(); String parvalue = command.getValue().toString(); Iterator<Wme> children = command.getChildren(); while (children.hasNext()) { Wme child = children.next(); parameter = child.getAttribute().toString(); parvalue = child.getValue().toString(); Float floatvalue = tryParseFloat(parvalue); if (floatvalue != null) { json.get(commandType).getAsJsonObject().addProperty(parameter, floatvalue); } else { json.get(commandType).getAsJsonObject().addProperty(parameter, parvalue); } } } } } catch (Exception e) { logger.severe("Error while creating SOAR Kernel" + e); } setJsonOutputLinkAsString(json.toString()); return (json); }
From source file:brooklyn.entity.monitoring.zabbix.ZabbixFeed.java
License:Apache License
@Override protected void preStart() { final Supplier<URI> baseUriProvider = getConfig(BASE_URI_PROVIDER); final Function<? super EntityLocal, String> uniqueHostnameGenerator = getConfig(UNIQUE_HOSTNAME_GENERATOR); final Integer groupId = getConfig(GROUP_ID); final Integer templateId = getConfig(TEMPLATE_ID); final Set<ZabbixPollConfig<?>> polls = getConfig(POLLS); log.info("starting zabbix feed for {}", entity); // TODO if supplier returns null, we may wish to defer initialization until url available? // TODO for https should we really trust all? final HttpClient httpClient = HttpTool.httpClientBuilder().trustAll() .clientConnectionManager(new ThreadSafeClientConnManager()) .reuseStrategy(new NoConnectionReuseStrategy()).uri(baseUriProvider.get()).build(); // Registration job, calls Zabbix host.create API final Callable<HttpToolResponse> registerJob = new Callable<HttpToolResponse>() { @Override/*from w ww .jav a2 s . co m*/ public HttpToolResponse call() throws Exception { if (!registered.get()) { // Find the first machine, if available Optional<Location> location = Iterables.tryFind(entity.getLocations(), Predicates.instanceOf(MachineLocation.class)); if (!location.isPresent()) { return null; // Do nothing until location is present } MachineLocation machine = (MachineLocation) location.get(); String host = uniqueHostnameGenerator.apply(entity); // Select address and port using port-forwarding if available String address = entity.getAttribute(Attributes.ADDRESS); Integer port = entity.getAttribute(ZabbixMonitored.ZABBIX_AGENT_PORT); if (machine instanceof SupportsPortForwarding) { Cidr management = entity.getConfig(BrooklynAccessUtils.MANAGEMENT_ACCESS_CIDR); HostAndPort forwarded = ((SupportsPortForwarding) machine).getSocketEndpointFor(management, port); address = forwarded.getHostText(); port = forwarded.getPort(); } // Fill in the JSON template and POST it byte[] body = JSON_HOST_CREATE .replace("{{token}}", entity.getConfig(ZabbixMonitored.ZABBIX_SERVER) .getAttribute(ZabbixServer.ZABBIX_TOKEN)) .replace("{{host}}", host).replace("{{ip}}", address) .replace("{{port}}", Integer.toString(port)) .replace("{{groupId}}", Integer.toString(groupId)) .replace("{{templateId}}", Integer.toString(templateId)) .replace("{{id}}", Integer.toString(id.incrementAndGet())).getBytes(); return HttpTool.httpPost(httpClient, baseUriProvider.get(), ImmutableMap.of("Content-Type", "application/json"), body); } return null; } }; // The handler for the registration job PollHandler<? super HttpToolResponse> registrationHandler = new PollHandler<HttpToolResponse>() { @Override public void onSuccess(HttpToolResponse val) { if (registered.get() || val == null) { return; // Skip if we are registered already or no data from job } JsonObject response = HttpValueFunctions.jsonContents().apply(val).getAsJsonObject(); if (response.has("error")) { // Parse the JSON error object and log the message JsonObject error = response.get("error").getAsJsonObject(); String message = error.get("message").getAsString(); String data = error.get("data").getAsString(); log.warn("zabbix failed registering host - {}: {}", message, data); } else if (response.has("result")) { // Parse the JSON result object and save the hostId JsonObject result = response.get("result").getAsJsonObject(); String hostId = result.get("hostids").getAsJsonArray().get(0).getAsString(); // Update the registered status if not set if (registered.compareAndSet(false, true)) { entity.setAttribute(ZabbixMonitored.ZABBIX_AGENT_HOSTID, hostId); log.info("zabbix registered host as id {}", hostId); } } else { throw new IllegalStateException(String .format("zabbix host registration returned invalid result: %s", response.toString())); } } @Override public boolean checkSuccess(HttpToolResponse val) { return (val.getResponseCode() == 200); } @Override public void onFailure(HttpToolResponse val) { log.warn("zabbix sever returned failure code: {}", val.getResponseCode()); } @Override public void onException(Exception exception) { log.warn("zabbix exception registering host", exception); } @Override public String toString() { return super.toString() + "[" + getDescription() + "]"; } @Override public String getDescription() { return "Zabbix rest poll"; } }; // Schedule registration attempt once per second getPoller().scheduleAtFixedRate(registerJob, registrationHandler, 1000l); // TODO make configurable // Create a polling job for each Zabbix metric for (final ZabbixPollConfig<?> config : polls) { Callable<HttpToolResponse> pollJob = new Callable<HttpToolResponse>() { @Override public HttpToolResponse call() throws Exception { if (registered.get()) { if (log.isTraceEnabled()) log.trace("zabbix polling {} for {}", entity, config); byte[] body = JSON_ITEM_GET .replace("{{token}}", entity.getConfig(ZabbixMonitored.ZABBIX_SERVER) .getAttribute(ZabbixServer.ZABBIX_TOKEN)) .replace("{{hostId}}", entity.getAttribute(ZabbixMonitored.ZABBIX_AGENT_HOSTID)) .replace("{{itemKey}}", config.getItemKey()) .replace("{{id}}", Integer.toString(id.incrementAndGet())).getBytes(); return HttpTool.httpPost(httpClient, baseUriProvider.get(), ImmutableMap.of("Content-Type", "application/json"), body); } else { throw new IllegalStateException("zabbix agent not yet registered"); } } }; // Schedule the Zabbix polling job AttributePollHandler<? super HttpToolResponse> pollHandler = new AttributePollHandler<HttpToolResponse>( config, entity, this); long minPeriod = Integer.MAX_VALUE; // TODO make configurable if (config.getPeriod() > 0) minPeriod = Math.min(minPeriod, config.getPeriod()); getPoller().scheduleAtFixedRate(pollJob, pollHandler, minPeriod); } }
From source file:callAPIHelper.CallApiHelper.java
public String CallAPIForURL(DataURL dataUrl, RowDataFromFile data) throws UnsupportedEncodingException, IOException { String code = ""; String POST_URL = dataUrl.getUrl(); CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(POST_URL); httpPost.setHeader("Content-type", dataUrl.getContentType()); httpPost.setHeader("Accept-Content Type", dataUrl.getAcceptType()); JsonObject jdata = data.getData(); System.out.println("data post: " + jdata.toString()); httpPost.setEntity(new StringEntity(jdata.toString())); CloseableHttpResponse httpResponse = httpClient.execute(httpPost); if (httpResponse.getStatusLine().getStatusCode() == 200) { BufferedReader reader = new BufferedReader( new InputStreamReader(httpResponse.getEntity().getContent())); String inputLine;// w w w . ja v a 2 s . c om StringBuffer response = new StringBuffer(); while ((inputLine = reader.readLine()) != null) { response.append(inputLine); } reader.close(); JsonObject jresp = new JsonObject(); jresp = gson.fromJson(response.toString(), JsonObject.class); System.out.println("data resp: " + jresp.toString()); // JsonElement je = jresp.get("code"); code = jresp.toString(); } else { System.out.println("API Fail status code = " + httpResponse.getStatusLine().getStatusCode()); // return new DataResponseWithdrawFunds();/ code = "-1"; } return code; }
From source file:carsharing.starter.automotive.iot.ibm.com.mobilestarterapp.AnalyzeMyDriving.java
License:Open Source License
public void sendLocation(final Location location) { if (connectDeviceClient()) { final GregorianCalendar cal = new GregorianCalendar(); final TimeZone gmt = TimeZone.getTimeZone("GMT"); cal.setTimeZone(gmt);//from w w w . ja va 2s .c o m final SimpleDateFormat formattedCal = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); formattedCal.setCalendar(cal); final String timestamp = formattedCal.format(cal.getTime()); final double speed = Math.max(0.0, location.getSpeed() * 60 * 60 / 1000); final double longitude = location.getLongitude(); final double latitude = location.getLatitude(); final String mobileAppDeviceId = FirstPage.mobileAppDeviceId; final String status = tripID != null ? "Unlocked" : "Locked"; if (tripID == null) { // this trip should be completed, so lock device now userUnlocked = false; } final JsonObject event = new JsonObject(); final JsonObject data = new JsonObject(); event.add("d", data); data.addProperty("trip_id", tripID); data.addProperty("speed", speed); data.addProperty("lng", longitude); data.addProperty("lat", latitude); data.addProperty("ts", timestamp); data.addProperty("id", mobileAppDeviceId); data.addProperty("status", status); final ActionBar supportActionBar = ((AppCompatActivity) getActivity()).getSupportActionBar(); if (deviceClient.publishEvent("sensorData", event, 0)) { Log.d("MQTT", "publish event " + event.toString()); supportActionBar.setTitle(speedMessage + " - Data sent (" + (++transmissionCount) + ")"); } else { Log.d("MQTT", "ERROR in publishing event " + event.toString()); supportActionBar.setTitle("Data Transmission Error."); } } }
From source file:catalog.CloudantUtil.java
License:Apache License
public static JsonObject createDocParameterForWhisk(String doc) { JsonObject cloudantDoc = new JsonObject(); String now = new Date().toString(); cloudantDoc.addProperty("_id", DOC_ID); cloudantDoc.addProperty("date", now); // Create JSON object that will be passed as an argument to whisk cli JsonObject param = new JsonObject(); if (doc != null && !doc.isEmpty()) { param.addProperty("doc", doc); } else {/*from w ww .ja v a 2s . c o m*/ param.addProperty("doc", cloudantDoc.toString()); } return param; }
From source file:cd.go.artifact.dummy.DummyArtifactPlugin.java
License:Apache License
@Override public GoPluginApiResponse handle(GoPluginApiRequest request) throws UnhandledRequestTypeException { final RequestFromServer requestFromServer = RequestFromServer.from(request.requestName()); try {/*ww w . ja v a 2 s . co m*/ switch (requestFromServer) { case REQUEST_GET_CAPABILITIES: return DefaultGoPluginApiResponse.success("{}"); case REQUEST_STORE_CONFIG_METADATA: return DefaultGoPluginApiResponse.success(artifactStoreMetadata()); case REQUEST_STORE_CONFIG_VIEW: return DefaultGoPluginApiResponse.success(new View("/artifact-store.template.html").toJSON()); case REQUEST_STORE_CONFIG_VALIDATE: return DefaultGoPluginApiResponse .success(ArtifactStoreConfig.from(request.requestBody()).validate().toJSON()); case REQUEST_PUBLISH_ARTIFACT_METADATA: return DefaultGoPluginApiResponse.success(ArtifactConfig.artifactConfigMetadata()); case REQUEST_PUBLISH_ARTIFACT_VIEW: return DefaultGoPluginApiResponse.success(new View("/publish-artifact.template.html").toJSON()); case REQUEST_PUBLISH_ARTIFACT_VALIDATE: return DefaultGoPluginApiResponse .success(ArtifactConfig.from(request.requestBody()).validate().toJSON()); case REQUEST_FETCH_ARTIFACT_METADATA: return DefaultGoPluginApiResponse.success(FetchArtifact.metadata()); case REQUEST_FETCH_ARTIFACT_VIEW: return DefaultGoPluginApiResponse.success(new View("/fetch-artifact.template.html").toJSON()); case REQUEST_FETCH_ARTIFACT_VALIDATE: return DefaultGoPluginApiResponse .success(FetchArtifact.from(request.requestBody()).validate().toJSON()); case REQUEST_PUBLISH_ARTIFACT: return publishArtifact(PublishArtifactRequest.fromJSON(request.requestBody())); case REQUEST_FETCH_ARTIFACT: return fetchArtifact(FetchArtifactRequest.fromJSON(request.requestBody())); case REQUEST_GET_PLUGIN_ICON: JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("content_type", "image/jpg"); jsonObject.addProperty("data", Base64.getEncoder().encodeToString(ResourceReader.readBytes("/icon.jpg"))); return DefaultGoPluginApiResponse.success(jsonObject.toString()); default: throw new RuntimeException("Error while executing request" + request.requestName()); } } catch (Exception e) { LOG.error("Error while executing request " + request.requestName(), e); throw new RuntimeException(e); } }
From source file:cd.go.contrib.elasticagents.dockerswarm.elasticagent.executors.AgentStatusReportExecutor.java
License:Apache License
public GoPluginApiResponse execute() throws Exception { String elasticAgentId = request.getElasticAgentId(); JobIdentifier jobIdentifier = request.getJobIdentifier(); LOG.info(String.format("[status-report] Generating status report for agent: %s with job: %s", elasticAgentId, jobIdentifier)); try {//w w w.j a v a 2 s .co m agentInstances.refreshAll(pluginRequest); final DockerClient dockerClient = dockerClientFactory.docker(pluginRequest.getPluginSettings()); Service dockerService = findService(elasticAgentId, jobIdentifier, dockerClient); DockerServiceElasticAgent elasticAgent = DockerServiceElasticAgent.fromService(dockerService, dockerClient); final String statusReportView = builder.build(builder.getTemplate("agent-status-report.template.ftlh"), elasticAgent); JsonObject responseJSON = new JsonObject(); responseJSON.addProperty("view", statusReportView); return DefaultGoPluginApiResponse.success(responseJSON.toString()); } catch (Exception e) { return StatusReportGenerationErrorHandler.handle(builder, e); } }
From source file:cd.go.contrib.elasticagents.dockerswarm.elasticagent.executors.StatusReportExecutor.java
License:Apache License
public GoPluginApiResponse execute() { try {// w ww . j a v a 2 s. c o m LOG.debug("[status-report] Generating status report."); agentInstances.refreshAll(pluginRequest); final DockerClient dockerClient = dockerClientFactory.docker(pluginRequest.getPluginSettings()); final SwarmCluster swarmCluster = new SwarmCluster(dockerClient); final Template template = statusReportViewBuilder.getTemplate("status-report.template.ftlh"); final String statusReportView = statusReportViewBuilder.build(template, swarmCluster); JsonObject responseJSON = new JsonObject(); responseJSON.addProperty("view", statusReportView); return DefaultGoPluginApiResponse.success(responseJSON.toString()); } catch (Exception e) { return StatusReportGenerationErrorHandler.handle(statusReportViewBuilder, e); } }