Java 类com.fasterxml.jackson.core.JsonParseException 实例源码

项目:xm-uaa    文件:TenantLoginsResource.java   
/**
 * 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();
    }
}
项目:GitHub    文件:JacksonPageModelParser.java   
/**
 * @param parser
 * @param layoutId
 * @throws JsonParseException
 * @throws IOException
 */
private List<RegionInstance> parseRegions(JsonParser parser, String segment) throws JsonParseException, IOException {

    JsonToken current = parser.nextToken();

    assertExpectedJsonToken(current, JsonToken.START_ARRAY, parser.getCurrentLocation());
    List<RegionInstance> instances = new ArrayList<RegionInstance>();
    while ((current = parser.nextToken()) != JsonToken.END_ARRAY) {

        assertExpectedJsonToken(current, JsonToken.START_OBJECT, parser.getCurrentLocation());

        String regionId = getNextTextValue("cid", parser); // get regionId
        RegionEnum region = RegionEnum.valueOf(regionId);

        current = parser.nextToken(); // move to field: widgtes
        assertExpectedFiled(parser.getCurrentName(), "widgets", parser.getCurrentLocation());
        RegionInstance instance = new RegionInstance();
        instance.setWidgtes(parseWidgets(parser, region));
        instances.add(instance);

        assertExpectedJsonToken((current = parser.nextToken()), JsonToken.END_OBJECT, parser.getCurrentLocation());
    }
    return instances;

}
项目:InComb    文件:ConfigTest.java   
@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));
}
项目:fresco_floodlight    文件:FirewallSubnetMaskResource.java   
/**
 * Extracts subnet mask from a JSON string
 * @param fmJson The JSON formatted string
 * @return The subnet mask
 * @throws IOException If there was an error parsing the JSON
 */
public static String jsonExtractSubnetMask(String fmJson) throws IOException {
    String subnet_mask = "";
    MappingJsonFactory f = new MappingJsonFactory();
    JsonParser jp;

    try {
        jp = f.createParser(fmJson);
    } catch (JsonParseException e) {
        throw new IOException(e);
    }

    jp.nextToken();
    if (jp.getCurrentToken() != JsonToken.START_OBJECT) {
        throw new IOException("Expected START_OBJECT");
    }

    while (jp.nextToken() != JsonToken.END_OBJECT) {
        if (jp.getCurrentToken() != JsonToken.FIELD_NAME) {
            throw new IOException("Expected FIELD_NAME");
        }

        String n = jp.getCurrentName();
        jp.nextToken();
        if (jp.getText().equals(""))
            continue;

        if (n == "subnet-mask") {
            subnet_mask = jp.getText();
            break;
        }
    }

    return subnet_mask;
}
项目:elasticsearch_my    文件:FunctionScoreQueryBuilderTests.java   
public void testMalformedThrowsException() throws IOException {
    String json = "{\n" +
        "    \"function_score\":{\n" +
        "        \"query\":{\n" +
        "            \"term\":{\n" +
        "                \"name.last\":\"banon\"\n" +
        "            }\n" +
        "        },\n" +
        "        \"functions\": [\n" +
        "            {\n" +
        "                {\n" +
        "            }\n" +
        "        ]\n" +
        "    }\n" +
        "}";
    JsonParseException e = expectThrows(JsonParseException.class, () -> parseQuery(json));
    assertThat(e.getMessage(), containsString("Unexpected character ('{"));
}
项目:BIMplatform    文件:QueryObjectProvider.java   
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");
    }
}
项目:open-kilda    文件:LoggingFilter.java   
/**
 * Log response.
 *
 * @param response the response
 * @param the
 * @throws IOException
 * @throws JsonMappingException
 * @throws JsonParseException
 */
private void logResponse(final ResponseWrapper response) throws JsonParseException,
        JsonMappingException, IOException {
    StringBuilder msg = new StringBuilder();
    msg.append(RESPONSE_PREFIX);
    msg.append("\nid: '").append((response.getId())).append("' ");
    try {

        ObjectMapper mapper = new ObjectMapper();
        Object json =
                mapper.readValue(
                        new String(response.getData(), response.getCharacterEncoding()),
                        Object.class);

        msg.append("\nResponse: \n").append(
                mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json));
    } catch (UnsupportedEncodingException e) {
        _log.error("[logResponse] Exception: " + e.getMessage(), e);
    }
    _log.info("[logResponse] Response: " + msg.toString());
}
项目:QDrill    文件:JSONRecordReader.java   
protected void handleAndRaise(String suffix, Exception e) throws UserException {

    String message = e.getMessage();
    int columnNr = -1;

    if (e instanceof JsonParseException) {
      final JsonParseException ex = (JsonParseException) e;
      message = ex.getOriginalMessage();
      columnNr = ex.getLocation().getColumnNr();
    }

    UserException.Builder exceptionBuilder = UserException.dataReadError(e)
            .message("%s - %s", suffix, message);
    if (columnNr > 0) {
      exceptionBuilder.pushContext("Column ", columnNr);
    }

    if (hadoopPath != null) {
      exceptionBuilder.pushContext("Record ", currentRecordNumberInFile())
          .pushContext("File ", hadoopPath.toUri().getPath());
    }

    throw exceptionBuilder.build(logger);
  }
项目:lambda-forest    文件:ResponseEntityTest.java   
@Test
public void shouldOverwriteDefaultHttpStatusCode() throws JsonParseException, JsonMappingException, IOException {
    UserRequestTest request = new UserRequestTest("user name", "user address");
    ResponseEntity response = ResponseEntity.of(request, HttpStatus.SC_ACCEPTED);

    Assert.assertEquals(HttpStatus.SC_ACCEPTED, 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());
}
项目:wamp2spring    文件:ParserUtilTest.java   
@SuppressWarnings("resource")
@Test
public void testReadArray() throws JsonParseException, IOException {
    ObjectMapper om = new ObjectMapper();
    JsonParser jp = om.getFactory().createParser("\"test\"");
    jp.nextToken();
    assertThat(ParserUtil.readArray(jp)).isNull();

    jp = om.getFactory().createParser("[1,2,3]");
    jp.nextToken();
    assertThat(ParserUtil.readArray(jp)).containsExactly(1, 2, 3);

    jp = om.getFactory().createParser("[[\"k\",\"l\",\"m\"],[\"a\",\"b\",\"c\"]]");
    jp.nextToken();
    assertThat(ParserUtil.readArray(jp)).containsExactly(Arrays.asList("k", "l", "m"),
            Arrays.asList("a", "b", "c"));
}
项目:wamp2spring    文件:WelcomeMessageTest.java   
@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));
}
项目:lambda-forest    文件:ResponseEntityTest.java   
@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());
}
项目:demo-spring-boot-security-oauth2    文件:GrantByImplicitProviderTest.java   
@Test
public void getJwtTokenByImplicitGrant() throws JsonParseException, JsonMappingException, IOException {
    String redirectUrl = "http://localhost:"+port+"/resources/user";
    ResponseEntity<String> response = new TestRestTemplate("user","password").postForEntity("http://localhost:" + port 
       + "oauth/authorize?response_type=token&client_id=normal-app&redirect_uri={redirectUrl}", null, String.class,redirectUrl);
    assertEquals(HttpStatus.OK, response.getStatusCode());
    List<String> setCookie = response.getHeaders().get("Set-Cookie");
    String jSessionIdCookie = setCookie.get(0);
    String cookieValue = jSessionIdCookie.split(";")[0];

    HttpHeaders headers = new HttpHeaders();
    headers.add("Cookie", cookieValue);
    response = new TestRestTemplate("user","password").postForEntity("http://localhost:" + port 
            + "oauth/authorize?response_type=token&client_id=normal-app&redirect_uri={redirectUrl}&user_oauth_approval=true&authorize=Authorize",
            new HttpEntity<>(headers), String.class, redirectUrl);
    assertEquals(HttpStatus.FOUND, response.getStatusCode());
    assertNull(response.getBody());
    String location = response.getHeaders().get("Location").get(0);

    //FIXME: Is this a bug with redirect URL?
    location = location.replace("#", "?");

    response = new TestRestTemplate().getForEntity(location, String.class);
    assertEquals(HttpStatus.OK, response.getStatusCode());
}
项目:bootstrap    文件:ExceptionMapperIT.java   
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();
        }
    }
}
项目:bootstrap    文件:ExceptionMapperIT.java   
private void assertUnavailable(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_SERVICE_UNAVAILABLE, response.getStatusLine().getStatusCode());
        final String content = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8);
        final Map<?, ?> result = new ObjectMapperTrim().readValue(content, HashMap.class);
        Assert.assertNull(result.get("message"));
        Assert.assertEquals("database-down", result.get("code"));
        Assert.assertNull(result.get("cause"));
    } finally {
        if (response != null) {
            response.getEntity().getContent().close();
        }
    }
}
项目:oscm    文件:LocalizedBillingResourceAssembler.java   
static boolean isValidJSON(String jsonString)
        throws BillingApplicationException {

    ObjectMapper om = new ObjectMapper();
    try {
        JsonParser parser = om.getFactory().createParser(jsonString);
        while (parser.nextToken() != null) {
        }
        return true;
    } catch (JsonParseException jpe) {
        logger.logError(Log4jLogger.SYSTEM_LOG, jpe,
                LogMessageIdentifier.ERROR_INVALID_JSON);
        return false;
    } catch (IOException e) {
        logger.logError(Log4jLogger.SYSTEM_LOG, e,
                LogMessageIdentifier.ERROR_IO_VALIDITY_EXTERNAL_JSON);
        throw new BillingApplicationException(
                "IO Error when checking JSON validity of external price model description.");
    }
}
项目:desafio-pagarme    文件:Client.java   
/**
 * Sets the api key.
 *
 * @throws JsonParseException the json parse exception
 * @throws JsonMappingException the json mapping exception
 * @throws IOException Signals that an I/O exception has occurred.
 */
private void setApiKey() throws JsonParseException, JsonMappingException, IOException{
    ArrayList<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>();
    interceptors.add((HttpRequest request, byte[] body, ClientHttpRequestExecution execution) -> {
        if(body.length > 0) {
            body = addTokenInObject(body, new JsonNodeFormatter());
        }else{
            try {
                request = addTokenInURI(request);
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }
        }
        return execution.execute(request, body);
    });
    this.restTemplate.setInterceptors(interceptors);
}
项目:tikv-client-lib-java    文件:CatalogTransaction.java   
public static <T> T parseFromJson(ByteString json, Class<T> cls) {
  Objects.requireNonNull(json, "json is null");
  Objects.requireNonNull(cls, "cls is null");

  logger.debug(String.format("Parse Json %s : %s", cls.getSimpleName(), json.toStringUtf8()));
  ObjectMapper mapper = new ObjectMapper();
  try {
    return mapper.readValue(json.toStringUtf8(), cls);
  } catch (JsonParseException | JsonMappingException e) {
    String errMsg =
        String.format(
            "Invalid JSON value for Type %s: %s\n", cls.getSimpleName(), json.toStringUtf8());
    throw new TiClientInternalException(errMsg, e);
  } catch (Exception e1) {
    throw new TiClientInternalException("Error parsing Json", e1);
  }
}
项目:smarti    文件:RocketBot.java   
public RocketBot deserialize(JsonParser parser, DeserializationContext context) throws IOException, JsonProcessingException {
    if(JsonToken.START_OBJECT.equals(parser.getCurrentToken())) {
        ObjectMapper mapper = new ObjectMapper();
        return mapper.readValue(parser, RocketBot.class);
    } else if (JsonToken.VALUE_FALSE.equals(parser.getCurrentToken())) {
        return null;
    } else
        throw new JsonParseException(parser, "Unexpected token received.");
}
项目:fresco_floodlight    文件:StaticFlowEntries.java   
/**
 * Gets the entry name of a flow mod
 * @param fmJson The OFFlowMod in a JSON representation
 * @return The name of the OFFlowMod, null if not found
 * @throws IOException If there was an error parsing the JSON
 */
public static String getEntryNameFromJson(String fmJson) throws IOException{
    MappingJsonFactory f = new MappingJsonFactory();
    JsonParser jp;

    try {
        jp = f.createParser(fmJson);
    } catch (JsonParseException e) {
        throw new IOException(e);
    }

    jp.nextToken();
    if (jp.getCurrentToken() != JsonToken.START_OBJECT) {
        throw new IOException("Expected START_OBJECT");
    }

    while (jp.nextToken() != JsonToken.END_OBJECT) {
        if (jp.getCurrentToken() != JsonToken.FIELD_NAME) {
            throw new IOException("Expected FIELD_NAME");
        }

        String n = jp.getCurrentName();
        jp.nextToken();
        if (jp.getText().equals("")) 
            continue;

        if (n == StaticFlowEntryPusher.COLUMN_NAME)
            return jp.getText();
    }
    return null;
}
项目:autorest.java    文件:NumberTests.java   
@Test
public void getInvalidDouble() throws Exception {
    try {
        client.numbers().getInvalidDouble();
        Assert.assertTrue(false);
    } catch (Exception exception) {
        // expected
        Assert.assertEquals(JsonParseException.class, exception.getCause().getClass());
    }
}
项目:GitHub    文件:JacksonGroupParser.java   
public static String getNextTextValue(String fieldName, JsonParser parser) throws JsonParseException, IOException {
    JsonToken current = parser.nextToken(); // move to filed
    if (current != JsonToken.FIELD_NAME || !fieldName.equals(parser.getCurrentName())) {
        reportParseError("Error occoured while getting value by field name:" + fieldName, parser.getCurrentLocation());
    }
    current = parser.nextToken(); // move to value
    return parser.getText();
}
项目:GitHub    文件:EnumIT.java   
@Test
@SuppressWarnings("unchecked")
public void intEnumIsSerializedCorrectly() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, JsonParseException, JsonMappingException, IOException, InstantiationException {

    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");

    // create an instance
    Object valueWithEnumProperty = typeWithEnumProperty.newInstance();
    Method enumSetter = typeWithEnumProperty.getMethod("setTestEnum", enumClass);

    // call setTestEnum(TestEnum.ONE)
    enumSetter.invoke(valueWithEnumProperty, enumClass.getEnumConstants()[0]);

    ObjectMapper objectMapper = new ObjectMapper();

    // write our instance out to json
    String jsonString = objectMapper.writeValueAsString(valueWithEnumProperty);
    JsonNode jsonTree = objectMapper.readTree(jsonString);

    assertThat(jsonTree.size(), is(1));
    assertThat(jsonTree.has("testEnum"), is(true));
    assertThat(jsonTree.get("testEnum").isIntegralNumber(), is(true));
    assertThat(jsonTree.get("testEnum").asInt(), is(1));
}
项目:GitHub    文件:AsyncMissingValuesInObjectTest.java   
private void assertUnexpected(AsyncReaderWrapper p, char c) throws IOException {
    try {
        p.nextToken();
        fail("No exception thrown");
    } catch (JsonParseException e) {
        verifyException(e, String.format("Unexpected character ('%s' (code %d))", c, (int) c));
    }
}
项目:GitHub    文件:ParserErrorHandlingTest.java   
private void _testMangledNumbersFloat(int mode) throws Exception
{
    // Also test with floats
    JsonParser p = createParser(mode, "1.5false");
    try {
        JsonToken t = p.nextToken();
        fail("Should have gotten an exception; instead got token: "+t);
    } catch (JsonParseException e) {
        verifyException(e, "expected space");
    }
    p.close();
}
项目:OpenLRW    文件:MongoEventRepositoryTest.java   
@Before
public void init() throws JsonParseException, JsonMappingException, UnsupportedEncodingException, IOException {
  ObjectMapper mapper = new ObjectMapper();
  mapper.findAndRegisterModules();
  mapper.setDateFormat(new ISO8601DateFormat());

  Envelope envelope = mapper.readValue(MediaEventTest.MEDIA_EVENT.getBytes("UTF-8"), Envelope.class);
  mediaEvent = envelope.getData().get(0);
}
项目:dremio-oss    文件:VectorOutput.java   
public boolean checkToken(final JsonToken t, final JsonToken expected1, final JsonToken expected2) throws IOException{
  if(t == JsonToken.VALUE_NULL){
    return true;
  }else if(t == expected1){
    return false;
  }else if(t == expected2){
    return false;
  }else{
    throw new JsonParseException(String.format("Failure while reading ExtendedJSON typed value. Expected a %s but "
        + "received a token of type %s", expected1, t), parser.getCurrentLocation());
  }
}
项目:Practical-Real-time-Processing-and-Analytics    文件:ElasticSearchBolt.java   
public Map<String,Object> convertStringtoMap(String fieldValue) throws JsonParseException, JsonMappingException, IOException {
    System.out.println("Orignal value  "+ fieldValue);
    Map<String,Object> convertedValue = new HashMap<>();
    Map<String,Object> readValue = mapper.readValue(fieldValue, new TypeReference<Map<String,Object>>() {});

    convertedValue.put("ambient_temperature", Double.parseDouble(String.valueOf(readValue.get("ambient_temperature"))));
    convertedValue.put("photosensor", Double.parseDouble(String.valueOf(readValue.get("photosensor"))));
    convertedValue.put("humidity", Double.parseDouble(String.valueOf(readValue.get("humidity"))));
    convertedValue.put("radiation_level", Integer.parseInt(String.valueOf(readValue.get("radiation_level"))));
    convertedValue.put("sensor_uuid", readValue.get("sensor_uuid"));
    convertedValue.put("timestamp", new Date());

    System.out.println("Converted value  "+ convertedValue);
    return convertedValue;
}
项目:InComb    文件:ConfigTest.java   
@Test
public void testBasicValues() throws JsonParseException, JsonMappingException, IOException {
    assertEquals("John", config.getProperty("firstName", String.class));
    assertEquals(true, config.getProperty("isAlive", Boolean.class));
    assertEquals(new Integer(25), config.getProperty("age", Integer.class));
    assertEquals(new Double(167.6), config.getProperty("height_cm", Double.class));
    assertNull(config.getProperty("spouse", Object.class));
}
项目:autorest.java    文件:IntOperationsTests.java   
@Test
public void getUnderflowInt32() throws Exception {
    try {
        client.ints().getUnderflowInt32();
        Assert.assertTrue(false);
    } catch (Exception exception) {
        Assert.assertEquals(JsonParseException.class, exception.getCause().getClass());
    }
}
项目:keti    文件:PolicyEvaluationServiceTest.java   
@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);
}
项目:BIMplatform    文件:MultiThreadQueryObjectProvider.java   
public static MultiThreadQueryObjectProvider fromJsonNode(ThreadPoolTaskExecutor executor,
        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 MultiThreadQueryObjectProvider(executor, catalogService, virtualObjectService, query,
                rid, packageMetaData);
    } else {
        throw new QueryException("Query root must be of type object");
    }
}
项目:dremio-oss    文件:VectorOutput.java   
long getType() throws JsonParseException, IOException {
  if (!checkNextToken(JsonToken.VALUE_NUMBER_INT, JsonToken.VALUE_STRING)) {
    long type = parser.getValueAsLong();
    //Advancing the token, as checking current token in binary
    parser.nextToken();
    return type;
  }
  throw new JsonParseException("Failure while reading $type value. Expected a NUMBER or STRING",
      parser.getCurrentLocation());
}
项目:keti    文件:AccessControlServiceIT.java   
@Test(dataProvider = "endpointProvider")
public void testPolicyUpdateWithNoOauthToken(final String endpoint)
        throws JsonParseException, JsonMappingException, IOException {
    RestTemplate acs = new RestTemplate();
    // Use vanilla rest template with no oauth token.
    try {
        String policyFile = "src/test/resources/policy-set-with-multiple-policies-na-with-condition.json";
        this.policyHelper.setTestPolicy(acs, this.acsitSetUpFactory.getZone1Headers(), endpoint, policyFile);
        Assert.fail("No exception thrown when making request without token.");
    } catch (HttpClientErrorException e) {
        Assert.assertEquals(e.getStatusCode(), HttpStatus.UNAUTHORIZED);
    }

}
项目:keti    文件:PolicyEvaluationServiceTest.java   
@Test(dataProvider = "policyDataProvider")
public void testEvaluateWithPolicy(final File inputPolicy, final Effect effect)
        throws JsonParseException, JsonMappingException, IOException {
    initializePolicyMock(inputPolicy);
    PolicyEvaluationResult evalPolicy = this.evaluationService
            .evalPolicy(createRequest("resource1", "subject1", "GET"));
    Assert.assertEquals(evalPolicy.getEffect(), effect);
}
项目:gitplex-mit    文件:UserResource.java   
@GET
  public Response get(@Context UriInfo uriInfo) throws JsonParseException, JsonMappingException, IOException {
Map<String, Object> entity = new HashMap<>();

User user = userManager.getCurrent();
entity.put("name", user.getFullName());
entity.put("login", user.getName());
entity.put("id", "1000000");
entity.put("type", "User");
entity.put("url", uriInfo.getBaseUri().toString() + "/users/" + user.getName());
entity.put("site_admin", SecurityUtils.isAdministrator());
entity.put("created_at", new SimpleDateFormat(RestConstants.DATE_FORMAT).format(new Date()));

return Response.ok(entity, RestConstants.JSON_UTF8).build();
  }
项目:desafio-pagarme    文件:CardHashKey.java   
@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);
}
项目:Snow-Globe    文件:CallUtility.java   
/**
 * Maps expected JSON formatted response from fake upstream server to the ResponseBody class.
 *
 * @param body String representation of the JSON response.
 * @return The ResponseBody object representing the JSON response.
 */
static ResponseBody buildResponseBody(String body) {
    ObjectMapper mapper = new ObjectMapper();
    ResponseBody res;
    try {
        res = mapper.readValue(body, ResponseBody.class);
    } catch (JsonParseException jpe) {
        res = ResponseBody.buildDirectResponseFromRp(body);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return res;
}
项目:csap-core    文件:DefinitionParser.java   
private void generateLifecycleServiceInstances (
                                                    ReleasePackage releasePackage,
                                                    String platformLifeCycle, StringBuffer resultsBuf, LifeCycleSettings lifeMetaData,
                                                    ArrayList<String> groupList, String platformSubLife, JsonNode subLifeNode,
                                                    ReleasePackage testRootModel
                                                    )
        throws IOException, JsonParseException, JsonMappingException {

    logger.debug( "Checking: {} ", releasePackage.getReleasePackageFileName() );

    if ( subLifeNode.has( DEFINITION_MONITORS ) ) {
        // this is a hook for cluster level settings that overwrite
        // the defaults
        List<JsonNode> nodes = subLifeNode.findValues( "hosts" );

        for ( JsonNode node : nodes ) {
            ArrayNode nodeArray = (ArrayNode) node;
            for ( JsonNode hostNameNode : nodeArray ) {
                String host = hostNameNode.asText().replaceAll( "\\$host", Application.getHOST_NAME() );
                lifeMetaData
                    .addHostMonitor( host, subLifeNode.path( DEFINITION_MONITORS ) );
            }
            // logger.warn("_node: " +
            // jacksonMapper.writeValueAsString( node));
        }
    }
    groupList.add( platformSubLife );

    // Any logic/semantic errors are pushed via
    // Application.CONFIG_PARSE_ERROR
    resultsBuf.append( "\n \t " + releasePackage.getReleasePackageFileName() + "\t - \t" + platformSubLife );


    configureAllJavaServices( resultsBuf, releasePackage, platformLifeCycle, platformSubLife, subLifeNode );

    configureAllOsProcesses( resultsBuf, releasePackage, platformLifeCycle, platformSubLife, subLifeNode, testRootModel );

    generateMapsForConfigScreen( releasePackage, platformLifeCycle, platformSubLife, subLifeNode );

}
项目:csap-core    文件:ErrorHandling.java   
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR, reason = "Exception during processing, examine server Logs")
@ExceptionHandler(JsonParseException.class)
public void handleJsonParsing(HttpServletRequest request,Exception e) {
    logger.warn( "{}: {}", request.getRequestURI(),CSAP.getCsapFilteredStackTrace( e ));
    logger.debug( "Full exception", e );
}