List of usage examples for com.google.gson JsonParser parse
@Deprecated public JsonElement parse(JsonReader json) throws JsonIOException, JsonSyntaxException
From source file:brooklyn.networking.cloudstack.CloudstackNew40FeaturesClient.java
License:Apache License
public static JsonElement json(InputStream is) { JsonParser parser = new JsonParser(); JsonReader reader = null;//from w w w. ja va 2 s .c o m try { reader = new JsonReader(new InputStreamReader(is, "UTF-8")); } catch (UnsupportedEncodingException e) { throw Exceptions.propagate(e); } JsonElement el = parser.parse(reader); return el; }
From source file:brooklyn.storage.softlayer.SoftLayerRestClient.java
License:Apache License
public static JsonElement json(InputStream is) { JsonParser parser = new JsonParser(); JsonReader reader = null;//from w w w . j a v a 2 s . c om try { reader = new JsonReader(new InputStreamReader(is, "UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } JsonElement el = parser.parse(reader); return el; }
From source file:ca.ualberta.cmput301w14t08.geochan.json.ThreadCommentOfflineJsonConverter.java
License:Apache License
private void recursiveDeserialize(JsonObject object, String id, ArrayList<Comment> list) { JsonParser parser = new JsonParser(); JsonArray array = parser.parse(object.get(id).getAsString()).getAsJsonArray(); for (int i = 0; i < array.size(); ++i) { list.add(GsonHelper.getOfflineGson().fromJson(array.get(i), Comment.class)); }/*w ww .j a va 2s. co m*/ for (Comment comment : list) { ArrayList<Comment> childList = new ArrayList<Comment>(); recursiveDeserialize(object, comment.getId(), childList); comment.setChildren(childList); } }
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 *//* w w w. j av a2 s . 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.elasticsearch.serializer.JSONtoElasticSearchEventSerializer.java
License:GNU General Public License
private void appendBody(XContentBuilder builder, Event event) throws IOException { JsonParser parser = new JsonParser(); JsonObject json = parser.parse(new String(event.getBody())).getAsJsonObject(); for (Entry<String, JsonElement> property : json.entrySet()) { if (property.getValue().isJsonNull()) { builder.nullField(property.getKey()); continue; }/*w w w. j a v a 2 s. c o m*/ if (!property.getValue().isJsonPrimitive()) { builder.field(property.getKey(), property.getValue()); continue; } JsonPrimitive primitiveValue = (JsonPrimitive) property.getValue(); if (primitiveValue.isBoolean()) builder.field(property.getKey(), primitiveValue.getAsBoolean()); else if (primitiveValue.isNumber()) if (primitiveValue.getAsString().indexOf('.') != -1) builder.field(property.getKey(), primitiveValue.getAsNumber().doubleValue()); else builder.field(property.getKey(), primitiveValue.getAsNumber().longValue()); else if (primitiveValue.isString()) builder.field(property.getKey(), primitiveValue.getAsString()); } }
From source file:ch.cyberduck.core.dropbox.DropboxExceptionMappingService.java
License:Open Source License
private void parse(final StringBuilder buffer, final String message) { final JsonParser parser = new JsonParser(); try {/* w w w . jav a2 s .co m*/ final JsonElement element = parser.parse(new StringReader(message)); if (element.isJsonObject()) { final JsonObject json = element.getAsJsonObject(); final JsonObject error = json.getAsJsonObject("error"); if (null == error) { this.append(buffer, message); } else { final JsonPrimitive tag = error.getAsJsonPrimitive(".tag"); if (null == tag) { this.append(buffer, message); } else { this.append(buffer, StringUtils.replace(tag.getAsString(), "_", " ")); } } } if (element.isJsonPrimitive()) { this.append(buffer, element.getAsString()); } } catch (JsonParseException e) { // Ignore } }
From source file:ch.cyberduck.core.hubic.HubicAuthenticationResponseHandler.java
License:Open Source License
@Override public AuthenticationResponse handleResponse(final HttpResponse response) throws IOException { if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { Charset charset = HTTP.DEF_CONTENT_CHARSET; ContentType contentType = ContentType.get(response.getEntity()); if (contentType != null) { if (contentType.getCharset() != null) { charset = contentType.getCharset(); }/* www .j a v a 2 s. c o m*/ } try { final JsonParser parser = new JsonParser(); final JsonObject json = parser .parse(new InputStreamReader(response.getEntity().getContent(), charset)).getAsJsonObject(); final String token = json.getAsJsonPrimitive("token").getAsString(); final String endpoint = json.getAsJsonPrimitive("endpoint").getAsString(); return new AuthenticationResponse(response, token, Collections.singleton(new Region(null, URI.create(endpoint), null, true))); } catch (JsonParseException e) { throw new IOException(e.getMessage(), e); } } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED || response.getStatusLine().getStatusCode() == HttpStatus.SC_FORBIDDEN) { throw new AuthorizationException(new Response(response)); } throw new GenericException(new Response(response)); }
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); }/* w ww. ja v a 2 s. c o 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.iterate.openstack.swift.Client.java
License:Open Source License
/** * Lists the segments associated with an existing object. * * @param region The name of the storage region * @param container The name of the container * @param name The name of the object * @return a Map from container to lists of storage objects if a large object is present, otherwise null *///from w w w. j a v a 2s. co m public Map<String, List<StorageObject>> listObjectSegments(Region region, String container, String name) throws IOException { Map<String, List<StorageObject>> existingSegments = new HashMap<String, List<StorageObject>>(); try { ObjectMetadata existingMetadata = getObjectMetaData(region, container, name); if (existingMetadata.getMetaData().containsKey(Constants.MANIFEST_HEADER)) { /* * We have found an existing dynamic large object, so use the prefix to get a list of * existing objects. If we're putting up a new dlo, make sure the segment prefixes are * different, then we can delete anything that's not in the new list if necessary. */ String manifestDLO = existingMetadata.getMetaData().get(Constants.MANIFEST_HEADER); String segmentContainer = manifestDLO.substring(1, manifestDLO.indexOf('/', 1)); String segmentPath = manifestDLO.substring(manifestDLO.indexOf('/', 1), manifestDLO.length()); existingSegments.put(segmentContainer, this.listObjects(region, segmentContainer, segmentPath)); } else if (existingMetadata.getMetaData().containsKey(Constants.X_STATIC_LARGE_OBJECT)) { /* * We have found an existing static large object, so grab the manifest data that * details the existing segments - delete any later that we don't need any more */ boolean isSLO = "true".equals(existingMetadata.getMetaData().get(Constants.X_STATIC_LARGE_OBJECT) .toLowerCase(Locale.ENGLISH)); if (isSLO) { final JsonParser parser = new JsonParser(); URIBuilder urlBuild = new URIBuilder(region.getStorageUrl(container, name)); urlBuild.setParameter("multipart-manifest", "get"); URI url = urlBuild.build(); HttpGet method = new HttpGet(url); Response response = this.execute(method); if (response.getStatusCode() == HttpStatus.SC_OK) { String manifest = response.getResponseBodyAsString(); JsonArray segments = parser.parse(manifest).getAsJsonArray(); for (JsonElement o : segments) { /* * Parse each JSON object in the list and create a list of Storage Objects */ JsonObject segment = o.getAsJsonObject(); String objectPath = segment.get("name").getAsString(); String segmentContainer = objectPath.substring(1, objectPath.indexOf('/', 1)); String segmentPath = objectPath.substring(objectPath.indexOf('/', 1) + 1, objectPath.length()); List<StorageObject> containerSegments = existingSegments.get(segmentContainer); if (containerSegments == null) { containerSegments = new ArrayList<StorageObject>(); existingSegments.put(segmentContainer, containerSegments); } final StorageObject object = new StorageObject(segmentPath); object.setSize(Long.valueOf(segment.get("bytes").getAsString())); object.setMd5sum(segment.get("hash").getAsString()); object.setLastModified(segment.get("last_modified").getAsString()); object.setMimeType(segment.get("content_type").getAsString()); containerSegments.add(object); } } else { method.abort(); throw new GenericException(response); } } } else { /* * Not a large object, so return null */ return null; } } catch (NotFoundException e) { /* * Just means no object exists with the specified region, container and name */ return null; } catch (JsonParseException e) { throw new GenericException("JSON parsing failed reading static large object manifest", e); } catch (URISyntaxException e) { throw new GenericException("URI Building failed reading static large object manifest", e); } return existingSegments; }
From source file:ch.there.gson.GsonInvokerServiceExporter.java
License:Apache License
@Override public void handle(HttpExchange exchange) throws IOException { Gson gson = GsonFactory.getGson();/*from w ww . ja v a 2s .com*/ try { Integer rpcVersion = Integer.valueOf(exchange.getRequestHeaders().getFirst("rpc-version")); CallerRemoteApiVersion.setVersion(rpcVersion); InputStreamReader reader = new InputStreamReader(exchange.getRequestBody()); JsonParser parser = new JsonParser(); JsonObject remote = parser.parse(reader).getAsJsonObject(); String methodName = remote.get("methodName").getAsString(); Type collectionType = new TypeToken<Collection<Class<?>>>() { }.getType(); Collection<Class<?>> parameterTypes = gson.fromJson(remote.get("parameterTypes"), collectionType); JsonArray args = remote.get("arguments").getAsJsonArray(); Class<?>[] params = parameterTypes.toArray(new Class[parameterTypes.size()]); Object[] arguments = new Object[params.length]; for (int i = 0; i < params.length; i++) { Class<?> clazz = params[i]; Object argument = gson.fromJson(args.get(i), clazz); arguments[i] = argument; } RemoteInvocation remoteInvocation = new RemoteInvocation(methodName, params, arguments); RemoteInvocationResult result = invokeAndCreateResult(remoteInvocation, getProxy()); writeRemoteInvocationResult(exchange, result); exchange.close(); } catch (Throwable e) { e.printStackTrace(); } }