com.fasterxml.jackson.core.JsonGenerationException Java Examples

The following examples show how to use com.fasterxml.jackson.core.JsonGenerationException. 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: ConfigTest.java    From mangooio with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetSessionCookieExpires() throws JsonGenerationException, JsonMappingException, IOException {
    // given
    System.setProperty(Key.APPLICATION_MODE.toString(), Mode.TEST.toString());
    String expires = "24";

    // when
    Map<String, String> configValues = ImmutableMap.of("session.cookie.expires", expires);
    File tempConfig = createTempConfig(configValues);
    System.setProperty("application.mode", Mode.TEST.toString());
    Config config = new Config();
    
    // then
    assertThat(config.getSessionCookieTokenExpires(), equalTo(Long.valueOf(expires)));
    assertThat(tempConfig.delete(), equalTo(true));
}
 
Example #2
Source File: TocCache.java    From crazyflie-android-client with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Save a new cache to file
 */
public void insert (int crc, CrtpPort port,  Toc toc) {
    String fileName = String.format("%08X.json", crc);
    String subDir = (port == CrtpPort.PARAMETERS) ? PARAM_CACHE_DIR : LOG_CACHE_DIR;
    File cacheDir = (mCacheDir != null) ? new File(mCacheDir, subDir) : new File(subDir);
    File cacheFile = new File(cacheDir, fileName);
    try {
        if (!cacheFile.exists()) {
            cacheFile.getParentFile().mkdirs();
            cacheFile.createNewFile();
        }
        this.mMapper.enable(SerializationFeature.INDENT_OUTPUT);
        this.mMapper.writeValue(cacheFile, toc.getTocElementMap());
        //TODO: add "__class__" : "LogTocElement",
        this.mLogger.info("Saved cache to " + fileName);
        this.mCacheFiles.add(cacheFile);
        //TODO: file leak?
    } catch (JsonGenerationException jge) {
        mLogger.error("Could not save cache to file " + fileName + ".\n" + jge.getMessage());
    } catch (JsonMappingException jme) {
        mLogger.error("Could not save cache to file " + fileName + ".\n" + jme.getMessage());
    } catch (IOException ioe) {
        mLogger.error("Could not save cache to file " + fileName + ".\n" + ioe.getMessage());
    }
}
 
Example #3
Source File: JoynrListSerializer.java    From joynr with Apache License 2.0 6 votes vote down vote up
@Override
public void serialize(List<?> value, JsonGenerator jgen, SerializerProvider provider) throws IOException,
                                                                                      JsonGenerationException {

    jgen.writeStartArray();
    for (Object elem : value) {
        if (elem == null) {
            provider.defaultSerializeNull(jgen);
        } else {
            Class<?> clazz = elem.getClass();
            JsonSerializer<Object> serializer = serializers.get(clazz);
            if (serializer == null) {
                serializer = provider.findTypedValueSerializer(clazz, false, null);
            }
            serializer.serialize(elem, jgen, provider);
        }
    }
    jgen.writeEndArray();

}
 
Example #4
Source File: JsonJacksonTests.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void testSerializeComment() throws IOException
{
    final Comment aComment = new Comment();
    aComment.setContent("<b>There it is</b>");
    ByteArrayOutputStream out = new ByteArrayOutputStream();

    jsonHelper.withWriter(out, new Writer()
    {
        @Override
        public void writeContents(JsonGenerator generator, ObjectMapper objectMapper)
                    throws JsonGenerationException, JsonMappingException, IOException
        {
            FilterProvider fp = new SimpleFilterProvider().addFilter(
                        JacksonHelper.DEFAULT_FILTER_NAME, new ReturnAllBeanProperties());
            objectMapper.writer(fp).writeValue(generator, aComment);
        }
    });
    assertTrue(out.toString().contains("{\"content\":\"<b>There it is</b>\""));
}
 
Example #5
Source File: SubscriptionManagerTest.java    From joynr with Apache License 2.0 6 votes vote down vote up
@Test
public void unregisterSubscription() throws JoynrSendBufferFullException, JoynrMessageNotSentException,
                                     JsonGenerationException, JsonMappingException, IOException {

    when(subscriptionStates.get(subscriptionId)).thenReturn(subscriptionState);
    when(missedPublicationTimers.containsKey(subscriptionId)).thenReturn(true);
    when(missedPublicationTimers.get(subscriptionId)).thenReturn(missedPublicationTimer);
    subscriptionManager.unregisterSubscription(fromParticipantId,
                                               new HashSet<DiscoveryEntryWithMetaInfo>(Arrays.asList(toDiscoveryEntry)),
                                               subscriptionId,
                                               qosSettings);

    verify(subscriptionStates).get(Mockito.eq(subscriptionId));
    verify(subscriptionState).stop();

    verify(dispatcher,
           times(1)).sendSubscriptionStop(Mockito.eq(fromParticipantId),
                                          eq(new HashSet<DiscoveryEntryWithMetaInfo>(Arrays.asList(toDiscoveryEntry))),
                                          Mockito.eq(new SubscriptionStop(subscriptionId)),
                                          Mockito.any(MessagingQos.class));

}
 
Example #6
Source File: AllOnes.java    From mrgeo with Apache License 2.0 6 votes vote down vote up
public static void main(String args[]) throws JsonGenerationException, JsonMappingException, IOException
{
  AllOnes allOnes = new AllOnes();
  int zoom = allOnes.getMetadata().getMaxZoomLevel();

  LongRectangle tb = allOnes.getMetadata().getTileBounds(zoom);
  long minX = tb.getMinX();
  long minY = tb.getMinY();

  for (int ty = 0; ty < allOnes.getRows(); ty++)
  {
    for (int tx = 0; tx < allOnes.getCols(); tx++)
    {
      System.out.println(String.format("Tile %d has bounds %s",
          TMSUtils.tileid(tx + minX, ty + minY, zoom),
          allOnes.getBounds(ty, tx)));
    }
  }
}
 
Example #7
Source File: WebScriptOptionsMetaData.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void writeMetaData(OutputStream out, ResourceWithMetadata resource, Map<String, ResourceWithMetadata> allApiResources) throws IOException
{
    
    final Object result = processResult(resource,allApiResources);

    assistant.getJsonHelper().withWriter(out, new Writer()
    {
        @Override
        public void writeContents(JsonGenerator generator, ObjectMapper objectMapper)
                    throws JsonGenerationException, JsonMappingException, IOException
        {           
           objectMapper.writeValue(generator, result);
        }
    });
}
 
Example #8
Source File: ConfigTest.java    From mangooio with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetConnectorAjpPort() throws JsonGenerationException, JsonMappingException, IOException {
    // given
    String port = "2542";
    System.setProperty(Key.APPLICATION_MODE.toString(), Mode.TEST.toString());

    // when
    Map<String, String> configValues = ImmutableMap.of("connector.ajp.port", port);
    File tempConfig = createTempConfig(configValues);
    System.setProperty("application.mode", Mode.TEST.toString());
    Config config = new Config();
    
    // then
    assertThat(config.getConnectorAjpPort(), equalTo(Integer.valueOf(port)));
    assertThat(tempConfig.delete(), equalTo(true));
}
 
Example #9
Source File: KpiService.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
@GET
@Path("/findKpiValuesTest")
public Response findKpiValuesTest() throws EMFUserError, JsonGenerationException, JsonMappingException, IOException {
	logger.debug("findKpiValuesTest IN");
	Response out;
	IKpiDAO kpiDao = DAOFactory.getKpiDAO();
	Map<String, String> attributesValues = new HashMap<>();
	attributesValues.put("STORE_CITY", "Los Angeles");
	attributesValues.put("STORE_TYPE", "Supermarket");
	attributesValues.put("OPENED_MONTH", "5");
	// attributesValues.put("SA2", "5");
	List<KpiValue> kpiValues = kpiDao.findKpiValues(11, 0, null, null, attributesValues);
	String result = new ObjectMapper().writeValueAsString(kpiValues);
	out = Response.ok(result).build();
	logger.debug("findKpiValuesTest OUT");
	return out;
}
 
Example #10
Source File: ConfigTest.java    From mangooio with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetAuthenticationCookieExpiresDefaultValue() throws JsonGenerationException, JsonMappingException, IOException {
    // given
    System.setProperty(Key.APPLICATION_MODE.toString(), Mode.TEST.toString());
    
    // when
    Map<String, String> configValues = new HashMap<>();
    File tempConfig = createTempConfig(configValues);
    Config config = new Config();

    // then
    assertThat(config.isAuthenticationCookieExpires(), equalTo(Default.AUTHENTICATION_COOKIE_EXPIRES.toBoolean()));
    assertThat(tempConfig.delete(), equalTo(true));
}
 
Example #11
Source File: ResponseWriter.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Renders the result of an execution.
 *
 * @param res         WebScriptResponse
 * @param toSerialize result of an execution
 * @throws IOException
 */
default void renderJsonResponse(final WebScriptResponse res, final Object toSerialize, final JacksonHelper jsonHelper) throws IOException
{
    jsonHelper.withWriter(res.getOutputStream(), new JacksonHelper.Writer()
    {
        @Override
        public void writeContents(JsonGenerator generator, ObjectMapper objectMapper)
                    throws JsonGenerationException, JsonMappingException, IOException
        {
            objectMapper.writeValue(generator, toSerialize);
        }
    });
}
 
Example #12
Source File: LogicalExpression.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(LogicalExpression value, JsonGenerator jgen, SerializerProvider provider) throws IOException,
    JsonGenerationException {
  StringBuilder sb = new StringBuilder();
  ExpressionStringBuilder esb = new ExpressionStringBuilder();
  value.accept(esb, sb);
  jgen.writeString(sb.toString());
}
 
Example #13
Source File: PercentDoubleSerialiser.java    From amazon-kinesis-scaling-utils with Apache License 2.0 5 votes vote down vote up
public void serialize(Double value, JsonGenerator jgen, SerializerProvider provider)
		throws IOException, JsonGenerationException {
	if (null == value) {
		// write the word 'null' if there's no value available
		jgen.writeNull();
	} else {
		final String output = myFormatter.format(value);
		jgen.writeNumber(output);
	}
}
 
Example #14
Source File: ConfigTest.java    From mangooio with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetAuthenticationCookieName() throws JsonGenerationException, JsonMappingException, IOException {
    // given
    String authenticationCookieName = UUID.randomUUID().toString();
    System.setProperty(Key.APPLICATION_MODE.toString(), Mode.TEST.toString());

    // when
    Map<String, String> configValues = ImmutableMap.of("authentication.cookie.name", authenticationCookieName);
    File tempConfig = createTempConfig(configValues);
    Config config = new Config();
    
    // then
    assertThat(config.getAuthenticationCookieName(), equalTo(authenticationCookieName));
    assertThat(tempConfig.delete(), equalTo(true));
}
 
Example #15
Source File: DistributedCacheTest.java    From foxtrot with Apache License 2.0 5 votes vote down vote up
@Test
public void testPutCacheException() throws Exception {
    doThrow(new JsonGenerationException("TEST_EXCEPTION")).when(mapper)
            .writeValueAsString(any());
    ActionResponse returnResponse = distributedCache.put("DUMMY_KEY_PUT", null);
    verify(mapper, times(1)).writeValueAsString(any());
    assertNull(returnResponse);
    assertNull(hazelcastInstance.getMap("TEST")
                       .get("DUMMY_KEY_PUT"));
}
 
Example #16
Source File: ConfigTest.java    From mangooio with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetConnectorHttpHostDefaultValue() throws JsonGenerationException, JsonMappingException, IOException {
    // given
    System.setProperty(Key.APPLICATION_MODE.toString(), Mode.TEST.toString());
    
    // when
    Map<String, String> configValues = new HashMap<>();
    File tempConfig = createTempConfig(configValues);
    Config config = new Config();

    // then
    assertThat(config.getConnectorHttpHost(), equalTo(null));
    assertThat(tempConfig.delete(), equalTo(true));
}
 
Example #17
Source File: ConfigTest.java    From mangooio with Apache License 2.0 5 votes vote down vote up
@Test
public void testAplicationLanguage() throws JsonGenerationException, JsonMappingException, IOException {
    // given
    System.setProperty(Key.APPLICATION_MODE.toString(), Mode.TEST.toString());
    String language = "fr";

    // when
    Map<String, String> configValues = ImmutableMap.of("application.language", language);
    File tempConfig = createTempConfig(configValues);
    Config config = new Config();
    
    // then
    assertThat(config.getApplicationLanguage(), equalTo(language));
    assertThat(tempConfig.delete(), equalTo(true));
}
 
Example #18
Source File: SerializeTests.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
private String writeResponse(final Object respons) throws IOException
{
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    jsonHelper.withWriter(out, new Writer()
    {
        @Override
        public void writeContents(JsonGenerator generator, ObjectMapper objectMapper)
                    throws JsonGenerationException, JsonMappingException, IOException
        {
            objectMapper.writeValue(generator, respons);
        }
    });
    System.out.println(out.toString());
    return out.toString();
}
 
Example #19
Source File: ConfigTest.java    From mangooio with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetAuthenticationCookieExpires() throws JsonGenerationException, JsonMappingException, IOException {
    // given
    System.setProperty(Key.APPLICATION_MODE.toString(), Mode.TEST.toString());
    String expires = "42";

    // when
    Map<String, String> configValues = ImmutableMap.of("authentication.cookie.expires", expires);
    File tempConfig = createTempConfig(configValues);
    Config config = new Config();
    
    // then
    assertThat(config.isAuthenticationCookieExpires(), equalTo(Boolean.valueOf(expires)));
    assertThat(tempConfig.delete(), equalTo(true));
}
 
Example #20
Source File: StoneSerializer.java    From dropbox-sdk-java with MIT License 5 votes vote down vote up
public void serialize(T value, OutputStream out, boolean pretty) throws IOException {
    JsonGenerator g = Util.JSON.createGenerator(out);
    if (pretty) {
        g.useDefaultPrettyPrinter();
    }
    try {
        serialize(value, g);
    } catch (JsonGenerationException ex) {
        throw new IllegalStateException("Impossible JSON generation exception", ex);
    }
    g.flush();
}
 
Example #21
Source File: ConfigTest.java    From mangooio with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetFlashCookieEncryptionKeyDefaultValue() throws JsonGenerationException, JsonMappingException, IOException {
    // given
    String secret = UUID.randomUUID().toString();
    System.setProperty(Key.APPLICATION_MODE.toString(), Mode.TEST.toString());
    
    // when
    Map<String, String> configValues = ImmutableMap.of("application.secret", secret);
    File tempConfig = createTempConfig(configValues);
    Config config = new Config();

    // then
    assertThat(config.getFlashCookieSecret(), equalTo(secret));
    assertThat(tempConfig.delete(), equalTo(true));
}
 
Example #22
Source File: ElasticsearchRecordReader.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
private void print(NonNullableStructVector structVector, int count) throws JsonGenerationException, IOException{
  if(PRINT_OUTPUT){
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    JsonWriter jsonWriter = new JsonWriter(baos, true, false);
    FieldReader reader = new SingleStructReaderImpl(structVector);
    for(int index = 0; index < count; index++){
      reader.setPosition(index);
      jsonWriter.write(reader);
    }

    System.out.println(baos.toString());
  }
}
 
Example #23
Source File: DateTimeSerializer.java    From govpay with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void serialize(DateTime dateTime,
                      JsonGenerator jsonGenerator,
                      SerializerProvider provider) throws IOException, JsonGenerationException {
    String dateTimeAsString = DateFormatUtils.newSimpleDateFormatNoMillis().format(dateTime.toDate());
    jsonGenerator.writeString(dateTimeAsString);
}
 
Example #24
Source File: PdxInstanceWrapperUnitTests.java    From spring-boot-data-geode with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void getObjectCallsPdxInstanceGetObjectWhenExceptionIsThrown() throws JsonProcessingException {

	Object value = new Object();

	ObjectMapper mockObjectMapper = mock(ObjectMapper.class);

	PdxInstance mockPdxInstance = mock(PdxInstance.class);

	String json = String.format("{ \"@type\": \"%s\", \"name\": \"Checking\"}", Account.class.getName());

	doReturn(JSONFormatter.JSON_CLASSNAME).when(mockPdxInstance).getClassName();
	doReturn(true).when(mockPdxInstance).hasField(eq(PdxInstanceWrapper.AT_TYPE_FIELD_NAME));
	doReturn(Account.class.getName()).when(mockPdxInstance).getField(eq(PdxInstanceWrapper.AT_TYPE_FIELD_NAME));
	doReturn(value).when(mockPdxInstance).getObject();

	PdxInstanceWrapper wrapper = spy(PdxInstanceWrapper.from(mockPdxInstance));

	assertThat(wrapper).isNotNull();
	assertThat(wrapper.getDelegate()).isEqualTo(mockPdxInstance);

	doReturn(Optional.of(mockObjectMapper)).when(wrapper).getObjectMapper();
	doReturn(json).when(wrapper).jsonFormatterToJson(eq(mockPdxInstance));
	doThrow(new JsonGenerationException("TEST", mock(JsonGenerator.class)))
		.when(mockObjectMapper).readValue(anyString(), any(Class.class));

	assertThat(wrapper.getObject()).isEqualTo(value);

	verify(wrapper, times(1)).getObjectMapper();
	verify(mockPdxInstance, times(1)).getClassName();
	verify(mockPdxInstance, times(1)).hasField(eq(PdxInstanceWrapper.AT_TYPE_FIELD_NAME));
	verify(mockPdxInstance, times(1)).getField(eq(PdxInstanceWrapper.AT_TYPE_FIELD_NAME));
	verify(wrapper, atLeastOnce()).getDelegate();
	verify(wrapper, times(1)).jsonFormatterToJson(eq(mockPdxInstance));
	verify(mockObjectMapper, times(1)).readValue(eq(json), eq(Account.class));
	verify(mockPdxInstance, times((1))).getObject();
	verifyNoMoreInteractions(mockObjectMapper, mockPdxInstance);
}
 
Example #25
Source File: BeakerDashboard.java    From beakerx with Apache License 2.0 5 votes vote down vote up
public void serialize(JsonGenerator jgen, BeakerObjectConverter boc) throws JsonGenerationException, IOException {
  jgen.writeStartObject();
  if (theStyle!=null) jgen.writeStringField("thestyle", theStyle);
  if (theClass!=null) jgen.writeStringField("theclass", theClass);
  jgen.writeArrayFieldStart("cols");
  for (dashColumn r : payload)
    r.serialize(jgen, boc);
  jgen.writeEndArray();
  jgen.writeEndObject();
}
 
Example #26
Source File: ColorScaleManagerTest.java    From mrgeo with Apache License 2.0 5 votes vote down vote up
private String getTestColorScale() throws JsonGenerationException, JsonMappingException,
    IOException
{
  // create colorScale json
  final ObjectMapper mapper = new ObjectMapper();

  final Map<String, Object> colorScale = new HashMap<String, Object>();
  colorScale.put("Scaling", "Absolute");
  colorScale.put("Interpolate", "1");
  colorScale.put("ForceValuesIntoRange", "1");

  final Map<String, String> nullColor = new HashMap<String, String>();
  nullColor.put("color", "0,0,0");
  nullColor.put("opacity", "0");
  colorScale.put("NullColor", nullColor);
  final Map<String, String> color1 = new HashMap<String, String>();
  color1.put("value", "0.0");
  color1.put("color", "0,0,127");
  color1.put("opacity", "170");
  final Map<String, String> color2 = new HashMap<String, String>();
  color2.put("value", "0.5");
  color2.put("color", "0,0,255");
  color2.put("opacity", "170");
  final Map<String, String> color3 = new HashMap<String, String>();
  color3.put("value", "1.0");
  color3.put("color", "255,0,0");
  color3.put("opacity", "170");

  final ArrayList<Map<String, String>> colors = new ArrayList<Map<String, String>>();
  colors.add(color1);
  colors.add(color2);
  colors.add(color3);

  colorScale.put("Colors", colors);

  return mapper.writeValueAsString(colorScale);
}
 
Example #27
Source File: ConfigTest.java    From mangooio with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetCorsHeadersAllowCredentialsDefaultValue() throws JsonGenerationException, JsonMappingException, IOException {
    // given
    System.setProperty(Key.APPLICATION_MODE.toString(), Mode.TEST.toString());
    
    // when
    Map<String, String> configValues = new HashMap<>();
    File tempConfig = createTempConfig(configValues);
    Config config = new Config();

    // then
    assertThat(config.getCorsHeadersAllowCredentials(), equalTo(Default.CORS_HEADERS_ALLOWCREDENTIALS.toString()));
    assertThat(tempConfig.delete(), equalTo(true));
}
 
Example #28
Source File: ConfigTest.java    From mangooio with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetSessionCookieName() throws JsonGenerationException, JsonMappingException, IOException {
    // given
    String sessionCookieName = UUID.randomUUID().toString();
    System.setProperty(Key.APPLICATION_MODE.toString(), Mode.TEST.toString());

    // when
    Map<String, String> configValues = ImmutableMap.of("session.cookie.name", sessionCookieName);
    File tempConfig = createTempConfig(configValues);
    Config config = new Config();
    
    // then
    assertThat(config.getSessionCookieName(), equalTo(sessionCookieName));
    assertThat(tempConfig.delete(), equalTo(true));
}
 
Example #29
Source File: ConfigTest.java    From mangooio with Apache License 2.0 5 votes vote down vote up
@Test
public void testIsCacheClusterEnable() throws JsonGenerationException, JsonMappingException, IOException {
    // given
    System.setProperty(Key.APPLICATION_MODE.toString(), Mode.TEST.toString());
    String enable = "true";

    // when
    Map<String, String> configValues = ImmutableMap.of("cache.cluster.enable", enable);
    File tempConfig = createTempConfig(configValues);
    Config config = new Config();
    
    // then
    assertThat(config.isCacheCluserEnable(), equalTo(Boolean.valueOf(enable)));
    assertThat(tempConfig.delete(), equalTo(true));
}
 
Example #30
Source File: JsonSerializerTest.java    From Wikidata-Toolkit with Apache License 2.0 5 votes vote down vote up
@Test
public void testJacksonObjectToJsonError() {
	Object obj = new Object() {
		@SuppressWarnings("unused")
		public String getData() throws JsonGenerationException {
			throw new JsonGenerationException("Test exception");
		}
	};

	String result = JsonSerializer.jacksonObjectToString(obj);
	assertNull(result);
}