List of usage examples for java.io Writer toString
public String toString()
From source file:org.apache.ambari.server.state.services.AlertNoticeDispatchService.java
/** * Generates digest content for the {@link Notification} using the * {@link #m_alertTemplates} and the list of alerts passed in. If there is a * problem with the templates, this will fallback to non-formatted content. * * @param notification/*from ww w. j a v a 2 s .c o m*/ * the notification (not {@code null}). * @param histories * the alerts to generate the content from (not {@code null}. * @param target * the target of the {@link Notification}. */ private void renderDigestNotificationContent(Notification notification, List<AlertHistoryEntity> histories, AlertTargetEntity target) throws IOException { String targetType = target.getNotificationType(); // build the velocity objects for template rendering AmbariInfo ambari = new AmbariInfo(m_metaInfo.get()); AlertSummaryInfo summary = new AlertSummaryInfo(histories); DispatchInfo dispatch = new DispatchInfo(target); // get the template for this target type final Writer subjectWriter = new StringWriter(); final Writer bodyWriter = new StringWriter(); final AlertTemplate template = m_alertTemplates.getTemplate(targetType); if (null != template) { // create the velocity context for template rendering VelocityContext velocityContext = new VelocityContext(); velocityContext.put(VELOCITY_AMBARI_KEY, ambari); velocityContext.put(VELOCITY_SUMMARY_KEY, summary); velocityContext.put(VELOCITY_DISPATCH_KEY, dispatch); // render the template and assign the content to the notification String subjectTemplate = template.getSubject(); String bodyTemplate = template.getBody(); // render the subject Velocity.evaluate(velocityContext, subjectWriter, VELOCITY_LOG_TAG, subjectTemplate); // render the body Velocity.evaluate(velocityContext, bodyWriter, VELOCITY_LOG_TAG, bodyTemplate); } else { // a null template is possible from parsing incorrectly or not // having the correct type defined for the target for (AlertHistoryEntity alert : histories) { subjectWriter.write("Apache Ambari Alert Summary"); bodyWriter.write(alert.getAlertState().name()); bodyWriter.write(" "); bodyWriter.write(alert.getAlertDefinition().getLabel()); bodyWriter.write(" "); bodyWriter.write(alert.getAlertText()); bodyWriter.write("\n"); } } notification.Subject = subjectWriter.toString(); notification.Body = bodyWriter.toString(); }
From source file:com.comcast.cqs.persistence.CQSMessagePartitionedCassandraPersistence.java
private String getMessageJSON(CQSMessage message) throws JSONException { Writer writer = new StringWriter(); JSONWriter jw = new JSONWriter(writer); jw = jw.object();/*ww w. ja v a 2 s .com*/ jw.key("MessageId").value(message.getMessageId()); jw.key("MD5OfBody").value(message.getMD5OfBody()); jw.key("Body").value(message.getBody()); if (message.getAttributes() == null) { message.setAttributes(new HashMap<String, String>()); } if (!message.getAttributes().containsKey(CQSConstants.SENT_TIMESTAMP)) { message.getAttributes().put(CQSConstants.SENT_TIMESTAMP, "" + System.currentTimeMillis()); } if (!message.getAttributes().containsKey(CQSConstants.APPROXIMATE_RECEIVE_COUNT)) { message.getAttributes().put(CQSConstants.APPROXIMATE_RECEIVE_COUNT, "0"); } if (message.getAttributes() != null) { for (String key : message.getAttributes().keySet()) { String value = message.getAttributes().get(key); if (value == null || value.isEmpty()) { value = ""; } jw.key(key).value(value); } } if (message.getMessageAttributes() != null && message.getMessageAttributes().size() > 0) { jw.key("MD5OfMessageAttributes").value(message.getMD5OfMessageAttributes()); jw.key("MessageAttributes"); jw.object(); for (String key : message.getMessageAttributes().keySet()) { jw.key(key); jw.object(); CQSMessageAttribute messageAttribute = message.getMessageAttributes().get(key); if (messageAttribute.getStringValue() != null) { jw.key("StringValue").value(messageAttribute.getStringValue()); } else if (messageAttribute.getBinaryValue() != null) { jw.key("BinaryValue").value(messageAttribute.getBinaryValue()); } jw.key("DataType").value(messageAttribute.getDataType()); jw.endObject(); } jw.endObject(); } jw.endObject(); return writer.toString(); }
From source file:org.apache.tinkerpop.gremlin.structure.IoTest.java
private String streamToString(final InputStream in) throws IOException { final Writer writer = new StringWriter(); final char[] buffer = new char[1024]; try (final Reader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"))) { int n;/*w w w . j ava 2 s. co m*/ while ((n = reader.read(buffer)) != -1) { writer.write(buffer, 0, n); } } return writer.toString(); }
From source file:org.apache.manifoldcf.crawler.connectors.wiki.WikiConnector.java
protected static String readResponseAsString(HttpResponse httpResponse) throws IOException { HttpEntity entity = httpResponse.getEntity(); if (entity != null) { InputStream is = entity.getContent(); try {// w ww .j ava2s. c om Charset charSet; try { ContentType ct = ContentType.get(entity); if (ct == null) charSet = StandardCharsets.UTF_8; else charSet = ct.getCharset(); } catch (ParseException e) { charSet = StandardCharsets.UTF_8; } char[] buffer = new char[65536]; Reader r = new InputStreamReader(is, charSet); Writer w = new StringWriter(); try { while (true) { int amt = r.read(buffer); if (amt == -1) break; w.write(buffer, 0, amt); } } finally { w.flush(); } return w.toString(); } finally { is.close(); } } return ""; }
From source file:org.apache.slider.client.SliderClient.java
private void actionDiagnosticYarn(ActionDiagnosticArgs diagnosticArgs) throws IOException, YarnException { JSONObject converter = null;//from w w w .ja v a2 s.c om log.info("the node in the YARN cluster has below state: "); List<NodeReport> yarnClusterInfo; try { yarnClusterInfo = yarnClient.getNodeReports(NodeState.RUNNING); } catch (YarnException e1) { log.error("Exception happened when fetching node report from the YARN cluster: " + e1.toString()); throw e1; } catch (IOException e1) { log.error("Network problem happened when fetching node report YARN cluster: " + e1.toString()); throw e1; } for (NodeReport nodeReport : yarnClusterInfo) { log.info(nodeReport.toString()); } if (diagnosticArgs.verbose) { Writer configWriter = new StringWriter(); try { Configuration.dumpConfiguration(yarnClient.getConfig(), configWriter); } catch (IOException e1) { log.error("Network problem happened when retrieving YARN config from YARN: " + e1.toString()); throw e1; } try { converter = new JSONObject(configWriter.toString()); log.info("the configuration of the YARN cluster is: " + converter.toString(2)); } catch (JSONException e) { log.error("JSONException happened during parsing response from YARN: " + e.toString()); } } }
From source file:com.glaf.jbpm.web.springmvc.MxJbpmCompleteTaskController.java
@RequestMapping public ModelAndView completeTask(HttpServletRequest request, HttpServletResponse response) throws Exception { Map<String, Object> paramMap = RequestUtils.getParameterMap(request); logger.debug(paramMap);/*from w w w .ja v a 2 s . co m*/ String json = RequestUtils.getStringValue(request, "json"); Long processInstanceId = ParamUtils.getLong(paramMap, "processInstanceId"); Long taskInstanceId = ParamUtils.getLong(paramMap, "taskInstanceId"); String transitionName = RequestUtils.getStringValue(request, "transitionName"); String jumpToNode = RequestUtils.getStringValue(request, "jumpToNode"); String isAgree = RequestUtils.getStringValue(request, "isAgree"); String opinion = RequestUtils.getStringValue(request, "opinion"); logger.debug("json:" + json); logger.debug("processInstanceId:" + processInstanceId); logger.debug("taskInstanceId:" + taskInstanceId); logger.debug("transitionName:" + transitionName); logger.debug("jumpToNode:" + jumpToNode); logger.debug("isAgree:" + isAgree); logger.debug("opinion:" + opinion); String actorId = RequestUtils.getActorId(request); ProcessContainer container = ProcessContainer.getContainer(); String processName = null; boolean canSubmit = false; boolean isOK = false; TaskItem taskItem = null; if ("0".equals(isAgree)) { isAgree = "false"; } else if ("1".equals(isAgree)) { isAgree = "true"; } if (taskInstanceId != null && StringUtils.isNotEmpty(actorId)) { /** * ???? */ taskItem = container.getTaskItem(taskInstanceId, actorId); if (taskItem != null) { if (processInstanceId != null) { canSubmit = true; processInstanceId = taskItem.getProcessInstanceId(); processName = taskItem.getProcessName(); } } } else if (processInstanceId != null && StringUtils.isNotEmpty(actorId)) { /** * ????? */ taskItem = container.getMinTaskItem(actorId, processInstanceId); if (taskItem != null) { canSubmit = true; processName = taskItem.getProcessName(); } } /** * ??? */ if (canSubmit && taskItem != null) { ProcessContext ctx = new ProcessContext(); /** * ??json?.<br> * {money:100000,day:5,pass:true,deptId:"123", roleId:"R001"} */ if (StringUtils.isNotEmpty(json)) { Map<String, Object> jsonMap = JsonUtils.decode(json); if (jsonMap != null && jsonMap.size() > 0) { Set<Entry<String, Object>> entrySet = jsonMap.entrySet(); for (Entry<String, Object> entry : entrySet) { String name = entry.getKey(); Object value = entry.getValue(); if (name != null && value != null) { DataField dataField = new DataField(); dataField.setName(name); dataField.setValue(value); ctx.addDataField(dataField); } } } } DataField dataField = new DataField(); dataField.setName("isAgree"); dataField.setValue(isAgree); ctx.addDataField(dataField); ctx.setActorId(actorId); ctx.setOpinion(opinion); ctx.setProcessInstanceId(taskItem.getProcessInstanceId()); ctx.setTaskInstanceId(taskItem.getTaskInstanceId()); ctx.setJumpToNode(jumpToNode); ctx.setTransitionName(transitionName); try { isOK = container.completeTask(ctx); request.setAttribute("isOK", Boolean.valueOf(isOK)); if (isOK) { request.setAttribute("statusCode", 200); request.setAttribute("message", ViewProperties.getString("res_submit_ok")); } else { request.setAttribute("statusCode", 500); request.setAttribute("message", ViewProperties.getString("res_submit_error")); } } catch (Exception ex) { request.setAttribute("statusCode", 500); request.setAttribute("message", ViewProperties.getString("res_submit_error")); if (LogUtils.isDebug()) { ex.printStackTrace(); logger.debug(ex); } } } String responseDataType = RequestUtils.getStringValue(request, "responseDataType"); /** * ??jsonxml???<br> * 200-? <br> * 500-<br> */ if (StringUtils.equals(responseDataType, "json")) { String encoding = request.getParameter("encoding"); if (encoding == null) { encoding = "UTF-8"; } request.setCharacterEncoding(encoding); response.setCharacterEncoding(encoding); response.setContentType("text/plain;charset=" + encoding); Map<String, Object> jsonMap = new java.util.HashMap<String, Object>(); if (isOK) { jsonMap.put("statusCode", 200); jsonMap.put("success", "true"); jsonMap.put("data", ViewProperties.getString("res_submit_ok")); jsonMap.put("message", ViewProperties.getString("res_submit_ok")); } else { jsonMap.put("statusCode", 500); jsonMap.put("success", "false"); jsonMap.put("data", ViewProperties.getString("res_submit_error")); jsonMap.put("message", ViewProperties.getString("res_submit_error")); } JSONObject object = new JSONObject(jsonMap); Writer writer = response.getWriter(); writer.write(object.toString()); writer.flush(); writer.close(); writer = null; return null; } else if (StringUtils.equals(responseDataType, "xml")) { String encoding = request.getParameter("encoding"); if (encoding == null) { encoding = "UTF-8"; } request.setCharacterEncoding(encoding); response.setCharacterEncoding(encoding); response.setContentType("text/xml;charset=" + encoding); StringBuffer buffer = new StringBuffer(); buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); buffer.append("<response>"); if (isOK) { buffer.append("\n <statusCode>200</statusCode>"); buffer.append("\n <message>").append(ViewProperties.getString("res_submit_ok")) .append("</message>"); } else { buffer.append("\n <statusCode>500</statusCode>"); buffer.append("\n <message>").append(ViewProperties.getString("res_submit_error")) .append("</message>"); } buffer.append("\n</response>"); Writer writer = response.getWriter(); writer.write(buffer.toString()); writer.flush(); writer.close(); writer = null; return null; } /** * ?????<br> * ?????_complete_template??jbpm_complete_template * WEB-INF\conf\extension?? */ String templateId = RequestUtils.getStringValue(request, "y_templateId"); if (StringUtils.isEmpty(templateId)) { templateId = CustomProperties.getString(processName + "_complete_template"); } if (StringUtils.isEmpty(templateId)) { templateId = CustomProperties.getString("jbpm_complete_template"); } if (StringUtils.isNotEmpty(templateId)) { Map<String, Object> context = new java.util.HashMap<String, Object>(); context.putAll(paramMap); context.put("actorId", actorId); context.put("canSubmit", canSubmit); context.put("isOK", isOK); context.put("taskItem", taskItem); context.put("processInstanceId", processInstanceId); context.put("contextPath", request.getContextPath()); if (isOK) { context.put("statusCode", 200); context.put("message", ViewProperties.getString("res_submit_ok")); } else { context.put("statusCode", 500); context.put("message", ViewProperties.getString("res_submit_error")); } try { logger.debug(context); Writer writer = new StringWriter(); TemplateUtils.evaluate(templateId, context, writer); request.setAttribute("templateScript", writer.toString()); String encoding = request.getParameter("encoding"); if (encoding == null) { encoding = "UTF-8"; } request.setCharacterEncoding(encoding); response.setCharacterEncoding(encoding); response.setContentType("text/html;charset=" + encoding); response.getWriter().write(writer.toString()); return null; } catch (Exception ex) { if (LogUtils.isDebug()) { ex.printStackTrace(); logger.debug(ex); } } } String jx_view = request.getParameter("jx_view"); if (StringUtils.isNotEmpty(jx_view)) { return new ModelAndView(jx_view); } String x_view = ViewProperties.getString("jbpm_complete.complateTask"); if (StringUtils.isNotEmpty(x_view)) { return new ModelAndView(x_view); } return new ModelAndView("/jbpm/complete"); }
From source file:com.googlecode.jmxtrans.model.output.StackdriverWriter.java
/** * Take query results, make a JSON String * /*from w w w .j a v a2s .com*/ * @param results List of Result objects * @return a String containing a JSON message, or null if there are no values to report * * @throws IOException if there is some problem generating the JSON, should be uncommon */ private String getGatewayMessage(final List<Result> results) throws IOException { int valueCount = 0; Writer writer = new StringWriter(); JsonGenerator g = jsonFactory.createGenerator(writer); g.writeStartObject(); g.writeNumberField("timestamp", System.currentTimeMillis() / 1000); g.writeNumberField("proto_version", STACKDRIVER_PROTOCOL_VERSION); g.writeArrayFieldStart("data"); List<String> typeNames = this.getTypeNames(); for (Result metric : results) { Map<String, Object> values = metric.getValues(); if (values != null) { for (Entry<String, Object> entry : values.entrySet()) { if (isNumeric(entry.getValue())) { // we have a numeric value, write a value into the message StringBuilder nameBuilder = new StringBuilder(); // put the prefix if set if (this.prefix != null) { nameBuilder.append(prefix); nameBuilder.append("."); } // put the class name or its alias if available if (!metric.getKeyAlias().isEmpty()) { nameBuilder.append(metric.getKeyAlias()); } else { nameBuilder.append(metric.getClassName()); } // Wildcard "typeNames" substitution String typeName = com.googlecode.jmxtrans.model.naming.StringUtils .cleanupStr(TypeNameValuesStringBuilder.getDefaultBuilder().build(typeNames, metric.getTypeName())); if (typeName != null && typeName.length() > 0) { nameBuilder.append("."); nameBuilder.append(typeName); } // add the attribute name nameBuilder.append("."); nameBuilder.append(metric.getAttributeName()); // put the value name if it differs from the attribute name if (!entry.getKey().equals(metric.getAttributeName())) { nameBuilder.append("."); nameBuilder.append(entry.getKey()); } // check for Float/Double NaN since these will cause the message validation to fail if (entry.getValue() instanceof Float && ((Float) entry.getValue()).isNaN()) { logger.info("Metric value for " + nameBuilder.toString() + " is NaN, skipping"); continue; } if (entry.getValue() instanceof Double && ((Double) entry.getValue()).isNaN()) { logger.info("Metric value for " + nameBuilder.toString() + " is NaN, skipping"); continue; } valueCount++; g.writeStartObject(); g.writeStringField("name", nameBuilder.toString()); g.writeNumberField("value", Double.valueOf(entry.getValue().toString())); // if the metric is attached to an instance, include that in the message if (instanceId != null && !instanceId.isEmpty()) { g.writeStringField("instance", instanceId); } g.writeNumberField("collected_at", metric.getEpoch() / 1000); g.writeEndObject(); } } } } g.writeEndArray(); g.writeEndObject(); g.flush(); g.close(); // return the message if there are any values to report if (valueCount > 0) { return writer.toString(); } else { return null; } }
From source file:org.apache.geode.internal.cache.GemFireCacheImpl.java
public void loadCacheXml(InputStream stream) throws TimeoutException, CacheWriterException, GatewayException, RegionExistsException { // make this cache available to callbacks being initialized during xml create final Object oldValue = xmlCache.get(); xmlCache.set(this); try {//from w ww . j a va 2 s.co m CacheXmlParser xml; if (xmlParameterizationEnabled) { char[] buffer = new char[1024]; Reader reader = new BufferedReader(new InputStreamReader(stream, "ISO-8859-1")); Writer stringWriter = new StringWriter(); int n = -1; while ((n = reader.read(buffer)) != -1) { stringWriter.write(buffer, 0, n); } /** * Now replace all replaceable system properties here using <code>PropertyResolver</code> */ String replacedXmlString = resolver.processUnresolvableString(stringWriter.toString()); /* * Turn the string back into the default encoding so that the XML parser can work correctly * in the presence of an "encoding" attribute in the XML prolog. */ ByteArrayOutputStream baos = new ByteArrayOutputStream(); OutputStreamWriter writer = new OutputStreamWriter(baos, "ISO-8859-1"); writer.write(replacedXmlString); writer.flush(); xml = CacheXmlParser.parse(new ByteArrayInputStream(baos.toByteArray())); } else { xml = CacheXmlParser.parse(stream); } xml.create(this); } catch (IOException e) { throw new CacheXmlException("Input Stream could not be read for system property substitutions."); } finally { xmlCache.set(oldValue); } }
From source file:com.dragome.compiler.units.ClassUnit.java
private String generateJsCode(int depth, Writer writer) throws IOException { Log.getLogger().debug(getIndent(depth) + this); if (getData() != null) { writer.write(getData());// www .j a v a 2 s . co m } else { throw new RuntimeException("Cannot compile the class: " + getName()); } Set<MemberUnit> notImplementedMethods = getNotImplementedMethods(); if (interfaces.size() > 0) { String extendOperator = "implement"; if (isInterface) extendOperator = "extend"; // writer.write("_T.interfaces = ["); writer.write(extendOperator + ": ["); int i = 0; for (ClassUnit interFace : interfaces) { if (i++ > 0) writer.write(", "); writer.write(DragomeJavaScriptGenerator.normalizeExpression(interFace.getSignature().toString())); } writer.write("],\n"); } writer.write("members:\n"); writer.write("{\n"); MemberUnit clinitMethod = null; List<MemberUnit> staticMethods = new ArrayList<MemberUnit>(); boolean first = true; for (MemberUnit member : getDeclaredMembers()) { if (member.getData() != null && member.getData().startsWith(STATIC_MEMBER)) { staticMethods.add(member); } else if (member.getData() != null && member.getData().contains("_dragomeJs.StringInit")) { stringInits.add(member); } else { if (member.getData() != null && member.getData().trim().length() > 0) { if (!first) writer.write(",\n"); first = false; writeMethodAlternative(depth, writer, member); if (member instanceof ProcedureUnit) { project.currentGeneratedMethods++; writer.flush(); } } } if (isClinit(member)) clinitMethod = member; } for (MemberUnit member : notImplementedMethods) { if (!first) writer.write(",\n"); first = false; String methodData = member.getData().replace(STATIC_MEMBER, ""); methodData = methodData.substring(0, methodData.indexOf("{")); writer.write(methodData); writer.write("{\n return "); writer.write(member.getDeclaringClass().toString().replace(".", "_")); writer.write(".$$members."); writer.write( methodData.replace(": function ()", ".call (this)").replace(": function (", ".call (this, ")); writer.write("}\n"); if (member instanceof ProcedureUnit) { project.currentGeneratedMethods++; writer.flush(); } } writer.write("\n},\n"); writer.write("statics:\n"); writer.write("{\n"); if (clinitMethod != null) { String name = DragomeJavaScriptGenerator .normalizeExpression(clinitMethod.getDeclaringClass().getName()); String replace = clinitMethod.getData().replace("this.", name + "."); replace = replace.replace("{", "{ this.$$clinit_=function(){return this};"); replace = replace.substring(0, replace.length() - 2) + "\n return this;\n}"; String memberData = clinitMethod.getData(); clinitMethod.setData(replace.replace(STATIC_MEMBER, "")); clinitMethod.write(depth, writer); clinitMethod.setData(memberData); String modifyMethodName = DragomeJavaScriptGenerator.normalizeExpression(clinitMethod.getSignature()); project.getClinits().add("initClass(" + name + ");"); } else { String replace = "$$clinit_: function(){return this}"; writer.write(replace); } boolean hasStaticMembers = staticMethods.size() > 0; if (hasStaticMembers) writer.write(","); writer.write("\n"); first = true; for (MemberUnit member : staticMethods) { if (member != clinitMethod) { if (!first) writer.write(",\n"); first = false; String memberData = member.getData(); member.setData(member.getData().replace(STATIC_MEMBER, "")); writeMethodAlternative(depth, writer, member); member.setData(memberData); if (member instanceof ProcedureUnit || member instanceof FieldUnit) { if (member instanceof ProcedureUnit) project.currentGeneratedMethods++; writer.flush(); } } } first = addSuperStaticMethods(writer, !hasStaticMembers ^ first); // addAnnotationsAsStaticMember(writer, first); writer.write("\n}\n"); writer.write("\n}\n\n"); writer.write(");\n"); return writer.toString(); }