下面列出了怎么用com.fasterxml.jackson.core.JsonGenerationException的API类实例代码及写法,或者点击链接到github查看源代码。
@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));
}
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)));
}
}
}
@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));
}
@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;
}
@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));
}
@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);
}
});
}
@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>\""));
}
/**
* 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());
}
}
@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();
}
@Test
public void testIsSchedulerEnabled() throws JsonGenerationException, JsonMappingException, IOException {
// given
System.setProperty(Key.APPLICATION_MODE.toString(), Mode.TEST.toString());
String enabled = "false";
// when
Map<String, String> configValues = ImmutableMap.of("scheduler.enable", enabled);
File tempConfig = createTempConfig(configValues);
Config config = new Config();
// then
assertThat(config.isSchedulerEnabled(), equalTo(Boolean.valueOf(enabled)));
assertThat(tempConfig.delete(), equalTo(true));
}
@Test
public void testGetUndertowMaxEntitySize() throws JsonGenerationException, JsonMappingException, IOException {
// given
String size = "4096";
System.setProperty(Key.APPLICATION_MODE.toString(), Mode.TEST.toString());
// when
Map<String, String> configValues = ImmutableMap.of("undertow.maxentitysize", size);
File tempConfig = createTempConfig(configValues);
Config config = new Config();
// then
assertThat(config.getUndertowMaxEntitySize(), equalTo(Long.valueOf(size)));
assertThat(tempConfig.delete(), equalTo(true));
}
@Test
public void testGetAuthenticationCookieNameDefaultValue() 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.getAuthenticationCookieName(), equalTo(Default.AUTHENTICATION_COOKIE_NAME.toString()));
assertThat(tempConfig.delete(), equalTo(true));
}
@Test
public void testIsApplicationMinifyCSSDefaultValue() 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.isApplicationMinifyCSS(), equalTo(Default.APPLICATION_MINIFY_CSS.toBoolean()));
assertThat(tempConfig.delete(), equalTo(true));
}
@Test
public void testGetApplicationThreadpoolDefaultValue() 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.getApplicationThreadpool(), equalTo(Default.APPLICATION_THREADPOOL.toInt()));
assertThat(tempConfig.delete(), equalTo(true));
}
@Test
public void testGetSmptHost() throws JsonGenerationException, JsonMappingException, IOException {
// given
System.setProperty(Key.APPLICATION_MODE.toString(), Mode.TEST.toString());
String host = "192.168.2.24";
// when
Map<String, String> configValues = ImmutableMap.of("smtp.host", host);
File tempConfig = createTempConfig(configValues);
Config config = new Config();
// then
assertThat(config.getSmtpHost(), equalTo(host));
assertThat(tempConfig.delete(), equalTo(true));
}
@Test
public void testIsApplicationMinifyJS() throws JsonGenerationException, JsonMappingException, IOException {
// given
System.setProperty(Key.APPLICATION_MODE.toString(), Mode.TEST.toString());
String minify = "true";
// when
Map<String, String> configValues = ImmutableMap.of("application.minify.js", minify);
File tempConfig = createTempConfig(configValues);
Config config = new Config();
// then
assertThat(config.isApplicationMinifyJS(), equalTo(Boolean.valueOf(minify)));
assertThat(tempConfig.delete(), equalTo(true));
}
@Test(expected = IllegalArgumentException.class)
public void serializeException() throws JsonProcessingException {
// given
ObjectMapper objectMapper = mock(ObjectMapper.class);
when(objectMapper.writeValueAsString(any())).thenThrow(new JsonGenerationException("", (JsonGenerator) null));
JacksonPrinter jacksonPrinter = new JacksonPrinter(objectMapper);
String string = "string";
// when
jacksonPrinter.serialize(string);
// then expected exception
}
@Test
public void testBase() throws JsonGenerationException, JsonMappingException, IOException {
List<Base> objs = new ArrayList<Base>();
ClassA a = new ClassA();
a.setA(1);
ClassB b = new ClassB();
b.setB("2");
objs.add(a);
objs.add(b);
ObjectMapper om = new ObjectMapper();
om.enableDefaultTyping();
// om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
String value = om.writeValueAsString(objs);
System.out.println("value = " + value);
@SuppressWarnings("rawtypes")
List result = om.readValue(value, ArrayList.class);
System.out.println("size = " + result.size());
Object obj1 = result.get(0);
Object obj2 = result.get(1);
Assert.assertEquals("ClassA", obj1.getClass().getSimpleName());
Assert.assertEquals(1, ((ClassA)obj1).getA());
Assert.assertEquals("ClassB", obj2.getClass().getSimpleName());
Assert.assertEquals("2", ((ClassB)obj2).getB());
}
public synchronized void saveInIndex(Path metadataPath, T content) throws IOException {
Path indexPath = jsonFile(metadataPath, INDEX_METADATA);
Map<String, String> index = loadIndex(indexPath);
try {
if (getUUIDIfExist(content) != null) {
index.put(getUUIDIfExist(content), content.getId());
}
writeIndexFile(indexPath, index);
} catch (JsonGenerationException e) {
logger.error(format("Cannot generate index for file %s. Maybe a migration is required.", content.getId()));
}
}
@Test
public void testGetAuthenticationCookieSecret() throws JsonGenerationException, JsonMappingException, IOException {
// given
String key = UUID.randomUUID().toString();
// when
Map<String, String> configValues = ImmutableMap.of("authentication.cookie.secret", key);
File tempConfig = createTempConfig(configValues);
Config config = new Config();
// then
assertThat(config.getAuthenticationCookieSecret(), equalTo(key));
assertThat(tempConfig.delete(), equalTo(true));
}
/**
* Write a GATE document to the specified JsonGenerator. The document
* text will be written as a property named "text" and the specified
* annotations will be written as "entities".
*
* @param doc the document to write
* @param annotationsMap annotations to write.
* @param json the {@link JsonGenerator} to write to.
* @throws JsonGenerationException if a problem occurs while
* generating the JSON
* @throws IOException if an I/O error occurs.
*/
public static void writeDocument(Document doc,
Map<String, Collection<Annotation>> annotationsMap, JsonGenerator json)
throws JsonGenerationException, IOException {
try {
writeDocument(doc, 0L, doc.getContent().size(), annotationsMap, json);
} catch(InvalidOffsetException e) {
// shouldn't happen
throw new GateRuntimeException(
"Got invalid offset exception when passing "
+ "offsets that are known to be valid");
}
}
@Test
public void testGetConnectorAjpHostDefaultValue() 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.getConnectorAjpHost(), equalTo(null));
assertThat(tempConfig.delete(), equalTo(true));
}
@Test
public void testGetSessionCookieSecret() throws JsonGenerationException, JsonMappingException, IOException {
// given
String key = UUID.randomUUID().toString();
System.setProperty(Key.APPLICATION_MODE.toString(), Mode.TEST.toString());
// when
Map<String, String> configValues = ImmutableMap.of("session.cookie.secret", key);
File tempConfig = createTempConfig(configValues);
Config config = new Config();
// then
assertThat(config.getSessionCookieSecret(), equalTo(key));
assertThat(tempConfig.delete(), equalTo(true));
}
@Override
public void writeEndArray() throws IOException, JsonGenerationException {
if (!_writeContext.inArray()) {
_reportError("Current context not an array but " + _writeContext.getTypeDesc());
}
getStackTopForArray();
_writeContext = _writeContext.getParent();
popStackAndStoreTheItemAsValue();
}
@Test
public void testGetApplicationSecret() throws JsonGenerationException, JsonMappingException, IOException {
// given
String applicationSecret = UUID.randomUUID().toString();
System.setProperty(Key.APPLICATION_MODE.toString(), Mode.TEST.toString());
// when
Map<String, String> configValues = ImmutableMap.of("application.secret", applicationSecret);
File tempConfig = createTempConfig(configValues);
Config config = new Config();
// then
assertThat(config.getApplicationSecret(), equalTo(applicationSecret));
assertThat(tempConfig.delete(), equalTo(true));
}
public static void generateVertexLine(StringWriter sw, ObjectMapper mapper, VertexBean vBean) throws JsonGenerationException, JsonMappingException, IOException {
sw.getBuffer().setLength(0);
sw.append('V'); // Record type
sw.append('=');
mapper.writeValue(sw, vBean);
sw.append('#');
int hashCode = hashCode(sw.toString());
sw.append(toHex(hashCode));
sw.append('\n');
}
@Test
public void testIsAuthentication() throws JsonGenerationException, JsonMappingException, IOException {
// given
System.setProperty(Key.APPLICATION_MODE.toString(), Mode.TEST.toString());
String ssl = "true";
// when
Map<String, String> configValues = ImmutableMap.of("smtp.authentication", ssl);
File tempConfig = createTempConfig(configValues);
Config config = new Config();
// then
assertThat(config.isSmtpAuthentication(), equalTo(Boolean.valueOf(ssl)));
assertThat(tempConfig.delete(), equalTo(true));
}
public void writeIndentation(JsonGenerator jg, int level) throws IOException, JsonGenerationException {
jg.writeRaw(SYSTEM_LINE_SEPARATOR);
if (level > 0) {
level += level; // 2 spaces per level
while (level > SPACE_COUNT) { // should never happen but...
jg.writeRaw(SPACES, 0, SPACE_COUNT);
level -= SPACES.length;
}
jg.writeRaw(SPACES, 0, level);
}
}
@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));
}
@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));
}