public static Echo_sol_Echo getEchoContract() throws JsonParseException, JsonMappingException, IOException, CipherException { Web3j web3j = Web3j.build(new HttpService()); logger.debug("[ETH-INFO] Connected to TestRPC"); ObjectMapper objectMapper = ObjectMapperFactory.getObjectMapper(); WalletFile walletFile = objectMapper .readValue(ContractHelper.class.getResourceAsStream("/accountKeystore.json"), WalletFile.class); Credentials credentials = Credentials.create(Wallet.decrypt(password, walletFile)); logger.debug("[ETH-INFO] Credentials: " + credentials.getAddress()); logger.debug("[ETH-INFO] Loading contract: " + contractAddress); ese = Echo_sol_Echo.load(contractAddress, web3j, credentials, GAS_PRICE, GAS_LIMIT); startObservable(); return ese; }
/** * Validate logins yml. * @param loginsYml logins yml * @return true if valid */ @PostMapping(value = "/logins/validate", consumes = {TEXT_PLAIN_VALUE}) @ApiOperation(value = "Validate uaa login properties format", response = UaaValidationVM.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Uaa validation result", response = UaaValidationVM.class), @ApiResponse(code = 500, message = "Internal server error")}) @SneakyThrows @Timed public UaaValidationVM validate(@RequestBody String loginsYml) { try { mapper.readValue(loginsYml, TenantLogins.class); return UaaValidationVM.builder().isValid(true).build(); } catch (JsonParseException | JsonMappingException e) { return UaaValidationVM.builder().isValid(false).errorMessage(e.getLocalizedMessage()).build(); } }
/** * Loads and returns the AWS Java SDK internal configuration from the classpath. */ static InternalConfig load() throws JsonParseException, JsonMappingException, IOException { // First try loading via the class by using a relative path URL url = ClassLoaderHelper.getResource(DEFAULT_CONFIG_RESOURCE_RELATIVE_PATH, true, InternalConfig.class); // classesFirst=true if (url == null) { // Then try with the absolute path url = ClassLoaderHelper.getResource(DEFAULT_CONFIG_RESOURCE_ABSOLUTE_PATH, InternalConfig.class); } InternalConfigJsonHelper config = loadfrom(url); InternalConfigJsonHelper configOverride; URL overrideUrl = ClassLoaderHelper.getResource("/" + CONFIG_OVERRIDE_RESOURCE, InternalConfig.class); if (overrideUrl == null) { // Try without a leading "/" overrideUrl = ClassLoaderHelper.getResource(CONFIG_OVERRIDE_RESOURCE, InternalConfig.class); } if (overrideUrl == null) { log.debug("Configuration override " + CONFIG_OVERRIDE_RESOURCE + " not found."); configOverride = new InternalConfigJsonHelper(); } else { configOverride = loadfrom(overrideUrl); } InternalConfig merged = new InternalConfig(config, configOverride); merged.setDefaultConfigFileLocation(url); merged.setOverrideConfigFileLocation(overrideUrl); return merged; }
@PostMapping(value = "/timelines/properties/validate", consumes = {TEXT_PLAIN_VALUE}) @ApiOperation(value = "Validate timeline properties format", response = TimeLineValidationVM.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Timeline validation result", response = TimeLineValidationVM.class), @ApiResponse(code = 500, message = "Internal server error")}) @SneakyThrows @Timed public TimeLineValidationVM validate(@RequestBody String timelineYml) { try { mapper.readValue(timelineYml, TenantProperties.class); return TimeLineValidationVM.builder().isValid(true).build(); } catch (JsonParseException | JsonMappingException e) { log.error("Error while validation", e); return TimeLineValidationVM.builder().isValid(false).errorMessage(e.getLocalizedMessage()).build(); } }
@Test void getBadReportDetails() throws NoSuchFieldException, IllegalAccessException, JsonProcessingException { ObjectMapper mockMapper = mock(ObjectMapper.class); when(mockMapper.writeValueAsBytes(any(AllErrors.class))) .thenThrow(new JsonMappingException("meep")); Converter converter = new Converter( new PathSource(Paths.get("../qrda-files/valid-QRDA-III-latest.xml"))); Converter.ConversionReport badReport = converter.getReport(); Field field = badReport.getClass().getDeclaredField("mapper"); field.setAccessible(true); field.set(badReport, mockMapper); assertThrows(EncodeException.class, badReport::getValidationErrorsSource); }
@Test public void testArray() throws JsonParseException, JsonMappingException, IOException { assertTrue(config.getProperty("phoneNumbers", List.class) instanceof List); final List<Map<String, String>> testList = new ArrayList<>(); Map<String, String> testMapEntry = new HashMap<>(); testMapEntry.put("type", "home"); testMapEntry.put("number", "212 555-1234"); testList.add(testMapEntry); testMapEntry = new HashMap<>(); testMapEntry.put("type", "office"); testMapEntry.put("number", "646 555-4567"); testList.add(testMapEntry); assertEquals(testList, config.getProperty("phoneNumbers", List.class)); assertEquals(new ArrayList<>(), config.getProperty("children", List.class)); }
private static Optional<JsonSchema> getSchemma(Class<?> clazz) { ObjectMapper mapper = new ObjectMapper(); Optional<JsonSchema> schema = Optional.empty(); SchemaFactoryWrapper visitor = new SchemaFactoryWrapper(); Optional<Class<?>> realClazz = ReflectionUtils.getGenericClass(clazz); boolean iterable = Iterable.class.isAssignableFrom(clazz) && realClazz.isPresent(); if (iterable) { clazz = realClazz.get(); } try { mapper.acceptJsonFormatVisitor(clazz, visitor); JsonSchemaGenerator schemaGen = new JsonSchemaGenerator(mapper); schema = Optional.ofNullable(schemaGen.generateSchema(clazz)); if (iterable) { // TODO: decirle que es una collection } } catch (JsonMappingException e) { LOGGER.error("Se produjo un error al crear el JsonSchemma para la clase {}", clazz.getSimpleName(), e); } return schema; }
private List<String> getAPIKeyList() throws ServerError, JsonParseException, JsonMappingException, IOException{ List<String> list = new ArrayList<String>(); String accountListUrlPath = props.getProperty("application-list-url-path"); accountListUrlPath=accountListUrlPath.replaceAll("<token>", props.getProperty("acccess-token")); accountListUrlPath=accountListUrlPath.replaceAll("<serviceid>", props.getProperty("service-id-a")); //String body = props.getProperty("tempbody"); String body = apiAccessor.get(HOST+accountListUrlPath).getBody(); while ( body.indexOf("user_key")!=-1){ int indexOfStartOfKey = body.indexOf("user_key") + 11; int indexOfEndOfKey = indexOfStartOfKey+32; String apiKey = body.substring(indexOfStartOfKey, indexOfEndOfKey); list.add(apiKey); body = body.substring(indexOfEndOfKey); } return list; }
public static QueryObjectProvider fromJsonNode(CatalogService catalogService, VirtualObjectService virtualObjectService, PlatformServer server, JsonNode fullQuery, Integer rid, PackageMetaData packageMetaData) throws JsonParseException, JsonMappingException, IOException, QueryException { if (fullQuery instanceof ObjectNode) { JsonQueryObjectModelConverter converter = new JsonQueryObjectModelConverter(packageMetaData); Query query = converter.parseJson("query", (ObjectNode) fullQuery); return new QueryObjectProvider(catalogService, virtualObjectService, server, query, rid, packageMetaData); } else { throw new QueryException("Query root must be of type object"); } }
@StreamListener(target = Sink.INPUT, condition="payload.messageType.toString()=='FetchGoodsCommand'") @Transactional public void retrievePaymentCommandReceived(String messageJson) throws JsonParseException, JsonMappingException, IOException { Message<FetchGoodsCommandPayload> message = new ObjectMapper().readValue(messageJson, new TypeReference<Message<FetchGoodsCommandPayload>>(){}); FetchGoodsCommandPayload fetchGoodsCommand = message.getPayload(); String pickId = inventoryService.pickItems( // fetchGoodsCommand.getItems(), fetchGoodsCommand.getReason(), fetchGoodsCommand.getRefId()); messageSender.send( // new Message<GoodsFetchedEventPayload>( // "GoodsFetchedEvent", // message.getTraceId(), // new GoodsFetchedEventPayload() // .setRefId(fetchGoodsCommand.getRefId()) .setPickId(pickId))); }
/** * A callback so a JsonGenerator can be used inline but exception are handled here * @param outStream OutputStream * @param writer The writer interface * @throws IOException */ public void withWriter(OutputStream outStream, Writer writer) throws IOException { try { JsonGenerator generator = objectMapper.getJsonFactory().createJsonGenerator(outStream, encoding); writer.writeContents(generator, objectMapper); } catch (JsonMappingException error) { logger.error("Failed to write Json output",error); } catch (JsonGenerationException generror) { logger.error("Failed to write Json output",generror); } }
private void assertForbidden(final String path) throws IOException, ClientProtocolException, JsonParseException, JsonMappingException { final HttpDelete httpdelete = new HttpDelete(BASE_URI + RESOURCE + path); HttpResponse response = null; try { response = httpclient.execute(httpdelete); Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusLine().getStatusCode()); final String content = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8); final Map<?, ?> result = new ObjectMapperTrim().readValue(content, HashMap.class); Assert.assertEquals("security", result.get("code")); Assert.assertNull(result.get("cause")); Assert.assertNull(result.get("message")); } finally { if (response != null) { response.getEntity().getContent().close(); } } }
@Override public <T> Document asDocumentInternal(T object) { ObjectMapper objectMapper = getObjectMapper(); try { JsonNode node = objectMapper.convertValue(object, JsonNode.class); return loadDocument(node); } catch (IllegalArgumentException iae) { log.error("Error while converting object to document ", iae); if (iae.getCause() instanceof JsonMappingException) { JsonMappingException jme = (JsonMappingException) iae.getCause(); if (jme.getCause() instanceof StackOverflowError) { throw new ObjectMappingException(errorMessage( "cyclic reference detected. " + jme.getPathReference(), OME_CYCLE_DETECTED)); } } throw iae; } }
@StreamListener(target = Sink.INPUT, condition="payload.messageType.toString()=='RetrievePaymentCommand'") @Transactional public void retrievePaymentCommandReceived(String messageJson) throws JsonParseException, JsonMappingException, IOException { Message<RetrievePaymentCommandPayload> message = new ObjectMapper().readValue(messageJson, new TypeReference<Message<RetrievePaymentCommandPayload>>(){}); RetrievePaymentCommandPayload retrievePaymentCommand = message.getPayload(); System.out.println("Retrieve payment: " + retrievePaymentCommand.getAmount() + " for " + retrievePaymentCommand.getRefId()); camunda.getRuntimeService().createMessageCorrelation(message.getMessageType()) // .processInstanceBusinessKey(message.getTraceId()) .setVariable("amount", retrievePaymentCommand.getAmount()) // .setVariable("remainingAmount", retrievePaymentCommand.getAmount()) // .setVariable("refId", retrievePaymentCommand.getRefId()) // .correlateWithResult(); }
@Test public void shouldSerializeSimpleResponseBody() throws JsonParseException, JsonMappingException, IOException { UserRequestTest request = new UserRequestTest("user name", "user address"); ResponseEntity response = ResponseEntity.of(request); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); Assert.assertNotNull(response.getBody()); //should be able to deserialize UserRequestTest deserialized = new ObjectMapper().readValue(response.getBody(), UserRequestTest.class); Assert.assertNotNull(request); Assert.assertEquals(request.getName(), deserialized.getName()); Assert.assertEquals(request.getAddress(), deserialized.getAddress()); Assert.assertNull(response.getHeaders()); }
@CsapDoc ( notes = { "Summary status of host" } , linkTests = "default" ) @RequestMapping ( { "/status" } ) public ObjectNode status () throws JsonGenerationException, JsonMappingException, IOException { ObjectNode healthJson = jacksonMapper.createObjectNode(); if ( Application.isJvmInManagerMode() ) { healthJson.put( "error", "vmHealth is only enabled on CsAgent urls." ); } else { healthJson = csapApp.statusForAdminOrAgent( ServiceAlertsEnum.ALERT_LEVEL ); } return healthJson; }
@SuppressWarnings({ "unchecked" }) @Test public void serializeTest() throws JsonParseException, JsonMappingException, IOException { List<WampRole> roles = createRoles(); WelcomeMessage welcomeMessage = new WelcomeMessage(9129137332L, roles, "realm"); assertThat(welcomeMessage.getCode()).isEqualTo(2); assertThat(welcomeMessage.getSessionId()).isEqualTo(9129137332L); assertThat(welcomeMessage.getRoles()).isEqualTo(roles); String json = serializeToJson(welcomeMessage); String expected = "[2,9129137332,{\"roles\":{\"dealer\":{\"features\":{\"caller_identification\":true}},\"broker\":{\"features\":{\"subscriber_blackwhite_listing\":true,\"publisher_exclusion\":true,\"publisher_identification\":true,\"pattern_based_subscription\":true}}},\"realm\":\"realm\"}]"; ObjectMapper om = new ObjectMapper(); assertThat(om.readValue(json, List.class)) .isEqualTo(om.readValue(expected, List.class)); }
/** * Main API call method. Takes in a {@link HttpUriRequest} comprising of a * URI and method * * @param request * with the relevant URI and method (with associated data is * appropriate) * @param type * what the response should interpreted as * @param login * whether this is a call specifically to login * @return the type requested * @throws IOException * if it's not possible to get a valid response from the API * @throws GroupsIOApiException * if the API returns an error, or an error is experienced * during deserialisation */ protected <T> T callApi(final HttpUriRequest request, final Class<T> type, final Boolean login) throws IOException, GroupsIOApiException { try (final CloseableHttpClient client = getHttpClient(login, request)) { final HttpResponse response = client.execute(request); final InputStream stream = response.getEntity().getContent(); final byte[] bytes = IOUtils.toByteArray(stream); if (response.getStatusLine().getStatusCode() != 200) { throw new GroupsIOApiException(mapToError(bytes)); } try { return type.cast(OM.readValue(bytes, Class.forName(type.getName()))); } catch (final JsonMappingException | ClassNotFoundException jme) { throw new GroupsIOApiException(mapToError(bytes)); } } }
@Test public void testNullInComment() throws IOException { final Comment aComment = new Comment(); aComment.setContent(null); ByteArrayOutputStream out = new ByteArrayOutputStream(); jsonHelper.withWriter(out, new Writer() { @Override public void writeContents(JsonGenerator generator, ObjectMapper objectMapper) throws JsonGenerationException, JsonMappingException, IOException { FilterProvider fp = new SimpleFilterProvider().addFilter( JacksonHelper.DEFAULT_FILTER_NAME, new ReturnAllBeanProperties()); objectMapper.writer(fp).writeValue(generator, aComment); } }); assertEquals("Null values should not be output.", "{\"canEdit\":false,\"canDelete\":false}", out.toString()); }
@SuppressWarnings({"rawtypes", "unchecked"}) @Test public void getJwtTokenByClientCredentialForAdmin() throws JsonParseException, JsonMappingException, IOException { ResponseEntity<String> response = new TestRestTemplate("trusted-app", "secret").postForEntity("http://localhost:" + port + "/oauth/token?grant_type=password&username=admin&password=password", null, String.class); String responseText = response.getBody(); assertEquals(HttpStatus.OK, response.getStatusCode()); HashMap jwtMap = new ObjectMapper().readValue(responseText, HashMap.class); assertEquals("bearer", jwtMap.get("token_type")); assertEquals("read write", jwtMap.get("scope")); assertTrue(jwtMap.containsKey("access_token")); assertTrue(jwtMap.containsKey("expires_in")); assertTrue(jwtMap.containsKey("jti")); String accessToken = (String) jwtMap.get("access_token"); Jwt jwtToken = JwtHelper.decode(accessToken); String claims = jwtToken.getClaims(); HashMap claimsMap = new ObjectMapper().readValue(claims, HashMap.class); assertEquals("spring-boot-application", ((List<String>) claimsMap.get("aud")).get(0)); assertEquals("trusted-app", claimsMap.get("client_id")); assertEquals("admin", claimsMap.get("user_name")); assertEquals("read", ((List<String>) claimsMap.get("scope")).get(0)); assertEquals("write", ((List<String>) claimsMap.get("scope")).get(1)); assertEquals("ROLE_ADMIN", ((List<String>) claimsMap.get("authorities")).get(0)); }
@Test public void accessProtectedResourceByJwtTokenForAdmin() throws JsonParseException, JsonMappingException, IOException { ResponseEntity<String> response = new TestRestTemplate().getForEntity("http://localhost:" + port + "/resources/admin", String.class); assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode()); response = new TestRestTemplate("trusted-app", "secret").postForEntity("http://localhost:" + port + "/oauth/token?grant_type=password&username=admin&password=password", null, String.class); String responseText = response.getBody(); assertEquals(HttpStatus.OK, response.getStatusCode()); HashMap jwtMap = new ObjectMapper().readValue(responseText, HashMap.class); String accessToken = (String) jwtMap.get("access_token"); HttpHeaders headers = new HttpHeaders(); headers.set("Authorization", "Bearer " + accessToken); response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/admin", HttpMethod.GET, new HttpEntity<>(null, headers), String.class); assertEquals(HttpStatus.OK, response.getStatusCode()); response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/principal", HttpMethod.GET, new HttpEntity<>(null, headers), String.class); assertEquals("admin", response.getBody()); response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/roles", HttpMethod.GET, new HttpEntity<>(null, headers), String.class); assertEquals("[{\"authority\":\"ROLE_ADMIN\"}]", response.getBody()); }
@PostMapping(value = "/uaa/properties/validate", consumes = {TEXT_PLAIN_VALUE}) @ApiOperation(value = "Validate uaa properties format", response = UaaValidationVM.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Uaa validation result", response = UaaValidationVM.class), @ApiResponse(code = 500, message = "Internal server error")}) @SneakyThrows @Timed public UaaValidationVM validate(@RequestBody String timelineYml) { try { mapper.readValue(timelineYml, TenantProperties.class); return UaaValidationVM.builder().isValid(true).build(); } catch (JsonParseException | JsonMappingException e) { return UaaValidationVM.builder().isValid(false).errorMessage(e.getLocalizedMessage()).build(); } }
@Test @SuppressWarnings("unchecked") public void intEnumIsDeserializedCorrectly() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, JsonParseException, JsonMappingException, IOException { ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/schema/enum/integerEnumToSerialize.json", "com.example"); // the schema for a valid instance Class<?> typeWithEnumProperty = resultsClassLoader.loadClass("com.example.enums.IntegerEnumToSerialize"); Class<Enum> enumClass = (Class<Enum>) resultsClassLoader.loadClass("com.example.enums.IntegerEnumToSerialize$TestEnum"); // read the instance into the type ObjectMapper objectMapper = new ObjectMapper(); Object valueWithEnumProperty = objectMapper.readValue("{\"testEnum\" : 2}", typeWithEnumProperty); Method getEnumMethod = typeWithEnumProperty.getDeclaredMethod("getTestEnum"); Method getValueMethod = enumClass.getDeclaredMethod("value"); // call getTestEnum on the value assertThat(getEnumMethod, is(notNullValue())); Object enumObject = getEnumMethod.invoke(valueWithEnumProperty); // assert that the object returned is a) a TestEnum, and b) calling .value() on it returns 2 // as per the json snippet above assertThat(enumObject, IsInstanceOf.instanceOf(enumClass)); assertThat(getValueMethod, is(notNullValue())); assertThat((Integer)getValueMethod.invoke(enumObject), is(2)); }
@DataProvider(name = "multiplePolicySetsRequestDataProvider") private Object[][] multiplePolicySetsRequestDataProvider() throws JsonParseException, JsonMappingException, IOException { List<PolicySet> denyPolicySet = createDenyPolicySet(); List<PolicySet> notApplicableAndDenyPolicySets = createNotApplicableAndDenyPolicySets(); return new Object[][] { requestEvaluationWithEmptyPolicySetsListAndEmptyPriorityList(), requestEvaluationWithOnePolicySetAndEmptyPriorityList(denyPolicySet), requestEvaluationWithFirstOfOnePolicySets(denyPolicySet), requestEvaluationWithFirstOfTwoPolicySets(notApplicableAndDenyPolicySets), requestEvaluationWithSecondOfTwoPolicySets(notApplicableAndDenyPolicySets), requestEvaluationWithAllOfTwoPolicySets(notApplicableAndDenyPolicySets) }; }
@Override public void acceptJsonFormatVisitor(JsonFormatVisitorWrapper visitor, JavaType typeHint) throws JsonMappingException { if (visitor != null) { visitor.expectStringFormat(typeHint); } }
private String writeResponse(final Object respons) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); jsonHelper.withWriter(out, new Writer() { @Override public void writeContents(JsonGenerator generator, ObjectMapper objectMapper) throws JsonGenerationException, JsonMappingException, IOException { objectMapper.writeValue(generator, respons); } }); System.out.println(out.toString()); return out.toString(); }
@SuppressWarnings("unchecked") public String generate(Client client, Card card, String encryptionKey) throws JsonParseException, JsonMappingException, IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidKeySpecException, IllegalBlockSizeException, BadPaddingException, CertificateException{ String encrypted; //pegando publickey List<NameValuePair> encReq = new ArrayList<>(); encReq.add(new BasicNameValuePair("encryption_key", encryptionKey)); CardHashKey gen = client.get(encReq, CardHashKey.class); //criando queryString List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("card_number", card.getCardNumber())); params.add(new BasicNameValuePair("card_holder_name", card.getHolderName())); params.add(new BasicNameValuePair("card_expiration_date", card.getExpirationDate())); params.add(new BasicNameValuePair("card_cvv", card.getCvv())); String queryString = URLEncodedUtils.format(params, "UTF-8"); String publickey = gen.getPublicKey(); publickey = publickey.replaceAll("-----BEGIN PUBLIC KEY-----", ""); publickey = publickey.replaceAll("-----END PUBLIC KEY-----", ""); //criptografando;; BASE64Decoder b64 = new BASE64Decoder(); byte[] decoded = b64.decodeBuffer(publickey); X509EncodedKeySpec spec = new X509EncodedKeySpec(decoded); Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); KeyFactory kf = KeyFactory.getInstance("RSA"); PublicKey key = kf.generatePublic(spec); cipher.init(Cipher.ENCRYPT_MODE, key); //toBase64 encrypted = Base64.getEncoder().encodeToString(cipher.doFinal(queryString.getBytes())); return String.valueOf(gen.getId()).concat("_").concat(encrypted); }
@SuppressWarnings("unchecked") @Test public void validateConfiguredParameters_createJsonError() throws Exception { // given prepareServiceAccessible(true); model.setServiceParameters(new ArrayList<PricedParameterRow>()); bean.setJsonValidator(new JsonParameterValidator(bean .getJsonConverter())); addPricedParameterRow("ABoolean", ParameterValueType.BOOLEAN, false); model.setParameterConfigResponse(CONFIG_RESPONSE_ERROR); JsonObject configRequest = givenConfigRequest(); addJsonParameter(configRequest, "ABoolean", "false", false); doReturn(configRequest).when(jsonConverter) .getServiceParametersAsJsonObject(Matchers.any(List.class), Matchers.anyBoolean(), Matchers.anyBoolean()); doThrow(new JsonMappingException("Error in json mapping")).when( jsonConverter).createJsonString(Matchers.any(JsonObject.class)); // when String outcome = bean.getJsonValidator().validateConfiguredParameters( bean.getModel()); // then assertEquals("Outcome error expected: Rerender parent page", SubscriptionDetailsCtrlConstants.OUTCOME_ERROR, outcome); assertTrue("Error expected in validation result", model .getParameterValidationResult().getValidationError()); assertNull("No config request expected in validation result", model .getParameterValidationResult().getConfigRequest()); }
@Override public Response toResponse(JsonMappingException exception) { if(exception instanceof UnrecognizedPropertyException) { return buildResponse(BAD_REQUEST, "Unrecognized property.", Collections.singletonMap("property_name", ((UnrecognizedPropertyException) exception).getPropertyName())); } return buildResponse(BAD_REQUEST, "Mapping error - Some fields are missing."); }
public static UpgradeProcessorsConfig newInstance(Path configFilePath) throws JsonParseException, JsonMappingException, IOException { JacksonXmlModule module = new JacksonXmlModule(); module.setDefaultUseWrapper(false); XmlMapper xmlMapper = new XmlMapper(module); return xmlMapper.readValue(configFilePath.toFile(), UpgradeProcessorsConfig.class); }
@Test public void blowsUpIfPassWordsFileIsMalformed() throws Exception { File tempFile = temporaryFolder.newFile("passwords.yml"); FileWriter fileWriter = new FileWriter(tempFile); fileWriter.write("invalid content"); fileWriter.flush(); assertThatThrownBy(() -> passwordsUnmarshaller.parsePasswords(tempFile)) .isExactlyInstanceOf(IllegalArgumentException.class) .hasMessage(format("Error occurred reading passwords file '%s'", tempFile.getName())) .hasCauseExactlyInstanceOf(JsonMappingException.class); }
@Test public void getInvalidDate() throws Exception { try { client.datetimerfc1123s().getInvalid(); Assert.assertTrue(false); } catch (Exception exception) { // expected Assert.assertEquals(JsonMappingException.class, exception.getCause().getClass()); } }
@Test public void shouldFailToDeserializeIfNumwantIsNotDefined() throws IOException { final String jsonWithoutNumwant = validJSON.replaceAll("\"numwant\":[ ]*[0-9]+,", ""); assertThatThrownBy(() -> mapper.readValue(jsonWithoutNumwant, BitTorrentClientConfig.class)) .isInstanceOf(JsonMappingException.class) .hasMessageContaining("Missing required creator property 'numwant'"); }
@Override public Response toResponse(JsonMappingException e) { return Response .status(Response.Status.BAD_REQUEST) .entity(JsonError.builder() .code(Response.Status.BAD_REQUEST.getStatusCode()) .message("Unable to map request JSON") .build()) .type(MediaType.APPLICATION_JSON) .build(); }
@ExceptionHandler(value = {ServiceException.class, JsonMappingException.class}) protected ResponseEntity<Object> handleServiceException(Exception ex, WebRequest request) { ex.printStackTrace(); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); return handleExceptionInternal(ex, new HttpErrorServer(ex.getLocalizedMessage()), headers, HttpStatus.INTERNAL_SERVER_ERROR, request); }
@Test(dataProvider = "policyDataProvider") public void testEvaluateWithPolicyWithCacheSetException(final File inputPolicy, final Effect effect) throws JsonParseException, JsonMappingException, IOException { Mockito.doThrow(new RuntimeException()).when(this.cache) .set(Mockito.any(PolicyEvaluationRequestCacheKey.class), Mockito.any(PolicyEvaluationResult.class)); testEvaluateWithPolicy(inputPolicy, effect); }
public static MultiThreadQueryObjectProvider fromJsonString(ThreadPoolTaskExecutor executor, CatalogService catalogService, VirtualObjectService virtualObjectService, PlatformServer server, String json, Integer rid, PackageMetaData packageMetaData) throws JsonParseException, JsonMappingException, IOException, QueryException { return fromJsonNode(executor, catalogService, virtualObjectService, server, OBJECT_MAPPER.readValue(json, ObjectNode.class), rid, packageMetaData); }
@Test public void canGenerateJSON() throws JsonParseException, JsonMappingException, IOException { // Exclusive lock LockInfoImpl lockInfo = new LockInfoImpl(); lockInfo.setExclusiveLockToken("opaque-lock-token"); lockInfo.setDepth(WebDAV.INFINITY); lockInfo.setScope(WebDAV.XML_EXCLUSIVE); String json = lockInfo.toJSON(); ObjectMapper objectMapper = new ObjectMapper(); assertTrue("ADDINFO_WEBDAV_MARKER", json.startsWith(LockInfoImpl.ADDINFO_WEBDAV_MARKER)); json = json.substring(LockInfoImpl.ADDINFO_WEBDAV_MARKER.length() + 1); LockInfoImpl parsed = objectMapper.readValue(json, LockInfoImpl.class); assertEquals("opaque-lock-token", parsed.getExclusiveLockToken()); assertEquals(WebDAV.INFINITY, parsed.getDepth()); assertEquals(WebDAV.XML_EXCLUSIVE, parsed.getScope()); // Shared lock lockInfo = new LockInfoImpl(); lockInfo.addSharedLockToken("opaque-lock-token-1"); lockInfo.addSharedLockToken("opaque-lock-token-2"); lockInfo.addSharedLockToken("opaque-lock-token-3"); lockInfo.setDepth(WebDAV.ZERO); lockInfo.setScope(WebDAV.XML_SHARED); json = lockInfo.toJSON(); assertTrue("ADDINFO_WEBDAV_MARKER", json.startsWith(LockInfoImpl.ADDINFO_WEBDAV_MARKER)); json = json.substring(LockInfoImpl.ADDINFO_WEBDAV_MARKER.length() + 1); parsed = objectMapper.readValue(json, LockInfoImpl.class); Set<String> sortedTokens = new TreeSet<String>(parsed.getSharedLockTokens()); Iterator<String> tokenIt = sortedTokens.iterator(); assertEquals("opaque-lock-token-1", tokenIt.next()); assertEquals("opaque-lock-token-2", tokenIt.next()); assertEquals("opaque-lock-token-3", tokenIt.next()); assertEquals(WebDAV.ZERO, parsed.getDepth()); assertEquals(WebDAV.XML_SHARED, parsed.getScope()); }
/** * Method to update a review with RabbitMQ * @return * @throws IOException * @throws JsonMappingException * @throws JsonParseException */ @RequestMapping(value = "/updateReview", method = RequestMethod.POST) public String updateReview(@RequestParam Map<String, String> body) throws JsonParseException, JsonMappingException, IOException{ Log .forContext("person", body.get("review")) .forContext("MemberName", "updateReview") .forContext("Service", appName) .information("Request : updateReview"); return new RabbitClient(EXCHANGE).rabbitRPCRoutingKeyExchange(body.get("review").getBytes(ENCODE),"updateReview"); }
private HttpResponseMetaData getResponseMetaData(ClientResponseContext responseContext) throws IOException { Map<String, String> headers = FormatUtil.MultiMapAsStringMap(responseContext.getHeaders()); HttpResponseMetaData.HttpResponseMetaDataBuilder builder = HttpResponseMetaData.builder() .status(responseContext.getStatus()) .headers(headers); if (responseContext.hasEntity()) { String body; // setUp the "real" error message try (BufferedReader buffer = new BufferedReader(new InputStreamReader(responseContext.getEntityStream(), "UTF-8"))) { body = buffer.lines().collect(Collectors.joining("\n")); } try { ProblemResponse problem = mapper.readValue(body, ProblemResponse.class); if (problemWasParsed(problem)) { builder.problemResponse(problem) .incidentReferenceId(problem.incidentReferenceId); } } catch (JsonParseException | JsonMappingException e) { //ignore } if (builder.build().problemResponse == null) { builder.response(body); } } return builder.build(); }