Search in sources :

Example 41 with JsonParser

use of org.apache.flink.shaded.jackson2.com.fasterxml.jackson.core.JsonParser in project keycloak by keycloak.

the class ClaimInformationPointProviderTest method testBodyJsonObjectClaim.

@Test
public void testBodyJsonObjectClaim() throws Exception {
    Map<String, List<String>> headers = new HashMap<>();
    headers.put("Content-Type", Arrays.asList("application/json"));
    ObjectMapper mapper = JsonSerialization.mapper;
    JsonParser parser = mapper.getFactory().createParser("{\"Individual\" : {\n" + "\n" + "                \"Name\":  \"John\",\n" + "\n" + "                \"Lastname\": \"Doe\",\n" + "\n" + "                \"individualRoles\" : [ {\n" + "\n" + "                                \"roleSpec\": 2342,\n" + "\n" + "                                \"roleId\": 4234},\n" + "\n" + "{\n" + "\n" + "                                \"roleSpec\": 4223,\n" + "\n" + "                                \"roleId\": 523\n" + "\n" + "                }\n" + "\n" + "                ]\n" + "\n" + "}}");
    TreeNode treeNode = mapper.readTree(parser);
    HttpFacade httpFacade = createHttpFacade(headers, new ByteArrayInputStream(treeNode.toString().getBytes()));
    Map<String, List<String>> claims = getClaimInformationProviderForPath("/claims-from-body-json-object", "claims").resolve(httpFacade);
    assertEquals(1, claims.size());
    assertEquals(2, claims.get("individualRoles").size());
    assertEquals("{\"roleSpec\":2342,\"roleId\":4234}", claims.get("individualRoles").get(0));
    assertEquals("{\"roleSpec\":4223,\"roleId\":523}", claims.get("individualRoles").get(1));
    headers.put("Content-Type", Arrays.asList("application/json; charset=utf-8"));
    httpFacade = createHttpFacade(headers, new ByteArrayInputStream(treeNode.toString().getBytes()));
    claims = getClaimInformationProviderForPath("/claims-from-body-json-object", "claims").resolve(httpFacade);
    assertEquals(1, claims.size());
    assertEquals(2, claims.get("individualRoles").size());
    assertEquals("{\"roleSpec\":2342,\"roleId\":4234}", claims.get("individualRoles").get(0));
    assertEquals("{\"roleSpec\":4223,\"roleId\":523}", claims.get("individualRoles").get(1));
}
Also used : HashMap(java.util.HashMap) ByteArrayInputStream(java.io.ByteArrayInputStream) TreeNode(com.fasterxml.jackson.core.TreeNode) OIDCHttpFacade(org.keycloak.adapters.OIDCHttpFacade) HttpFacade(org.keycloak.adapters.spi.HttpFacade) List(java.util.List) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) JsonParser(com.fasterxml.jackson.core.JsonParser) Test(org.junit.Test) AbstractKeycloakTest(org.keycloak.testsuite.AbstractKeycloakTest)

Example 42 with JsonParser

use of org.apache.flink.shaded.jackson2.com.fasterxml.jackson.core.JsonParser in project keycloak by keycloak.

the class AccessTokenTest method accessTokenRequest.

@Test
public void accessTokenRequest() throws Exception {
    oauth.doLogin("test-user@localhost", "password");
    EventRepresentation loginEvent = events.expectLogin().assertEvent();
    String sessionId = loginEvent.getSessionId();
    String codeId = loginEvent.getDetails().get(Details.CODE_ID);
    String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
    OAuthClient.AccessTokenResponse response = oauth.doAccessTokenRequest(code, "password");
    assertEquals(200, response.getStatusCode());
    Assert.assertThat(response.getExpiresIn(), allOf(greaterThanOrEqualTo(250), lessThanOrEqualTo(300)));
    Assert.assertThat(response.getRefreshExpiresIn(), allOf(greaterThanOrEqualTo(1750), lessThanOrEqualTo(1800)));
    assertEquals("Bearer", response.getTokenType());
    String expectedKid = oauth.doCertsRequest("test").getKeys()[0].getKeyId();
    JWSHeader header = new JWSInput(response.getAccessToken()).getHeader();
    assertEquals("RS256", header.getAlgorithm().name());
    assertEquals("JWT", header.getType());
    assertEquals(expectedKid, header.getKeyId());
    assertNull(header.getContentType());
    header = new JWSInput(response.getIdToken()).getHeader();
    assertEquals("RS256", header.getAlgorithm().name());
    assertEquals("JWT", header.getType());
    assertEquals(expectedKid, header.getKeyId());
    assertNull(header.getContentType());
    header = new JWSInput(response.getRefreshToken()).getHeader();
    assertEquals("HS256", header.getAlgorithm().name());
    assertEquals("JWT", header.getType());
    assertNull(header.getContentType());
    AccessToken token = oauth.verifyToken(response.getAccessToken());
    assertEquals(findUserByUsername(adminClient.realm("test"), "test-user@localhost").getId(), token.getSubject());
    assertNotEquals("test-user@localhost", token.getSubject());
    assertEquals(sessionId, token.getSessionState());
    JWSInput idToken = new JWSInput(response.getIdToken());
    ObjectMapper mapper = JsonSerialization.mapper;
    JsonParser parser = mapper.getFactory().createParser(idToken.readContentAsString());
    TreeNode treeNode = mapper.readTree(parser);
    String sid = ((TextNode) treeNode.get("sid")).asText();
    assertEquals(sessionId, sid);
    assertNull(token.getNbf());
    assertEquals(0, token.getNotBefore());
    assertNotNull(token.getIat());
    assertEquals(token.getIat().intValue(), token.getIssuedAt());
    assertNotNull(token.getExp());
    assertEquals(token.getExp().intValue(), token.getExpiration());
    assertEquals(1, token.getRealmAccess().getRoles().size());
    assertTrue(token.getRealmAccess().isUserInRole("user"));
    assertEquals(1, token.getResourceAccess(oauth.getClientId()).getRoles().size());
    assertTrue(token.getResourceAccess(oauth.getClientId()).isUserInRole("customer-user"));
    EventRepresentation event = events.expectCodeToToken(codeId, sessionId).assertEvent();
    assertEquals(token.getId(), event.getDetails().get(Details.TOKEN_ID));
    assertEquals(oauth.parseRefreshToken(response.getRefreshToken()).getId(), event.getDetails().get(Details.REFRESH_TOKEN_ID));
    assertEquals(sessionId, token.getSessionState());
}
Also used : OAuthClient(org.keycloak.testsuite.util.OAuthClient) AccessToken(org.keycloak.representations.AccessToken) TreeNode(com.fasterxml.jackson.core.TreeNode) EventRepresentation(org.keycloak.representations.idm.EventRepresentation) TextNode(com.fasterxml.jackson.databind.node.TextNode) JWSInput(org.keycloak.jose.jws.JWSInput) JWSHeader(org.keycloak.jose.jws.JWSHeader) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) JsonParser(com.fasterxml.jackson.core.JsonParser) AbstractKeycloakTest(org.keycloak.testsuite.AbstractKeycloakTest) Test(org.junit.Test)

Example 43 with JsonParser

use of org.apache.flink.shaded.jackson2.com.fasterxml.jackson.core.JsonParser in project components by Talend.

the class DatasetWritePayload method readAvroSchema.

private static Schema readAvroSchema(JsonParser parser) throws IOException {
    JsonToken avroSchemaFieldToken = parser.nextToken();
    isTrue(FIELD_NAME == avroSchemaFieldToken, invalidInputMessage(FIELD_NAME, avroSchemaFieldToken));
    isTrue(Objects.equals(AVRO_SCHEMA_FIELD_NAME, parser.getText()), invalidInputMessage(AVRO_SCHEMA_FIELD_NAME, parser.getText()));
    JsonToken configFieldObjectStartToken = parser.nextToken();
    isTrue(START_OBJECT == configFieldObjectStartToken, invalidInputMessage(START_OBJECT, configFieldObjectStartToken));
    // This code is so awful I will certainly have cancer
    ObjectNode schemaAsJson = parser.readValueAsTree();
    Schema.Parser avroSchemaParser = new Schema.Parser();
    return avroSchemaParser.parse(new ObjectMapper().writeValueAsString(schemaAsJson));
}
Also used : ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) Schema(org.apache.avro.Schema) JsonToken(com.fasterxml.jackson.core.JsonToken) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) JsonParser(com.fasterxml.jackson.core.JsonParser)

Example 44 with JsonParser

use of org.apache.flink.shaded.jackson2.com.fasterxml.jackson.core.JsonParser in project jocean-http by isdom.

the class DefaultSignalClient method toRESP.

@SuppressWarnings("unchecked")
private <RESP> RESP toRESP(final FullHttpResponse fullresp, final Class<?> respType, final Class<?> bodyType) {
    if (null != fullresp) {
        try {
            final byte[] bytes = Nettys.dumpByteBufAsBytes(fullresp.content());
            if (LOG.isTraceEnabled()) {
                try {
                    LOG.trace("receive signal response: {}", new String(bytes, CharsetUtil.UTF_8));
                } catch (Exception e) {
                // decode bytes as UTF-8 error, just ignore
                }
            }
            if (null != respType) {
                return DefaultSignalClient.<RESP>convertResponseTo(fullresp, bytes, respType);
            }
            if (null != bodyType) {
                if (bodyType.equals(String.class)) {
                    return (RESP) new String(bytes, CharsetUtil.UTF_8);
                } else {
                    // try need decode as xml
                    final Consumes consumes = bodyType.getAnnotation(Consumes.class);
                    if (null != consumes) {
                        final Collection<String> mimeTypes = Arrays.asList(consumes.value());
                        if (mimeTypes.contains(MediaType.APPLICATION_XML)) {
                            final XmlMapper mapper = new XmlMapper();
                            mapper.addHandler(new DeserializationProblemHandler() {

                                @Override
                                public boolean handleUnknownProperty(final DeserializationContext ctxt, final JsonParser p, final JsonDeserializer<?> deserializer, final Object beanOrClass, final String propertyName) throws IOException {
                                    LOG.warn("UnknownProperty [{}], just skip", propertyName);
                                    p.skipChildren();
                                    return true;
                                }
                            });
                            try {
                                return (RESP) mapper.readValue(bytes, bodyType);
                            } catch (Exception e) {
                                LOG.warn("exception when parse xml, detail: {}", ExceptionUtils.exception2detail(e));
                                return null;
                            }
                        }
                    }
                    // try need decode as json
                    return JSON.<RESP>parseObject(bytes, bodyType);
                }
            } else {
                final RESP respObj = (RESP) bytes;
                return respObj;
            }
        } catch (Exception e) {
            LOG.warn("exception when parse response {}, detail:{}", fullresp, ExceptionUtils.exception2detail(e));
            throw new RuntimeException(e);
        }
    }
    throw new RuntimeException("invalid response");
}
Also used : IOException(java.io.IOException) TransportException(org.jocean.http.TransportException) IOException(java.io.IOException) ErrorDataEncoderException(io.netty.handler.codec.http.multipart.HttpPostRequestEncoder.ErrorDataEncoderException) XmlMapper(com.fasterxml.jackson.dataformat.xml.XmlMapper) DeserializationProblemHandler(com.fasterxml.jackson.databind.deser.DeserializationProblemHandler) Consumes(javax.ws.rs.Consumes) DeserializationContext(com.fasterxml.jackson.databind.DeserializationContext) JsonParser(com.fasterxml.jackson.core.JsonParser)

Example 45 with JsonParser

use of org.apache.flink.shaded.jackson2.com.fasterxml.jackson.core.JsonParser in project steve by RWTH-i5-IDSG.

the class Deserializer method accept.

/**
 * Parsing with streaming API is cumbersome, but only it allows to parse the String step for step
 * and build, if any, a corresponding error message.
 */
@Override
public void accept(CommunicationContext context) {
    try (JsonParser parser = mapper.getFactory().createParser(context.getIncomingString())) {
        // set cursor to '['
        parser.nextToken();
        parser.nextToken();
        int messageTypeNr = parser.getIntValue();
        parser.nextToken();
        String messageId = parser.getText();
        MessageType messageType = MessageType.fromTypeNr(messageTypeNr);
        switch(messageType) {
            case CALL:
                handleCall(context, messageId, parser);
                break;
            case CALL_RESULT:
                handleResult(context, messageId, parser);
                break;
            case CALL_ERROR:
                handleError(context, messageId, parser);
                break;
            default:
                throw new SteveException("Unknown enum type");
        }
    } catch (IOException e) {
        throw new SteveException("Deserialization of incoming string failed: %s", context.getIncomingString(), e);
    }
}
Also used : IOException(java.io.IOException) MessageType(de.rwth.idsg.steve.ocpp.ws.data.MessageType) JsonParser(com.fasterxml.jackson.core.JsonParser) SteveException(de.rwth.idsg.steve.SteveException)

Aggregations

JsonParser (com.fasterxml.jackson.core.JsonParser)587 KriptonRuntimeException (com.abubusoft.kripton.exception.KriptonRuntimeException)258 JacksonWrapperParser (com.abubusoft.kripton.persistence.JacksonWrapperParser)258 KriptonJsonContext (com.abubusoft.kripton.KriptonJsonContext)257 ArrayList (java.util.ArrayList)171 IOException (java.io.IOException)126 JsonFactory (com.fasterxml.jackson.core.JsonFactory)76 Test (org.junit.Test)57 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)51 JsonNode (com.fasterxml.jackson.databind.JsonNode)46 HashSet (java.util.HashSet)43 JsonToken (com.fasterxml.jackson.core.JsonToken)41 LinkedHashSet (java.util.LinkedHashSet)38 HashMap (java.util.HashMap)35 LinkedList (java.util.LinkedList)26 JsonParseException (com.fasterxml.jackson.core.JsonParseException)23 JsonUtil.createJsonParser (com.facebook.presto.util.JsonUtil.createJsonParser)21 List (java.util.List)21 DeserializationContext (com.fasterxml.jackson.databind.DeserializationContext)20 InputStream (java.io.InputStream)20