com.google.gson.JsonObject Java Examples

The following examples show how to use com.google.gson.JsonObject. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: XpubFull.java    From api-v1-client-java with MIT License 7 votes vote down vote up
public XpubFull (JsonObject json) {
    this(
            json.has("address") ? json.get("address").getAsString() : "",
            json.has("n_tx") ? json.get("n_tx").getAsInt() : 0,
            json.has("total_received") ? json.get("total_received").getAsLong() : 0,
            json.has("total_sent") ? json.get("total_sent").getAsLong() : 0,
            json.has("final_balance") ? json.get("final_balance").getAsLong() : 0,
            json.has("change_index") ? json.get("change_index").getAsInt() : 0,
            json.has("account_index") ? json.get("account_index").getAsInt() : 0,
            json.has("gap_limit") ? json.get("gap_limit").getAsInt() : 0,
            null
    );

    txs = new ArrayList<Transaction>();
    for (JsonElement txElem : json.get("txs").getAsJsonArray()) {
        JsonObject addrObj = txElem.getAsJsonObject();
        txs.add(new Transaction(addrObj));
    }
}
 
Example #2
Source File: JobsConfigGenerator.java    From simpleci with MIT License 6 votes vote down vote up
private boolean isValidCell(JsonObject matrixCell, Build build) {
    if (!matrixCell.has("on")) {
        return true;
    }

    JsonObject onCond = matrixCell.get("on").getAsJsonObject();
    if (onCond.has("branch")) {
        JsonElement branchCond = onCond.get("branch");
        Set<String> allowedBranches;
        if (branchCond.isJsonPrimitive()) {
            allowedBranches = ImmutableSet.of(branchCond.getAsString());
        } else if(branchCond.isJsonArray()) {
            allowedBranches = ImmutableSet.copyOf(JsonUtils.jsonArrayToStringList(branchCond.getAsJsonArray()));
        } else {
            return false;
        }
        if (!allowedBranches.contains(build.branch)) {
            return false;
        }

    }
    return true;
}
 
Example #3
Source File: SessionTpidGetValidatedHandler.java    From mxisd with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) {
    String sid = getQueryParameter(exchange, "sid");
    String secret = getQueryParameter(exchange, "client_secret");

    try {
        ThreePidValidation pid = mgr.getValidated(sid, secret);

        JsonObject obj = new JsonObject();
        obj.addProperty("medium", pid.getMedium());
        obj.addProperty("address", pid.getAddress());
        obj.addProperty("validated_at", pid.getValidation().toEpochMilli());

        respond(exchange, obj);
    } catch (SessionNotValidatedException e) {
        log.info("Session {} was requested but has not yet been validated", sid);
        throw e;
    }
}
 
Example #4
Source File: WxMpCardServiceImpl.java    From weixin-java-tools with Apache License 2.0 6 votes vote down vote up
@Override
public String getCardDetail(String cardId) throws WxErrorException {
  JsonObject param = new JsonObject();
  param.addProperty("card_id", cardId);
  String responseContent = this.wxMpService.post(CARD_GET, param.toString());

  // 判断返回值
  JsonObject json = (new JsonParser()).parse(responseContent).getAsJsonObject();
  String errcode = json.get("errcode").getAsString();
  if (!"0".equals(errcode)) {
    String errmsg = json.get("errmsg").getAsString();
    throw new WxErrorException(WxError.builder()
      .errorCode(Integer.valueOf(errcode)).errorMsg(errmsg)
      .build());
  }

  return responseContent;
}
 
Example #5
Source File: GroupClient.java    From jmessage-api-java-client with MIT License 6 votes vote down vote up
public ResponseWrapper changeGroupAdmin(long gid, String appKey, String username)
        throws APIConnectionException, APIRequestException {
    Preconditions.checkArgument(gid > 0, "gid should more than 0.");

    if (StringUtils.isTrimedEmpty(appKey) && StringUtils.isTrimedEmpty(username)) {
        Preconditions.checkArgument(false, "appKey and username should not be null at the same time.");
    }

    JsonObject json = new JsonObject();
    if (StringUtils.isNotEmpty(appKey)){
        appKey=appKey.trim();
        json.addProperty("appKey",appKey);
    }

    if (StringUtils.isNotEmpty(username)){
        username=username.trim();
        json.addProperty("username",username);
    }

    return _httpClient.sendPut(_baseUrl + groupPath + "/owner/" + gid,json.toString());
}
 
Example #6
Source File: StreamsBuildService.java    From streamsx.topology with Apache License 2.0 6 votes vote down vote up
@Override
	public Build createBuild(String name, JsonObject buildConfig) throws IOException {
		
		JsonObject buildParams = new JsonObject();

		buildParams.addProperty("type", buildType.getJsonValue());
		buildParams.addProperty("incremental", false);		
		if (name != null)
			buildParams.addProperty("name", name);
		String bodyStr = buildParams.toString();
//        System.out.println("StreamsBuildService: =======> POST body = " + bodyStr);
		Request post = Request.Post(endpoint)	      
		    .addHeader("Authorization", getAuthorization())
		    .bodyString(bodyStr,
		                ContentType.APPLICATION_JSON);
		
		Build build = Build.create(this, this, StreamsRestUtils.requestGsonResponse(executor, post));
		return build;
	}
 
Example #7
Source File: HarFileHandler.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
private JsonArray handleHeaders(MimeHeaders headers) throws IOException {
   JsonArray response = new JsonArray();
   if (headers != null) {
      Iterator headersIterator = headers.getAllHeaders();

      while(headersIterator.hasNext()) {
         MimeHeader mimheader = (MimeHeader)headersIterator.next();
         JsonObject header = new JsonObject();
         header.addProperty("name", mimheader.getName());
         header.addProperty("value", mimheader.getValue());
         response.add(header);
      }
   }

   return response;
}
 
Example #8
Source File: JsonParser.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
private void parseChildren(String path, JsonObject object, Element context, boolean hasResourceType) throws FHIRException {
	reapComments(object, context);
	List<Property> properties = context.getProperty().getChildProperties(context.getName(), null);
	Set<String> processed = new HashSet<String>();
	if (hasResourceType)
		processed.add("resourceType");
	processed.add("fhir_comments");

	// note that we do not trouble ourselves to maintain the wire format order here - we don't even know what it was anyway
	// first pass: process the properties
	for (Property property : properties) {
		parseChildItem(path, object, context, processed, property);
	}

	// second pass: check for things not processed
	if (policy != ValidationPolicy.NONE) {
		for (Entry<String, JsonElement> e : object.entrySet()) {
			if (!processed.contains(e.getKey())) {
				logError(line(e.getValue()), col(e.getValue()), path, IssueType.STRUCTURE, "Unrecognised property '@"+e.getKey()+"'", IssueSeverity.ERROR);      		
			}
		}
	}
}
 
Example #9
Source File: Product.java    From EasyVolley with Apache License 2.0 6 votes vote down vote up
public static ArrayList<Product> parseJsonArray(JsonArray jsonArray) {
    ArrayList<Product> products = new ArrayList<>(jsonArray.size());

    Gson gson = new Gson();
    for (int i=0 ; i<jsonArray.size() ; i++) {
        JsonObject jsonObject = jsonArray.get(i).getAsJsonObject();
        Product product = gson.fromJson(jsonObject, Product.class);

        // temp hack for build
        for (int j=0 ; j<product.getImages().length ; j++) {
            product.getImages()[j].setPath(product.getImages()[j].getPath().replace("-catalogmobile", ""));
        }

        products.add(product);
    }

    return products;
}
 
Example #10
Source File: JsonTuples.java    From quarks with Apache License 2.0 6 votes vote down vote up
/**
     * Create a JsonObject wrapping a raw {@code Pair<Long msec,T reading>>} sample.
     * @param sample the raw sample
     * @param id the sensor's Id
     * @return the wrapped sample
     */
    public static <T> JsonObject wrap(Pair<Long,T> sample, String id) {
        JsonObject jo = new JsonObject();
        jo.addProperty(KEY_ID, id);
        jo.addProperty(KEY_TS, sample.getFirst());
        T value = sample.getSecond();
        if (value instanceof Number)
            jo.addProperty(KEY_READING, (Number)sample.getSecond());
        else if (value instanceof String)
            jo.addProperty(KEY_READING, (String)sample.getSecond());
        else if (value instanceof Boolean)
            jo.addProperty(KEY_READING, (Boolean)sample.getSecond());
//        else if (value instanceof array) {
//            // TODO cvt to JsonArray
//        }
//        else if (value instanceof Object) {
//            // TODO cvt to JsonObject
//        }
        else {
            Class<?> clazz = value != null ? value.getClass() : Object.class;
            throw new IllegalArgumentException("Unhandled value type: "+ clazz);
        }
        return jo;
    }
 
Example #11
Source File: JsonDVReportGenerator.java    From jumbune with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Generate data validation report.
 *
 * @param dvReport the dv report
 * @return the string
 */
public String generateDataValidationReport(String dvReport) {
	JsonDataValidationDashBoardReport boardReport = new JsonDataValidationDashBoardReport();
	JsonElement jelement = new JsonParser().parse(dvReport);
	JsonObject jobject = jelement.getAsJsonObject();
	
	setNullViolations(jobject, boardReport);
	setRegexViolations(jobject, boardReport);
	setDataTypeChecks(jobject, boardReport);
	setSchemaViolations(jobject, boardReport);
	setMissingViolations(jobject, boardReport);
	
	JsonElement jsonElement = new Gson().toJsonTree(boardReport, JsonDataValidationDashBoardReport.class);
	jobject.add("DVSUMMARY", jsonElement);
	return jobject.toString();

}
 
Example #12
Source File: JavascriptServiceNameStrategy.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
@Nullable
public static Object run(@NotNull Project project, @NotNull String className, @NotNull String serviceJsNameStrategy) throws ScriptException {

    JsonObject jsonObject = new JsonObject();

    jsonObject.addProperty("className", className);
    jsonObject.addProperty("projectName", project.getName());
    jsonObject.addProperty("projectBasePath", project.getBasePath());
    jsonObject.addProperty("defaultNaming", new DefaultServiceNameStrategy().getServiceName(new ServiceNameStrategyParameter(project, className)));

    PhpClass aClass = PhpElementsUtil.getClass(project, className);
    if(aClass != null) {
        String relativePath = VfsUtil.getRelativePath(aClass.getContainingFile().getVirtualFile(), ProjectUtil.getProjectDir(aClass), '/');
        if(relativePath != null) {
            jsonObject.addProperty("relativePath", relativePath);
        }
        jsonObject.addProperty("absolutePath", aClass.getContainingFile().getVirtualFile().toString());
    }

    ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
    if(engine == null) {
        return null;
    }

    return engine.eval("var __p = eval(" + jsonObject.toString() + "); result = function(args) { " + serviceJsNameStrategy + " }(__p)");
}
 
Example #13
Source File: BsonDecimal128Test.java    From immutables with Apache License 2.0 6 votes vote down vote up
@Test
public void write() throws Exception {
  JsonObject obj = new JsonObject();
  BigInteger bigInteger = new BigInteger(Long.toString(Long.MAX_VALUE)).multiply(new BigInteger("128"));
  obj.addProperty("bigInteger", bigInteger);

  BigDecimal bigDecimal = new BigDecimal(Long.MAX_VALUE).multiply(new BigDecimal(1024));
  obj.addProperty("bigDecimal", bigDecimal);

  BsonDocument doc = Jsons.toBson(obj);

  check(doc.get("bigInteger").getBsonType()).is(BsonType.DECIMAL128);
  check(doc.get("bigInteger").asDecimal128().decimal128Value().bigDecimalValue().toBigInteger()).is(bigInteger);

  check(doc.get("bigDecimal").getBsonType()).is(BsonType.DECIMAL128);
  check(doc.get("bigDecimal").asDecimal128().decimal128Value().bigDecimalValue()).is(bigDecimal);
}
 
Example #14
Source File: JoinBatchInformationTypeAdapter.java    From rya with Apache License 2.0 6 votes vote down vote up
@Override
public JsonElement serialize(final JoinBatchInformation batch, final Type typeOfSrc, final JsonSerializationContext context) {
    final JsonObject result = new JsonObject();
    result.add("class", new JsonPrimitive(batch.getClass().getName()));
    result.add("batchSize", new JsonPrimitive(batch.getBatchSize()));
    result.add("task", new JsonPrimitive(batch.getTask().name()));
    final Column column = batch.getColumn();
    result.add("column", new JsonPrimitive(column.getsFamily() + "\u0000" + column.getsQualifier()));
    final Span span = batch.getSpan();
    result.add("span", new JsonPrimitive(span.getStart().getsRow() + "\u0000" + span.getEnd().getsRow()));
    result.add("startInc", new JsonPrimitive(span.isStartInclusive()));
    result.add("endInc", new JsonPrimitive(span.isEndInclusive()));
    result.add("side", new JsonPrimitive(batch.getSide().name()));
    result.add("joinType", new JsonPrimitive(batch.getJoinType().name()));
    final String updateVarOrderString = Joiner.on(";").join(batch.getBs().getBindingNames());
    final VariableOrder updateVarOrder = new VariableOrder(updateVarOrderString);
    result.add("bindingSet", new JsonPrimitive(converter.convert(batch.getBs(), updateVarOrder)));
    result.add("updateVarOrder", new JsonPrimitive(updateVarOrderString));
    return result;
}
 
Example #15
Source File: SerializedTransaction.java    From mangopay2-java-sdk with MIT License 6 votes vote down vote up
static JsonObject getTransactionObject(Transaction source, JsonSerializationContext context) {
    JsonObject object = new JsonObject();
    object.add("Id", context.serialize(source.getId()));
    object.add("Tag", context.serialize(source.getTag()));
    object.add("CreationDate", context.serialize(source.getCreationDate()));

    object.add("AuthorId", context.serialize(source.getAuthorId()));
    object.add("CreditedUserId", context.serialize(source.getCreditedUserId()));
    object.add("DebitedFunds", context.serialize(source.getDebitedFunds()));
    object.add("CreditedFunds", context.serialize(source.getCreditedFunds()));
    object.add("Fees", context.serialize(source.getFees()));
    object.add("Status", context.serialize(source.getStatus()));
    object.add("ResultCode", context.serialize(source.getResultCode()));
    object.add("ResultMessage", context.serialize(source.getResultMessage()));
    object.add("ExecutionDate", context.serialize(source.getExecutionDate()));
    object.add("Type", context.serialize(source.getType()));
    object.add("Nature", context.serialize(source.getNature()));

    return object;
}
 
Example #16
Source File: TopicsImpl.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@Override
public CompletableFuture<JsonObject> getInternalInfoAsync(String topic) {
    TopicName tn = validateTopic(topic);
    WebTarget path = topicPath(tn, "internal-info");
    final CompletableFuture<JsonObject> future = new CompletableFuture<>();
    asyncGetRequest(path,
            new InvocationCallback<String>() {
                @Override
                public void completed(String response) {
                    JsonObject json = new Gson().fromJson(response, JsonObject.class);
                    future.complete(json);
                }

                @Override
                public void failed(Throwable throwable) {
                    future.completeExceptionally(getApiException(throwable.getCause()));
                }
            });
    return future;
}
 
Example #17
Source File: JsonLoader.java    From asteria-3.0 with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Loads the parsed data. How the data is loaded is defined by
 * {@link JsonLoader#load(JsonObject, Gson)}.
 *
 * @return the loader instance, for chaining.
 */
public final JsonLoader load() {
    try (FileReader in = new FileReader(Paths.get(path).toFile())) {
        JsonParser parser = new JsonParser();
        JsonArray array = (JsonArray) parser.parse(in);
        Gson builder = new GsonBuilder().create();

        for (int i = 0; i < array.size(); i++) {
            JsonObject reader = (JsonObject) array.get(i);
            load(reader, builder);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return this;
}
 
Example #18
Source File: UpsertBlockTest.java    From dgraph4j with Apache License 2.0 5 votes vote down vote up
@Test
public void upsertMultipleWithinSingleTransactionTest() {
  DgraphProto.Operation op =
      DgraphProto.Operation.newBuilder()
          .setSchema("email: string @index(exact) @upsert .")
          .build();
  dgraphClient.alter(op);

  JsonArray jsonData = new JsonArray();
  JsonObject person = new JsonObject();
  person.addProperty("uid", "uid(v)");
  person.addProperty("name", "wrong");
  jsonData.add(person);

  JsonObject person2 = new JsonObject();
  person2.addProperty("email", "[email protected]");
  person2.addProperty("uid", "uid(v)");
  jsonData.add(person2);

  String query =
      "{\n"
          + "    me(func: eq(email, \"[email protected]\")) {\n"
          + "        v as uid\n"
          + "    }\n"
          + "}\n";
  Mutation mu =
      Mutation.newBuilder().setSetJson(ByteString.copyFromUtf8(jsonData.toString())).build();
  Request request = Request.newBuilder().addMutations(mu).setQuery(query).build();

  Transaction transaction = dgraphClient.newTransaction();
  transaction.doRequest(request);

  try {
    transaction.doRequest(request);
  } catch (RuntimeException e) {
    fail(e.getMessage());
  }

  transaction.discard();
}
 
Example #19
Source File: AmadronOfferConfig.java    From PneumaticCraft with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected final void writeToJson(JsonObject json){
    JsonArray array = new JsonArray();
    for(AmadronOffer offer : getOffers()) {
        array.add(offer.toJson());
    }
    json.addProperty("description", getComment());
    writeToJsonCustom(json);
    json.add("offers", array);
}
 
Example #20
Source File: LocalFileCodec.java    From twill with Apache License 2.0 5 votes vote down vote up
@Override
public LocalFile deserialize(JsonElement json, Type typeOfT,
                             JsonDeserializationContext context) throws JsonParseException {
  JsonObject jsonObj = json.getAsJsonObject();

  String name = jsonObj.get("name").getAsString();
  URI uri = URI.create(jsonObj.get("uri").getAsString());
  long lastModified = jsonObj.get("lastModified").getAsLong();
  long size = jsonObj.get("size").getAsLong();
  boolean archive = jsonObj.get("archive").getAsBoolean();
  JsonElement pattern = jsonObj.get("pattern");

  return new DefaultLocalFile(name, uri, lastModified, size,
                              archive, (pattern == null || pattern.isJsonNull()) ? null : pattern.getAsString());
}
 
Example #21
Source File: ChatRoomClient.java    From jmessage-api-java-client with MIT License 5 votes vote down vote up
/**
 * Update chat room info
 *
 * @param roomId        room id
 * @param ownerUsername owner username
 * @param name          new chat room name
 * @param desc          chat room description
 * @return No content
 * @throws APIConnectionException connect exception
 * @throws APIRequestException    request exception
 */
public ResponseWrapper updateChatRoomInfo(long roomId, String ownerUsername, String name, String desc)
        throws APIConnectionException, APIRequestException {
    Preconditions.checkArgument(roomId > 0, "room id is invalid");
    StringUtils.checkUsername(ownerUsername);
    Preconditions.checkArgument(null != name, "Chat room name is null");
    Preconditions.checkArgument(null != desc, "Description is null");
    JsonObject jsonObject = new JsonObject();
    jsonObject.addProperty(ChatRoomPayload.OWNER, ownerUsername);
    jsonObject.addProperty(ChatRoomPayload.NAME, name);
    jsonObject.addProperty(ChatRoomPayload.DESC, desc);
    return _httpClient.sendPut(_baseUrl + mChatRoomPath + "/" + roomId, _gson.toJson(jsonObject));
}
 
Example #22
Source File: SnapshotAPIStateBuilder.java    From writelatex-git-bridge with MIT License 5 votes vote down vote up
private void addPostbackForProject(
        String projectName,
        JsonObject jsonPostback
) {
    SnapshotPostbackRequest p;
    String type = jsonPostback.get("type").getAsString();
    if (type.equals("success")) {
        p = new SnapshotPostbackRequestSuccess(
                jsonPostback.get("versionID").getAsInt()
        );
    } else if (type.equals("outOfDate")) {
        p = new SnapshotPostbackRequestOutOfDate();
    } else if (type.equals("invalidFiles")) {
        p = new SnapshotPostbackRequestInvalidFiles(
                jsonPostback.get("errors").getAsJsonArray()
        );
    } else if (type.equals("invalidProject")) {
        p = new SnapshotPostbackRequestInvalidProject(
                jsonPostback.get("errors").getAsJsonArray()
        );
    } else if (type.equals("error")) {
        p = new SnapshotPostbackRequestError();
    } else {
        throw new IllegalArgumentException("invalid postback type");
    }
    postback.put(projectName, p);
}
 
Example #23
Source File: AccountingEventsPaymentManagerController.java    From fenixedu-academic with GNU Lesser General Public License v3.0 5 votes vote down vote up
private Map<LocalDate, Money> createMapFromJSON(String jsonString) {
    JsonObject json = (JsonObject) new JsonParser().parse(jsonString);
    JsonObject map = json.getAsJsonObject("map");
    HashMap<LocalDate, Money> hashMap = new HashMap<>();

    map.entrySet().forEach(e -> hashMap.put(new LocalDate(e.getKey()), new Money(e.getValue().getAsString())));
    return hashMap;
}
 
Example #24
Source File: SmartQQApi.java    From SmartIM with Apache License 2.0 5 votes vote down vote up
/**
 * 获得最近会话列表
 *
 * @return
 */
public JsonArray getRecentList() throws Exception {
    LOGGER.info("开始获取最近会话列表");
    
    JsonObject r = new JsonObject();
    r.addProperty("vfwebqq", vfwebqq);
    r.addProperty("clientid", Client_ID);
    r.addProperty("psessionid", "");
    
    Response response = post(ApiURL.GET_RECENT_LIST, r);
    return (getJsonArrayResult(response));
}
 
Example #25
Source File: PayOutSerializer.java    From mangopay2-java-sdk with MIT License 5 votes vote down vote up
@Override
public JsonElement serialize(PayOut src, Type typeOfSrc, JsonSerializationContext context) {
    JsonObject object = SerializedTransaction.getTransactionObject(src, context);
    object.add("DebitedWalletId", context.serialize(src.getDebitedWalletId()));
    object.add("PaymentType", context.serialize(src.getPaymentType()));
    switch (src.getMeanOfPaymentDetails().getClass().getSimpleName()) {
        case "PayOutPaymentDetailsBankWire":
            object.add("BankAccountId", context.serialize(((PayOutPaymentDetailsBankWire) src.getMeanOfPaymentDetails()).getBankAccountId()));
            object.add("BankWireRef", context.serialize(((PayOutPaymentDetailsBankWire) src.getMeanOfPaymentDetails()).getBankWireRef()));
            return object;
        default:
            return null;
    }
}
 
Example #26
Source File: PlatformServiceUtil.java    From Insights with Apache License 2.0 5 votes vote down vote up
public static ClientResponse publishConfigChanges(String host, int port, JsonObject requestJson) {
	WebResource resource = Client.create()
			.resource("http://" + host + ":" + port + "/PlatformEngine/refreshAggregators");
	ClientResponse response = resource.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON)
			.entity(requestJson.toString()).post(ClientResponse.class);
	return response;
}
 
Example #27
Source File: VariantJsonSerializer.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public JsonElement serialize ( final Variant src, final Type typeOfSrc, final JsonSerializationContext context )
{
    if ( src == null )
    {
        return JsonNull.INSTANCE;
    }

    final JsonObject result = new JsonObject ();
    result.addProperty ( VariantJson.FIELD_TYPE, src.getType ().toString () );
    switch ( src.getType () )
    {
        case BOOLEAN:
            result.addProperty ( VariantJson.FIELD_VALUE, src.asBoolean ( null ) );
            break;
        case DOUBLE: //$FALL-THROUGH$
        case INT32: //$FALL-THROUGH$
        case INT64:
            result.addProperty ( VariantJson.FIELD_VALUE, (Number)src.getValue () );
            break;
        case STRING:
            result.addProperty ( VariantJson.FIELD_VALUE, src.asString ( null ) );
            break;
        case NULL:
            result.add ( VariantJson.FIELD_VALUE, JsonNull.INSTANCE );
            break;
        default:
            throw new RuntimeException ( String.format ( "Unknown variant type '%s' encountered", src.getType () ) );
    }
    return result;
}
 
Example #28
Source File: ShadowGraphBuilder.java    From javers with Apache License 2.0 5 votes vote down vote up
private ShadowBuilder assembleShadowStub(CdoSnapshot cdoSnapshot) {
    ShadowBuilder shadowBuilder = new ShadowBuilder(cdoSnapshot, null);
    builtNodes.put(cdoSnapshot.getGlobalId(), shadowBuilder);

    JsonObject jsonElement = toJson(cdoSnapshot.getState());
    mapCustomPropertyNamesToJavaOrigin(cdoSnapshot.getManagedType(), jsonElement);
    followReferences(shadowBuilder, jsonElement);

    shadowBuilder.withStub(
            deserializeObjectFromJsonElement(cdoSnapshot.getManagedType(), jsonElement));

    return shadowBuilder;
}
 
Example #29
Source File: XVerExtensionManager.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
public XVerExtensionStatus status(String url) throws FHIRException {
  String v = url.substring(20, 23);
  if ("5.0".equals(v)) {
    v = Constants.VERSION_MM;
  }
  String e = url.substring(54);
  if (!lists.containsKey(v)) {
    if (context.getBinaries().containsKey("xver-paths-"+v+".json")) {
      try {
        lists.put(v, JsonTrackingParser.parseJson(context.getBinaries().get("xver-paths-"+v+".json")));
      } catch (IOException e1) {
        throw new FHIRException(e);
      }
    } else {
      return XVerExtensionStatus.BadVersion;
    }
  }
  JsonObject root = lists.get(v);
  JsonObject path = root.getAsJsonObject(e);
  if (path == null) {
    return XVerExtensionStatus.Unknown;
  }
  if (path.has("elements") || path.has("types")) {
    return XVerExtensionStatus.Valid;
  } else {
    return XVerExtensionStatus.Invalid;
  }
}
 
Example #30
Source File: ServicesHealthStatus.java    From Insights with Apache License 2.0 5 votes vote down vote up
private JsonObject getVersionDetails(String fileName, String hostEndPoint, String type) throws IOException {
	
	String version ="";
	String strResponse  = "";
	if(version.equalsIgnoreCase("") ) {
		version=ServicesHealthStatus.class.getPackage().getSpecificationVersion();
		log.info("message version =================== "+version);
		strResponse = "Version captured as "+version;
		return buildSuccessResponse(strResponse, hostEndPoint, type,version);	
	}else {
		strResponse = "Error while capturing PlatformService (version "+version+") health check at "+hostEndPoint;
		return buildFailureResponse(strResponse, hostEndPoint, type,version);
	}
}