javatips.net counter

Java Examples for org.codehaus.jackson.JsonFactory

The following java examples will help you to understand the usage of org.codehaus.jackson.JsonFactory. These source code samples are taken from different open source projects.

Example 1
Project: stickypunch-master  File: TestUtils.java View source code
public static String getRandomLogJson() {
    JsonFactory jsonfactory = new JsonFactory();
    Writer writer = new StringWriter();
    String json = null;
    try {
        JsonGenerator jsonGenerator = jsonfactory.createJsonGenerator(writer);
        jsonGenerator.writeStartObject();
        jsonGenerator.writeArrayFieldStart("logs");
        jsonGenerator.writeString("authenticationToken must be at least 16 characters.");
        jsonGenerator.writeString("Downloading push notification package failed.");
        jsonGenerator.writeString("Extracting push notification package failed.");
        jsonGenerator.writeString("Missing file in push notification package.");
        jsonGenerator.writeString("Missing image in push notification package.");
        jsonGenerator.writeEndArray();
        jsonGenerator.writeEndObject();
        jsonGenerator.close();
        json = writer.toString();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return json;
}
Example 2
Project: teiid-designer-master  File: RestUtils.java View source code
private static List<String> parseRepositories(final String jsonResponse) throws Exception {
    if (!jsonResponse.isEmpty()) {
        final JsonFactory jsonFactory = new JsonFactory();
        final JsonParser jp = jsonFactory.createJsonParser(jsonResponse);
        final ObjectMapper mapper = new ObjectMapper();
        final JsonNode rootNode = mapper.readTree(jp);
        // should only get one repositories node back
        if ((rootNode != null) && (rootNode.size() == 1)) {
            final JsonNode repositoriesNode = rootNode.iterator().next();
            final List<String> result = new ArrayList<String>(repositoriesNode.size());
            for (final JsonNode repoNode : repositoriesNode) {
                //$NON-NLS-1$
                result.add(repoNode.path("name").getTextValue());
            }
            return result;
        }
    }
    return Collections.emptyList();
}
Example 3
Project: databus-master  File: InteractiveSchemaGenerator.java View source code
private String filterUserFields(String schema) throws IOException, DatabusException {
    //No filtering is necessary, just return the same schema
    if (!_areFieldsFiltered) {
        return schema;
    }
    Schema avroSchema = Schema.parse(schema);
    ObjectMapper mapper = new ObjectMapper();
    JsonFactory factory = new JsonFactory();
    StringWriter writer = new StringWriter();
    JsonGenerator jgen = factory.createJsonGenerator(writer);
    jgen.useDefaultPrettyPrinter();
    @SuppressWarnings("checked") HashMap<String, Object> schemaMap = new ObjectMapper().readValue(schema, HashMap.class);
    @SuppressWarnings("checked") ArrayList<HashMap<String, String>> list = (ArrayList<HashMap<String, String>>) schemaMap.get("fields");
    int i = 0;
    while (i < list.size()) {
        Schema.Field field = avroSchema.getField(list.get(i).get("name"));
        String dbFieldName;
        if (field.schema().getType() == Schema.Type.ARRAY) {
            throw new DatabusException("Field not supported for filtering");
        //TODO fix this
        /*
        String innerSchema = field.getProp("items");
        if(innerSchema == null)
          throw new DatabusException("Unable to the inner schema type of the array");
        Schema innerSchemaParsed = Schema.parse(innerSchema);
        dbFieldName = SchemaHelper.getMetaField(innerSchemaParsed, "dbFieldName");
        */
        } else
            dbFieldName = SchemaHelper.getMetaField(field, "dbFieldName");
        if (dbFieldName == null)
            throw new DatabusException("Unable to determine the dbFieldName from the meta information");
        if (!_userFields.contains(dbFieldName.toUpperCase(Locale.ENGLISH)))
            list.remove(i);
        else
            i++;
    }
    mapper.writeValue(jgen, schemaMap);
    return writer.getBuffer().toString();
}
Example 4
Project: yarn-comment-master  File: Configuration.java View source code
/**
   *  Writes out all the parameters and their properties (final and resource) to
   *  the given [email protected] Writer}
   *  The format of the output would be 
   *  { "properties" : [ {key1,value1,key1.isFinal,key1.resource}, {key2,value2,
   *  key2.isFinal,key2.resource}... ] } 
   *  It does not output the parameters of the configuration object which is 
   *  loaded from an input stream.
   * @param out the Writer to write to
   * @throws IOException
   */
public static void dumpConfiguration(Configuration config, Writer out) throws IOException {
    JsonFactory dumpFactory = new JsonFactory();
    JsonGenerator dumpGenerator = dumpFactory.createJsonGenerator(out);
    dumpGenerator.writeStartObject();
    dumpGenerator.writeFieldName("properties");
    dumpGenerator.writeStartArray();
    dumpGenerator.flush();
    synchronized (config) {
        for (Map.Entry<Object, Object> item : config.getProps().entrySet()) {
            dumpGenerator.writeStartObject();
            dumpGenerator.writeStringField("key", (String) item.getKey());
            dumpGenerator.writeStringField("value", config.get((String) item.getKey()));
            dumpGenerator.writeBooleanField("isFinal", config.finalParameters.contains(item.getKey()));
            dumpGenerator.writeStringField("resource", config.updatingResource.get(item.getKey()));
            dumpGenerator.writeEndObject();
        }
    }
    dumpGenerator.writeEndArray();
    dumpGenerator.writeEndObject();
    dumpGenerator.flush();
}
Example 5
Project: flink-master  File: PreviewPlanDumpTest.java View source code
private void dump(Plan p) {
    try {
        List<DataSinkNode> sinks = Optimizer.createPreOptimizedPlan(p);
        PlanJSONDumpGenerator dumper = new PlanJSONDumpGenerator();
        String json = dumper.getPactPlanAsJSON(sinks);
        JsonParser parser = new JsonFactory().createJsonParser(json);
        while (parser.nextToken() != null) ;
    } catch (JsonParseException e) {
        e.printStackTrace();
        Assert.fail("JSON Generator produced malformatted output: " + e.getMessage());
    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail("An error occurred in the test: " + e.getMessage());
    }
}
Example 6
Project: HDP-2.2-Patched-master  File: Configuration.java View source code
/**
   *  Writes out all the parameters and their properties (final and resource) to
   *  the given [email protected] Writer}
   *  The format of the output would be 
   *  { "properties" : [ {key1,value1,key1.isFinal,key1.resource}, {key2,value2,
   *  key2.isFinal,key2.resource}... ] } 
   *  It does not output the parameters of the configuration object which is 
   *  loaded from an input stream.
   * @param out the Writer to write to
   * @throws IOException
   */
public static void dumpConfiguration(Configuration config, Writer out) throws IOException {
    JsonFactory dumpFactory = new JsonFactory();
    JsonGenerator dumpGenerator = dumpFactory.createJsonGenerator(out);
    dumpGenerator.writeStartObject();
    dumpGenerator.writeFieldName("properties");
    dumpGenerator.writeStartArray();
    dumpGenerator.flush();
    synchronized (config) {
        for (Map.Entry<Object, Object> item : config.getProps().entrySet()) {
            dumpGenerator.writeStartObject();
            dumpGenerator.writeStringField("key", (String) item.getKey());
            dumpGenerator.writeStringField("value", config.get((String) item.getKey()));
            dumpGenerator.writeBooleanField("isFinal", config.finalParameters.contains(item.getKey()));
            String[] resources = config.updatingResource.get(item.getKey());
            String resource = UNKNOWN_RESOURCE;
            if (resources != null && resources.length > 0) {
                resource = resources[0];
            }
            dumpGenerator.writeStringField("resource", resource);
            dumpGenerator.writeEndObject();
        }
    }
    dumpGenerator.writeEndArray();
    dumpGenerator.writeEndObject();
    dumpGenerator.flush();
}
Example 7
Project: org.ops4j.pax.url-master  File: AssemblyDescriptorParser.java View source code
/**
     * Reads descriptor file.
     *
     * @param url descriptor file url
     *
     * @throws IOException - If a problem encountered while parsing descriptor file
     */
private void parseDescriptor(final URL url) throws IOException {
    final JsonFactory jFactory = new JsonFactory();
    jFactory.enable(JsonParser.Feature.ALLOW_COMMENTS);
    final JsonParser jp = jFactory.createJsonParser(url);
    if (jp.nextToken() != JsonToken.START_OBJECT) {
        throw new IOException(String.format("Descriptor [%s] not in JSON format", url.toExternalForm()));
    }
    final Collection<Source> sources = new HashSet<Source>();
    try {
        while (jp.nextToken() != JsonToken.END_OBJECT) {
            final String currentName = jp.getCurrentName();
            jp.nextToken();
            if ("manifest".equals(currentName)) {
                m_manifest = jp.getText();
            } else if ("assembly".equals(currentName)) {
                sources.addAll(parseAssembly(jp));
            } else if ("mergePolicy".equals(currentName)) {
                m_mergePolicy = "last".equalsIgnoreCase(jp.getText()) ? MergePolicy.LAST : MergePolicy.FIRST;
            }
        }
    } finally {
        jp.close();
    }
    m_sources = sources.toArray(new Source[sources.size()]);
}
Example 8
Project: hadoop-on-lustre2-master  File: Configuration.java View source code
/**
   *  Writes out all the parameters and their properties (final and resource) to
   *  the given [email protected] Writer}
   *  The format of the output would be 
   *  { "properties" : [ {key1,value1,key1.isFinal,key1.resource}, {key2,value2,
   *  key2.isFinal,key2.resource}... ] } 
   *  It does not output the parameters of the configuration object which is 
   *  loaded from an input stream.
   * @param out the Writer to write to
   * @throws IOException
   */
public static void dumpConfiguration(Configuration config, Writer out) throws IOException {
    JsonFactory dumpFactory = new JsonFactory();
    JsonGenerator dumpGenerator = dumpFactory.createJsonGenerator(out);
    dumpGenerator.writeStartObject();
    dumpGenerator.writeFieldName("properties");
    dumpGenerator.writeStartArray();
    dumpGenerator.flush();
    synchronized (config) {
        for (Map.Entry<Object, Object> item : config.getProps().entrySet()) {
            dumpGenerator.writeStartObject();
            dumpGenerator.writeStringField("key", (String) item.getKey());
            dumpGenerator.writeStringField("value", config.get((String) item.getKey()));
            dumpGenerator.writeBooleanField("isFinal", config.finalParameters.contains(item.getKey()));
            String[] resources = config.updatingResource.get(item.getKey());
            String resource = UNKNOWN_RESOURCE;
            if (resources != null && resources.length > 0) {
                resource = resources[0];
            }
            dumpGenerator.writeStringField("resource", resource);
            dumpGenerator.writeEndObject();
        }
    }
    dumpGenerator.writeEndArray();
    dumpGenerator.writeEndObject();
    dumpGenerator.flush();
}
Example 9
Project: tdq-studio-se-master  File: EcosystemService.java View source code
public static <T> List<T> parseJsonObject(String jsonContent, Class<T> clazz) throws Exception {
    // need factory for creating parser to use
    JsonFactory jf = new JsonFactory();
    if (jsonContent == null || clazz == null) {
        return new ArrayList<T>();
    }
    List<?> result = (List<?>) new JavaTypeMapper().read(jf.createJsonParser(new StringReader(jsonContent)));
    List<T> objList = new ArrayList<T>(result.size());
    for (int i = 0; i < result.size(); i++) {
        T obj = clazz.newInstance();
        Object source = result.get(i);
        BeanUtils.copyProperties(obj, source);
        objList.add(obj);
    }
    return objList;
}
Example 10
Project: hadoop-20-master  File: Configuration.java View source code
/**
   *  Writes out all the parameters and their properties (final and resource) to
   *  the given [email protected] Writer}
   *  The format of the output would be 
   *  { "properties" : [ {key1,value1,key1.isFinal,key1.resource}, {key2,value2,
   *  key2.isFinal,key2.resource}... ] } 
   *  It does not output the parameters of the configuration object which is 
   *  loaded from an input stream.
   * @param out the Writer to write to
   * @throws IOException
   */
public static void dumpConfiguration(Configuration config, Writer out) throws IOException {
    JsonFactory dumpFactory = new JsonFactory();
    JsonGenerator dumpGenerator = dumpFactory.createJsonGenerator(out);
    dumpGenerator.writeStartObject();
    dumpGenerator.writeFieldName("properties");
    dumpGenerator.writeStartArray();
    dumpGenerator.flush();
    synchronized (config) {
        for (Map.Entry<Object, Object> item : config.getProps().entrySet()) {
            dumpGenerator.writeStartObject();
            dumpGenerator.writeStringField("key", (String) item.getKey());
            dumpGenerator.writeStringField("value", config.get((String) item.getKey()));
            dumpGenerator.writeBooleanField("isFinal", config.finalParameters.contains(item.getKey()));
            dumpGenerator.writeStringField("resource", config.updatingResource.get(item.getKey()));
            dumpGenerator.writeEndObject();
        }
    }
    dumpGenerator.writeEndArray();
    dumpGenerator.writeEndObject();
    dumpGenerator.flush();
}
Example 11
Project: flare-spork-master  File: JsonLoader.java View source code
@SuppressWarnings("unchecked")
public void prepareToRead(RecordReader reader, PigSplit split) throws IOException {
    this.reader = reader;
    // Get the schema string from the UDFContext object.
    UDFContext udfc = UDFContext.getUDFContext();
    Properties p = udfc.getUDFProperties(this.getClass(), new String[] { udfcSignature });
    String strSchema = p.getProperty(SCHEMA_SIGNATURE);
    if (strSchema == null) {
        throw new IOException("Could not find schema in UDF context");
    }
    // Parse the schema from the string stored in the properties object.
    schema = new ResourceSchema(Utils.getSchemaFromString(strSchema));
    jsonFactory = new JsonFactory();
}
Example 12
Project: ohmagePhone-master  File: OhmageApi.java View source code
private Response parseStreamingReadResponse(String url, HttpResponse response, StreamingResponseListener listener) {
    Result result = Result.HTTP_ERROR;
    String[] errorCodes = null;
    // the response object that will be returned; its type is decided by outputType
    // it's also populated by a call to populateFromJSON() which transforms the server response into the Response object
    Response candidate = new Response();
    CountingInputStream inputstream = null;
    if (response != null) {
        Log.v(TAG, response.getStatusLine().toString());
        if (response.getStatusLine().getStatusCode() == 200) {
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                try {
                    // rather than use the regular json parsing library here,
                    // we use jackson to parse the first part, then return a
                    // reference to use for reading the data section
                    // note that we open the inputstream rather than reading the whole thing to a string
                    JsonFactory f = new MappingJsonFactory();
                    inputstream = new CountingInputStream(responseEntity.getContent());
                    JsonParser jp = f.createJsonParser(inputstream);
                    // expecting: {result: "<status>", data: [{},{},{}...]}
                    // ensure the first token in the stream is the start of an object
                    JsonToken cur = jp.nextToken();
                    if (cur != JsonToken.START_OBJECT)
                        throw new JSONException("Top-level entity expected to be an object, found " + cur.toString());
                    // read through the top-level object one attribute at a time
                    while (jp.nextToken() != JsonToken.END_OBJECT) {
                        // get the field name first...
                        String fieldName = jp.getCurrentName();
                        // ...and move on to the token representing the value
                        cur = jp.nextToken();
                        // dispatch on the field name
                        if (fieldName.equalsIgnoreCase("result")) {
                            // figure out the data in the result type
                            JsonNode resultNode = jp.readValueAsTree();
                            if (resultNode.getTextValue().equalsIgnoreCase("success")) {
                                result = Result.SUCCESS;
                            } else {
                                result = Result.FAILURE;
                            }
                        } else if (fieldName.equalsIgnoreCase("data")) {
                            // ensure that the data section is an array
                            if (cur != JsonToken.START_ARRAY)
                                throw new JSONException("Data section expected to be an array, found " + cur.toString());
                            // do pre-read init
                            listener.beforeRead();
                            // now that we know it's an array, read it off and call the listener on each object read
                            while (jp.nextToken() != JsonToken.END_ARRAY && listener.isListening()) {
                                listener.readObject(jp.readValueAsTree());
                            }
                            // do post-read cleanup
                            listener.afterRead();
                        } else if (fieldName.equalsIgnoreCase("errors")) {
                            // ensure that the errors section is an array
                            if (cur != JsonToken.START_ARRAY)
                                throw new JSONException("Errors section expected to be an array, found " + cur.toString());
                            List<String> errorList = new ArrayList<String>();
                            while (jp.nextToken() != JsonToken.END_ARRAY) {
                                // read off each of the errors and stick it into the error array
                                JsonNode error = jp.readValueAsTree();
                                errorList.add(error.get("code").getTextValue());
                            }
                            errorCodes = errorList.toArray(new String[errorList.size()]);
                        } else {
                            // don't know what to do with this, just skip it?
                            Log.v(TAG, "Unprocessed field in response: " + fieldName);
                            jp.skipChildren();
                        }
                    }
                // and we're done!
                } catch (JSONException e) {
                    Log.e(TAG, "Problem parsing response json", e);
                    result = Result.INTERNAL_ERROR;
                } catch (IOException e) {
                    Log.e(TAG, "Problem reading response body", e);
                    result = Result.INTERNAL_ERROR;
                }
            } else {
                Log.e(TAG, "No response entity in response");
                result = Result.HTTP_ERROR;
            }
        } else {
            Log.e(TAG, "Returned status code: " + String.valueOf(response.getStatusLine().getStatusCode()));
            result = Result.HTTP_ERROR;
        }
    } else {
        Log.e(TAG, "Response is null");
        result = Result.HTTP_ERROR;
    }
    if (inputstream != null && result == Result.SUCCESS)
        Analytics.network(mContext, url, inputstream.amountRead());
    listener.readResult(result, errorCodes);
    candidate.setResponseStatus(result, errorCodes);
    return candidate;
}
Example 13
Project: bigpetstore-master  File: Configuration.java View source code
/**
   *  Writes out all the parameters and their properties (final and resource) to
   *  the given [email protected] Writer}
   *  The format of the output would be 
   *  { "properties" : [ {key1,value1,key1.isFinal,key1.resource}, {key2,value2,
   *  key2.isFinal,key2.resource}... ] } 
   *  It does not output the parameters of the configuration object which is 
   *  loaded from an input stream.
   * @param out the Writer to write to
   * @throws IOException
   */
public static void dumpConfiguration(Configuration config, Writer out) throws IOException {
    JsonFactory dumpFactory = new JsonFactory();
    JsonGenerator dumpGenerator = dumpFactory.createJsonGenerator(out);
    dumpGenerator.writeStartObject();
    dumpGenerator.writeFieldName("properties");
    dumpGenerator.writeStartArray();
    dumpGenerator.flush();
    synchronized (config) {
        for (Map.Entry<Object, Object> item : config.getProps().entrySet()) {
            dumpGenerator.writeStartObject();
            dumpGenerator.writeStringField("key", (String) item.getKey());
            dumpGenerator.writeStringField("value", config.get((String) item.getKey()));
            dumpGenerator.writeBooleanField("isFinal", config.finalParameters.contains(item.getKey()));
            dumpGenerator.writeStringField("resource", config.updatingResource.get(item.getKey()));
            dumpGenerator.writeEndObject();
        }
    }
    dumpGenerator.writeEndArray();
    dumpGenerator.writeEndObject();
    dumpGenerator.flush();
}
Example 14
Project: AIDR-master  File: TaggerServiceImpl.java View source code
private int getCurrentRetrainingThreshold() throws Exception {
    try {
        String retrainingThreshold = this.getRetainingThreshold();
        ObjectMapper mapper = JacksonWrapper.getObjectMapper();
        // since 2.1 use
        JsonFactory factory = mapper.getJsonFactory();
        // mapper.getFactory()
        // instead
        JsonParser jp = factory.createJsonParser(retrainingThreshold);
        JsonNode actualObj = mapper.readTree(jp);
        JsonNode nameNode = actualObj.get("sampleCountThreshold");
        int sampleCountThreshold = Integer.parseInt(nameNode.asText());
        return sampleCountThreshold;
    } catch (Exception e) {
        logger.error("Exception while getting CurrentRetrainingThreshold", e);
        return 50;
    }
}
Example 15
Project: spork-streaming-master  File: JsonLoader.java View source code
@SuppressWarnings("unchecked")
public void prepareToRead(RecordReader reader, PigSplit split) throws IOException {
    this.reader = reader;
    // Get the schema string from the UDFContext object.
    UDFContext udfc = UDFContext.getUDFContext();
    Properties p = udfc.getUDFProperties(this.getClass(), new String[] { udfcSignature });
    String strSchema = p.getProperty(SCHEMA_SIGNATURE);
    if (strSchema == null) {
        throw new IOException("Could not find schema in UDF context");
    }
    // Parse the schema from the string stored in the properties object.
    schema = new ResourceSchema(Utils.getSchemaFromString(strSchema));
    jsonFactory = new JsonFactory();
}
Example 16
Project: PonIC-master  File: JsonLoader.java View source code
@SuppressWarnings("unchecked")
public void prepareToRead(RecordReader reader, PigSplit split) throws IOException {
    this.reader = reader;
    // Get the schema string from the UDFContext object.
    UDFContext udfc = UDFContext.getUDFContext();
    Properties p = udfc.getUDFProperties(this.getClass(), new String[] { udfcSignature });
    String strSchema = p.getProperty(SCHEMA_SIGNATURE);
    if (strSchema == null) {
        throw new IOException("Could not find schema in UDF context");
    }
    // Parse the schema from the string stored in the properties object.
    schema = new ResourceSchema(Utils.getSchemaFromString(strSchema));
    jsonFactory = new JsonFactory();
}