List of usage examples for com.fasterxml.jackson.core JsonGenerator writeObjectField
public final void writeObjectField(String fieldName, Object pojo) throws IOException, JsonProcessingException
From source file:com.neoteric.starter.metrics.report.elastic.ElasticsearchReporter.java
private void checkForIndexTemplate() { try {//from ww w. ja v a 2 s.c o m HttpURLConnection connection = openConnection("/_template/metrics_template", "HEAD"); connection.disconnect(); boolean isTemplateMissing = connection.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND; // nothing there, lets create it if (isTemplateMissing) { LOGGER.debug("No metrics template found in elasticsearch. Adding..."); HttpURLConnection putTemplateConnection = openConnection("/_template/metrics_template", "PUT"); JsonGenerator json = new JsonFactory().createGenerator(putTemplateConnection.getOutputStream()); json.writeStartObject(); json.writeStringField("template", index + "*"); json.writeObjectFieldStart("mappings"); json.writeObjectFieldStart("_default_"); json.writeObjectFieldStart("_all"); json.writeBooleanField("enabled", false); json.writeEndObject(); json.writeObjectFieldStart("properties"); json.writeObjectFieldStart("name"); json.writeObjectField("type", "string"); json.writeObjectField("index", "not_analyzed"); json.writeEndObject(); json.writeEndObject(); json.writeEndObject(); json.writeEndObject(); json.writeEndObject(); json.flush(); putTemplateConnection.disconnect(); if (putTemplateConnection.getResponseCode() != HttpStatus.OK.value()) { LOGGER.error( "Error adding metrics template to elasticsearch: {}/{}" + putTemplateConnection.getResponseCode(), putTemplateConnection.getResponseMessage()); } } checkedForIndexTemplate = true; } catch (IOException e) { LOGGER.error("Error when checking/adding metrics template to elasticsearch", e); } }
From source file:org.createnet.raptor.models.objects.serializer.RecordSetSerializer.java
@Override public void serialize(RecordSet r, JsonGenerator jg, SerializerProvider sp) throws IOException { final Stream stream = r.getStream(); ServiceObject obj = null;/* w w w.jav a 2s. c o m*/ if (stream != null) { obj = stream.getServiceObject(); } jg.writeStartObject(); jg.writeObjectFieldStart("channels"); for (Map.Entry<String, IRecord> item : r.channels.entrySet()) { String channelName = item.getKey(); IRecord channel = item.getValue(); // enforce stream schema if available if (r.getStream() != null) { if (!r.getStream().channels.containsKey(channelName)) { // skip unmanaged field return; } } if (channel == null) { continue; } if (channel.getValue() == null) { continue; } jg.writeObjectField(channelName, channel.getValue()); // jg.writeObjectFieldStart(channelName); // jg.writeObjectField("current-value", channel.getValue()); // jg.writeEndObject(); } jg.writeEndObject(); jg.writeNumberField("timestamp", r.getTimestampTime()); // try to get a value if (r.userId == null && obj != null) { r.userId = obj.userId; } if (r.userId != null) { jg.writeStringField("userId", r.userId); } // try to get a value if (r.objectId == null && obj != null) { r.objectId = obj.id; } if (r.objectId != null) { jg.writeStringField("objectId", r.objectId); } // try to get a value if (r.streamId == null && stream != null) { r.streamId = stream.name; } if (r.streamId != null) { jg.writeStringField("streamId", r.streamId); } jg.writeEndObject(); }
From source file:com.strategicgains.hyperexpress.serialization.jackson.HalResourceSerializer.java
private void writeLinks(HalResource resource, boolean isEmbedded, JsonGenerator jgen) throws JsonGenerationException, IOException { List<Link> links = resource.getLinks(); List<Namespace> namespaces = resource.getNamespaces(); if (links.isEmpty() && (isEmbedded || namespaces.isEmpty())) return;/*from w w w.j ava 2 s .com*/ jgen.writeObjectFieldStart(LINKS); writeCuries(namespaces, isEmbedded, jgen); Map<String, List<HalLink>> linksByRel = indexLinksByRel(resource.getLinks()); for (Entry<String, List<HalLink>> entry : linksByRel.entrySet()) { if (entry.getValue().size() == 1 && !resource.isMultipleLinks(entry.getKey())) // Write single link { HalLink link = entry.getValue().iterator().next(); if (null == link.getTemplated()) { link.setTemplated(link.hasTemplate() ? true : null); } jgen.writeObjectField(entry.getKey(), link); } else // Write link array { jgen.writeArrayFieldStart(entry.getKey()); for (HalLink link : entry.getValue()) { if (null == link.getTemplated()) { link.setTemplated(link.hasTemplate() ? true : null); } jgen.writeObject(link); } jgen.writeEndArray(); } } jgen.writeEndObject(); }
From source file:com.basho.riak.client.query.MapReduce.java
/** * @param jg// w w w . j a va 2s . com */ private void writeMapReducePhases(JsonGenerator jg) throws IOException { int cnt = 0; synchronized (phases) { final int lastPhase = phases.size(); for (MapReducePhase phase : phases) { cnt++; jg.writeStartObject(); jg.writeFieldName(phase.getType().toString()); jg.writeStartObject(); switch (phase.getType()) { case MAP: case REDUCE: MapPhase mapPhase = (MapPhase) phase; FunctionToJson.newWriter(mapPhase.getPhaseFunction(), jg).write(); if (mapPhase.getArg() != null) { jg.writeObjectField("arg", mapPhase.getArg()); } break; case LINK: jg.writeStringField("bucket", ((LinkPhase) phase).getBucket()); jg.writeStringField("tag", ((LinkPhase) phase).getTag()); break; } //the final phase results should be returned, unless specifically set otherwise if (cnt == lastPhase) { jg.writeBooleanField("keep", isKeepResult(true, phase.isKeep())); } else { jg.writeBooleanField("keep", isKeepResult(false, phase.isKeep())); } jg.writeEndObject(); jg.writeEndObject(); } } }
From source file:org.elasticsearch.metrics.ElasticsearchReporter.java
/** * This index template is automatically applied to all indices which start with the index name * The index template simply configures the name not to be analyzed */// w w w . jav a2 s . co m private void checkForIndexTemplate() { try { HttpURLConnection connection = openConnection("/_template/metrics_template", "HEAD"); if (connection == null) { LOGGER.error("Could not connect to any configured elasticsearch instances: {}", Arrays.asList(hosts)); return; } connection.disconnect(); boolean isTemplateMissing = connection.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND; // nothing there, lets create it if (isTemplateMissing) { LOGGER.debug("No metrics template found in elasticsearch. Adding..."); HttpURLConnection putTemplateConnection = openConnection("/_template/metrics_template", "PUT"); if (putTemplateConnection == null) { LOGGER.error("Error adding metrics template to elasticsearch"); return; } JsonGenerator json = new JsonFactory().createGenerator(putTemplateConnection.getOutputStream()); json.writeStartObject(); json.writeStringField("template", index + "*"); json.writeObjectFieldStart("mappings"); json.writeObjectFieldStart("_default_"); json.writeObjectFieldStart("_all"); json.writeBooleanField("enabled", false); json.writeEndObject(); json.writeObjectFieldStart("properties"); json.writeObjectFieldStart("name"); json.writeObjectField("type", "string"); json.writeObjectField("index", "not_analyzed"); json.writeEndObject(); json.writeEndObject(); json.writeEndObject(); json.writeEndObject(); json.writeEndObject(); json.flush(); putTemplateConnection.disconnect(); if (putTemplateConnection.getResponseCode() != 200) { LOGGER.error( "Error adding metrics template to elasticsearch: {}/{}" + putTemplateConnection.getResponseCode(), putTemplateConnection.getResponseMessage()); } } checkedForIndexTemplate = true; } catch (IOException e) { LOGGER.error("Error when checking/adding metrics template to elasticsearch", e); } }
From source file:com.oneops.metrics.es.ElasticsearchReporter.java
/** * This index template is automatically applied to all indices which start with the index name * The index template simply configures the name not to be analyzed *///from w w w . j a v a 2 s .c o m private void checkForIndexTemplate() { try { HttpURLConnection connection = openConnection("/_template/metrics_template", "HEAD"); if (connection == null) { LOGGER.error("Could not connect to any configured elasticsearch instances: {}", Arrays.asList(hosts)); return; } connection.disconnect(); boolean isTemplateMissing = connection.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND; // nothing there, lets create it if (isTemplateMissing) { LOGGER.debug("No metrics template found in elasticsearch. Adding..."); HttpURLConnection putTemplateConnection = openConnection("/_template/metrics_template", "PUT"); JsonGenerator json = new JsonFactory().createGenerator(putTemplateConnection.getOutputStream()); json.writeStartObject(); json.writeStringField("template", index + "*"); json.writeObjectFieldStart("mappings"); json.writeObjectFieldStart("_default_"); json.writeObjectFieldStart("_all"); json.writeBooleanField("enabled", false); json.writeEndObject(); json.writeObjectFieldStart("properties"); json.writeObjectFieldStart("name"); json.writeObjectField("type", "string"); json.writeObjectField("index", "not_analyzed"); json.writeEndObject(); json.writeEndObject(); json.writeEndObject(); json.writeEndObject(); json.writeEndObject(); json.flush(); putTemplateConnection.disconnect(); if (putTemplateConnection.getResponseCode() != 200) { LOGGER.error( "Error adding metrics template to elasticsearch: {}/{}" + putTemplateConnection.getResponseCode(), putTemplateConnection.getResponseMessage()); } } checkedForIndexTemplate = true; } catch (IOException e) { LOGGER.error("Error when checking/adding metrics template to elasticsearch", e); } }
From source file:net.logstash.logback.composite.loggingevent.ArgumentsJsonProvider.java
@Override public void writeTo(JsonGenerator generator, ILoggingEvent event) throws IOException { Object[] args = event.getArgumentArray(); if (args == null || args.length == 0) { return;// w w w . j av a 2 s.co m } boolean hasWrittenFieldName = false; for (int argIndex = 0; argIndex < args.length; argIndex++) { Object arg = args[argIndex]; if (arg instanceof StructuredArgument) { if (!hasWrittenFieldName && getFieldName() != null) { generator.writeObjectFieldStart(getFieldName()); hasWrittenFieldName = true; } StructuredArgument structuredArgument = (StructuredArgument) arg; structuredArgument.writeTo(generator); } else if (includeNonStructuredArguments) { if (!hasWrittenFieldName && getFieldName() != null) { generator.writeObjectFieldStart(getFieldName()); hasWrittenFieldName = true; } String fieldName = nonStructuredArgumentsFieldPrefix + argIndex; generator.writeObjectField(fieldName, arg); } } if (hasWrittenFieldName) { generator.writeEndObject(); } }
From source file:com.baidubce.services.bmr.BmrClient.java
/** * Add steps to a BMR cluster./*from w ww . j ava 2s. c o m*/ * * @param request containing the ID of target BMR cluster and several steps to be added. * @return The response containing a list of IDs of newly added steps. */ public AddStepsResponse addSteps(AddStepsRequest request) { checkNotNull(request, "request should not be null."); checkNotNull(request.getSteps(), "The parameter steps should not be null."); checkStringNotEmpty(request.getClusterId(), "The parameter clusterId should not be null or empty string."); StringWriter writer = new StringWriter(); List<StepConfig> steps = request.getSteps(); try { JsonGenerator jsonGenerator = JsonUtils.jsonGeneratorOf(writer); jsonGenerator.writeStartObject(); jsonGenerator.writeArrayFieldStart("steps"); for (StepConfig step : steps) { jsonGenerator.writeStartObject(); if (step.getName() != null) { jsonGenerator.writeStringField("name", step.getName()); } jsonGenerator.writeStringField("type", step.getType()); jsonGenerator.writeStringField("actionOnFailure", step.getActionOnFailure()); jsonGenerator.writeObjectFieldStart("properties"); for (String propertyKey : step.getProperties().keySet()) { jsonGenerator.writeObjectField(propertyKey, step.getProperties().get(propertyKey)); } jsonGenerator.writeEndObject(); jsonGenerator.writeEndObject(); } jsonGenerator.writeEndArray(); jsonGenerator.writeEndObject(); jsonGenerator.close(); } catch (IOException e) { throw new BceClientException("Fail to generate json", e); } byte[] json = null; try { json = writer.toString().getBytes(DEFAULT_ENCODING); } catch (UnsupportedEncodingException e) { throw new BceClientException("Fail to get UTF-8 bytes", e); } InternalRequest internalRequest = this.createRequest(request, HttpMethodName.POST, CLUSTER, request.getClusterId(), STEP); internalRequest.addHeader(Headers.CONTENT_LENGTH, String.valueOf(json.length)); internalRequest.addHeader(Headers.CONTENT_TYPE, "application/json"); internalRequest.setContent(RestartableInputStream.wrap(json)); if (request.getClientToken() != null) { internalRequest.addParameter("clientToken", request.getClientToken()); } return this.invokeHttpClient(internalRequest, AddStepsResponse.class); }
From source file:jp.classmethod.aws.brian.utils.TriggerSerializer.java
@Override public void serialize(Trigger value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { if (value == null) { jgen.writeNull();// ww w. j av a2s . c o m return; } jgen.writeStartObject(); if (value.getKey() != null) { if (value.getKey().getGroup() != null) jgen.writeStringField("group", value.getKey().getGroup()); if (value.getKey().getName() != null) jgen.writeStringField("name", value.getKey().getName()); } if (value.getDescription() != null) { jgen.writeStringField("description", value.getDescription()); } if (value.getStartTime() != null) { jgen.writeFieldName("startTime"); provider.defaultSerializeDateValue(value.getStartTime(), jgen); } if (value.getEndTime() != null) { jgen.writeFieldName("endTime"); provider.defaultSerializeDateValue(value.getEndTime(), jgen); } if (value.getNextFireTime() != null) { jgen.writeFieldName("nextFireTime"); provider.defaultSerializeDateValue(value.getNextFireTime(), jgen); } if (value.getJobDataMap() != null) { jgen.writeObjectField("jobDataMap", value.getJobDataMap().getWrappedMap()); } jgen.writeNumberField("misfireInstruction", value.getMisfireInstruction()); jgen.writeNumberField("priority", value.getPriority()); if (value instanceof CronTrigger) { CronTrigger cronTrigger = (CronTrigger) value; jgen.writeFieldName("cronEx"); jgen.writeStartObject(); if (cronTrigger.getCronExpression() != null) { jgen.writeStringField("cronExpression", cronTrigger.getCronExpression()); } if (cronTrigger.getTimeZone() != null) { provider.defaultSerializeField("timeZone", cronTrigger.getTimeZone(), jgen); } jgen.writeEndObject(); } if (value instanceof SimpleTrigger) { SimpleTrigger simpleTrigger = (SimpleTrigger) value; jgen.writeFieldName("simple"); jgen.writeStartObject(); jgen.writeNumberField("repeatInterval", simpleTrigger.getRepeatInterval()); jgen.writeNumberField("repeatCount", simpleTrigger.getRepeatCount()); jgen.writeNumberField("timesTriggered", simpleTrigger.getTimesTriggered()); jgen.writeEndObject(); } jgen.writeEndObject(); }
From source file:org.springframework.security.oauth2.common.OAuth2AccessTokenJackson2Serializer.java
@Override public void serialize(OAuth2AccessToken token, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException { jgen.writeStartObject();//from w w w . j a va 2 s . c o m jgen.writeStringField(OAuth2AccessToken.ACCESS_TOKEN, token.getValue()); jgen.writeStringField(OAuth2AccessToken.TOKEN_TYPE, token.getTokenType()); OAuth2RefreshToken refreshToken = token.getRefreshToken(); if (refreshToken != null) { jgen.writeStringField(OAuth2AccessToken.REFRESH_TOKEN, refreshToken.getValue()); } Date expiration = token.getExpiration(); if (expiration != null) { long now = System.currentTimeMillis(); jgen.writeNumberField(OAuth2AccessToken.EXPIRES_IN, (expiration.getTime() - now) / 1000); } Set<String> scope = token.getScope(); if (scope != null && !scope.isEmpty()) { StringBuffer scopes = new StringBuffer(); for (String s : scope) { Assert.hasLength(s, "Scopes cannot be null or empty. Got " + scope + ""); scopes.append(s); scopes.append(" "); } jgen.writeStringField(OAuth2AccessToken.SCOPE, scopes.substring(0, scopes.length() - 1)); } Map<String, Object> additionalInformation = token.getAdditionalInformation(); for (String key : additionalInformation.keySet()) { jgen.writeObjectField(key, additionalInformation.get(key)); } jgen.writeEndObject(); }