public BpPagedResults<BpClass> findAllClassesInOntology( String ontology, int page, int pageSize, String apiKey) throws HTTPException, IOException { String url = BP_API_BASE + BP_ONTOLOGIES + ontology + "/" + BP_CLASSES + "?include=prefLabel,hasChildren,created,synonym,definition" + "&page=" + page + "&pagesize=" + pageSize; HttpResponse response = HttpUtil.makeHttpRequest( Request.Get(url) .addHeader("Authorization", Util.getBioPortalAuthHeader(apiKey)) .connectTimeout(connectTimeout) .socketTimeout(socketTimeout)); int statusCode = response.getStatusLine().getStatusCode(); // The classes were successfully retrieved if (statusCode == 200) { ObjectMapper mapper = new ObjectMapper(); JsonNode bpResult = mapper.readTree(new String(EntityUtils.toByteArray(response.getEntity()))); return mapper.readValue( mapper.treeAsTokens(bpResult), new TypeReference<BpPagedResults<BpClass>>() {}); } else { throw new HTTPException(statusCode); } }
public BpPagedResults<BpClass> findValueSetsByValueSetCollection( String vsCollection, int page, int pageSize, String apiKey) throws IOException { String url = BP_API_BASE + BP_SEARCH + "?also_search_provisional=true&valueset_roots_only=true&ontology_types=VALUE_SET_COLLECTION&ontologies=" + vsCollection + "&page=" + page + "&pagesize=" + pageSize; HttpResponse response = HttpUtil.makeHttpRequest( Request.Get(url) .addHeader("Authorization", Util.getBioPortalAuthHeader(apiKey)) .connectTimeout(connectTimeout) .socketTimeout(socketTimeout)); int statusCode = response.getStatusLine().getStatusCode(); // Success if (statusCode == 200) { ObjectMapper mapper = new ObjectMapper(); JsonNode bpResult = mapper.readTree(new String(EntityUtils.toByteArray(response.getEntity()))); return mapper.readValue( mapper.treeAsTokens(bpResult), new TypeReference<BpPagedResults<BpClass>>() {}); } else { throw new HTTPException(statusCode); } }
/** * Invokes the given method on the {@code handler} passing the given params (after converting them * to beans\objects) to it. * * @param m the method to invoke * @param params the params to pass to the method * @return the return value (or null if no return) * @throws IOException on error * @throws IllegalAccessException on error * @throws InvocationTargetException on error */ protected JsonNode invoke(Method m, List<JsonNode> params) throws IOException, IllegalAccessException, InvocationTargetException { // debug log if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Invoking method: " + m.getName()); } // convert the parameters Object[] convertedParams = new Object[params.size()]; Type[] parameterTypes = m.getGenericParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { JsonParser paramJsonParser = mapper.treeAsTokens(params.get(i)); JavaType paramJavaType = TypeFactory.defaultInstance().constructType(parameterTypes[i]); convertedParams[i] = mapper.readValue(paramJsonParser, paramJavaType); } // invoke the method Object result = m.invoke(handler, convertedParams); Type genericReturnType = m.getGenericReturnType(); if (genericReturnType != null) { if (Collection.class.isInstance(result) && genericReturnType instanceof ParameterizedType) { try { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "attempting custom collection serialization"); } TypeFactory typeFactory = mapper.getTypeFactory(); Type actualTypeInCollection = ((ParameterizedType) genericReturnType).getActualTypeArguments()[0]; if (actualTypeInCollection instanceof TypeVariable) { // collection actually has a generic return type actualTypeInCollection = ((TypeVariable) actualTypeInCollection).getBounds()[0]; } JavaType rootType = typeFactory.constructCollectionType( Collection.class, typeFactory.constructType(actualTypeInCollection)); return valueToTree(mapper.writerWithType(rootType), result); } catch (Exception e) { LOGGER.log( Level.WARNING, "could not do custom collection serialization falling back to default", e); } } return mapper.valueToTree(result); } else { return null; } // return (genericReturnType!=null) ? mapper.valueToTree(result) : null; }
@Test public void test_add_customer_shipping_to_customer() throws JsonParseException, JsonMappingException, IOException { Client client = JerseyClientBuilder.createClient(); HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic("*****@*****.**", "password"); client.register(feature); // CREATE NEW USER Customer customer = new Customer(); customer.setUsername("*****@*****.**"); customer.setPassword("password"); Customer customerPersisted = client .target(String.format(REST_PRODUCT_SERVICE_URL, RULE.getLocalPort())) .path(new StringBuilder("/customer").append("/signup").toString()) .request(MediaType.APPLICATION_JSON) .post(Entity.json(customer), Customer.class); assertThat(customerPersisted.getId()).isNotNull(); // ADD CCHAT TO USER CChat cchat = new CChat("Usman-Asifa"); CChat persistedCchat = client .target(String.format(REST_PRODUCT_SERVICE_URL, RULE.getLocalPort())) .path( new StringBuilder("/customer/") .append(customerPersisted.getId()) .append("/cchat") .toString()) .request(MediaType.APPLICATION_JSON) .post(Entity.json(cchat), CChat.class); assertThat(persistedCchat.getId()).isNotNull(); // assertThat(persistedCchat.getUniqueName()).isEqualTo("Usman-Asifa"); // ADD CCHAT1 TO USER CChat cchat1 = new CChat("Usman-Gulgs"); CChat persistedCchat1 = client .target(String.format(REST_PRODUCT_SERVICE_URL, RULE.getLocalPort())) .path( new StringBuilder("/customer/") .append(customerPersisted.getId()) .append("/cchat") .toString()) .request(MediaType.APPLICATION_JSON) .post(Entity.json(cchat1), CChat.class); assertThat(persistedCchat1.getId()).isNotNull(); // assertThat(persistedCchat1.getUniqueName()).isEqualTo("Usman-Gulgs"); // ADD CUSTOMERSHIPPING TO USER CustomerShipping customerShipping = new CustomerShipping( "Usman", "Chaudhri", "2460 Fulton", "San Francisco", "CA", "94118", "USA", "Y"); CustomerShipping persistedCustomerShipping = client .target(String.format(REST_PRODUCT_SERVICE_URL, RULE.getLocalPort())) .path( new StringBuilder("/customer/") .append(customerPersisted.getId()) .append("/customershipping") .toString()) .request(MediaType.APPLICATION_JSON) .post(Entity.json(customerShipping), CustomerShipping.class); assertThat(persistedCustomerShipping.getId()).isNotNull(); assertThat(persistedCustomerShipping.getFirstName()).isEqualTo("Usman"); assertThat(persistedCustomerShipping.getLastName()).isEqualTo("Chaudhri"); // ADD ORDER TO USER Order orderRequest = new Order(); orderRequest.setProductId("101"); orderRequest.setProductCategoryId("10"); orderRequest.setProductImagePath("/image/listing"); orderRequest.setProductName("shirt"); orderRequest.setProductPrice("10.99"); orderRequest.setProductQuantity("5"); orderRequest.setProductShopId("40"); orderRequest.setProductSku("SKU_101"); orderRequest.setStatus("Processed"); Order persistedOrder = client .target(String.format(REST_PRODUCT_SERVICE_URL, RULE.getLocalPort())) .path(new StringBuilder("/orders").toString()) .request(MediaType.APPLICATION_JSON) .post(Entity.json(orderRequest), Order.class); assertThat(persistedOrder.getId()).isNotNull(); // GET PERSISTED CUSTOMER Customer getPersistedCustomer = client .target(String.format(REST_PRODUCT_SERVICE_URL, RULE.getLocalPort())) .path(new StringBuilder("/customer").append("/login").toString()) .request(MediaType.APPLICATION_JSON) .get(Customer.class); assertThat(getPersistedCustomer.getId()).isNotNull(); assertThat(getPersistedCustomer.getCustomerShipping().get(0).getId()).isNotNull(); assertThat(getPersistedCustomer.getCustomerShipping().get(0).getFirstName()).isNotNull(); // lazy load cchat JsonNode getPersistedCustomerCchat = client .target(String.format(REST_PRODUCT_SERVICE_URL, RULE.getLocalPort())) .path( new StringBuilder("/customer/") .append(getPersistedCustomer.getId()) .append("/cchat") .toString()) .request(MediaType.APPLICATION_JSON) .get(JsonNode.class); ObjectMapper mapper = new ObjectMapper(); List<CChat> getPersistedCChats = mapper.readValue( mapper.treeAsTokens(getPersistedCustomerCchat), new TypeReference<List<CChat>>() {}); assertThat(getPersistedCChats.get(0).getId()).isNotNull(); assertThat(getPersistedCChats.get(1).getId()).isNotNull(); }
public <T> T getListWith(DrillConfig config, TypeReference<T> t) throws IOException { ObjectMapper mapper = config.getMapper(); return mapper.treeAsTokens(root).readValueAs(t); // return mapper.treeToValue(root, mapper.getTypeFactory().constructCollectionType(List.class, // c)); }