List of usage examples for com.google.gson JsonObject getAsJsonPrimitive
public JsonPrimitive getAsJsonPrimitive(String memberName)
From source file:fr.zcraft.zbanque.network.PacketSender.java
License:Open Source License
/** * Sends a packet.//from w ww.j a v a 2 s .c o m * * @param packet The packet to send. */ public static void sendPacket(final PacketPlayOut packet) { if (packet == null) return; sendPacket(packet, new WorkerCallback<JsonElement>() { @Override public void finished(JsonElement result) { if (packet.getHttpResponse().getResponseCode() == 401) { PluginLogger.error("Request to {0} failed: authentication needed", packet.getEndpoint()); return; } if (result != null) { packet.onResponse(result); for (Callback<JsonElement> callback : packet.getSuccessCallbacks()) { try { callback.call(result); } catch (Exception e) { PluginLogger.error("Uncaught exception thrown by a {0} success callback", e, packet.getClass().getSimpleName()); } } } } @Override public void errored(Throwable exception) { if (exception instanceof JsonParseException) { PluginLogger.error("The packet {0} received an invalid JSON response {1} (HTTP code {2})", packet.getClass().getSimpleName(), packet.getHttpResponse().getBody(), packet.getHttpResponse().getResponseCode()); return; } else if (exception instanceof FailedRequestException) { PluginLogger.error("The packet {0} request failed (HTTP code {1})", packet.getClass().getSimpleName(), ((FailedRequestException) exception).getResponse().getResponseCode()); final JsonObject error = ((FailedRequestException) exception).getJsonError().getAsJsonObject(); PluginLogger.error("Message: {0}", error.getAsJsonPrimitive("message").getAsString()); PluginLogger.error("Error: {0}", error.getAsJsonPrimitive("erreur").getAsString()); PluginLogger.error("Error code: {0}", error.getAsJsonPrimitive("code").getAsString()); return; } packet.onError(exception); for (Callback<Throwable> callback : packet.getErrorsCallbacks()) { try { callback.call(exception); } catch (Exception e) { PluginLogger.error("Uncaught exception thrown by a {0} error callback", e, packet.getClass().getSimpleName()); } } } }); }
From source file:geomesa.example.twitter.ingest.TwitterParser.java
License:Apache License
private SimpleFeature convertToFeature(final JsonObject obj, final SimpleFeatureBuilder builder, final GeometryFactory factory, final DateTimeFormatter df) { builder.reset();//from w ww. ja v a2s .c o m // user info final JsonObject user = obj.getAsJsonObject(USER); final String userName = user.getAsJsonPrimitive(USER_NAME).getAsString(); final String userId = user.getAsJsonPrimitive(USER_ID).getAsString(); builder.set(TwitterFeatureIngester.FEAT_USER_NAME, utf8(userName)); builder.set(TwitterFeatureIngester.FEAT_USER_ID, userId); builder.set(TwitterFeatureIngester.FEAT_TEXT, utf8(obj.get(TEXT).getAsString())); // geo info final boolean hasGeoJson = obj.has(COORDS_GEO_JSON) && obj.get(COORDS_GEO_JSON) != JsonNull.INSTANCE; if (hasGeoJson) { final JsonObject geo = obj.getAsJsonObject(COORDS_GEO_JSON); final JsonArray coords = geo.getAsJsonArray(COORDS); double lat = coords.get(0).getAsDouble(); double lon = coords.get(1).getAsDouble(); if (lon != 0.0 && lat != 0.0) { final Coordinate coordinate = new Coordinate(lat, lon); final Geometry g = new Point(new CoordinateArraySequence(new Coordinate[] { coordinate }), factory); builder.set(TwitterFeatureIngester.FEAT_GEOM, g); } } // time and id final String tweetId = obj.get(TWEET_ID).getAsString(); final Date date = df.parseDateTime(obj.get(CREATED_AT).getAsString()).toDate(); builder.set(TwitterFeatureIngester.FEAT_TWEET_ID, tweetId); builder.set(TwitterFeatureIngester.FEAT_DTG, date); if (useExtendedFeatures) { conditionalSetString(builder, obj, FEAT_IS_RETWEET); conditionalSetString(builder, obj, FEAT_SOURCE); conditionalSetString(builder, obj, FEAT_RETWEETS); conditionalSetString(builder, obj, FEAT_IN_REPLY_TO_USER_ID); conditionalSetString(builder, obj, FEAT_IN_REPLY_TO_USER_NAME); conditionalSetString(builder, obj, FEAT_IN_REPLY_TO_STATUS); conditionalSetString(builder, obj, FEAT_FILTER_LEVEL); conditionalSetString(builder, obj, FEAT_LANGUAGE); conditionalSetString(builder, obj, FEAT_WITHHELD_COPYRIGHT); conditionalSetString(builder, obj, FEAT_WITHHELD_SCOPE); conditionalSetArray(builder, obj, FEAT_WITHHELD_COUNTRIES); JsonElement entities = obj.get("entities"); if (entities != null && entities != JsonNull.INSTANCE) { JsonObject e = (JsonObject) entities; conditionalSetObjectArray(builder, e, FEAT_HASHTAGS, "text"); conditionalSetObjectArray(builder, e, FEAT_URLS, "url"); conditionalSetObjectArray(builder, e, FEAT_SYMBOLS, "text"); conditionalSetObjectArray(builder, e, FEAT_USER_MENTIONS, "id"); conditionalSetObjectArray(builder, e, FEAT_MEDIA, "media_url"); } } return builder.buildFeature(tweetId); }
From source file:geomesa.example.twitter.ingest.TwitterParser.java
License:Apache License
private void fillFeature(final JsonObject obj, final SimpleFeature sf, final GeometryFactory factory, final DateTimeFormatter df) { // user info/*from w w w .j av a 2s. c om*/ final JsonObject user = obj.getAsJsonObject(USER); final String userName = user.getAsJsonPrimitive(USER_NAME).getAsString(); final String userId = user.getAsJsonPrimitive(USER_ID).getAsString(); sf.setAttribute(TwitterFeatureIngester.FEAT_USER_NAME, utf8(userName)); sf.setAttribute(TwitterFeatureIngester.FEAT_USER_ID, userId); sf.setAttribute(TwitterFeatureIngester.FEAT_TEXT, utf8(obj.get(TEXT).getAsString())); // geo info final boolean hasGeoJson = obj.has(COORDS_GEO_JSON) && obj.get(COORDS_GEO_JSON) != JsonNull.INSTANCE; if (hasGeoJson) { final JsonObject geo = obj.getAsJsonObject(COORDS_GEO_JSON); final JsonArray coords = geo.getAsJsonArray(COORDS); double lat = coords.get(0).getAsDouble(); double lon = coords.get(1).getAsDouble(); if (lon != 0.0 && lat != 0.0) { final Coordinate coordinate = new Coordinate(lat, lon); final Geometry g = new Point(new CoordinateArraySequence(new Coordinate[] { coordinate }), factory); sf.setAttribute(TwitterFeatureIngester.FEAT_GEOM, g); } } // time and id final String tweetId = obj.get(TWEET_ID).getAsString(); final Date date = df.parseDateTime(obj.get(CREATED_AT).getAsString()).toDate(); sf.setAttribute(TwitterFeatureIngester.FEAT_TWEET_ID, tweetId); sf.setAttribute(TwitterFeatureIngester.FEAT_DTG, date); if (useExtendedFeatures) { conditionalSetString(sf, obj, FEAT_IS_RETWEET); conditionalSetString(sf, obj, FEAT_SOURCE); conditionalSetString(sf, obj, FEAT_RETWEETS); conditionalSetString(sf, obj, FEAT_IN_REPLY_TO_USER_ID); conditionalSetString(sf, obj, FEAT_IN_REPLY_TO_USER_NAME); conditionalSetString(sf, obj, FEAT_IN_REPLY_TO_STATUS); conditionalSetString(sf, obj, FEAT_FILTER_LEVEL); conditionalSetString(sf, obj, FEAT_LANGUAGE); conditionalSetString(sf, obj, FEAT_WITHHELD_COPYRIGHT); conditionalSetString(sf, obj, FEAT_WITHHELD_SCOPE); conditionalSetArray(sf, obj, FEAT_WITHHELD_COUNTRIES); JsonElement entities = obj.get("entities"); if (entities != null && entities != JsonNull.INSTANCE) { JsonObject e = (JsonObject) entities; conditionalSetObjectArray(sf, e, FEAT_HASHTAGS, "text"); conditionalSetObjectArray(sf, e, FEAT_URLS, "url"); conditionalSetObjectArray(sf, e, FEAT_SYMBOLS, "text"); conditionalSetObjectArray(sf, e, FEAT_USER_MENTIONS, "id"); conditionalSetObjectArray(sf, e, FEAT_MEDIA, "media_url"); } } //((FeatureIdImpl)sf.getIdentifier()).setID(Long.toString(tweetId)); //sf.getUserData().put(Hints.USE_PROVIDED_FID, Boolean.TRUE); }
From source file:gov.usgs.cida.iplover.auth.CrowdAuth.java
private static User authenticate(String username, char[] password, String basicAuth, String url) { User user = new User(); user.setAuthenticated(false);// w ww. j a v a2s. c o m Client client = ClientBuilder.newClient(); WebTarget target = client.target(url).path("authentication"); LOG.debug("target URI = " + target.getUri()); Invocation.Builder request = target.queryParam("username", username) .request(MediaType.APPLICATION_JSON_TYPE).header("Authorization", basicAuth) .header("Content-Type", MediaType.APPLICATION_JSON); Response result = request.post(Entity.json("{ \"value\" : \"" + String.valueOf(password) + "\" }")); String resultText = result.readEntity(String.class); LOG.debug("custom authenticate request result = " + result.getStatus()); LOG.debug(resultText); if (Response.Status.OK.getStatusCode() == result.getStatus()) { JsonElement element = new JsonParser().parse(resultText); JsonObject object = element.getAsJsonObject(); user.setUsername(object.getAsJsonPrimitive("name").getAsString()); user.setGivenName(object.getAsJsonPrimitive("display-name").getAsString()); user.setEmail(object.getAsJsonPrimitive("email").getAsString()); user.setAuthenticated(true); } else { throw new NotAuthorizedException(resultText); } if (user.isAuthenticated()) { target = client.target(url).path("user").path("group").path("direct"); request = target.queryParam("username", username).request(MediaType.APPLICATION_JSON_TYPE) .header("Authorization", basicAuth); result = request.get(); resultText = result.readEntity(String.class); LOG.debug("custom authorize request result = " + result.getStatus()); LOG.debug(resultText); if (Response.Status.OK.getStatusCode() == result.getStatus()) { JsonElement element = new JsonParser().parse(resultText); JsonArray groups = element.getAsJsonObject().getAsJsonArray("groups"); List<String> roles = new ArrayList<>(); for (int i = 0; i < groups.size(); i++) { String groupName = groups.get(i).getAsJsonObject().getAsJsonPrimitive("name").getAsString(); LOG.debug("adding group: " + groupName); if (groupName.toLowerCase().contains("iplover")) { roles.add(groupName); } } user.setRoles(roles); } } client.close(); return user; }
From source file:guru.qas.martini.report.column.ScenarioNameColumn.java
License:Apache License
@Override public void addResult(State state, Cell cell, JsonObject o) { JsonPrimitive primitive = o.getAsJsonPrimitive("name"); String name = null == primitive ? null : primitive.getAsString(); RichTextString richTextString = new XSSFRichTextString(name); cell.setCellValue(richTextString);/*w w w.j a va 2 s . co m*/ }
From source file:guru.qas.martini.report.column.StatusColumn.java
License:Apache License
@Override public void addResult(State state, Cell cell, JsonObject o) { JsonPrimitive primitive = o.getAsJsonPrimitive(KEY); String status = null == primitive ? null : primitive.getAsString(); RichTextString richTextString = new XSSFRichTextString(status); cell.setCellValue(richTextString);/*w w w . ja v a2 s . c om*/ state.setStatus(cell, status); }
From source file:guru.qas.martini.report.column.ThreadColumn.java
License:Apache License
@Override public void addResult(State state, Cell cell, JsonObject o) { JsonPrimitive primitive = o.getAsJsonPrimitive(KEY_GROUP); String group = null == primitive ? "" : primitive.getAsString(); primitive = o.getAsJsonPrimitive(KEY_NAME); String thread = null == primitive ? "" : primitive.getAsString(); String value = group.isEmpty() ? thread : String.format("%s %s", group, thread); RichTextString richTextString = new XSSFRichTextString(value); cell.setCellValue(richTextString);/* w w w . java2 s. c om*/ }
From source file:guru.qas.martini.report.column.TimestampColumn.java
License:Apache License
@Override public void addResult(State state, Cell cell, JsonObject o) { JsonPrimitive primitive = o.getAsJsonPrimitive(KEY); if (null != primitive) { addResult(cell, primitive);/* w w w . j a v a2 s . c o m*/ } }
From source file:guru.qas.martini.report.DefaultState.java
License:Apache License
protected String getId(JsonObject object) { JsonPrimitive primitive = object.getAsJsonPrimitive("id"); return primitive.getAsString(); }
From source file:guru.qas.martini.report.DefaultState.java
License:Apache License
@Override public void updateSuites(Sheet sheet) { int lastRowNum = sheet.getLastRowNum(); Row row = sheet.createRow(0 == lastRowNum ? 0 : lastRowNum + 1); row.createCell(0, CellType.STRING).setCellValue("ID"); row.createCell(1, CellType.STRING).setCellValue("Date"); row.createCell(2, CellType.STRING).setCellValue("Name"); row.createCell(3, CellType.STRING).setCellValue("Hostname"); row.createCell(4, CellType.STRING).setCellValue("IP"); row.createCell(5, CellType.STRING).setCellValue("Username"); row.createCell(6, CellType.STRING).setCellValue("Profiles"); row.createCell(7, CellType.STRING).setCellValue("Environment Variables"); for (Map.Entry<String, JsonObject> mapEntry : suites.entrySet()) { row = sheet.createRow(sheet.getLastRowNum() + 1); String id = mapEntry.getKey(); row.createCell(0, CellType.STRING).setCellValue(id); JsonObject suite = mapEntry.getValue(); JsonPrimitive primitive = suite.getAsJsonPrimitive("startTimestamp"); Long timestamp = null == primitive ? null : primitive.getAsLong(); Cell cell = row.createCell(1);/*from w w w .j a v a2 s .co m*/ if (null != timestamp) { Workbook workbook = sheet.getWorkbook(); CellStyle cellStyle = workbook.createCellStyle(); CreationHelper creationHelper = workbook.getCreationHelper(); cellStyle.setDataFormat(creationHelper.createDataFormat().getFormat("m/d/yy h:mm")); cellStyle.setVerticalAlignment(VerticalAlignment.TOP); cell.setCellValue(new Date(timestamp)); cell.setCellStyle(cellStyle); } cell = row.createCell(2); primitive = suite.getAsJsonPrimitive("name"); cell.setCellValue(null == primitive ? "" : primitive.getAsString()); cell = row.createCell(3); JsonObject host = suite.getAsJsonObject("host"); primitive = null == host ? null : host.getAsJsonPrimitive("name"); cell.setCellValue(null == primitive ? "" : primitive.getAsString()); cell = row.createCell(4); primitive = null == host ? null : host.getAsJsonPrimitive("ip"); cell.setCellValue(null == primitive ? "" : primitive.getAsString()); cell = row.createCell(5); primitive = null == host ? null : host.getAsJsonPrimitive("username"); cell.setCellValue(null == primitive ? "" : primitive.getAsString()); cell = row.createCell(6); JsonArray array = suite.getAsJsonArray("profiles"); List<String> profiles = Lists.newArrayList(); if (null != array) { int size = array.size(); for (int i = 0; i < size; i++) { JsonElement element = array.get(i); String profile = null == element ? null : element.getAsString(); profiles.add(profile); } String profilesValue = Joiner.on('\n').skipNulls().join(profiles); cell.setCellValue(profilesValue); } cell = row.createCell(7); JsonObject environmentVariables = suite.getAsJsonObject("environment"); Map<String, String> index = new TreeMap<>(); if (null != environmentVariables) { Set<Map.Entry<String, JsonElement>> entries = environmentVariables.entrySet(); for (Map.Entry<String, JsonElement> environmentEntry : entries) { String key = environmentEntry.getKey(); JsonElement element = environmentEntry.getValue(); String value = null == element ? "" : element.getAsString(); index.put(key, value); } String variablesValue = Joiner.on('\n').withKeyValueSeparator('=').useForNull("").join(index); cell.setCellValue(variablesValue); } } for (int i = 0; i < 8; i++) { sheet.autoSizeColumn(i, false); } }