List of usage examples for com.google.gson JsonElement toString
@Override
public String toString()
From source file:com.hybris.datahub.service.impl.DefaultJsonService.java
License:Open Source License
private String convertJsonValue(final JsonElement jsonElement) { if (jsonElement.isJsonPrimitive()) { return jsonElement.getAsString(); } else if (jsonElement.isJsonNull()) { return ""; } else {/*from w w w . j a v a 2 s . c o m*/ return jsonElement.toString(); } }
From source file:com.hybris.mobile.lib.http.converter.JsonDataConverter.java
License:Open Source License
/** * @param data String of character to be parsed * @param property Attributes to be parse * @param element JSON element to get data from * @return List of String//from w ww .ja va 2 s . co m */ protected List<String> getValuesFromPropertyElement(String data, String property, String element, boolean recursive) { List<String> listToReturn = new ArrayList<>(); if (data == null) { throw new IllegalArgumentException(); } JsonParser parser = new JsonParser(); JsonArray jsonArray; JsonElement jsonElement; try { if (StringUtils.isNotBlank(property)) { jsonElement = parser.parse(data).getAsJsonObject().get(property); } else { jsonElement = parser.parse(data); } if (jsonElement != null) { if (jsonElement.isJsonArray()) { jsonArray = jsonElement.getAsJsonArray(); } else { jsonArray = new JsonArray(); jsonArray.add(jsonElement); } if (jsonArray != null) { for (JsonElement currentJsonElement : jsonArray) { if (StringUtils.isNotBlank(element)) { if (recursive) { try { listToReturn.addAll(getValuesFromPropertyElement(currentJsonElement.toString(), property, element, recursive)); } catch (NoSuchElementException e) { Log.d(TAG, "End of getting the recursive property " + property + "."); } } currentJsonElement = currentJsonElement.getAsJsonObject().get(element); } if (currentJsonElement != null) { if (currentJsonElement.isJsonPrimitive()) { listToReturn.add(currentJsonElement.getAsString()); } else { listToReturn.add(currentJsonElement.toString()); } } else { Log.d(TAG, "No data found for element " + element + "."); } } } } else { Log.d(TAG, "No data found on " + data + " for property " + property + "."); } } catch (Exception e) { Log.e(TAG, "Error parsing the data " + data + " for property " + property + " and element " + element + "."); throw new NoSuchElementException("Error parsing the data " + data + " for property " + property + " and element " + element + "."); } return listToReturn; }
From source file:com.ibm.iotf.sample.client.application.api.SampleDataManagementAPIOperations.java
License:Open Source License
public static void main(String[] args) { Properties props = new Properties(); try {/*from w w w . j av a2s . co m*/ props.load(SampleDataManagementAPIOperations.class.getResourceAsStream(APPLICATION_PROPERTIES_FILE)); } catch (IOException e1) { System.err.println("Not able to read the properties file, exiting.."); return; } // SystemObject object = new SystemObject(); APIClient myClient = null; try { //Instantiate the class by passing the properties file myClient = new APIClient(props); } catch (Exception e) { System.out.println("" + e.getMessage()); // Looks like the properties file is not updated, just ignore; return; } try { //Create Schema Resource for Draft Physical Interface JsonObject draftPhysicalSchemaResponse = myClient.addDraftSchemaDefinition(new File(EVENT_SCHEMA1), SCHEMA_NAME1, SCHEMA_DESCRIPTION1, SCHEMA_TYPE1); JsonElement draftSchemaId = draftPhysicalSchemaResponse.get("id"); System.out.println("Creating artifacts"); System.out.println( "1. Schema for Draft Physical Interface created with id = " + draftSchemaId.getAsString()); System.out.println("Schema Object = " + draftPhysicalSchemaResponse.toString()); //Create Event Type JsonObject draftEventTypeRequest = new JsonObject(); draftEventTypeRequest.add("schemaId", draftSchemaId); draftEventTypeRequest.addProperty("name", EVT_TOPIC); JsonObject draftEventTypeResponse = myClient.addDraftEventType(draftEventTypeRequest.toString()); JsonElement draftEventTypeId = draftEventTypeResponse.get("id"); System.out.println("\n2. Event Type created with id = " + draftEventTypeId.getAsString()); System.out.println("Event Type Object = " + draftEventTypeResponse); //Create Draft Physical Interface JsonObject draftPhysicalInterfaceRequest = new JsonObject(); draftPhysicalInterfaceRequest.addProperty("name", "Env sensor physical interface 7"); JsonObject draftPhysicalInterfaceResponse = myClient .addDraftPhysicalInterface(draftPhysicalInterfaceRequest.toString()); System.out.println("\n3. Draft Physical Interface created with id = " + draftPhysicalInterfaceResponse.get("id").getAsString()); System.out.println("Draft Physical Interface Object = " + draftPhysicalInterfaceResponse.toString()); //Add Event to Physical Interface JsonObject eventTypeToPIRequest = new JsonObject(); eventTypeToPIRequest.addProperty("eventId", EVT_TOPIC); eventTypeToPIRequest.addProperty("eventTypeId", draftEventTypeId.getAsString()); JsonObject eventTypeToPIResponse = myClient.addEventToPhysicalInterface( draftPhysicalInterfaceResponse.get("id").getAsString(), eventTypeToPIRequest.toString()); System.out.println("\n4. Event Type to Draft Physical Interface added with eventTypeId = " + eventTypeToPIResponse.get("eventTypeId").getAsString()); System.out.println("Event Type to Physical Interface = " + eventTypeToPIResponse.toString()); //Update Draft Device Type to connect the Draft Physical Interface JsonObject updateDraftDTToPIRequest = new JsonObject(); JsonObject refs = new JsonObject(); refs.addProperty("events", "/api/v0002/draft/physicalinterfaces/" + draftPhysicalInterfaceResponse.get("id").getAsString() + "/events"); Gson gson = new Gson(); JsonElement element = gson.fromJson(refs.toString(), JsonElement.class); updateDraftDTToPIRequest.add("refs", element); updateDraftDTToPIRequest.addProperty("version", "draft"); updateDraftDTToPIRequest.addProperty("name", "Env sensor physical interface 1"); updateDraftDTToPIRequest.addProperty("createdBy", API_KEY); updateDraftDTToPIRequest.addProperty("updatedBy", API_KEY); updateDraftDTToPIRequest.addProperty("id", draftPhysicalInterfaceResponse.get("id").getAsString()); JsonObject updateDraftDTToPIResponse = myClient.associateDraftPhysicalInterfaceWithDeviceType(TYPE_ID, updateDraftDTToPIRequest.toString()); System.out.println("\n5. Draft Device Type added to draft Physical Interface with id = " + updateDraftDTToPIResponse.get("id").getAsString()); System.out.println( "Draft Device Type to draft Physical Interface = " + updateDraftDTToPIResponse.toString()); //Create schema for draft logical interface JsonObject draftLogicalSchemaResponse = myClient.addDraftSchemaDefinition(new File(EVENT_SCHEMA2), SCHEMA_NAME2, SCHEMA_DESCRIPTION2, SCHEMA_TYPE2); JsonElement draftLogicalSchemaId = draftLogicalSchemaResponse.get("id"); System.out.println("\n6. Schema for Draft Logical Interface created with Id = " + draftLogicalSchemaId.getAsString()); System.out.println( "Schema for Draft Logical Interface Object = " + draftLogicalSchemaResponse.toString()); //Create Draft Logical Interface JsonObject draftLogicalInterfaceRequest = new JsonObject(); draftLogicalInterfaceRequest.addProperty("name", "environment sensor interface"); draftLogicalInterfaceRequest.addProperty("schemaId", draftLogicalSchemaId.getAsString()); JsonObject draftLogicalInterfaceResponse = myClient .addDraftLogicalInterface(draftLogicalInterfaceRequest.toString()); System.out.println("\n7. Draft Logical Interface created with Id = " + draftLogicalInterfaceResponse.get("id").getAsString() + " and schemaId = " + draftLogicalInterfaceResponse.get("schemaId").getAsString()); System.out.println("Draft for Logical Interface Object = " + draftLogicalInterfaceResponse.toString()); //Add Draft Logical Interface to Device Type JsonObject draftLIToDTRequest = new JsonObject(); refs = new JsonObject(); refs.addProperty("schema", "/api/v0002/draft/schemas/" + draftLogicalSchemaId.getAsString()); element = gson.fromJson(refs.toString(), JsonElement.class); draftLIToDTRequest.add("refs", element); draftLIToDTRequest.addProperty("version", "draft"); draftLIToDTRequest.addProperty("name", "environment sensor interface"); draftLIToDTRequest.addProperty("createdBy", API_KEY); draftLIToDTRequest.addProperty("updatedBy", API_KEY); draftLIToDTRequest.addProperty("schemaId", draftLogicalSchemaId.getAsString()); draftLIToDTRequest.addProperty("id", draftLogicalInterfaceResponse.get("id").getAsString()); JsonObject draftLIToDTResponse = myClient.associateDraftLogicalInterfaceToDeviceType(TYPE_ID, draftLIToDTRequest.toString()); System.out.println("\n8. Draft Logical Interface added to device Type with id = " + draftLIToDTResponse.get("id").getAsString()); System.out.println("Draft Logical Interface to Device Type Object = " + draftLIToDTResponse.toString()); //Create mapping between Device Type and Logical Interface JsonObject mappings = new JsonObject(); mappings.addProperty("logicalInterfaceId", draftLIToDTResponse.get("id").getAsString()); mappings.addProperty("notificationStrategy", NOTIFICATION_STRATEGY); JsonObject propertyMapping = new JsonObject(); propertyMapping.addProperty("temperature", "($event.temp - 32) / 1.8"); JsonObject tempMapping = new JsonObject(); tempMapping.add(EVT_TOPIC, gson.fromJson(propertyMapping.toString(), JsonElement.class)); element = gson.fromJson(tempMapping.toString(), JsonElement.class); mappings.add("propertyMappings", tempMapping); JsonObject deviceToLImappings = myClient.addDraftPropertyMappingsToDeviceType(TYPE_ID, mappings.toString()); System.out.println("\n9. Mapping created between device type and Logical Interface with Id = " + deviceToLImappings.get("logicalInterfaceId").getAsString()); System.out.println( "Mapping between device type and logical interface = " + deviceToLImappings.toString()); //Validating configuration JsonObject validateOperation = new JsonObject(); validateOperation.addProperty("operation", SchemaOperation.VALIDATE.getOperation()); System.out.println("id" + draftLogicalInterfaceResponse.get("id").getAsString() + "validateOperation.toString()" + validateOperation.toString()); JsonObject validated = myClient.performOperationAgainstDraftLogicalInterface( draftLogicalInterfaceResponse.get("id").getAsString(), validateOperation.toString()); System.out.println("\n10. Validate operation = " + validated.toString()); Thread.sleep(20000); //Activating configuration if (validated.get("failures").getAsJsonArray().size() == 0) { System.out.println("No validation failures"); JsonObject activateOperation = new JsonObject(); activateOperation.addProperty("operation", SchemaOperation.ACTIVATE.getOperation()); System.out.println("id" + draftLogicalInterfaceResponse.get("id").getAsString() + " activateOperation.toString()" + activateOperation.toString()); JsonObject activated = myClient.performOperationAgainstDraftLogicalInterface( draftLogicalInterfaceResponse.get("id").getAsString(), activateOperation.toString()); System.out.println("\n11. Activate operation = " + activated.toString()); } Thread.sleep(25000); System.out.println("\n\nEnter anything to delete the artifacts created......"); System.out.println("Deleting artifacts"); System.out.println("\n12. Dissociating the device type from Physical Interface = " + TYPE_ID + " = " + myClient.dissociateDraftPhysicalInterfaceFromDeviceType(TYPE_ID)); System.out.println("\n13. Mappings between device type and LogicalInterface deleted = " + myClient.deleteDraftPropertyMappings(TYPE_ID, deviceToLImappings.get("logicalInterfaceId").getAsString())); System.out.println("\n14. Dissociating the device type from Logical Interface = " + TYPE_ID + " = " + myClient.dissociateDraftLogicalInterfaceFromDeviceType(TYPE_ID, draftLIToDTResponse.get("id").getAsString())); System.out.println("\n15. Mapping between Event = " + EVT_TOPIC + " and Physical Interface = " + draftPhysicalInterfaceResponse.get("id").getAsString() + " deleted = " + myClient.deleteEventMappingFromPhysicalInterface( draftPhysicalInterfaceResponse.get("id").getAsString(), EVT_TOPIC)); JsonObject deactivateOperation = new JsonObject(); deactivateOperation.addProperty("operation", SchemaOperation.DEACTIVATE.getOperation()); System.out.println("id" + draftLogicalInterfaceResponse.get("id").getAsString() + " deactivateOperation.toString()" + deactivateOperation.toString()); JsonObject deactivated = myClient.performOperationAgainstLogicalInterface( draftLogicalInterfaceResponse.get("id").getAsString(), deactivateOperation.toString()); System.out.println("\n16. Dectivate operation = " + deactivated.toString()); System.out.println("\n17. Draft Physical Interface with Id = " + draftPhysicalInterfaceResponse.get("id").getAsString() + " deleted = " + myClient .deleteDraftPhysicalInterface(draftPhysicalInterfaceResponse.get("id").getAsString())); System.out.println("\n18. Draft Event Type with Id = " + draftEventTypeId.toString() + " deleted = " + myClient.deleteDraftEventType(draftEventTypeId.getAsString())); System.out.println("\n19. Physical Schema with Id = " + draftSchemaId.toString() + " deleted = " + myClient.deleteDraftSchemaDefinition(draftSchemaId.getAsString())); System.out.println("\n20. Draft Logical Interface with Id = " + draftLogicalInterfaceResponse.get("id").getAsString() + " deleted = " + myClient.deleteDraftLogicalInterface(draftLogicalInterfaceResponse.get("id").getAsString())); System.out.println("\n21. Logical Schema with Id = " + draftLogicalSchemaId.toString() + " deleted = " + myClient.deleteDraftSchemaDefinition(draftLogicalSchemaId.getAsString())); } catch (Exception ioe) { ioe.printStackTrace(); } }
From source file:com.ibm.watson.movieapp.dialog.fvt.rest.RestAPI.java
License:Open Source License
/** * /*from www . j a va 2 s .com*/ * @param jsonFile * @return */ public String getFileAsString(String jsonFile) { String fileContents = ""; try { if (!jsonFile.startsWith("/")) { //All of the JSON files are stored in the "questions" package/folder //All json file paths should start with '/questions/' jsonFile = "/" + jsonFile; } JsonElement jelmnt = new JsonParser() .parse(new InputStreamReader(this.getClass().getResourceAsStream(jsonFile))); fileContents = jelmnt.toString(); } catch (JsonIOException | JsonSyntaxException e) { e.printStackTrace(); } return fileContents; }
From source file:com.ikanow.infinit.e.data_model.index.ElasticSearchManager.java
License:Apache License
public boolean addDocument(JsonElement docJson, String _id, boolean bAllowOverwrite, String sParentId) { if (null != _multiIndex) { throw new RuntimeException("addDocument not supported on multi-index manager"); }// w w w .j a va 2 s .c o m IndexRequestBuilder irb = _elasticClient.prepareIndex(_sIndexName, _sIndexType) .setSource(docJson.toString()); if (null != _id) { irb.setId(_id); } //TESTED else { // If an _id is already specified use that JsonElement _idJson = docJson.getAsJsonObject().get("_id"); if (null != _idJson) { _id = _idJson.getAsString(); if (null != _id) { irb.setId(_id); } } } //TOTEST if (!bAllowOverwrite) { irb.setOpType(OpType.CREATE); } //TESTED if (null != sParentId) { irb.setParent(sParentId); } // This ensures that the write goes through if I can write to any nodes, which seems sensible // You could always check the response and handle minimal success like failure if you want irb.setConsistencyLevel(WriteConsistencyLevel.ONE); try { irb.execute().actionGet(); } catch (org.elasticsearch.transport.RemoteTransportException e) { boolean bDocAlreadyExists = e .contains(org.elasticsearch.index.engine.DocumentAlreadyExistsEngineException.class) // 0.18 || e.contains(org.elasticsearch.index.engine.DocumentAlreadyExistsException.class); // 0.19 if (!bDocAlreadyExists) { throw e; } return false; } return true; }
From source file:com.ikanow.infinit.e.data_model.index.ElasticSearchManager.java
License:Apache License
public BulkResponse bulkAddDocuments(JsonElement docsJson, String idFieldName, String sParentId, boolean bAllowOverwrite) { if (null != _multiIndex) { throw new RuntimeException("bulkAddDocuments not supported on multi-index manager"); }/*from ww w . j a v a 2s.c o m*/ if (!docsJson.isJsonArray()) { throw new RuntimeException("bulkAddDocuments - not a list"); } BulkRequestBuilder brb = _elasticClient.prepareBulk(); JsonArray docJsonArray = docsJson.getAsJsonArray(); for (JsonElement docJson : docJsonArray) { IndexRequest ir = new IndexRequest(_sIndexName); ir.type(_sIndexType); if (null != sParentId) { ir.parent(sParentId); } if (!bAllowOverwrite) { ir.opType(OpType.CREATE); } //TESTED // Some _id unpleasantness if (null != idFieldName) { String id = docJson.getAsJsonObject().get(idFieldName).getAsString(); ir.id(id); ir.source(docJson.toString()); } //TESTED brb.add(ir); } brb.setConsistencyLevel(WriteConsistencyLevel.ONE); return brb.execute().actionGet(); }
From source file:com.iluwatar.event.sourcing.processor.JsonFileJournal.java
License:Open Source License
/** * Write./*from w w w .j av a 2s. c om*/ * * @param domainEvent the domain event */ public void write(DomainEvent domainEvent) { Gson gson = new Gson(); JsonElement jsonElement; if (domainEvent instanceof AccountCreateEvent) { jsonElement = gson.toJsonTree(domainEvent, AccountCreateEvent.class); } else if (domainEvent instanceof MoneyDepositEvent) { jsonElement = gson.toJsonTree(domainEvent, MoneyDepositEvent.class); } else if (domainEvent instanceof MoneyTransferEvent) { jsonElement = gson.toJsonTree(domainEvent, MoneyTransferEvent.class); } else { throw new RuntimeException("Journal Event not recegnized"); } try (Writer output = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(aFile, true), "UTF-8"))) { String eventString = jsonElement.toString(); output.write(eventString + "\r\n"); } catch (IOException e) { throw new RuntimeException(e); } }
From source file:com.intellij.openapi.updateSettings.impl.pluginsAdvertisement.PluginsAdvertiser.java
License:Apache License
public static List<PluginId> retrieve(UnknownFeature unknownFeature) { final String featureType = unknownFeature.getFeatureType(); final String implementationName = unknownFeature.getImplementationName(); final String buildNumber = ApplicationInfo.getInstance().getBuild().asString(); final String pluginRepositoryUrl = FEATURE_IMPLEMENTATIONS_URL + "featureType=" + featureType + "&implementationName=" + implementationName.replaceAll("#", "%23") + "&build=" + buildNumber; try {//from ww w . j av a2s . com HttpURLConnection connection = HttpConfigurable.getInstance().openHttpConnection(pluginRepositoryUrl); connection.connect(); final InputStreamReader streamReader = new InputStreamReader(connection.getInputStream()); try { final JsonReader jsonReader = new JsonReader(streamReader); jsonReader.setLenient(true); final JsonElement jsonRootElement = new JsonParser().parse(jsonReader); final List<PluginId> result = new ArrayList<PluginId>(); for (JsonElement jsonElement : jsonRootElement.getAsJsonArray()) { final JsonObject jsonObject = jsonElement.getAsJsonObject(); final JsonElement pluginId = jsonObject.get("pluginId"); result.add(PluginId.getId(StringUtil.unquoteString(pluginId.toString()))); } return result; } finally { streamReader.close(); } } catch (IOException e) { LOG.info(e); return null; } }
From source file:com.intellij.openapi.updateSettings.impl.pluginsAdvertisement.PluginsAdvertiser.java
License:Apache License
private static Map<String, Set<PluginId>> loadSupportedExtensions() { final String pluginRepositoryUrl = FEATURE_IMPLEMENTATIONS_URL + "featureType=" + FileTypeFactory.FILE_TYPE_FACTORY_EP.getName(); try {/*w ww . jav a 2 s . co m*/ HttpURLConnection connection = HttpConfigurable.getInstance().openHttpConnection(pluginRepositoryUrl); connection.connect(); final InputStreamReader streamReader = new InputStreamReader(connection.getInputStream()); try { final JsonReader jsonReader = new JsonReader(streamReader); jsonReader.setLenient(true); final JsonElement jsonRootElement = new JsonParser().parse(jsonReader); final Map<String, Set<PluginId>> result = new HashMap<String, Set<PluginId>>(); for (JsonElement jsonElement : jsonRootElement.getAsJsonArray()) { final JsonObject jsonObject = jsonElement.getAsJsonObject(); final JsonElement ext = jsonObject.get("implementationName"); final String extension = StringUtil.unquoteString(ext.toString()); Set<PluginId> pluginIds = result.get(extension); if (pluginIds == null) { pluginIds = new HashSet<PluginId>(); result.put(extension, pluginIds); } pluginIds.add(PluginId.getId(StringUtil.unquoteString(jsonObject.get("pluginId").toString()))); } saveExtensions(result); return result; } finally { streamReader.close(); } } catch (IOException e) { LOG.info(e); return null; } }
From source file:com.intuit.wasabi.tests.service.IntegrationAuthorization.java
License:Apache License
/** * Test getting user permission/*www .j a v a 2 s.c o m*/ */ @Test(dependsOnMethods = { "t_createExperiments" }) public void t_getUserPermissions() { String uri = "authorization/users/" + userName + "/permissions"; response = apiServerConnector.doGet(uri); assertReturnCode(response, HttpStatus.SC_OK); List<Map<String, Object>> jsonStrings = response.jsonPath().getList("permissionsList"); Assert.assertTrue(!jsonStrings.isEmpty()); boolean foundApp = false; for (@SuppressWarnings("rawtypes") Map jsonMap : jsonStrings) { String permissionJStr = simpleGson.toJson(jsonMap); JsonElement jElement = new JsonParser().parse(permissionJStr); JsonObject jobject = jElement.getAsJsonObject(); JsonElement jElement2 = jobject.get("permissions"); Assert.assertTrue(jElement2.toString().contains("SUPERADMIN")); JsonElement jsonElement = jobject.get("applicationName"); String applicationName = jsonElement.getAsString(); if (applicationName.equals(experiment.applicationName)) { LOGGER.info("Found application=" + experiment.applicationName); foundApp = true; break; } } Assert.assertTrue(foundApp); }