Java Code Examples for com.fasterxml.jackson.core.type.TypeReference

The following examples show how to use com.fasterxml.jackson.core.type.TypeReference. These examples are extracted from open source projects. 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 Project: jackson-modules-base   Source File: CollectionMergeTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testGenericListMerging() throws Exception
{
    Collection<String> l = new ArrayList<>();
    l.add("foo");
    MergedX<Collection<String>> input = new MergedX<Collection<String>>(l);

    MergedX<Collection<String>> result = MAPPER
            .readerFor(new TypeReference<MergedX<Collection<String>>>() {})
            .withValueToUpdate(input)
            .readValue(aposToQuotes("{'value':['bar']}"));
    assertSame(input, result);
    assertEquals(2, result.value.size());
    Iterator<String> it = result.value.iterator();
    assertEquals("foo", it.next());
    assertEquals("bar", it.next());
}
 
Example 2
@Override
public Mono<GatewayPayload<?>> read(ByteBuf buf) {
    return Mono.create(sink -> {
        sink.onRequest(__ -> {
            try {
                GatewayPayload<?> value = mapper.readValue(
                        ByteBufUtil.getBytes(buf, buf.readerIndex(), buf.readableBytes(), false),
                        new TypeReference<GatewayPayload<?>>() {});
                sink.success(value);
            } catch (IOException | IllegalArgumentException e) {
                if (lenient) {
                    // if eof input - just ignore
                    if (buf.readableBytes() > 0) {
                        log.warn("Error while decoding JSON ({}): {}", e.toString(),
                                new String(ByteBufUtil.getBytes(buf), StandardCharsets.UTF_8));
                    }
                    sink.success();
                } else {
                    sink.error(Exceptions.propagate(e));
                }
            }
        });
        sink.onDispose(() -> ReferenceCountUtil.release(buf));
    });
}
 
Example 3
Source Project: graphql-java-examples   Source File: GraphQLController.java    License: MIT License 6 votes vote down vote up
@RequestMapping(value = "/graphql", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@CrossOrigin
public void graphqlGET(@RequestParam("query") String query,
                       @RequestParam(value = "operationName", required = false) String operationName,
                       @RequestParam("variables") String variablesJson,
                       HttpServletResponse httpServletResponse) throws IOException {
    if (query == null) {
        query = "";
    }
    Map<String, Object> variables = new LinkedHashMap<>();
    ;
    if (variablesJson != null) {
        variables = objectMapper.readValue(variablesJson, new TypeReference<Map<String, Object>>() {
        });
    }
    executeGraphqlQuery(httpServletResponse, operationName, query, variables);
}
 
Example 4
@Test
public void n4_getAllDomainRecords() throws Exception {
    MvcResult result = mockMvc.perform(get(API_PATH + "/Closed_Domain?orderBy=code")
            .contentType(APPLICATION_JSON)
            .accept(APPLICATION_JSON))
            .andDo(print())
            .andExpect(status().isOk())
            .andReturn();
    String stringResponseBody = result.getResponse().getContentAsString();
    List<Map<String, Object>> listRecord = new ObjectMapper().readValue(stringResponseBody,
            new TypeReference<List<Map<String, Object>>>() {
            });
    Assert.assertEquals(2, listRecord.size());
    Map<String, Object> v1 = listRecord.get(0);
    Map<String, Object> v2 = listRecord.get(1);
    Assert.assertEquals("VALUE_1", v1.get("code"));
    Assert.assertEquals("VALUE_2", v2.get("code"));
}
 
Example 5
Source Project: smockin   Source File: StatefulServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void findDataStateRecord_complexJson_Test() {

    // Setup
    final String json = "[{\"version\":1,\"system\":\"Foo1\",\"active\":true,\"data\":[{\"type\":\"customers\",\"meta\":null,\"keys\":[{\"name\":\"Sian\"}]}],\"included\":[]},{\"version\":1,\"system\":\"Foo2\",\"active\":true,\"data\":[{\"type\":\"customers\",\"meta\":[\"A\",\"B\",\"C\"],\"keys\":[{\"name\":\"Sam\"}]}],\"included\":[]},{\"version\":1,\"system\":\"Foo3\",\"active\":true,\"data\":[{\"type\":\"customers\",\"meta\":[\"A\",\"C\"],\"keys\":[{\"name\":\"Will\"}]}],\"included\":[]},{\"version\":1,\"system\":\"Foo4\",\"active\":true,\"data\":[{\"type\":\"customers\",\"meta\":null,\"keys\":[{\"name\":\"Billy\"}]}],\"included\":[]}]";

    final List<Map<String, Object>> allState = GeneralUtils.deserialiseJson(json,
            new TypeReference<List<Map<String, Object>>>() {});

    // Test
    final Optional<Map<String, Object>> record = statefulServiceImpl.findDataStateRecord(allState, "data.keys.name", "Will");

    // Assertions
    Assert.assertTrue(record.isPresent());
    Assert.assertNotNull(record.get());
    Assert.assertTrue(record.get().get("data") instanceof List);
    Assert.assertEquals(1, ((List)record.get().get("data")).size());
    Assert.assertTrue(((List)record.get().get("data")).get(0) instanceof Map);
    Assert.assertTrue(((Map)((List)record.get().get("data")).get(0)).get("keys") instanceof List);
    Assert.assertEquals(1, ((List)((Map)((List)record.get().get("data")).get(0)).get("keys")).size());
    Assert.assertTrue(((List)((Map)((List)record.get().get("data")).get(0)).get("keys")).get(0) instanceof Map);
    Assert.assertEquals("Will", ((Map)((List)((Map)((List)record.get().get("data")).get(0)).get("keys")).get(0)).get("name") );
}
 
Example 6
Source Project: wingtips   Source File: SpanParserTest.java    License: Apache License 2.0 6 votes vote down vote up
@UseDataProvider("escapeJsonScenarioDataProvider")
@Test
public void unescapeJson_unescapes_characters_as_expected(EscapeJsonScenario scenario) throws IOException {
    // given
    // Have jackson deserialize something with the scenario's escaped-value, and compare our unescapeJson result to it.
    Map<String, String> jacksonDeserialized = objectMapper.readValue(
        "{\"foo\":\"" + scenario.expectedEscaped + "\"}",
        new TypeReference<Map<String, String>>(){}
    );
    String jacksonUnescaped = jacksonDeserialized.get("foo");

    // when
    String unescaped = SpanParser.unescapeJson(scenario.expectedEscaped);

    // then
    assertThat(unescaped).isEqualTo(jacksonUnescaped);
    assertThat(unescaped).isEqualTo(scenario.strToEscape);
}
 
Example 7
private void parseInput(String inputAppsLocation, String inputServicesLocation) {
    this.inputEntities = new ArrayList<CloudEntity>();
    String inputJson;

    if (inputAppsLocation != null) {
        inputJson = TestUtil.getResourceAsString(inputAppsLocation, getClass());
        this.inputEntities.addAll(JsonUtil.fromJson(inputJson, new TypeReference<List<CloudApplication>>() {
        }));
    }

    if (inputServicesLocation != null) {
        inputJson = TestUtil.getResourceAsString(inputServicesLocation, getClass());
        this.inputEntities.addAll(JsonUtil.fromJson(inputJson, new TypeReference<List<CloudServiceInstance>>() {
        }));
    }
}
 
Example 8
Source Project: Xero-Java   Source File: PayrollAuApi.java    License: MIT License 6 votes vote down vote up
/**
* searches for an payrun by unique id
* <p><b>200</b> - search results matching criteria
* @param xeroTenantId Xero identifier for Tenant
* @param payRunID PayRun id for single object
* @param accessToken Authorization token for user set in header of each request
* @return PayRuns
* @throws IOException if an error occurs while attempting to invoke the API
**/
public PayRuns  getPayRun(String accessToken, String xeroTenantId, UUID payRunID) throws IOException {
    try {
        TypeReference<PayRuns> typeRef = new TypeReference<PayRuns>() {};
        HttpResponse response = getPayRunForHttpResponse(accessToken, xeroTenantId, payRunID);
        return apiClient.getObjectMapper().readValue(response.getContent(), typeRef);
    } catch (HttpResponseException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("------------------ HttpResponseException " + e.getStatusCode() + " : getPayRun -------------------");
            logger.debug(e.toString());
        }
        XeroApiExceptionHandler handler = new XeroApiExceptionHandler();
        handler.execute(e);
    } catch (IOException ioe) {
        throw ioe;
    }
    return null;
}
 
Example 9
/**
 * 评论  修改页面显示
 */
@RequestMapping(params="method=edit",method=RequestMethod.GET)
public String editUI(ModelMap model,Long commentId,
		HttpServletRequest request, HttpServletResponse response) throws Exception {
	model.addAttribute("availableTag",commentManage.availableTag());
	Comment comment = commentService.findByCommentId(commentId);
	if(comment != null){
		
		if(comment.getQuote() != null && !"".equals(comment.getQuote().trim())){
			//引用
			List<Quote> customQuoteList = JsonUtils.toGenericObject(comment.getQuote(), new TypeReference< List<Quote> >(){});
			comment.setQuoteList(customQuoteList);
		}
		model.addAttribute("comment", comment);
		String username = "";
		Object obj  =  SecurityContextHolder.getContext().getAuthentication().getPrincipal(); 
		if(obj instanceof UserDetails){
			username =((UserDetails)obj).getUsername();	
		}
		model.addAttribute("userName", username);
	}
	return "jsp/topic/edit_comment";
}
 
Example 10
Source Project: JTelegramBot   Source File: JTelegramBot.java    License: MIT License 6 votes vote down vote up
@Override
public ChatMember getChatMember(ChatIdentifier targetChatIdentifier, int userId) throws IOException, NegativeResponseException
{
	List<NameValueParameter<String, String>> formFields = new ArrayList<NameValueParameter<String, String>>();
	
	String username = targetChatIdentifier.getUsername();
	Long id = targetChatIdentifier.getId();
	if(username != null) formFields.add(new NameValueParameter<String, String>("chat_id", username));
	else formFields.add(new NameValueParameter<String, String>("chat_id", String.valueOf(id)));
	
	formFields.add(new NameValueParameter<String, String>("user_id", String.valueOf(userId)));
	
	HttpResponse response = HttpClient.sendHttpPost(API_URL_PREFIX + apiToken + "/getChatMember", formFields);
	TelegramResult<ChatMember> telegramResult = JsonUtils.toJavaObject(response.getResponseBody(), new TypeReference<TelegramResult<ChatMember>>(){});
	
	if(!telegramResult.isOk()) throw new NegativeResponseException(response.getHttpStatusCode(), telegramResult);
	
	return telegramResult.getResult();
}
 
Example 11
Source Project: nifi   Source File: DruidTranquilityController.java    License: Apache License 2.0 6 votes vote down vote up
private List<AggregatorFactory> getAggregatorList(String aggregatorJSON) {
    ComponentLog log = getLogger();
    ObjectMapper mapper = new ObjectMapper(null);
    mapper.registerModule(new AggregatorsModule());
    mapper.registerModules(Lists.newArrayList(new SketchModule().getJacksonModules()));
    mapper.registerModules(Lists.newArrayList(new ApproximateHistogramDruidModule().getJacksonModules()));

    try {
        return mapper.readValue(
            aggregatorJSON,
            new TypeReference<List<AggregatorFactory>>() {
            }
        );
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        return null;
    }
}
 
Example 12
public void testNullsSkipWithOverrides() throws Exception
{
    final String JSON = aposToQuotes("{'values':[null]}");
    TypeReference<NullContentSkip<List<Long>>> listType = new TypeReference<NullContentSkip<List<Long>>>() { };

    ObjectMapper mapper = afterburnerMapperBuilder()
    // defaults call for fail; but POJO specifies "skip"; latter should win
            .changeDefaultNullHandling(n -> n.withContentNulls(Nulls.FAIL))
            .build();
    NullContentSkip<List<Long>> result = mapper.readValue(JSON, listType);
    assertEquals(0, result.values.size());

    // ditto for per-type defaults
    mapper = afterburnerMapperBuilder()
            .withConfigOverride(List.class,
                    o -> o.setNullHandling(JsonSetter.Value.forContentNulls(Nulls.FAIL)))
            .build();
    result = mapper.readValue(JSON, listType);
    assertEquals(0, result.values.size());
}
 
Example 13
Source Project: foxtrot   Source File: MultiQueryActionTest.java    License: Apache License 2.0 6 votes vote down vote up
public void compare(List<Document> expectedDocuments, List<Document> actualDocuments) {
    assertEquals(expectedDocuments.size(), actualDocuments.size());
    for(int i = 0; i < expectedDocuments.size(); i++) {
        Document expected = expectedDocuments.get(i);
        Document actual = actualDocuments.get(i);
        assertNotNull(expected);
        assertNotNull(actual);
        assertNotNull("Actual document Id should not be null", actual.getId());
        assertNotNull("Actual document data should not be null", actual.getData());
        assertEquals("Actual Doc Id should match expected Doc Id", expected.getId(), actual.getId());
        assertEquals("Actual Doc Timestamp should match expected Doc Timestamp", expected.getTimestamp(), actual.getTimestamp());
        Map<String, Object> expectedMap = getMapper().convertValue(expected.getData(), new TypeReference<HashMap<String, Object>>() {
        });
        Map<String, Object> actualMap = getMapper().convertValue(actual.getData(), new TypeReference<HashMap<String, Object>>() {
        });
        assertEquals("Actual data should match expected data", expectedMap, actualMap);
    }
}
 
Example 14
Source Project: components   Source File: DefinitionsControllerTest.java    License: Apache License 2.0 6 votes vote down vote up
public void shouldListDefinitions(List<String> names, //
        Class clazz, //
        Function<List<String>, Map<String, ? extends Definition>> provider, //
        DefinitionType wantedType, //
        String expectedType) throws IOException {
    // given
    BDDMockito.given(delegate.getDefinitionsMapByType(clazz)) //
            .willReturn(provider.apply(names));

    // when
    final Response response = when().get(getVersionPrefix() + "/definitions/" + wantedType).andReturn();

    // then
    assertEquals(OK.value(), response.getStatusCode());
    List<DefinitionDTO> actual = objectMapper.readValue(response.asInputStream(), new TypeReference<List<DefinitionDTO>>() {
    });
    assertEquals(names.size(), actual.size());
    actual.forEach(d -> {
        assertEquals(expectedType, d.getType());
        assertTrue(names.contains(d.getName().substring("mock ".length()))); // it's expected
    });
}
 
Example 15
Source Project: vavr-jackson   Source File: ParameterizedPojoTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void testLinkedHashMultimapOfSeqTuple() throws Exception {
    String src00 = "A";
    String src010 = "A";
    String src011 = "B";
    Tuple2<String, String> src01 = Tuple.of(src010, src011);
    Tuple2<String, Tuple2<String, String>> src0 = Tuple.of(src00, src01);
    String src10 = "A";
    String src110 = "C";
    String src111 = "D";
    Tuple2<String, String> src11 = Tuple.of(src110, src111);
    Tuple2<String, Tuple2<String, String>> src1 = Tuple.of(src10, src11);
    LinkedHashMultimap<String, Tuple2<String, String>> src = LinkedHashMultimap.withSeq().ofEntries(src0, src1);
    String json = MAPPER.writeValueAsString(new ParameterizedLinkedHashMultimapPojo<>(src));
    Assertions.assertEquals(json, "{\"value\":{\"A\":[[\"A\",\"B\"],[\"C\",\"D\"]]}}");
    ParameterizedLinkedHashMultimapPojo<java.lang.String, io.vavr.Tuple2<java.lang.String, java.lang.String>> restored =
            MAPPER.readValue(json, new TypeReference<ParameterizedLinkedHashMultimapPojo<java.lang.String, io.vavr.Tuple2<java.lang.String, java.lang.String>>>(){});
    Assertions.assertEquals(src, restored.getValue());
}
 
Example 16
Source Project: components   Source File: DefinitionsControllerTest.java    License: Apache License 2.0 6 votes vote down vote up
public void shouldFilterComponentsByExecutionEngine(ExecutionEngine executionEngine, int expectedResults) throws IOException {
    // given
    Map<String, ComponentDefinition> definitions = getComponentsDefinitions();

    BDDMockito.given(delegate.getDefinitionsMapByType(ComponentDefinition.class)) //
            .willReturn(definitions);

    // when
    final Response response = when()
            .get(getVersionPrefix() + "/definitions/components?executionEngine=" + executionEngine.name()).andReturn();

    // then
    assertEquals(OK.value(), response.getStatusCode());
    List<DefinitionDTO> actual = objectMapper.readValue(response.asInputStream(), new TypeReference<List<DefinitionDTO>>() {
    });
    assertEquals(expectedResults, actual.size());
    assertEquals(expectedResults,
            actual.stream().filter(dto -> dto.getExecutionEngines().contains(executionEngine.name())).count());
}
 
Example 17
Source Project: auth0-java   Source File: JobsEntity.java    License: MIT License 6 votes vote down vote up
/**
 * Requests a Users Imports job. A token with scope write:users is needed.
 * See https://auth0.com/docs/api/management/v2#!/Jobs/post_users_imports.
 * See https://auth0.com/docs/users/guides/bulk-user-imports.
 *
 * @param connectionId The id of the connection to import the users to.
 * @param users        The users file. Must have an array with the users' information in JSON format.
 * @param options      Optional parameters to set. Can be null.
 * @return a Request to execute.
 */
public Request<Job> importUsers(String connectionId, File users, UsersImportOptions options) {
    Asserts.assertNotNull(connectionId, "connection id");
    Asserts.assertNotNull(users, "users file");

    String url = baseUrl
            .newBuilder()
            .addPathSegments("api/v2/jobs/users-imports")
            .build()
            .toString();
    MultipartRequest<Job> request = new MultipartRequest<>(client, url, "POST", new TypeReference<Job>() {
    });
    if (options != null) {
        for (Map.Entry<String, Object> e : options.getAsMap().entrySet()) {
            request.addPart(e.getKey(), String.valueOf(e.getValue()));
        }
    }
    request.addPart("connection_id", connectionId);
    request.addPart("users", users, "text/json");
    request.addHeader("Authorization", "Bearer " + apiToken);
    return request;
}
 
Example 18
Source Project: docker-java   Source File: ListTasksCmdExec.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected List<Task> execute(ListTasksCmd command) {
    WebTarget webTarget = getBaseResource().path("/tasks");

    if (command.getFilters() != null && !command.getFilters().isEmpty()) {
        webTarget = webTarget
                .queryParam("filters", FiltersEncoder.jsonEncode(command.getFilters()));
    }

    LOGGER.trace("GET: {}", webTarget);

    List<Task> tasks = webTarget.request().accept(MediaType.APPLICATION_JSON)
            .get(new TypeReference<List<Task>>() {
            });

    LOGGER.trace("Response: {}", tasks);

    return tasks;
}
 
Example 19
Source Project: Partner-Center-Java   Source File: ProductUpgradeOperations.java    License: MIT License 6 votes vote down vote up
/**
   * Checks the product upgrade status
   * 
   * @param productUpgradeRequest The product upgrade status request.
   * @return The status of the product upgrade.
   */
  public ProductUpgradeStatus checkStatus(ProductUpgradeRequest productUpgradeRequest)
  {
      if (productUpgradeRequest == null)
{
	throw new IllegalArgumentException("The productUpgradeRequest parameter cannot be null.");
}

return this.getPartner().getServiceClient().post(
	this.getPartner(), 
	new TypeReference<ProductUpgradeStatus>(){},
	MessageFormat.format(
		PartnerService.getInstance().getConfiguration().getApis().get("GetProductUpgradeStatus").getPath(),
		this.getContext()),
              productUpgradeRequest);   
  }
 
Example 20
Source Project: beam   Source File: AwsModule.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public SSECustomerKey deserialize(JsonParser parser, DeserializationContext context)
    throws IOException {
  Map<String, String> asMap = parser.readValueAs(new TypeReference<Map<String, String>>() {});

  final String key = asMap.getOrDefault("key", null);
  final String algorithm = asMap.getOrDefault("algorithm", null);
  final String md5 = asMap.getOrDefault("md5", null);
  SSECustomerKey sseCustomerKey = new SSECustomerKey(key);
  if (algorithm != null) {
    sseCustomerKey.setAlgorithm(algorithm);
  }
  if (md5 != null) {
    sseCustomerKey.setMd5(md5);
  }
  return sseCustomerKey;
}
 
Example 21
@Test
public void testDeserializationOfMultipleJobExecutions() throws IOException {

	final ObjectMapper objectMapper = DataFlowTemplate.prepareObjectMapper(new ObjectMapper());

	final InputStream inputStream = JobExecutionDeserializationTests.class
			.getResourceAsStream("/JobExecutionJson.txt");

	final String json = new String(StreamUtils.copyToByteArray(inputStream));

	final PagedModel<EntityModel<JobExecutionResource>> paged = objectMapper.readValue(json,
			new TypeReference<PagedModel<EntityModel<JobExecutionResource>>>() {
			});
	final JobExecutionResource jobExecutionResource = paged.getContent().iterator().next().getContent();
	assertEquals("Expect 1 JobExecutionInfoResource", 6, paged.getContent().size());
	assertEquals(Long.valueOf(6), jobExecutionResource.getJobId());
	assertEquals("job200616815", jobExecutionResource.getName());
	assertEquals("COMPLETED", jobExecutionResource.getJobExecution().getStatus().name());
}
 
Example 22
/**
 * 用户自定义注册功能项  修改界面显示
 */
@RequestMapping(params="method=edit",method=RequestMethod.GET)
public String editUI(ModelMap model,Integer id,
		HttpServletRequest request, HttpServletResponse response) throws Exception {
	if(id == null){
		throw new SystemException("参数错误");
	}
	
	UserCustom userCustom = userCustomService.findUserCustomById(id);
	if(userCustom == null){
		throw new SystemException("自定义注册功能项不存在");
	}
	
	if(userCustom.getValue() != null && !"".equals(userCustom.getValue())){
		
		LinkedHashMap<String,String> itemValue_map = JsonUtils.toGenericObject(userCustom.getValue(), new TypeReference<LinkedHashMap<String,String>>(){});//key:选项值 value:选项文本
		model.addAttribute("itemValue_map", itemValue_map);
	}
	
	
	model.addAttribute("userCustom", userCustom);
	return "jsp/user/edit_userCustom";
}
 
Example 23
Source Project: Xero-Java   Source File: PayrollAuApi.java    License: MIT License 6 votes vote down vote up
/**
* Update a Superfund
* Update properties on a single Superfund
* <p><b>200</b> - A successful request
* @param xeroTenantId Xero identifier for Tenant
* @param superFundID Superfund id for single object
* @param superFund The superFund parameter
* @param accessToken Authorization token for user set in header of each request
* @return SuperFunds
* @throws IOException if an error occurs while attempting to invoke the API
**/
public SuperFunds  updateSuperfund(String accessToken, String xeroTenantId, UUID superFundID, List<SuperFund> superFund) throws IOException {
    try {
        TypeReference<SuperFunds> typeRef = new TypeReference<SuperFunds>() {};
        HttpResponse response = updateSuperfundForHttpResponse(accessToken, xeroTenantId, superFundID, superFund);
        return apiClient.getObjectMapper().readValue(response.getContent(), typeRef);
    } catch (HttpResponseException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("------------------ HttpResponseException " + e.getStatusCode() + " : updateSuperfund -------------------");
            logger.debug(e.toString());
        }
        XeroApiExceptionHandler handler = new XeroApiExceptionHandler();
        handler.execute(e);
    } catch (IOException ioe) {
        throw ioe;
    }
    return null;
}
 
Example 24
Source Project: WeEvent   Source File: CommonUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static Map<String, String> contactsql(CEPRule rule, WeEvent eventMessage) throws BrokerException {
    String content = new String(eventMessage.getContent());

    // get select field
    List<String> result = getSelectFieldList(rule.getSelectField(), rule.getPayload());
    Map<String, Object> table = JsonHelper.json2Object(rule.getPayload(), new TypeReference<Map<String, Object>>() {
    });

    Map eventContent;
    Map<String, String> sqlOrder;

    if (JsonHelper.isValid(content)) {
        eventContent = JsonHelper.json2Object(content, Map.class);
        sqlOrder = generateSqlOrder(rule.getBrokerId(), rule.getGroupId(), eventMessage.getEventId(), eventMessage.getTopic(), result, eventContent, table);
    } else {
        sqlOrder = generateSystemSqlOrder(rule.getBrokerId(), rule.getGroupId(), eventMessage.getEventId(), eventMessage.getTopic(), result);
    }

    return sqlOrder;
}
 
Example 25
public List<APIMethod> getAllMethodsForAPI(String apiId) throws AppException {
	ObjectMapper mapper = new ObjectMapper();
	String response = null;
	URI uri;
	List<APIMethod> apiMethods = new ArrayList<APIMethod>();
	HttpResponse httpResponse = null;
	try {
		uri = new URIBuilder(CommandParameters.getInstance().getAPIManagerURL()).setPath(RestAPICall.API_VERSION + "/proxies/"+apiId+"/operations").build();
		RestAPICall getRequest = new GETRequest(uri, null);
		httpResponse = getRequest.execute();
		response = EntityUtils.toString(httpResponse.getEntity());
		apiMethods = mapper.readValue(response, new TypeReference<List<APIMethod>>(){});
		return apiMethods;
	} catch (Exception e) {
		LOG.error("Error cant load API-Methods for API: '"+apiId+"' from API-Manager. Can't parse response: " + response);
		throw new AppException("Error cant load API-Methods for API: '"+apiId+"' from API-Manager", ErrorCode.API_MANAGER_COMMUNICATION, e);
	} finally {
		try {
			if(httpResponse!=null) 
				((CloseableHttpResponse)httpResponse).close();
		} catch (Exception ignore) {}
	}
}
 
Example 26
public List<Repo> getForRepos(String token, String url) {

        HttpClient client = HttpClientFactory.httpClient(url);
        HttpGet get = new HttpGet(url);
        HttpClientFactory.authorizationHeader(get, token);

        HttpResponse response = HttpClientFactory.execute(client, get);

        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            return HttpClientFactory.read(response, new TypeReference<List<Repo>>() {
            });
        }
        else {
            throw new CommandException("Failed to configure team-scoped repositories.",
                    "repositories configure");
        }
    }
 
Example 27
/**
 * Retrieves the customer relationship request which can be used by a customer to establish a relationship with the
 * current partner.
 * 
 * @return A customer relationship request.
 */
@Override
public CustomerRelationshipRequest get()
{
	return this.getPartner().getServiceClient().get(
		this.getPartner(),
		new TypeReference<CustomerRelationshipRequest>(){}, 
		PartnerService.getInstance().getConfiguration().getApis().get("GetCustomerRelationshipRequest").getPath());
}
 
Example 28
Source Project: mojito   Source File: ObjectMapper.java    License: Apache License 2.0 5 votes vote down vote up
public <T> T readValueUnchecked(String content, TypeReference valueTypeRef) {
    try {
        return super.readValue(content, valueTypeRef);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example 29
Source Project: zheshiyigeniubidexiangmu   Source File: HuobiApiClient.java    License: MIT License 5 votes vote down vote up
/**
 * GET /market/order 获取 Trade Detail 数据
 *
 * @param symbol
 * @return
 */
public TradeResponse trade(String symbol) {
    HashMap map = new HashMap();
    map.put("symbol", symbol);
    TradeResponse resp = get("/market/order", map, new TypeReference<TradeResponse>() {
    });
    return resp;
}
 
Example 30
Source Project: android-uiconductor   Source File: ActionEntityFileUtil.java    License: Apache License 2.0 5 votes vote down vote up
/** Loads single action from file */
public static ActionEntity loadSingleTestCases(Path testcasePath) throws UicdActionException {
  try {
    String testcaseContent = new String(Files.readAllBytes(testcasePath), UTF_8);
    return JsonUtilEx.fromJson(testcaseContent, new TypeReference<ActionEntity>() {});
  } catch (IOException e) {
    throw new UicdActionException("Can find file in folder: " + testcasePath + e.getMessage());
  }
}