List of usage examples for com.google.gson JsonObject get
public JsonElement get(String memberName)
From source file:cf.adriantodt.utils.data.ConfigUtils.java
License:LGPL
public static void requireValid(JsonObject object, String element, Predicate<JsonElement> correctState) { if (!correctState.test(object.get(element))) throw new IllegalStateException("\"" + element + "\" is invalid"); }
From source file:cf.funge.aworldofplants.RequestRouter.java
License:Open Source License
/** * The main Lambda function handler. Receives the request as an input stream, parses the json and looks for the * "action" property to decide where to route the request. The "body" property of the incoming request is passed * to the Action implementation as a request body. * * @param request The InputStream for the incoming event. This should contain an "action" and "body" properties. The * action property should contain the namespaced name of the class that should handle the invocation. * The class should implement the Action interface. The body property should contain the full * request body for the action class. * @param response An OutputStream where the response returned by the action class is written * @param context The Lambda Context object * @throws BadRequestException This Exception is thrown whenever parameters are missing from the request or the action * class can't be found * @throws InternalErrorException This Exception is thrown when an internal error occurs, for example when the database * is not accessible *//*from w w w . ja va 2s.c o m*/ public static void lambdaHandler(InputStream request, OutputStream response, Context context) throws BadRequestException, InternalErrorException { LambdaLogger logger = context.getLogger(); JsonParser parser = new JsonParser(); JsonObject inputObj; try { inputObj = parser.parse(IOUtils.toString(request)).getAsJsonObject(); } catch (IOException e) { logger.log("Error while reading request\n" + e.getMessage()); throw new InternalErrorException(e.getMessage()); } if (inputObj == null || inputObj.get("action") == null || inputObj.get("action").getAsString().trim().equals("")) { logger.log("Invald inputObj, could not find action parameter"); throw new BadRequestException("Could not find action value in request"); } String actionClass = inputObj.get("action").getAsString(); Action action; try { action = Action.class.cast(Class.forName(actionClass).newInstance()); } catch (final InstantiationException e) { logger.log("Error while instantiating action class\n" + e.getMessage()); throw new InternalErrorException(e.getMessage()); } catch (final IllegalAccessException e) { logger.log("Illegal access while instantiating action class\n" + e.getMessage()); throw new InternalErrorException(e.getMessage()); } catch (final ClassNotFoundException e) { logger.log("Action class could not be found\n" + e.getMessage()); throw new InternalErrorException(e.getMessage()); } if (action == null) { logger.log("Action class is null"); throw new BadRequestException("Invalid action class"); } JsonObject body = null; if (inputObj.get("body") != null) { body = inputObj.get("body").getAsJsonObject(); } String output = action.handle(body, context); try { IOUtils.write(output, response); } catch (final IOException e) { logger.log("Error while writing response\n" + e.getMessage()); throw new InternalErrorException(e.getMessage()); } }
From source file:ch.cern.db.flume.sink.kite.parser.JSONtoAvroParser.java
License:GNU General Public License
/** * Parse the entity from the body in JSON of the given event. * /*from w w w . j av a2 s. c o m*/ * @param event * The event to parse. * @param reuse * If non-null, this may be reused and returned from this method. * @return The parsed entity as a GenericRecord. * @throws EventDeliveryException * A recoverable error such as an error downloading the schema * from the URL has occurred. * @throws NonRecoverableEventException * A non-recoverable error such as an unparsable schema or * entity has occurred. */ @Override public GenericRecord parse(Event event, GenericRecord reuse) throws EventDeliveryException, NonRecoverableEventException { JsonObject parser = new JsonParser().parse(new String(event.getBody())).getAsJsonObject(); GenericRecordBuilder recordBuilder = new GenericRecordBuilder(datasetSchema); for (Field field : datasetSchema.getFields()) { String at_header = field.getProp(FIELD_AT_HEADER_PROPERTY); if (at_header != null && at_header.equals(Boolean.TRUE.toString())) { recordBuilder.set(field.name(), event.getHeaders().get(field.name())); } else { JsonElement element = parser.get(field.name()); recordBuilder.set(field.name(), getElementAsType(field.schema(), element)); } } return recordBuilder.build(); }
From source file:ch.cern.db.flume.source.deserializer.RecoveryManagerDeserializer.java
License:GNU General Public License
/** * Reads a line from a file and returns an event * // w w w . j a v a 2 s .co m * @return Event containing parsed line * @throws IOException */ @Override public Event readEvent() throws IOException { ensureOpen(); in.mark(); if (in.read() == -1) return null; in.reset(); RecoveryManagerLogFile rman_log = new RecoveryManagerLogFile(in, maxLineLength); JSONEvent event = new JSONEvent(); event.addProperty("startTimestamp", rman_log.getStartTimestamp()); event.addProperty("backupType", rman_log.getBackupType()); event.addProperty("destination", rman_log.getBackupDestination()); event.addProperty("entityName", rman_log.getEntityName()); //Process properties like (name = value) for (Pair<String, String> property : rman_log.getProperties()) event.addProperty(property.getFirst(), property.getSecond()); String v_params = rman_log.getVParams(); event.addProperty("v_params", v_params != null ? new JsonParser().parse(v_params).getAsJsonObject() : null); JsonArray mountPointNASRegexResult = rman_log.getMountPointNASRegexResult(); event.addProperty("mountPointNASRegexResult", mountPointNASRegexResult); JsonArray volInfoBackuptoDiskFinalResult = rman_log.getVolInfoBackuptoDiskFinalResult(); event.addProperty("volInfoBackuptoDiskFinalResult", volInfoBackuptoDiskFinalResult); JsonArray valuesOfFilesystems = rman_log.getValuesOfFilesystems(); event.addProperty("valuesOfFilesystems", valuesOfFilesystems); List<RecoveryManagerReport> recoveryManagerReports = rman_log.getRecoveryManagerReports(); JsonArray recoveryManagerReportsJson = recoveryManagerReportsToJSON(recoveryManagerReports); event.addProperty("recoveryManagerReports", recoveryManagerReportsJson); int recoveryManagerReportsSize = recoveryManagerReportsJson.size(); if (recoveryManagerReportsSize > 0) { JsonObject lastReport = (JsonObject) recoveryManagerReportsJson.get(recoveryManagerReportsSize - 1); event.addProperty("finishTime", lastReport.get("finishTime")); event.addProperty("finalStatus", lastReport.get("status")); } else { event.addProperty("finishTime", null); event.addProperty("finalStatus", null); } return event; }
From source file:ch.cyberduck.core.sds.SDSExceptionMappingService.java
License:Open Source License
@Override public BackgroundException map(final ApiException failure) { for (Throwable cause : ExceptionUtils.getThrowableList(failure)) { if (cause instanceof SocketException) { // Map Connection has been shutdown: javax.net.ssl.SSLException: java.net.SocketException: Broken pipe return new DefaultSocketExceptionMappingService().map((SocketException) cause); }/*from w w w. ja v a2s. co m*/ if (cause instanceof HttpResponseException) { return new HttpResponseExceptionMappingService().map((HttpResponseException) cause); } if (cause instanceof IOException) { return new DefaultIOExceptionMappingService().map((IOException) cause); } } final StringBuilder buffer = new StringBuilder(); if (null != failure.getResponseBody()) { final JsonParser parser = new JsonParser(); try { final JsonObject json = parser.parse(new StringReader(failure.getResponseBody())).getAsJsonObject(); if (json.has("errorCode")) { if (json.get("errorCode").isJsonPrimitive()) { final int errorCode = json.getAsJsonPrimitive("errorCode").getAsInt(); if (log.isDebugEnabled()) { log.debug(String.format("Failure with errorCode %s", errorCode)); } final String key = String.format("Error %d", errorCode); final String localized = LocaleFactory.get().localize(key, "SDS"); this.append(buffer, localized); if (StringUtils.equals(localized, key)) { log.warn(String.format("Missing user message for error code %d", errorCode)); if (json.has("debugInfo")) { if (json.get("debugInfo").isJsonPrimitive()) { this.append(buffer, json.getAsJsonPrimitive("debugInfo").getAsString()); } } } switch (failure.getCode()) { case HttpStatus.SC_NOT_FOUND: switch (errorCode) { case -70501: // [-70501] User not found return new AccessDeniedException(buffer.toString(), failure); case -40761: // [-40761] Filekey not found for encrypted file return new AccessDeniedException(buffer.toString(), failure); } break; case HttpStatus.SC_PRECONDITION_FAILED: switch (errorCode) { case -10108: // [-10108] Radius Access-Challenge required. if (json.has("replyMessage")) { if (json.get("replyMessage").isJsonPrimitive()) { final JsonPrimitive replyMessage = json.getAsJsonPrimitive("replyMessage"); if (log.isDebugEnabled()) { log.debug(String.format("Failure with replyMessage %s", replyMessage)); } buffer.append(replyMessage.getAsString()); } } return new PartialLoginFailureException(buffer.toString(), failure); } break; case HttpStatus.SC_UNAUTHORIZED: switch (errorCode) { case -10012: // [-10012] Wrong token. return new ExpiredTokenException(buffer.toString(), failure); } break; } } } else { switch (failure.getCode()) { case HttpStatus.SC_INTERNAL_SERVER_ERROR: break; default: if (json.has("debugInfo")) { log.warn(String.format("Missing error code for failure %s", json)); if (json.get("debugInfo").isJsonPrimitive()) { this.append(buffer, json.getAsJsonPrimitive("debugInfo").getAsString()); } } } } } catch (JsonParseException e) { // Ignore this.append(buffer, failure.getMessage()); } } switch (failure.getCode()) { case HttpStatus.SC_PRECONDITION_FAILED: // [-10103] EULA must be accepted // [-10104] Password must be changed // [-10106] Username must be changed return new LoginFailureException(buffer.toString(), failure); } return new HttpResponseExceptionMappingService().map(failure, buffer, failure.getCode()); }
From source file:ch.ethz.inf.vs.hypermedia.corehal.block.CoREHalResourceFuture.java
License:Open Source License
@Override public V deserialize(String text) throws Exception { JsonObject jsonobj = getGson().fromJson(text, JsonObject.class); boolean hasDecoupled = jsonobj.has("_decoupled") && jsonobj.get("_decoupled").isJsonObject() && jsonobj.get("_decoupled").getAsJsonObject().entrySet().size() > 0; Class<V> type = hasDecoupled ? createProxyClass(getType()) : getType(); V item = getGson().fromJson(jsonobj, type); item.setJson(jsonobj);/*www. ja v a 2 s. c o m*/ if (hasDecoupled) { MethodHandler handler = (self, overridden, forwarder, args) -> { String methodName = overridden.getName(); if (methodName.equals("decoupledLoader")) { args[1] = getUrl(); } if ((!methodName.startsWith("get") && !methodName.startsWith("set")) || methodName.equals("getDecoupled")) { return forwarder.invoke(self, args); } // Intercept call to the getter function getter access String itemname = methodName.substring(3); if (methodName.equals("get") || methodName.equals("set")) { itemname = (String) args[0]; } itemname = itemname.substring(0, 1).toLowerCase() + itemname.substring(1); if (methodName.startsWith("get")) { if (item.getDecoupled() != null && item.getDecoupled().containsKey(itemname)) { return item.loadDecoupled(itemname, getUrl()); } } Object invoke = forwarder.invoke(self, args); if (methodName.startsWith("set")) { item.removeDecoupled(itemname); } return invoke; }; ((ProxyObject) item).setHandler(handler); } return item; }
From source file:ch.ethz.inf.vs.hypermedia.example.GithubBaseFuture.java
License:Open Source License
public <V extends GithubBaseFuture> V follow(String rel, Map<String, Object> parameters, Supplier<V> supplier) { V next = supplier.get();/* w ww . j av a2 s .com*/ next.addParent(this); next.setPreProcess(() -> { JsonObject item = get().getAsJsonObject(); // Get next link if (item.has(rel + "_url")) { // Resolve url template String uriTemplate = item.get(rel + "_url").getAsString(); String url = UriTemplate.fromTemplate(uriTemplate).expand(parameters); // Pass resolved url to future next.setRequestURL(url); return; } next.setException(new Exception("Not found")); }); return next; }
From source file:ch.gaps.slasher.views.main.MainController.java
License:Open Source License
/** * Read the save file and laod all the data in the software * * @throws IOException//from w w w . j a v a 2 s. c om */ private void readSave() { try { Gson gson = new Gson(); JsonReader reader = new JsonReader(new FileReader("save.json")); JsonArray mainArray = gson.fromJson(reader, JsonArray.class); LinkedList<Driver> drivers = DriverService.instance().getAll(); if (mainArray != null) { for (JsonElement e : mainArray) { JsonObject server = e.getAsJsonObject(); Driver driver = null; String serverDriver = server.get("serverDriver").getAsString(); for (Driver d : drivers) { if (d.toString().equals(serverDriver)) { driver = d.getClass().newInstance(); } } Server s = new Server(driver, server.get("serverHost").getAsString(), server.get("serverPort").getAsInt(), server.get("serverDescription").getAsString()); ServerTreeItem serverTreeItem = new ServerTreeItem(s); servers.add(s); JsonArray databases = server.get("databases").getAsJsonArray(); if (databases != null) { for (JsonElement d : databases) { if (!serverDriver.equals("Sqlite")) { driver = driver.getClass().newInstance(); } JsonObject database = d.getAsJsonObject(); Database db = new Database(driver, database.get("databaseName").getAsString(), database.get("databaseDescritpion").getAsString(), s, database.get("databaseUsername").getAsString()); s.addDatabase(db); if (serverDriver.equals("Sqlite")) { try { db.connect(""); } catch (SQLException | ClassNotFoundException e1) { e1.printStackTrace(); } } JsonArray tabs = database.get("tabs").getAsJsonArray(); for (JsonElement t : tabs) { JsonObject tab = t.getAsJsonObject(); if (tab.get("moduleName").getAsString().equals("Editor")) { loadEditorTab(db, tab.get("content").getAsString()); } } } } rootTreeItem.getChildren().add(serverTreeItem); } } } catch (IOException | IllegalAccessException | InstantiationException e) { addToUserCommunication(e.getMessage()); } }
From source file:ch.icclab.cyclops.consume.data.BillDeserializer.java
License:Open Source License
@Override public void preDeserialize(Class<? extends T> clazz, JsonElement jsonElement, Gson gson) { // valid JSON object if (jsonElement != null && jsonElement.isJsonObject()) { JsonObject root = jsonElement.getAsJsonObject(); // map data to string so it can be persisted as jsonb if (root.has(Bill.DATA_FIELD.getName())) { root.addProperty(Bill.DATA_FIELD.getName(), new Gson().toJson(root.get(Bill.DATA_FIELD.getName()))); }/*from ww w . ja v a 2 s.com*/ } }
From source file:ch.icclab.cyclops.consume.data.CDRDeserializer.java
License:Open Source License
@Override public void preDeserialize(Class<? extends T> clazz, JsonElement jsonElement, Gson gson) { // valid JSON object if (jsonElement != null && jsonElement.isJsonObject()) { JsonObject root = jsonElement.getAsJsonObject(); // map data to string so it can be persisted as jsonb if (root.has(CDR.DATA_FIELD.getName())) { root.addProperty(CDR.DATA_FIELD.getName(), new Gson().toJson(root.get(CDR.DATA_FIELD.getName()))); }//from w ww .j a v a 2s. c o m } }