Java Code Examples for com.fasterxml.jackson.core.JsonGenerator#writeEndArray()

The following examples show how to use com.fasterxml.jackson.core.JsonGenerator#writeEndArray() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Session.java    From jlibs with Apache License 2.0 6 votes vote down vote up
protected WAMPOutputStream welcomeMessage() throws Throwable{
    if(ROUTER)
        Debugger.temp("<- WelcomeMessage: [%d, %d, %s]", WelcomeMessage.ID, sessionID, Peer.router.details);
    WAMPOutputStream out = router.server.createOutputStream();
    try{
        JsonGenerator json = serialization.mapper().getFactory().createGenerator(out);
        json.writeStartArray();
        json.writeNumber(WelcomeMessage.ID);
        json.writeNumber(sessionID);
        json.writeTree(Peer.router.details);
        json.writeEndArray();
        json.close();
        return out;
    }catch(Throwable thr){
        out.release();
        throw thr;
    }
}
 
Example 2
Source File: WidgetConfigPropertiesSerializer.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void writeContentsConfig(JsonGenerator jsonGenerator, String key, String value) throws IOException {
    jsonGenerator.writeFieldName(key);
    jsonGenerator.writeStartArray();

    for (Map<String, String> config : extractConfigObject(value)) {
        jsonGenerator.writeStartObject();

        for(Entry<String, String> property : config.entrySet()) {
            writeProperty(jsonGenerator, property.getKey(), property.getValue());
        }

        jsonGenerator.writeEndObject();
    }

    jsonGenerator.writeEndArray();
}
 
Example 3
Source File: NameMappingParser.java    From iceberg with Apache License 2.0 6 votes vote down vote up
private static void toJson(MappedField field, JsonGenerator generator) throws IOException {
  generator.writeStartObject();

  generator.writeNumberField(FIELD_ID, field.id());

  generator.writeArrayFieldStart(NAMES);
  for (String name : field.names()) {
    generator.writeString(name);
  }
  generator.writeEndArray();

  MappedFields nested = field.nestedMapping();
  if (nested != null) {
    generator.writeFieldName(FIELDS);
    toJson(nested, generator);
  }

  generator.writeEndObject();
}
 
Example 4
Source File: NameMappingParser.java    From iceberg with Apache License 2.0 5 votes vote down vote up
private static void toJson(MappedFields mapping, JsonGenerator generator) throws IOException {
  generator.writeStartArray();

  for (MappedField field : mapping.fields()) {
    toJson(field, generator);
  }

  generator.writeEndArray();
}
 
Example 5
Source File: BindBeanSharedPreferences.java    From kripton with Apache License 2.0 5 votes vote down vote up
/**
 * for attribute valueCharTypeArray serialization
 */
protected String serializeValueCharTypeArray(char[] value) {
  if (value==null) {
    return null;
  }
  KriptonJsonContext context=KriptonBinder.jsonBind();
  try (KriptonByteArrayOutputStream stream=new KriptonByteArrayOutputStream(); JacksonWrapperSerializer wrapper=context.createSerializer(stream)) {
    JsonGenerator jacksonSerializer=wrapper.jacksonGenerator;
    jacksonSerializer.writeStartObject();
    int fieldCount=0;
    if (value!=null)  {
      fieldCount++;
      int n=value.length;
      char item;
      // write wrapper tag
      jacksonSerializer.writeFieldName("valueCharTypeArray");
      jacksonSerializer.writeStartArray();
      for (int i=0; i<n; i++) {
        item=value[i];
        jacksonSerializer.writeNumber(item);
      }
      jacksonSerializer.writeEndArray();
    }
    jacksonSerializer.writeEndObject();
    jacksonSerializer.flush();
    return stream.toString();
  } catch(Exception e) {
    e.printStackTrace();
    throw(new KriptonRuntimeException(e.getMessage()));
  }
}
 
Example 6
Source File: StringDaoImpl.java    From kripton with Apache License 2.0 5 votes vote down vote up
/**
 * for param serializer1 serialization
 */
private byte[] serializer1(String[] value) {
  if (value==null) {
    return null;
  }
  KriptonJsonContext context=KriptonBinder.jsonBind();
  try (KriptonByteArrayOutputStream stream=new KriptonByteArrayOutputStream(); JacksonWrapperSerializer wrapper=context.createSerializer(stream)) {
    JsonGenerator jacksonSerializer=wrapper.jacksonGenerator;
    int fieldCount=0;
    jacksonSerializer.writeStartObject();
    if (value!=null)  {
      int n=value.length;
      String item;
      // write wrapper tag
      jacksonSerializer.writeFieldName("element");
      jacksonSerializer.writeStartArray();
      for (int i=0; i<n; i++) {
        item=value[i];
        if (item==null) {
          jacksonSerializer.writeNull();
        } else {
          jacksonSerializer.writeString(item);
        }
      }
      jacksonSerializer.writeEndArray();
    }
    jacksonSerializer.writeEndObject();
    jacksonSerializer.flush();
    return stream.toByteArray();
  } catch(Exception e) {
    e.printStackTrace();
    throw(new KriptonRuntimeException(e.getMessage()));
  }
}
 
Example 7
Source File: BeanDaoImpl.java    From kripton with Apache License 2.0 5 votes vote down vote up
/**
 * for param serializer2 serialization
 */
private byte[] serializer2(HashMap<EnumType, Byte> value) {
  if (value==null) {
    return null;
  }
  KriptonJsonContext context=KriptonBinder.jsonBind();
  try (KriptonByteArrayOutputStream stream=new KriptonByteArrayOutputStream(); JacksonWrapperSerializer wrapper=context.createSerializer(stream)) {
    JsonGenerator jacksonSerializer=wrapper.jacksonGenerator;
    int fieldCount=0;
    jacksonSerializer.writeStartObject();
    if (value!=null)  {
      // write wrapper tag
      if (value.size()>0) {
        jacksonSerializer.writeFieldName("element");
        jacksonSerializer.writeStartArray();
        for (Map.Entry<EnumType, Byte> item: value.entrySet()) {
          jacksonSerializer.writeStartObject();
          jacksonSerializer.writeStringField(null, item.getKey().toString());
          if (item.getValue()==null) {
            jacksonSerializer.writeNullField(null);
          } else {
            jacksonSerializer.writeNumberField(null, item.getValue());
          }
          jacksonSerializer.writeEndObject();
        }
        jacksonSerializer.writeEndArray();
      } else {
        jacksonSerializer.writeNullField("element");
      }
    }
    jacksonSerializer.writeEndObject();
    jacksonSerializer.flush();
    return stream.toByteArray();
  } catch(Exception e) {
    e.printStackTrace();
    throw(new KriptonRuntimeException(e.getMessage()));
  }
}
 
Example 8
Source File: PrimitiveIterableSerializer.java    From jackson-datatypes-collections with Apache License 2.0 5 votes vote down vote up
@Override
public final void serialize(C value, JsonGenerator gen, SerializerProvider ctxt) throws IOException {
    if (((_unwrapSingle == null) &&
            ctxt.isEnabled(SerializationFeature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED))
            || (Boolean.TRUE.equals(_unwrapSingle))) {
        if (hasSingleElement(value)) {
            serializeContents(value, gen);
            return;
        }
    }
    gen.writeStartArray();
    serializeContents(value, gen);
    gen.writeEndArray();
}
 
Example 9
Source File: TraceCommonService.java    From glowroot with Apache License 2.0 5 votes vote down vote up
private static void writeJson(Trace.Entry entry, JsonGenerator jg) throws IOException {
    jg.writeNumberField("startOffsetNanos", entry.getStartOffsetNanos());
    jg.writeNumberField("durationNanos", entry.getDurationNanos());
    if (entry.getActive()) {
        jg.writeBooleanField("active", true);
    }
    if (entry.hasQueryEntryMessage()) {
        jg.writeObjectFieldStart("queryMessage");
        Trace.QueryEntryMessage queryMessage = entry.getQueryEntryMessage();
        jg.writeNumberField("sharedQueryTextIndex", queryMessage.getSharedQueryTextIndex());
        jg.writeStringField("prefix", queryMessage.getPrefix());
        jg.writeStringField("suffix", queryMessage.getSuffix());
        jg.writeEndObject();
    } else {
        jg.writeStringField("message", entry.getMessage());
    }
    List<Trace.DetailEntry> detailEntries = entry.getDetailEntryList();
    if (!detailEntries.isEmpty()) {
        jg.writeFieldName("detail");
        writeDetailEntries(detailEntries, jg);
    }
    List<Proto.StackTraceElement> locationStackTraceElements =
            entry.getLocationStackTraceElementList();
    if (!locationStackTraceElements.isEmpty()) {
        jg.writeArrayFieldStart("locationStackTraceElements");
        for (Proto.StackTraceElement stackTraceElement : locationStackTraceElements) {
            writeStackTraceElement(stackTraceElement, jg);
        }
        jg.writeEndArray();
    }
    if (entry.hasError()) {
        jg.writeFieldName("error");
        writeError(entry.getError(), jg);
    }
}
 
Example 10
Source File: IntBeanTable.java    From kripton with Apache License 2.0 5 votes vote down vote up
/**
 * for attribute value2 serialization
 */
public static byte[] serializeValue2(Integer[] value) {
  if (value==null) {
    return null;
  }
  KriptonJsonContext context=KriptonBinder.jsonBind();
  try (KriptonByteArrayOutputStream stream=new KriptonByteArrayOutputStream(); JacksonWrapperSerializer wrapper=context.createSerializer(stream)) {
    JsonGenerator jacksonSerializer=wrapper.jacksonGenerator;
    jacksonSerializer.writeStartObject();
    int fieldCount=0;
    if (value!=null)  {
      fieldCount++;
      int n=value.length;
      Integer item;
      // write wrapper tag
      jacksonSerializer.writeFieldName("element");
      jacksonSerializer.writeStartArray();
      for (int i=0; i<n; i++) {
        item=value[i];
        if (item==null) {
          jacksonSerializer.writeNull();
        } else {
          jacksonSerializer.writeNumber(item);
        }
      }
      jacksonSerializer.writeEndArray();
    }
    jacksonSerializer.writeEndObject();
    jacksonSerializer.flush();
    return stream.toByteArray();
  } catch(Exception e) {
    e.printStackTrace();
    throw(new KriptonRuntimeException(e.getMessage()));
  }
}
 
Example 11
Source File: BeanTable.java    From kripton with Apache License 2.0 5 votes vote down vote up
/**
 * for attribute valueDoubleSet serialization
 */
public static byte[] serializeValueDoubleSet(HashSet<Double> value) {
  if (value==null) {
    return null;
  }
  KriptonJsonContext context=KriptonBinder.jsonBind();
  try (KriptonByteArrayOutputStream stream=new KriptonByteArrayOutputStream(); JacksonWrapperSerializer wrapper=context.createSerializer(stream)) {
    JsonGenerator jacksonSerializer=wrapper.jacksonGenerator;
    jacksonSerializer.writeStartObject();
    int fieldCount=0;
    if (value!=null)  {
      fieldCount++;
      // write wrapper tag
      jacksonSerializer.writeFieldName("element");
      jacksonSerializer.writeStartArray();
      for (Double item: value) {
        if (item==null) {
          jacksonSerializer.writeNull();
        } else {
          jacksonSerializer.writeNumber(item);
        }
      }
      jacksonSerializer.writeEndArray();
    }
    jacksonSerializer.writeEndObject();
    jacksonSerializer.flush();
    return stream.toByteArray();
  } catch(Exception e) {
    e.printStackTrace();
    throw(new KriptonRuntimeException(e.getMessage()));
  }
}
 
Example 12
Source File: JsonHandler.java    From BIMserver with GNU Affero General Public License v3.0 5 votes vote down vote up
private void processMultiRequest(ArrayNode requests, String jsonToken, String oAuthCode, HttpServletRequest httpRequest, JsonGenerator out) throws Exception {
	out.writeFieldName("responses");
	out.writeStartArray();
	for (int r = 0; r < requests.size(); r++) {
		try {
			processSingleRequest((ObjectNode) requests.get(r), jsonToken, oAuthCode, httpRequest, out);
		} catch (Exception e) {
			handleThrowable(out, e);
		}
	}
	out.writeEndArray();
}
 
Example 13
Source File: JaxRsUtils.java    From cassandra-mesos-deprecated with Apache License 2.0 5 votes vote down vote up
public static void writeSeedIps(@NotNull final CassandraCluster cluster, @NotNull final JsonGenerator json) throws IOException {
    json.writeArrayFieldStart("seeds");
    for (final String seed : cluster.getSeedNodeIps(false)) {
        json.writeString(seed);
    }
    json.writeEndArray();
}
 
Example 14
Source File: JsonIOUtil.java    From protostuff with Apache License 2.0 5 votes vote down vote up
/**
 * Serializes the {@code messages} into the generator using the given schema.
 */
public static <T> void writeListTo(JsonGenerator generator, List<T> messages,
        Schema<T> schema, boolean numeric) throws IOException
{
    generator.writeStartArray();
    if (messages.isEmpty())
    {
        generator.writeEndArray();
        return;
    }

    final JsonOutput output = new JsonOutput(generator, numeric, schema);

    for (T m : messages)
    {
        generator.writeStartObject();

        schema.writeTo(output, m);
        if (output.isLastRepeated())
            generator.writeEndArray();

        generator.writeEndObject();
        output.reset();
    }

    generator.writeEndArray();
}
 
Example 15
Source File: StringBeanTable.java    From kripton with Apache License 2.0 5 votes vote down vote up
/**
 * for attribute value2 serialization
 */
public static byte[] serializeValue2(String[] value) {
  if (value==null) {
    return null;
  }
  KriptonJsonContext context=KriptonBinder.jsonBind();
  try (KriptonByteArrayOutputStream stream=new KriptonByteArrayOutputStream(); JacksonWrapperSerializer wrapper=context.createSerializer(stream)) {
    JsonGenerator jacksonSerializer=wrapper.jacksonGenerator;
    jacksonSerializer.writeStartObject();
    int fieldCount=0;
    if (value!=null)  {
      fieldCount++;
      int n=value.length;
      String item;
      // write wrapper tag
      jacksonSerializer.writeFieldName("element");
      jacksonSerializer.writeStartArray();
      for (int i=0; i<n; i++) {
        item=value[i];
        if (item==null) {
          jacksonSerializer.writeNull();
        } else {
          jacksonSerializer.writeString(item);
        }
      }
      jacksonSerializer.writeEndArray();
    }
    jacksonSerializer.writeEndObject();
    jacksonSerializer.flush();
    return stream.toByteArray();
  } catch(Exception e) {
    e.printStackTrace();
    throw(new KriptonRuntimeException(e.getMessage()));
  }
}
 
Example 16
Source File: DebugTabUri.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private void appendURIResourceParts(final JsonGenerator gen, final List<UriResource> uriResourceParts)
    throws IOException {
  gen.writeStartArray();
  for (UriResource resource : uriResourceParts) {
    gen.writeStartObject();
    gen.writeStringField("uriResourceKind", resource.getKind().toString());
    gen.writeStringField("segment", resource.toString());
    if (resource instanceof UriResourcePartTyped) {
      appendType(gen, "type", ((UriResourcePartTyped) resource).getType());
      gen.writeBooleanField("isCollection", ((UriResourcePartTyped) resource).isCollection());
    }
    if (resource instanceof UriResourceEntitySet) {
      appendParameters(gen, "keys", ((UriResourceEntitySet) resource).getKeyPredicates());
      appendType(gen, "typeFilterOnCollection", ((UriResourceEntitySet) resource).getTypeFilterOnCollection());
      appendType(gen, "typeFilterOnEntry", ((UriResourceEntitySet) resource).getTypeFilterOnEntry());
    } else if (resource instanceof UriResourceNavigation) {
      appendParameters(gen, "keys", ((UriResourceNavigation) resource).getKeyPredicates());
      appendType(gen, "typeFilterOnCollection", ((UriResourceNavigation) resource).getTypeFilterOnCollection());
      appendType(gen, "typeFilterOnEntry", ((UriResourceNavigation) resource).getTypeFilterOnEntry());
    } else if (resource instanceof UriResourceFunction) {
      appendParameters(gen, "parameters", ((UriResourceFunction) resource).getParameters());
      appendParameters(gen, "keys", ((UriResourceFunction) resource).getKeyPredicates());
      appendType(gen, "typeFilterOnCollection", ((UriResourceFunction) resource).getTypeFilterOnCollection());
      appendType(gen, "typeFilterOnEntry", ((UriResourceFunction) resource).getTypeFilterOnEntry());
    } else if (resource instanceof UriResourceSingleton) {
      appendType(gen, "typeFilter", ((UriResourceSingleton) resource).getEntityTypeFilter());
    } else if (resource instanceof UriResourceComplexProperty) {
      appendType(gen, "typeFilter", ((UriResourceComplexProperty) resource).getComplexTypeFilter());
    }
    gen.writeEndObject();
  }
  gen.writeEndArray();
}
 
Example 17
Source File: MessageListResponseBindMap.java    From kripton with Apache License 2.0 4 votes vote down vote up
@Override
public int serializeOnJacksonAsString(MessageListResponse object, JsonGenerator jacksonSerializer)
    throws Exception {
  jacksonSerializer.writeStartObject();
  int fieldCount=0;

  // Serialized Field:

  // field detailMessage (mapped with "detailMessage")
  if (object.getDetailMessage()!=null)  {
    fieldCount++;
    jacksonSerializer.writeStringField("detailMessage", object.getDetailMessage());
  }

  // field list (mapped with "list")
  if (object.getList()!=null)  {
    fieldCount++;
    int n=object.getList().size();
    Message item;
    // write wrapper tag
    jacksonSerializer.writeFieldName("list");
    if (n>0) {
      jacksonSerializer.writeStartArray();
      for (int i=0; i<n; i++) {
        item=object.getList().get(i);
        if (item==null) {
          jacksonSerializer.writeString("null");
        } else {
          if (messageBindMap.serializeOnJacksonAsString(item, jacksonSerializer)==0) {
            jacksonSerializer.writeNullField("list");
          }
        }
      }
      jacksonSerializer.writeEndArray();
    } else {
      jacksonSerializer.writeString("");
    }
  }

  // field status (mapped with "status")
  if (object.getStatus()!=null)  {
    fieldCount++;
    jacksonSerializer.writeStringField("status", object.getStatus().toString());
  }

  jacksonSerializer.writeEndObject();
  return fieldCount;
}
 
Example 18
Source File: TranslationBindMap.java    From kripton with Apache License 2.0 4 votes vote down vote up
@Override
public int serializeOnJacksonAsString(Translation object, JsonGenerator jacksonSerializer) throws
    Exception {
  jacksonSerializer.writeStartObject();
  int fieldCount=0;

  // Serialized Field:

  // field name (mapped with "name")
  if (object.getName()!=null)  {
    fieldCount++;
    jacksonSerializer.writeStringField("name", object.getName());
  }

  // field loop (mapped with "loop")
  jacksonSerializer.writeStringField("loop", PrimitiveUtils.writeBoolean(object.isLoop()));

  // field rate (mapped with "rate")
  jacksonSerializer.writeStringField("rate", PrimitiveUtils.writeFloat(object.getRate()));

  // field frames (mapped with "frames")
  if (object.frames!=null)  {
    fieldCount++;
    int n=object.frames.size();
    TranslationFrame item;
    // write wrapper tag
    jacksonSerializer.writeFieldName("frames");
    if (n>0) {
      jacksonSerializer.writeStartArray();
      for (int i=0; i<n; i++) {
        item=object.frames.get(i);
        if (item==null) {
          jacksonSerializer.writeString("null");
        } else {
          if (translationFrameBindMap.serializeOnJacksonAsString(item, jacksonSerializer)==0) {
            jacksonSerializer.writeNullField("frames");
          }
        }
      }
      jacksonSerializer.writeEndArray();
    } else {
      jacksonSerializer.writeString("");
    }
  }

  jacksonSerializer.writeEndObject();
  return fieldCount;
}
 
Example 19
Source File: ErrorAndToStringUnknownTypeSerializer.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
public void serializeFromError(JsonStreamContext ctxt, @Nullable Exception error, Object value, JsonGenerator jgen, SerializerProvider configurableSerializerProvider) throws IOException {
    if (log.isDebugEnabled())
        log.debug("Recovering from json serialization error, serializing "+value+": "+error);

    if (BidiSerialization.isStrictSerialization())
        throw new JsonMappingException("Cannot serialize "
            + (ctxt!=null && !ctxt.inRoot() ? "object containing " : "")
            + value.getClass().getName()+" when strict serialization requested");

    if (WARNED_CLASSES.add(value.getClass().getCanonicalName())) {
        log.warn("Standard serialization not possible for "+value.getClass()+" ("+value+")", error);
    }
    JsonStreamContext newCtxt = jgen.getOutputContext();

    // very odd, but flush seems necessary when working with large objects; presumably a buffer which is allowed to clear itself?
    // without this, when serializing the large (1.5M) Server json object from BrooklynJacksonSerializerTest creates invalid json,
    // containing:  "foo":false,"{"error":true,...
    jgen.flush();

    boolean createObject = !newCtxt.inObject() || newCtxt.getCurrentName()!=null;
    if (createObject) {
        jgen.writeStartObject();
    }

    if (allowEmpty(value.getClass())) {
        // write nothing
    } else {

        jgen.writeFieldName("error");
        jgen.writeBoolean(true);

        jgen.writeFieldName("errorType");
        jgen.writeString(NotSerializableException.class.getCanonicalName());

        jgen.writeFieldName("type");
        jgen.writeString(value.getClass().getCanonicalName());

        jgen.writeFieldName("toString");
        jgen.writeString(value.toString());

        if (error!=null) {
            jgen.writeFieldName("causedByError");
            jgen.writeString(error.toString());
        }

    }

    if (createObject) {
        jgen.writeEndObject();
    }

    while (newCtxt!=null && !newCtxt.equals(ctxt)) {
        if (jgen.getOutputContext().inArray()) { jgen.writeEndArray(); continue; }
        if (jgen.getOutputContext().inObject()) { jgen.writeEndObject(); continue; }
        break;
    }

}
 
Example 20
Source File: CommonAPI.java    From data-prep with Apache License 2.0 4 votes vote down vote up
/**
 * Describe the supported error codes.
 *
 * @param output the http response.
 */
@RequestMapping(value = "/api/errors", method = RequestMethod.GET, produces = APPLICATION_JSON_VALUE)
@ApiOperation(value = "Get all supported errors.", notes = "Returns the list of all supported errors.")
@Timed
public void listErrors(final OutputStream output) throws IOException {

    LOG.debug("Listing supported error codes");

    JsonFactory factory = new JsonFactory();
    JsonGenerator generator = factory.createGenerator(output);
    generator.setCodec(mapper);

    // start the errors array
    generator.writeStartArray();

    // write the direct known errors
    writeErrorsFromEnum(generator, CommonErrorCodes.values());
    writeErrorsFromEnum(generator, APIErrorCodes.values());

    // get dataset api errors
    HystrixCommand<InputStream> datasetErrors = getCommand(ErrorList.class, GenericCommand.DATASET_GROUP, DATASET);
    try (InputStream errorsInput = datasetErrors.execute()) {
        writeErrorsFromApi(generator, errorsInput);
    }

    // get preparation api errors
    HystrixCommand<InputStream> preparationErrors =
            getCommand(ErrorList.class, GenericCommand.PREPARATION_GROUP, PREPARATION);
    try (InputStream errorsInput = preparationErrors.execute()) {
        writeErrorsFromApi(generator, errorsInput);
    }

    // get transformation api errors
    HystrixCommand<InputStream> transformationErrors =
            getCommand(ErrorList.class, GenericCommand.TRANSFORM_GROUP, TRANSFORMATION);
    try (InputStream errorsInput = transformationErrors.execute()) {
        writeErrorsFromApi(generator, errorsInput);
    }

    // close the errors array
    generator.writeEndArray();
    generator.flush();
}