public RollupTask parseRollupTask(String json) throws BeanValidationException, QueryException { JsonParser parser = new JsonParser(); JsonObject taskObject = parser.parse(json).getAsJsonObject(); RollupTask task = parseRollupTask(taskObject, ""); task.addJson(taskObject.toString().replaceAll("\\n", "")); return task; }
@Override public DateMidnight deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { // We'll accept either long (timestamp) or array: if (jp.isExpectedStartArrayToken()) { jp.nextToken(); // VALUE_NUMBER_INT int year = jp.getIntValue(); jp.nextToken(); // VALUE_NUMBER_INT int month = jp.getIntValue(); jp.nextToken(); // VALUE_NUMBER_INT int day = jp.getIntValue(); if (jp.nextToken() != JsonToken.END_ARRAY) { throw ctxt.wrongTokenException(jp, JsonToken.END_ARRAY, "after DateMidnight ints"); } return new DateMidnight(year, month, day); } switch (jp.getCurrentToken()) { case VALUE_NUMBER_INT: return new DateMidnight(jp.getLongValue()); case VALUE_STRING: DateTime local = parseLocal(jp); if (local == null) { return null; } return local.toDateMidnight(); } throw ctxt.wrongTokenException( jp, JsonToken.START_ARRAY, "expected JSON Array, Number or String"); }
@Override public ReadablePeriod deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { // TODO: perhaps support array of numbers... // if (jp.isExpectedStartArrayToken()) { ] switch (jp.getCurrentToken()) { case VALUE_NUMBER_INT: // assume it's millisecond count return new Period(jp.getLongValue()); case VALUE_STRING: return new Period(jp.getText()); } throw ctxt.wrongTokenException(jp, JsonToken.START_ARRAY, "expected JSON Number or String"); }
public List<RollupTask> parseRollupTasks(String json) throws BeanValidationException, QueryException { List<RollupTask> tasks = new ArrayList<RollupTask>(); JsonParser parser = new JsonParser(); JsonArray rollupTasks = parser.parse(json).getAsJsonArray(); for (int i = 0; i < rollupTasks.size(); i++) { JsonObject taskObject = rollupTasks.get(i).getAsJsonObject(); RollupTask task = parseRollupTask(taskObject, "tasks[" + i + "]"); task.addJson(taskObject.toString().replaceAll("\\n", "")); tasks.add(task); } return tasks; }
private void setBuildStatus(CIBuild ciBuild, CIJob job) throws PhrescoException { S_LOGGER.debug("Entering Method CIManagerImpl.setBuildStatus(CIBuild ciBuild)"); S_LOGGER.debug("setBuildStatus() url = " + ciBuild.getUrl()); String buildUrl = ciBuild.getUrl(); String jenkinsUrl = job.getJenkinsUrl() + ":" + job.getJenkinsPort(); buildUrl = buildUrl.replaceAll( "localhost:" + job.getJenkinsPort(), jenkinsUrl); // display the jenkins running url in ci list String response = getJsonResponse(buildUrl + API_JSON); JsonParser parser = new JsonParser(); JsonElement jsonElement = parser.parse(response); JsonObject jsonObject = jsonElement.getAsJsonObject(); JsonElement resultJson = jsonObject.get(FrameworkConstants.CI_JOB_BUILD_RESULT); JsonElement idJson = jsonObject.get(FrameworkConstants.CI_JOB_BUILD_ID); JsonElement timeJson = jsonObject.get(FrameworkConstants.CI_JOB_BUILD_TIME_STAMP); JsonArray asJsonArray = jsonObject.getAsJsonArray(FrameworkConstants.CI_JOB_BUILD_ARTIFACTS); if (jsonObject .get(FrameworkConstants.CI_JOB_BUILD_RESULT) .toString() .equals(STRING_NULL)) { // when build is result is not known ciBuild.setStatus(INPROGRESS); } else if (resultJson.getAsString().equals(CI_SUCCESS_FLAG) && asJsonArray.size() < 1) { // when build is success and zip relative path is not added in json ciBuild.setStatus(INPROGRESS); } else { ciBuild.setStatus(resultJson.getAsString()); // download path for (JsonElement jsonArtElement : asJsonArray) { String buildDownloadZip = jsonArtElement .getAsJsonObject() .get(FrameworkConstants.CI_JOB_BUILD_DOWNLOAD_PATH) .toString(); if (buildDownloadZip.endsWith(CI_ZIP)) { if (debugEnabled) { S_LOGGER.debug("download artifact " + buildDownloadZip); } ciBuild.setDownload(buildDownloadZip); } } } ciBuild.setId(idJson.getAsString()); String dispFormat = DD_MM_YYYY_HH_MM_SS; ciBuild.setTimeStamp(getDate(timeJson.getAsString(), dispFormat)); }
private void skipToField(JsonParser jp, String fieldName, ParseState state) throws JsonParseException, IOException { String lastFieldName = null; while (jp.getCurrentToken() != null) { switch (jp.getCurrentToken()) { case FIELD_NAME: lastFieldName = jp.getCurrentName(); jp.nextToken(); break; case START_OBJECT: if (!state.inRow) { state.inRow = true; jp.nextToken(); } else { if (isInField(fieldName, lastFieldName)) { return; } else { jp.skipChildren(); } } break; default: if (isInField(fieldName, lastFieldName)) { jp.nextToken(); return; } jp.nextToken(); break; } } }
protected String _valueDesc() { try { return _desc(_parser.getText()); } catch (Exception e) { return "[N/A]"; } }
private ArrayList<RemoteObject> deserializeArrayAsJson(String queryScope, String input) { ArrayList<RemoteObject> objects = new ArrayList<RemoteObject>(); JsonParser parser = new JsonParser(input); JsonArray parent = ((JsonElement) parser.parse( HttpAdapter.createResponseWrangling(queryScope, this).getCollectionSelector(), JsonElement.class)) .getAsJsonArray(); for (int i = 0; i < parent.size(); i++) { objects.add(deserialize(queryScope, new JsonParser(parent.get(i)))); } return objects; }
protected DateTime parseLocal(JsonParser jp) throws IOException, JsonProcessingException { String str = jp.getText().trim(); if (str.length() == 0) { // [JACKSON-360] return null; } return _localDateTimeFormat.parseDateTime(str); }
@SuppressWarnings("unchecked") @Override public T deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { JsonToken t = jp.getCurrentToken(); if (t == JsonToken.VALUE_NUMBER_INT) { return (T) new DateTime(jp.getLongValue(), DateTimeZone.UTC); } if (t == JsonToken.VALUE_STRING) { String str = jp.getText().trim(); if (str.length() == 0) { // [JACKSON-360] return null; } return (T) new DateTime(str, DateTimeZone.UTC); } throw ctxt.mappingException(getValueClass()); }
@Override public Leaf deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { JsonNode tree = (JsonNode) jp.readValueAsTree(); Leaf leaf = new Leaf(); leaf.value = tree.get("value").intValue(); return leaf; }
private String toJsonString() { final Object json = jsonParser.parseWith(createConfigurableJsonSlurper()); final String jsonString; if (json instanceof Map) { jsonString = JsonOutput.toJson((Map) json); } else { jsonString = JsonOutput.toJson(json); } return jsonString; }
private JsonArray getBuildsArray(CIJob job) throws PhrescoException { try { String jenkinsUrl = "http://" + job.getJenkinsUrl() + ":" + job.getJenkinsPort() + "/ci/"; String jobNameUtf8 = job.getName().replace(" ", "%20"); String buildsJsonUrl = jenkinsUrl + "job/" + jobNameUtf8 + "/api/json"; String jsonResponse = getJsonResponse(buildsJsonUrl); JsonParser parser = new JsonParser(); JsonElement jsonElement = parser.parse(jsonResponse); JsonObject jsonObject = jsonElement.getAsJsonObject(); JsonElement element = jsonObject.get(FrameworkConstants.CI_JOB_JSON_BUILDS); JsonArray jsonArray = element.getAsJsonArray(); return jsonArray; } catch (Exception e) { throw new PhrescoException(e); } }
private Parser createJsonParser(String queryScope, String input) { Parser parser = new JsonParser(input); if (!HttpAdapter.createResponseWrangling(queryScope, this).getRecordSelector().isEmpty()) { ((JsonParser) parser) .setRootElement( parser.parse( HttpAdapter.createResponseWrangling(queryScope, this).getRecordSelector(), JsonElement.class)); } return parser; }
private Object success(Class<?> clazz, HttpInputMessage inputMessage) throws JsonParseException, IOException { // Note, parsing code used from ektorp project JsonParser jp = objectMapper.getJsonFactory().createJsonParser(inputMessage.getBody()); if (jp.nextToken() != JsonToken.START_OBJECT) { throw new RuntimeException("Expected data to start with an Object"); } Map<String, Integer> fields = readHeaderFields(jp); List result; if (fields.containsKey(TOTAL_ROWS_FIELD_NAME)) { int totalRows = fields.get(TOTAL_ROWS_FIELD_NAME); if (totalRows == 0) { return Collections.emptyList(); } result = new ArrayList(totalRows); } else { result = new ArrayList(); } ParseState state = new ParseState(); Object first = parseFirstRow(jp, state, clazz); if (first == null) { return Collections.emptyList(); } else { result.add(first); } while (jp.getCurrentToken() != null) { skipToField(jp, state.docFieldName, state); if (atEndOfRows(jp)) { return result; } result.add(jp.readValueAs(clazz)); endRow(jp, state); } return result; }
private int getTotalBuilds(CIJob job) throws PhrescoException { try { S_LOGGER.debug("Entering Method CIManagerImpl.getTotalBuilds(CIJob job)"); S_LOGGER.debug("getCIBuilds() JobName = " + job.getName()); JsonArray jsonArray = getBuildsArray(job); Gson gson = new Gson(); CIBuild ciBuild = null; if (jsonArray.size() > 0) { ciBuild = gson.fromJson(jsonArray.get(0), CIBuild.class); String buildUrl = ciBuild.getUrl(); String jenkinsUrl = job.getJenkinsUrl() + ":" + job.getJenkinsPort(); // display the jenkins running url in ci buildUrl = buildUrl.replaceAll("localhost:" + job.getJenkinsPort(), jenkinsUrl); // list String response = getJsonResponse(buildUrl + API_JSON); JsonParser parser = new JsonParser(); JsonElement jsonElement = parser.parse(response); JsonObject jsonObject = jsonElement.getAsJsonObject(); JsonElement resultJson = jsonObject.get(FrameworkConstants.CI_JOB_BUILD_RESULT); JsonArray asJsonArray = jsonObject.getAsJsonArray(FrameworkConstants.CI_JOB_BUILD_ARTIFACTS); // when build result is not known if (jsonObject.get(FrameworkConstants.CI_JOB_BUILD_RESULT).toString().equals(STRING_NULL)) { // it indicates the job is in progress and not yet completed return -1; // when build is success and build zip relative path is unknown } else if (resultJson.getAsString().equals(CI_SUCCESS_FLAG) && asJsonArray.size() < 1) { return -1; } else { return jsonArray.size(); } } else { return -1; // When the project is build first time, } } catch (ClientHandlerException ex) { S_LOGGER.error(ex.getLocalizedMessage()); throw new PhrescoException(ex); } }
private Object parseFirstRow(JsonParser jp, ParseState state, Class clazz) throws JsonParseException, IOException, JsonProcessingException, JsonMappingException { skipToField(jp, VALUE_FIELD_NAME, state); JsonNode value = null; if (atObjectStart(jp)) { value = jp.readValueAsTree(); jp.nextToken(); if (isEndOfRow(jp)) { state.docFieldName = VALUE_FIELD_NAME; Object doc = objectMapper.readValue(value, clazz); endRow(jp, state); return doc; } } skipToField(jp, INCLUDED_DOC_FIELD_NAME, state); if (atObjectStart(jp)) { state.docFieldName = INCLUDED_DOC_FIELD_NAME; Object doc = jp.readValueAs(clazz); endRow(jp, state); return doc; } return null; }
private Map<String, Integer> readHeaderFields(JsonParser jp) throws JsonParseException, IOException { Map<String, Integer> map = new HashMap<String, Integer>(); jp.nextToken(); String nextFieldName = jp.getCurrentName(); while (!nextFieldName.equals(ROWS_FIELD_NAME)) { jp.nextToken(); map.put(nextFieldName, Integer.valueOf(jp.getIntValue())); jp.nextToken(); nextFieldName = jp.getCurrentName(); } return map; }
@Override public EnumMap<?, ?> deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { // Ok: must point to START_OBJECT if (jp.getCurrentToken() != JsonToken.START_OBJECT) { return _deserializeFromEmpty(jp, ctxt); } EnumMap result = constructMap(); final JsonDeserializer<Object> valueDes = _valueDeserializer; final TypeDeserializer typeDeser = _valueTypeDeserializer; while ((jp.nextToken()) == JsonToken.FIELD_NAME) { String keyName = jp.getCurrentName(); // just for error message // but we need to let key deserializer handle it separately, nonetheless Enum<?> key = (Enum<?>) _keyDeserializer.deserializeKey(keyName, ctxt); if (key == null) { if (!ctxt.isEnabled(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL)) { throw ctxt.weirdStringException( keyName, _enumClass, "value not one of declared Enum instance names for " + _mapType.getKeyType()); } /* 24-Mar-2012, tatu: Null won't work as a key anyway, so let's * just skip the entry then. But we must skip the value as well, if so. */ jp.nextToken(); jp.skipChildren(); continue; } // And then the value... JsonToken t = jp.nextToken(); /* note: MUST check for nulls separately: deserializers will * not handle them (and maybe fail or return bogus data) */ Object value; try { if (t == JsonToken.VALUE_NULL) { value = valueDes.getNullValue(ctxt); } else if (typeDeser == null) { value = valueDes.deserialize(jp, ctxt); } else { value = valueDes.deserializeWithType(jp, ctxt, typeDeser); } } catch (Exception e) { wrapAndThrow(e, result, keyName); return null; } result.put(key, value); } return result; }
private boolean isEndOfRow(JsonParser jp) { return jp.getCurrentToken() == JsonToken.END_OBJECT; }
private void endRow(JsonParser jp, ParseState state) throws IOException, JsonParseException { state.inRow = false; jp.nextToken(); }
private boolean atObjectStart(JsonParser jp) { return jp.getCurrentToken() == JsonToken.START_OBJECT; }
@Override public LocalDateTime deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { // We'll accept either long (timestamp) or array: if (jp.isExpectedStartArrayToken()) { jp.nextToken(); // VALUE_NUMBER_INT int year = jp.getIntValue(); jp.nextToken(); // VALUE_NUMBER_INT int month = jp.getIntValue(); jp.nextToken(); // VALUE_NUMBER_INT int day = jp.getIntValue(); jp.nextToken(); // VALUE_NUMBER_INT int hour = jp.getIntValue(); jp.nextToken(); // VALUE_NUMBER_INT int minute = jp.getIntValue(); jp.nextToken(); // VALUE_NUMBER_INT int second = jp.getIntValue(); // let's leave milliseconds optional? int millisecond = 0; if (jp.nextToken() != JsonToken.END_ARRAY) { // VALUE_NUMBER_INT millisecond = jp.getIntValue(); jp.nextToken(); // END_ARRAY? } if (jp.getCurrentToken() != JsonToken.END_ARRAY) { throw ctxt.wrongTokenException(jp, JsonToken.END_ARRAY, "after LocalDateTime ints"); } return new LocalDateTime(year, month, day, hour, minute, second, millisecond); } switch (jp.getCurrentToken()) { case VALUE_NUMBER_INT: return new LocalDateTime(jp.getLongValue()); case VALUE_STRING: DateTime local = parseLocal(jp); if (local == null) { return null; } return local.toLocalDateTime(); } throw ctxt.wrongTokenException(jp, JsonToken.START_ARRAY, "expected JSON Array or Number"); }
@Override public CustomMap deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { CustomMap result = new CustomMap(); result.put("x", jp.getText()); return result; }
/** Helper method for constructing generic mapping exception for specified type */ public JsonMappingException mappingException(Class<?> targetClass) { return mappingException(targetClass, _parser.getCurrentToken()); }
public List<QueryMetric> parseQueryMetric(String json) throws QueryException, BeanValidationException { JsonParser parser = new JsonParser(); JsonObject obj = parser.parse(json).getAsJsonObject(); return parseQueryMetric(obj); }
private boolean atEndOfRows(JsonParser jp) { return jp.getCurrentToken() != JsonToken.START_OBJECT; }
public <T> T getJsonObject(String path) { final JSONAssertion jsonAssertion = createJsonAssertion(path); final Object json = jsonParser.parseWith(createConfigurableJsonSlurper()); return (T) jsonAssertion.getAsJsonObject(json); }
/** Helper method for indicating that the current token was expected to be another token. */ public JsonMappingException wrongTokenException(JsonParser jp, JsonToken expToken, String msg) { return JsonMappingException.from( jp, "Unexpected token (" + jp.getCurrentToken() + "), expected " + expToken + ": " + msg); }