Search in sources :

Example 11 with JsonToken

use of org.codehaus.jackson.JsonToken in project presto-hive-apache by prestodb.

the class JsonSerDe method deserialize.

/**
 * Takes JSON string in Text form, and has to return an object representation above
 * it that's readable by the corresponding object inspector.
 *
 * For this implementation, since we're using the jackson parser, we can construct
 * our own object implementation, and we use HCatRecord for it
 */
@Override
public Object deserialize(Writable blob) throws SerDeException {
    Text t = (Text) blob;
    JsonParser p;
    List<Object> r = new ArrayList<Object>(Collections.nCopies(columnNames.size(), null));
    try {
        p = jsonFactory.createJsonParser(new ByteArrayInputStream((t.getBytes())));
        if (p.nextToken() != JsonToken.START_OBJECT) {
            throw new IOException("Start token not found where expected");
        }
        JsonToken token;
        while (((token = p.nextToken()) != JsonToken.END_OBJECT) && (token != null)) {
            // iterate through each token, and create appropriate object here.
            populateRecord(r, token, p, schema);
        }
    } catch (JsonParseException e) {
        LOG.warn("Error [{}] parsing json text [{}].", e, t);
        LOG.debug(null, e);
        throw new SerDeException(e);
    } catch (IOException e) {
        LOG.warn("Error [{}] parsing json text [{}].", e, t);
        LOG.debug(null, e);
        throw new SerDeException(e);
    }
    return new DefaultHCatRecord(r);
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) ArrayList(java.util.ArrayList) Text(org.apache.hadoop.io.Text) JsonToken(org.codehaus.jackson.JsonToken) IOException(java.io.IOException) JsonParseException(org.codehaus.jackson.JsonParseException) SerDeException(org.apache.hadoop.hive.serde2.SerDeException) JsonParser(org.codehaus.jackson.JsonParser)

Example 12 with JsonToken

use of org.codehaus.jackson.JsonToken in project gwt-test-utils by gwt-test-utils.

the class JSONParserPatcher method evaluate.

@PatchMethod
static JSONValue evaluate(String json, boolean strict) {
    JsonParser jp = null;
    try {
        JsonFactory f = new JsonFactory();
        if (!strict) {
            f.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
            f.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
            f.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
            f.configure(JsonParser.Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER, true);
            f.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
            f.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
            f.configure(JsonParser.Feature.ALLOW_NUMERIC_LEADING_ZEROS, true);
        }
        jp = f.createJsonParser(json);
        JsonToken token = jp.nextToken();
        if (JsonToken.START_ARRAY == token) {
            JSONArray jsonArray = extractJSONArray(json, null, jp);
            return jsonArray;
        } else {
            JSONObject jsonObject = extractJSONObject(json, jp);
            return jsonObject;
        }
    } catch (Exception e) {
        if (e instanceof GwtTestException) {
            throw (GwtTestException) e;
        }
        throw new GwtTestJSONException("Error while parsing JSON string '" + json + "'", e);
    } finally {
        if (jp != null) {
            try {
                // ensure resources get cleaned up timely and properly
                jp.close();
            } catch (IOException e) {
            // should never happen
            }
        }
    }
}
Also used : GwtTestException(com.googlecode.gwt.test.exceptions.GwtTestException) GwtTestJSONException(com.googlecode.gwt.test.exceptions.GwtTestJSONException) JsonFactory(org.codehaus.jackson.JsonFactory) JsonToken(org.codehaus.jackson.JsonToken) IOException(java.io.IOException) JsonParseException(org.codehaus.jackson.JsonParseException) GwtTestException(com.googlecode.gwt.test.exceptions.GwtTestException) IOException(java.io.IOException) GwtTestJSONException(com.googlecode.gwt.test.exceptions.GwtTestJSONException) JsonParser(org.codehaus.jackson.JsonParser) PatchMethod(com.googlecode.gwt.test.patchers.PatchMethod)

Example 13 with JsonToken

use of org.codehaus.jackson.JsonToken in project WSPerfLab by Netflix-Skunkworks.

the class BackendResponse method parseBackendResponse.

public static BackendResponse parseBackendResponse(JsonParser parser) throws IOException {
    try {
        // Sanity check: verify that we got "Json Object":
        if (parser.nextToken() != JsonToken.START_OBJECT) {
            throw new IOException("Expected data to start with an Object");
        }
        long responseKey = 0;
        int delay = 0;
        int numItems = 0;
        int itemSize = 0;
        String[] items = null;
        JsonToken current;
        while (parser.nextToken() != JsonToken.END_OBJECT) {
            String fieldName = parser.getCurrentName();
            // advance
            current = parser.nextToken();
            if (fieldName.equals("responseKey")) {
                responseKey = parser.getLongValue();
            } else if (fieldName.equals("delay")) {
                delay = parser.getIntValue();
            } else if (fieldName.equals("itemSize")) {
                itemSize = parser.getIntValue();
            } else if (fieldName.equals("numItems")) {
                numItems = parser.getIntValue();
            } else if (fieldName.equals("items")) {
                // expect numItems to be populated before hitting this
                if (numItems == 0) {
                    throw new IllegalStateException("Expected numItems > 0");
                }
                items = new String[numItems];
                if (current == JsonToken.START_ARRAY) {
                    int j = 0;
                    // For each of the records in the array
                    while (parser.nextToken() != JsonToken.END_ARRAY) {
                        items[j++] = parser.getText();
                    }
                } else {
                    // System.out.println("Error: items should be an array: skipping.");
                    parser.skipChildren();
                }
            }
        }
        return new BackendResponse(responseKey, delay, numItems, itemSize, items);
    } finally {
        parser.close();
    }
}
Also used : JsonToken(org.codehaus.jackson.JsonToken) IOException(java.io.IOException)

Example 14 with JsonToken

use of org.codehaus.jackson.JsonToken in project spring-security-oauth by spring-projects.

the class OAuth2ExceptionJackson1Deserializer method deserialize.

@Override
public OAuth2Exception deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    JsonToken t = jp.getCurrentToken();
    if (t == JsonToken.START_OBJECT) {
        t = jp.nextToken();
    }
    Map<String, Object> errorParams = new HashMap<String, Object>();
    for (; t == JsonToken.FIELD_NAME; t = jp.nextToken()) {
        // Must point to field name
        String fieldName = jp.getCurrentName();
        // And then the value...
        t = jp.nextToken();
        // Note: must handle null explicitly here; value deserializers won't
        Object value;
        if (t == JsonToken.VALUE_NULL) {
            value = null;
        } else // Some servers might send back complex content
        if (t == JsonToken.START_ARRAY) {
            value = jp.readValueAs(List.class);
        } else if (t == JsonToken.START_OBJECT) {
            value = jp.readValueAs(Map.class);
        } else {
            value = jp.getText();
        }
        errorParams.put(fieldName, value);
    }
    Object errorCode = errorParams.get("error");
    String errorMessage = errorParams.containsKey("error_description") ? errorParams.get("error_description").toString() : null;
    if (errorMessage == null) {
        errorMessage = errorCode == null ? "OAuth Error" : errorCode.toString();
    }
    OAuth2Exception ex;
    if ("invalid_client".equals(errorCode)) {
        ex = new InvalidClientException(errorMessage);
    } else if ("unauthorized_client".equals(errorCode)) {
        ex = new UnauthorizedClientException(errorMessage);
    } else if ("invalid_grant".equals(errorCode)) {
        if (errorMessage.toLowerCase().contains("redirect") && errorMessage.toLowerCase().contains("match")) {
            ex = new RedirectMismatchException(errorMessage);
        } else {
            ex = new InvalidGrantException(errorMessage);
        }
    } else if ("invalid_scope".equals(errorCode)) {
        ex = new InvalidScopeException(errorMessage);
    } else if ("invalid_token".equals(errorCode)) {
        ex = new InvalidTokenException(errorMessage);
    } else if ("invalid_request".equals(errorCode)) {
        ex = new InvalidRequestException(errorMessage);
    } else if ("redirect_uri_mismatch".equals(errorCode)) {
        ex = new RedirectMismatchException(errorMessage);
    } else if ("unsupported_grant_type".equals(errorCode)) {
        ex = new UnsupportedGrantTypeException(errorMessage);
    } else if ("unsupported_response_type".equals(errorCode)) {
        ex = new UnsupportedResponseTypeException(errorMessage);
    } else if ("access_denied".equals(errorCode)) {
        ex = new UserDeniedAuthorizationException(errorMessage);
    } else if ("insufficient_scope".equals(errorCode)) {
        ex = new InsufficientScopeException(errorMessage, OAuth2Utils.parseParameterList((String) errorParams.get("scope")));
    } else {
        ex = new OAuth2Exception(errorMessage);
    }
    Set<Map.Entry<String, Object>> entries = errorParams.entrySet();
    for (Map.Entry<String, Object> entry : entries) {
        String key = entry.getKey();
        if (!"error".equals(key) && !"error_description".equals(key)) {
            Object value = entry.getValue();
            ex.addAdditionalInformation(key, value == null ? null : value.toString());
        }
    }
    return ex;
}
Also used : HashMap(java.util.HashMap) JsonToken(org.codehaus.jackson.JsonToken) Map(java.util.Map) HashMap(java.util.HashMap)

Example 15 with JsonToken

use of org.codehaus.jackson.JsonToken in project neo4j by neo4j.

the class StatementDeserializer method fetchNextOrNull.

@Override
protected Statement fetchNextOrNull() {
    try {
        if (errors != null) {
            return null;
        }
        switch(state) {
            case BEFORE_OUTER_ARRAY:
                if (!beginsWithCorrectTokens()) {
                    return null;
                }
                state = State.IN_BODY;
            case IN_BODY:
                String statement = null;
                Map<String, Object> parameters = null;
                List<Object> resultsDataContents = null;
                boolean includeStats = false;
                JsonToken tok;
                while ((tok = input.nextToken()) != null && tok != END_OBJECT) {
                    if (tok == END_ARRAY) {
                        // No more statements
                        state = State.FINISHED;
                        return null;
                    }
                    input.nextValue();
                    String currentName = input.getCurrentName();
                    switch(currentName) {
                        case "statement":
                            statement = input.readValueAs(String.class);
                            break;
                        case "parameters":
                            parameters = readMap(input);
                            break;
                        case "resultDataContents":
                            resultsDataContents = readArray(input);
                            break;
                        case "includeStats":
                            includeStats = input.getBooleanValue();
                            break;
                        default:
                            discardValue(input);
                    }
                }
                if (statement == null) {
                    addError(new Neo4jError(Status.Request.InvalidFormat, new DeserializationException("No statement provided.")));
                    return null;
                }
                return new Statement(statement, parameters == null ? NO_PARAMETERS : parameters, includeStats, ResultDataContent.fromNames(resultsDataContents));
            case FINISHED:
                return null;
            default:
                break;
        }
        return null;
    } catch (JsonParseException | JsonMappingException e) {
        addError(new Neo4jError(Status.Request.InvalidFormat, new DeserializationException("Unable to deserialize request", e)));
        return null;
    } catch (IOException e) {
        addError(new Neo4jError(Status.Network.CommunicationError, e));
        return null;
    } catch (Exception e) {
        addError(new Neo4jError(Status.General.UnknownError, e));
        return null;
    }
}
Also used : IOException(java.io.IOException) JsonParseException(org.codehaus.jackson.JsonParseException) JsonMappingException(org.codehaus.jackson.map.JsonMappingException) IOException(java.io.IOException) JsonParseException(org.codehaus.jackson.JsonParseException) Neo4jError(org.neo4j.server.rest.transactional.error.Neo4jError) JsonMappingException(org.codehaus.jackson.map.JsonMappingException) JsonToken(org.codehaus.jackson.JsonToken)

Aggregations

JsonToken (org.codehaus.jackson.JsonToken)19 IOException (java.io.IOException)6 ArrayList (java.util.ArrayList)4 JsonParseException (org.codehaus.jackson.JsonParseException)3 JsonParser (org.codehaus.jackson.JsonParser)3 TypeDeserializer (org.codehaus.jackson.map.TypeDeserializer)3 LinkedHashMap (java.util.LinkedHashMap)2 HiveChar (org.apache.hadoop.hive.common.type.HiveChar)2 HiveVarchar (org.apache.hadoop.hive.common.type.HiveVarchar)2 BaseCharTypeInfo (org.apache.hadoop.hive.serde2.typeinfo.BaseCharTypeInfo)2 HCatFieldSchema (org.apache.hive.hcatalog.data.schema.HCatFieldSchema)2 HCatSchema (org.apache.hive.hcatalog.data.schema.HCatSchema)2 Neo4jError (org.neo4j.server.rest.transactional.error.Neo4jError)2 ValueSerializationException (org.qi4j.api.value.ValueSerializationException)2 EvalError (com.google.refine.expr.EvalError)1 GwtTestException (com.googlecode.gwt.test.exceptions.GwtTestException)1 GwtTestJSONException (com.googlecode.gwt.test.exceptions.GwtTestJSONException)1 PatchMethod (com.googlecode.gwt.test.patchers.PatchMethod)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 Serializable (java.io.Serializable)1