public void testMessageWithFireEvent() throws IOException, JSONException { StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); ProtocolMessageWriter writer = new JsonMessageWriter(printWriter); Display display = new Display(); Shell shell = new Shell(display); Button button = new Button(shell, SWT.PUSH); writer.addFireEventPayload(WidgetUtil.getId(button), "selection"); String widgetId = WidgetUtil.getId(button); String actual = stringWriter.getBuffer().toString(); JSONObject message = new JSONObject(actual + "]}"); JSONArray widgetArray = message.getJSONArray(IProtocolConstants.MESSAGE_WIDGETS); JSONObject widgetObject = widgetArray.getJSONObject(0); String type = widgetObject.getString(IProtocolConstants.WIDGETS_TYPE); assertEquals(IProtocolConstants.PAYLOAD_FIRE_EVENT, type); String actualId = widgetObject.getString(IProtocolConstants.WIDGETS_ID); assertEquals(widgetId, actualId); JSONObject payload = widgetObject.getJSONObject(IProtocolConstants.WIDGETS_PAYLOAD); String actualEvent = payload.getString(IProtocolConstants.KEY_EVENT); assertEquals("selection", actualEvent); writer.addFireEventPayload(WidgetUtil.getId(button), "focus"); writer.finish(); actual = stringWriter.getBuffer().toString(); message = new JSONObject(actual); widgetArray = message.getJSONArray(IProtocolConstants.MESSAGE_WIDGETS); widgetObject = widgetArray.getJSONObject(1); type = widgetObject.getString(IProtocolConstants.WIDGETS_TYPE); assertEquals(IProtocolConstants.PAYLOAD_FIRE_EVENT, type); actualId = widgetObject.getString(IProtocolConstants.WIDGETS_ID); assertEquals(widgetId, actualId); payload = widgetObject.getJSONObject(IProtocolConstants.WIDGETS_PAYLOAD); actualEvent = payload.getString(IProtocolConstants.KEY_EVENT); assertEquals("focus", actualEvent); }
private String importXMI(File sourceFile) throws FileNotFoundException, TransformerConfigurationException, TransformerException { BufferedReader styledata; StreamSource sourcedata; Templates stylesheet; Transformer trans; // Get the stylesheet file stream styledata = new BufferedReader( new FileReader( new File( getClass().getClassLoader().getResource("verifier/xmi2lem.xsl").getFile()))); sourcedata = new StreamSource(new FileReader(sourceFile)); // Initialize Saxon TransformerFactory factory = TransformerFactoryImpl.newInstance(); stylesheet = factory.newTemplates(new StreamSource(styledata)); // Apply the transformation trans = stylesheet.newTransformer(); StringWriter sw = new StringWriter(); trans.transform(sourcedata, new StreamResult(sw)); // return sw.toString(); return sw.getBuffer().substring(sw.getBuffer().indexOf("model")); }
private boolean safeEquals(final ClasspathItemWrapper a, final ClasspathItemWrapper b) { try { final StringWriter as = new StringWriter(); final StringWriter bs = new StringWriter(); final BufferedWriter bas = new BufferedWriter(as); final BufferedWriter bbs = new BufferedWriter(bs); weaken(a).write(bas); weaken(b).write(bbs); bas.flush(); bbs.flush(); as.close(); bs.close(); final String x = as.getBuffer().toString(); final String y = bs.getBuffer().toString(); return x.equals(y); } catch (IOException e) { throw new RuntimeException(e); } }
public void testMessageWithDestroy() throws IOException, JSONException { StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); ProtocolMessageWriter writer = new JsonMessageWriter(printWriter); Display display = new Display(); Shell shell = new Shell(display); Button button = new Button(shell, SWT.PUSH); writer.addDestroyPayload(WidgetUtil.getId(button)); String widgetId = WidgetUtil.getId(button); String actual = stringWriter.getBuffer().toString(); JSONObject message = new JSONObject(actual + "]}"); JSONArray widgetArray = message.getJSONArray(IProtocolConstants.MESSAGE_WIDGETS); JSONObject widgetObject = widgetArray.getJSONObject(0); String type = widgetObject.getString(IProtocolConstants.WIDGETS_TYPE); assertEquals(IProtocolConstants.PAYLOAD_DESTROY, type); String actualId = widgetObject.getString(IProtocolConstants.WIDGETS_ID); assertEquals(widgetId, actualId); Object payload = widgetObject.get(IProtocolConstants.WIDGETS_PAYLOAD); assertEquals(JSONObject.NULL, payload); writer.addDestroyPayload(WidgetUtil.getId(shell)); writer.finish(); String shellId = WidgetUtil.getId(shell); actual = stringWriter.getBuffer().toString(); message = new JSONObject(actual); widgetArray = message.getJSONArray(IProtocolConstants.MESSAGE_WIDGETS); widgetObject = widgetArray.getJSONObject(1); type = widgetObject.getString(IProtocolConstants.WIDGETS_TYPE); assertEquals(IProtocolConstants.PAYLOAD_DESTROY, type); actualId = widgetObject.getString(IProtocolConstants.WIDGETS_ID); assertEquals(shellId, actualId); payload = widgetObject.get(IProtocolConstants.WIDGETS_PAYLOAD); assertEquals(JSONObject.NULL, payload); }
public String processInput(String input) { String output; boolean moreInputRequired; if (input == null) { // '\nHello {0}\nWelcome to the Ganymede Jython interpreter!\n\nType "quit" to exit.\n{1}' return ts.l("processInput.greeting", socket.getInetAddress().getHostAddress(), prompt); } if (input.equals(ts.l("processInput.quitcommand"))) { return doneString; } try { moreInputRequired = interp.push(input); if (moreInputRequired) { return "... "; } buffer.flush(); output = buffer.toString(); interp.resetbuffer(); buffer.getBuffer().setLength(0); } catch (PyException pex) { output = buffer.toString() + "\n" + pex.toString(); interp.resetbuffer(); buffer.getBuffer().setLength(0); } return output + prompt; }
/** @see org.eclipse.pde.api.tools.internal.tasks.UseTask#assertParameters() */ protected void assertParameters() throws BuildException { if (this.reportLocation == null) { StringWriter out = new StringWriter(); PrintWriter writer = new PrintWriter(out); writer.println( NLS.bind( Messages.ApiUseTask_missing_report_location, new String[] {this.reportLocation})); writer.flush(); writer.close(); throw new BuildException(String.valueOf(out.getBuffer())); } if (this.currentBaselineLocation == null) { StringWriter out = new StringWriter(); PrintWriter writer = new PrintWriter(out); writer.println( NLS.bind( Messages.ApiUseTask_missing_baseline_argument, new String[] {this.currentBaselineLocation})); writer.flush(); writer.close(); throw new BuildException(String.valueOf(out.getBuffer())); } // stop if we don't want to see anything if (!considerapi && !considerinternal && !considerillegaluse) { throw new BuildException(Messages.UseTask_no_scan_both_types_not_searched_for); } }
protected List<ModelNode> readFile(File file, int expectedRecords) throws IOException { List<ModelNode> list = new ArrayList<ModelNode>(); final BufferedReader reader = new BufferedReader(new FileReader(file)); try { StringWriter writer = null; String line = reader.readLine(); while (line != null) { if (DATE_STAMP_PATTERN.matcher(line).find()) { if (writer != null) { list.add(ModelNode.fromJSONString(writer.getBuffer().toString())); } writer = new StringWriter(); writer.append("{"); } else { if (writer != null) writer.append("\n" + line); } line = reader.readLine(); } if (writer != null) { list.add(ModelNode.fromJSONString(writer.getBuffer().toString())); } } finally { IoUtils.safeClose(reader); } Assert.assertEquals(list.toString(), expectedRecords, list.size()); return list; }
@SuppressWarnings("unchecked") public void testMetadataElement() throws Exception { // write XMLResource inResource = (XMLResource) resourceSet.createResource(URI.createURI("inputStream://dummyUriWithValidSuffix.xml")); inResource.getDefaultLoadOptions().put(XMLResource.OPTION_ENCODING, "UTF-8"); inResource.setEncoding("UTF-8"); DocumentRoot documentRoot = DroolsFactory.eINSTANCE.createDocumentRoot(); MetadataType metadataType = DroolsFactory.eINSTANCE.createMetadataType(); MetaentryType typeOne = DroolsFactory.eINSTANCE.createMetaentryType(); typeOne.setName("entry1"); typeOne.setValue("value1"); MetaentryType typeTwo = DroolsFactory.eINSTANCE.createMetaentryType(); typeTwo.setName("entry2"); typeTwo.setValue("value2"); metadataType.getMetaentry().add(typeOne); metadataType.getMetaentry().add(typeTwo); documentRoot.setMetadata(metadataType); inResource.getContents().add(documentRoot); StringWriter stringWriter = new StringWriter(); inResource.save(stringWriter, null); assertNotNull(stringWriter.getBuffer().toString()); if (stringWriter.getBuffer().toString().length() < 1) { fail("generated xml is empty"); } // read XMLResource outResource = (XMLResource) resourceSet.createResource(URI.createURI("inputStream://dummyUriWithValidSuffix.xml")); outResource.getDefaultLoadOptions().put(XMLResource.OPTION_ENCODING, "UTF-8"); outResource.setEncoding("UTF-8"); Map<String, Object> options = new HashMap<String, Object>(); options.put(XMLResource.OPTION_ENCODING, "UTF-8"); InputStream is = new ByteArrayInputStream(stringWriter.getBuffer().toString().getBytes("UTF-8")); outResource.load(is, options); DocumentRoot outRoot = (DocumentRoot) outResource.getContents().get(0); assertNotNull(outRoot.getMetadata()); MetadataType outMetadataType = outRoot.getMetadata(); assertTrue(outMetadataType.getMetaentry().size() == 2); MetaentryType outOne = (MetaentryType) outMetadataType.getMetaentry().get(0); MetaentryType outTwo = (MetaentryType) outMetadataType.getMetaentry().get(1); assertTrue(outOne.getName().equals("entry1")); assertTrue(outOne.getValue().equals("value1")); assertTrue(outTwo.getName().equals("entry2")); assertTrue(outTwo.getValue().equals("value2")); }
public Request<UpdateHostedZoneCommentRequest> marshall( UpdateHostedZoneCommentRequest updateHostedZoneCommentRequest) { if (updateHostedZoneCommentRequest == null) { throw new AmazonClientException("Invalid argument passed to marshall(...)"); } Request<UpdateHostedZoneCommentRequest> request = new DefaultRequest<UpdateHostedZoneCommentRequest>( updateHostedZoneCommentRequest, "AmazonRoute53"); request.setHttpMethod(HttpMethodName.POST); String uriResourcePath = "/2013-04-01/hostedzone/{Id}"; uriResourcePath = uriResourcePath.replace( "{Id}", (updateHostedZoneCommentRequest.getId() != null) ? SdkHttpUtils.urlEncode( StringUtils.fromString(updateHostedZoneCommentRequest.getId()), false) : ""); request.setResourcePath(uriResourcePath); try { StringWriter stringWriter = new StringWriter(); XMLWriter xmlWriter = new XMLWriter(stringWriter, "https://route53.amazonaws.com/doc/2013-04-01/"); xmlWriter.startElement("UpdateHostedZoneCommentRequest"); if (updateHostedZoneCommentRequest != null) { if (updateHostedZoneCommentRequest.getComment() != null) { xmlWriter .startElement("Comment") .value(updateHostedZoneCommentRequest.getComment()) .endElement(); } } xmlWriter.endElement(); request.setContent(new StringInputStream(stringWriter.getBuffer().toString())); request.addHeader( "Content-Length", Integer.toString(stringWriter.getBuffer().toString().getBytes(UTF8).length)); if (!request.getHeaders().containsKey("Content-Type")) { request.addHeader("Content-Type", "application/xml"); } } catch (Throwable t) { throw new AmazonClientException("Unable to marshall request to XML: " + t.getMessage(), t); } return request; }
public void render(final RenderBridge requestBridge) throws Throwable { // Collection<CompilationError> errors = null; try { boot(); } catch (CompilationException e) { errors = e.getErrors(); } // if (errors == null || errors.isEmpty()) { // if (errors != null) { requestBridge.purgeSession(); } // try { TrimmingException.invoke( new TrimmingException.Callback() { public void call() throws Throwable { try { runtime.getContext().invoke(requestBridge); } catch (ApplicationException e) { throw e.getCause(); } } }); } catch (TrimmingException e) { if (config.isProd()) { throw e.getSource(); } else { StringWriter writer = new StringWriter(); PrintWriter printer = new PrintWriter(writer); renderThrowable(printer, e); requestBridge.setResponse(Response.ok(writer.getBuffer())); } } finally { requestBridge.close(); } } else { try { StringWriter writer = new StringWriter(); PrintWriter printer = new PrintWriter(writer); renderErrors(printer, errors); requestBridge.setResponse(Response.ok(writer.getBuffer())); } finally { requestBridge.close(); } } }
protected Path marshal( Cluster cluster, JAXBElement<?> jaxbElement, JAXBContext jaxbContext, Path outPath) throws FalconException { try { Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); if (LOG.isDebugEnabled()) { StringWriter writer = new StringWriter(); marshaller.marshal(jaxbElement, writer); LOG.debug("Writing definition to {} on cluster {}", outPath, cluster.getName()); LOG.debug(writer.getBuffer().toString()); } FileSystem fs = HadoopClientFactory.get() .createProxiedFileSystem(outPath.toUri(), ClusterHelper.getConfiguration(cluster)); OutputStream out = fs.create(outPath); try { marshaller.marshal(jaxbElement, out); } finally { out.close(); } LOG.info("Marshalled {} to {}", jaxbElement.getDeclaredType(), outPath); return outPath; } catch (Exception e) { throw new FalconException("Unable to marshall app object", e); } }
// TODO: naming @SuppressWarnings("unchecked") void sendSyncObject(Object o, SendHandler handler) { if (o instanceof String) { remoteEndpoint.sendText((String) o, handler); } else { Object toSend = null; try { toSend = tyrusEndpointWrapper.doEncode(session, o); } catch (final Exception e) { handler.onResult(new SendResult(e)); } if (toSend instanceof String) { remoteEndpoint.sendText((String) toSend, handler); } else if (toSend instanceof ByteBuffer) { remoteEndpoint.sendBinary((ByteBuffer) toSend, handler); } else if (toSend instanceof StringWriter) { StringWriter writer = (StringWriter) toSend; StringBuffer sb = writer.getBuffer(); remoteEndpoint.sendText(sb.toString(), handler); } else if (toSend instanceof ByteArrayOutputStream) { ByteArrayOutputStream baos = (ByteArrayOutputStream) toSend; ByteBuffer buffer = ByteBuffer.wrap(baos.toByteArray()); remoteEndpoint.sendBinary(buffer, handler); } } }
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { StringBuilder sb = new StringBuilder(); try { Monitor.fetchData(); bannerText = sanitize(ServerConfiguration.getSystemConfiguration().get(Property.MONITOR_BANNER_TEXT)); bannerColor = ServerConfiguration.getSystemConfiguration() .get(Property.MONITOR_BANNER_COLOR) .replace("'", "'"); bannerBackground = ServerConfiguration.getSystemConfiguration() .get(Property.MONITOR_BANNER_BACKGROUND) .replace("'", "'"); pageStart(req, resp, sb); pageBody(req, resp, sb); pageEnd(req, resp, sb); } catch (Throwable t) { log.error("Error building page " + req.getRequestURI(), t); sb.append("\n<pre>\n"); StringWriter sw = new StringWriter(); t.printStackTrace(new PrintWriter(sw)); sb.append(sanitize(sw.getBuffer().toString())); sb.append("</pre>\n"); } finally { resp.getWriter().print(sb); resp.getWriter().flush(); } }
protected Result describeMbean( @Nonnull MBeanServerConnection mbeanServer, @Nonnull ObjectName objectName) throws IntrospectionException, ReflectionException, InstanceNotFoundException, IOException { MBeanInfo mbeanInfo = mbeanServer.getMBeanInfo(objectName); StringWriter sw = new StringWriter(); PrintWriter out = new PrintWriter(sw); out.println("# MBEAN"); out.println(objectName.toString()); out.println(); out.println("## OPERATIONS"); List<MBeanOperationInfo> operations = Arrays.asList(mbeanInfo.getOperations()); Collections.sort( operations, new Comparator<MBeanOperationInfo>() { @Override public int compare(MBeanOperationInfo o1, MBeanOperationInfo o2) { return o1.getName().compareTo(o1.getName()); } }); for (MBeanOperationInfo opInfo : operations) { out.print("* " + opInfo.getName() + "("); MBeanParameterInfo[] signature = opInfo.getSignature(); for (int i = 0; i < signature.length; i++) { MBeanParameterInfo paramInfo = signature[i]; out.print(paramInfo.getType() + " " + paramInfo.getName()); if (i < signature.length - 1) { out.print(", "); } } out.print("):" + opInfo.getReturnType() /* + " - " + opInfo.getDescription() */); out.println(); } out.println(); out.println("## ATTRIBUTES"); List<MBeanAttributeInfo> attributes = Arrays.asList(mbeanInfo.getAttributes()); Collections.sort( attributes, new Comparator<MBeanAttributeInfo>() { @Override public int compare(MBeanAttributeInfo o1, MBeanAttributeInfo o2) { return o1.getName().compareTo(o2.getName()); } }); for (MBeanAttributeInfo attrInfo : attributes) { out.println( "* " + attrInfo.getName() + ": " + attrInfo.getType() + " - " + (attrInfo.isReadable() ? "r" : "") + (attrInfo.isWritable() ? "w" : "") /* + " - " + attrInfo.getDescription() */); } String description = sw.getBuffer().toString(); return new Result(objectName, description, description); }
protected String renderTemplate(String template) throws Exception { Template t = ve.getTemplate(template); StringWriter sw = new StringWriter(); t.merge(vc, sw); return sw.getBuffer().toString(); }
public String getAggregateResult() { StringBuilder builder = new StringBuilder(); for (StringWriter writer : writers.values()) { builder.append(writer.getBuffer().toString()); } return builder.toString(); }
/** * Exports all data into an OWL API ontology. * * @return OWL ontology. * @throws RepositoryException * @throws MalformedQueryException * @throws QueryEvaluationException * @throws RDFHandlerException * @throws OWLOntologyCreationException */ public OWLOntology exportToOwl() throws RepositoryException, MalformedQueryException, QueryEvaluationException, RDFHandlerException, OWLOntologyCreationException { RepositoryConnection conn = SesameAdapter.getInstance(RepoType.EVALUATION).getRepository().getConnection(); GraphQuery query = conn.prepareGraphQuery(QueryLanguage.SPARQL, "CONSTRUCT {?s ?p ?o} WHERE {?s ?p ?o}"); query.evaluate(); StringWriter strWriter = new StringWriter(); RDFHandler writer = new RDFXMLWriter(strWriter); query.evaluate(writer); strWriter.flush(); StringBuffer buffer = strWriter.getBuffer(); OWLOntology o = OWLManager.createOWLOntologyManager() .loadOntologyFromOntologyDocument( new ReaderDocumentSource(new StringReader(buffer.toString()))); conn.close(); return o; }
public void testStreamArray() throws IOException, JSONException { StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); ProtocolMessageWriter writer = new JsonMessageWriter(printWriter); Display display = new Display(); Shell shell = new Shell(display); writer.appendPayload( WidgetUtil.getId(shell), IProtocolConstants.PAYLOAD_CONSTRUCT, "key", new Integer[] {new Integer(1), new Integer(2)}); writer.appendPayload( WidgetUtil.getId(shell), IProtocolConstants.PAYLOAD_CONSTRUCT, "key2", new Boolean(true)); writer.finish(); String actual = stringWriter.getBuffer().toString(); JSONObject message = new JSONObject(actual); JSONArray widgetArray = message.getJSONArray(IProtocolConstants.MESSAGE_WIDGETS); JSONObject widgetObject = widgetArray.getJSONObject(0); JSONObject payload = widgetObject.getJSONObject(IProtocolConstants.WIDGETS_PAYLOAD); JSONArray array = payload.getJSONArray("key"); assertEquals(1, array.getInt(0)); assertEquals(2, array.getInt(1)); assertTrue(payload.getBoolean("key2")); }
@Override public String format(LogRecord record) { ChatArguments args = LOG_TEMPLATE.getArguments(); ChatArguments level = colorizeLevel(record.getLevel()); args.setPlaceHolder(LEVEL, level); if (record instanceof FormattedLogRecord) { args.setPlaceHolder(MESSAGE, ((FormattedLogRecord) record).getFormattedMessage()); } else { args.setPlaceHolder(MESSAGE, new ChatArguments(super.formatMessage(record) + '\n')); } if (record.getThrown() != null) { StringWriter writer = new StringWriter(); record.getThrown().printStackTrace(new PrintWriter(writer)); String[] lines = writer.getBuffer().toString().split("\n"); for (String line : lines) { args.append( LOG_TEMPLATE .getArguments() .setPlaceHolder(LEVEL, level) .setPlaceHolder(MESSAGE, new ChatArguments(line)) .asString(handlerId)); args.append('\n'); } } args.append(ChatStyle.RESET); return args.asString(handlerId); }
public <T> T sendRequest(Class<T> cls, Object request) throws WasabiNetClientException { StringWriter sw = new StringWriter(); String convertida = null; String received = null; try { marshaller.setWriter(sw); marshaller.marshal(request); convertida = new String(sw.getBuffer().toString().getBytes("UTF8"), "UTF8"); System.out.println(convertida); received = getData(serviceUrl, convertida); System.out.println("---" + received + "---"); unmarshaller.setClass(cls); return (T) unmarshaller.unmarshal(new StringReader(received)); } catch (IOException e) { throw new WasabiNetClientException("Error de lectura/escritura:" + e.getMessage()); } catch (MarshalException e) { e.printStackTrace(); throw new WasabiNetClientException( "Error al armar la respuesta:" + e.getMessage(), convertida, received); } catch (ValidationException e) { throw new WasabiNetClientException( "Error en la validacion de la respuesta:" + e.getMessage(), convertida, received); } // catch WasabiNetClientException -> Esta directamente salta al metodo que ha llamado a // sendrequest }
/** * Serialize the given event data as a standalone XML document * * @param includeProlog if true, include an XML prolog; if not, just render a document fragment * @return the XML serialization, or null if <code>data</code> is null. */ public String serialize(EventDataElement data, boolean includeProlog) { if (data == null || data.isNull()) return null; try { // serialize the DOM to our string buffer. XMLStreamWriter writer = factory.createXMLStreamWriter(buffer); try { if (includeProlog) writer.writeStartDocument(); serializeElement(writer, data); writer.writeEndDocument(); writer.flush(); } finally { writer.close(); } // return buffer contents. return buffer.toString(); } catch (XMLStreamException ioe) { // this shouldn't happen, since the target output stream is a StringWriter, but // the compiler demands that we handle it. throw new RuntimeException("Error serializing XML data", ioe); } finally { // reset the internal buffer for next run. buffer.getBuffer().setLength(0); } }
public void storeMappings(WorkspaceLanguageConfiguration config) throws CoreException { try { // Encode mappings as XML and serialize as a String. Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); Element rootElement = doc.createElement(WORKSPACE_MAPPINGS); doc.appendChild(rootElement); addContentTypeMappings(config.getWorkspaceMappings(), rootElement); Transformer serializer = createSerializer(); DOMSource source = new DOMSource(doc); StringWriter buffer = new StringWriter(); StreamResult result = new StreamResult(buffer); serializer.transform(source, result); String encodedMappings = buffer.getBuffer().toString(); IEclipsePreferences node = InstanceScope.INSTANCE.getNode(CCorePlugin.PLUGIN_ID); node.put(CCorePreferenceConstants.WORKSPACE_LANGUAGE_MAPPINGS, encodedMappings); node.flush(); } catch (ParserConfigurationException e) { throw new CoreException(Util.createStatus(e)); } catch (TransformerException e) { throw new CoreException(Util.createStatus(e)); } catch (BackingStoreException e) { throw new CoreException(Util.createStatus(e)); } }
public String createDrawingXML(String drawing) { try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.newDocument(); Element rootElement = doc.createElement("message"); rootElement.setAttribute("drawing", drawing); rootElement.setAttribute("user", user); rootElement.setAttribute("cmd", "create"); doc.appendChild(rootElement); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(doc), new StreamResult(writer)); String xml = writer.getBuffer().toString().replaceAll("\n|\r", ""); postData(xml); return null; } catch (ParserConfigurationException ex) { Logger.getLogger(XMLManager.class.getName()).log(Level.SEVERE, null, ex); return null; } catch (TransformerConfigurationException ex) { Logger.getLogger(XMLManager.class.getName()).log(Level.SEVERE, null, ex); return null; } catch (TransformerException ex) { Logger.getLogger(XMLManager.class.getName()).log(Level.SEVERE, null, ex); return null; } }
public void xlstCompiledTransformation() throws Exception { String xsltFile = "D:\\JZarzuela\\D_S_Escritorio\\xml\\Sat-cfg.xsl"; String xmlFile = "D:\\JZarzuela\\D_S_Escritorio\\xml\\VariableCFG.xml"; Source xsltSrc = new StreamSource(xsltFile); Source inXML = new StreamSource(new FileInputStream(xmlFile)); StringWriter sw = new StringWriter(); Result outXML = new StreamResult(sw); // Set the TransformerFactory system property to generate and use a translet. // Note: To make this sample more flexible, load properties from a properties file. // The setting for the Xalan Transformer is "org.apache.xalan.processor.TransformerFactoryImpl" // String key = "javax.xml.transform.TransformerFactory"; // String value = "org.apache.xalan.xsltc.trax.TransformerFactoryImpl"; // Properties props = System.getProperties(); // props.put(key, value); // System.setProperties(props); org.apache.xalan.xsltc.trax.TransformerFactoryImpl tFactory = new org.apache.xalan.xsltc.trax.TransformerFactoryImpl(); tFactory.setAttribute(TransformerFactoryImpl.USE_CLASSPATH, Boolean.TRUE); tFactory.setAttribute(TransformerFactoryImpl.PACKAGE_NAME, "com.jzb.xslt.comp"); tFactory.setAttribute(TransformerFactoryImpl.GENERATE_TRANSLET, Boolean.FALSE); Transformer transformer = tFactory.newTransformer(xsltSrc); transformer.setParameter("PARAM_WHICH_CODE", "0001"); // Perform the transformation from a StreamSource to a StreamResult; transformer.transform(inXML, outXML); System.out.println(sw.getBuffer()); }
private String marshal(Object o) { StringWriter w = new StringWriter(); JAXB.marshal(o, w); w.flush(); return w.getBuffer().toString(); }
/* (non-Javadoc) * @see org.jboss.netty.channel.SimpleChannelHandler#messageReceived(org.jboss.netty.channel.ChannelHandlerContext, org.jboss.netty.channel.MessageEvent) */ @Override public void messageReceived(final ChannelHandlerContext context, final MessageEvent e) throws Exception { String decoded; synchronized (stringWriter) { // extract the buffer from the message event final Object message = e.getMessage(); if (!(message instanceof ChannelBuffer)) { context.sendUpstream(e); return; } final ChannelBuffer buffer = (ChannelBuffer) message; if (!buffer.readable()) { return; } // read all bytes from the buffer to the decoder stream final byte[] bytes = new byte[buffer.readableBytes()]; buffer.readBytes(bytes); writerOutputStream.write(bytes); writerOutputStream.flush(); decoded = stringWriter.toString(); stringWriter.getBuffer().setLength(0); } // push all successfully decoded characters upstream Channels.fireMessageReceived(context, decoded, e.getRemoteAddress()); }
public static String stackTraceToString(Throwable e) { StringWriter sw = new StringWriter(); PrintWriter writer = new PrintWriter(sw); e.printStackTrace(writer); writer.close(); return sw.getBuffer().toString(); }
/** * Individua le annotations salvate ed esegue il salvataggio sul dao. * * @param cas CAS da elaborare * @throws AnalysisEngineProcessException errore nell'analisi del documento * @see JCasAnnotator_ImplBase#process(JCas) */ public final void process(final JCas cas) throws AnalysisEngineProcessException { logger.debug("Start process - HpmAnnotator"); String actionType = getActionTypeAnnotation(cas).getValue(); try { // nel caso di PROCESS.PATTERN.CREATE.ATTACHDOCUMENT associo gli // attachments al pattern associato if (actionType.equals(PROCESS_PATTERN_CREATE_ATTACHDOCUMENT)) { processPatternAttachmentCas(cas); } else { processDefaultCas(cas); } } catch (Exception e) { logger.fatal("CAS non elaborata correttamente: "); logger.fatal("Salvataggio della cas " + cas.toString() + " su file"); StringWriter sWriter = new StringWriter(); e.printStackTrace(new PrintWriter(sWriter)); logger.fatal(sWriter.getBuffer().toString()); CasErrorManager cem = new CasErrorManager(); cem.storeCasInFile(cas); throw new AnalysisEngineProcessException(); } logger.debug("End process - HpmAnnotator"); }
@Override public void consumeData(IloOplModel oplModel) throws IOException { StringWriter sw = new StringWriter(); OutputStream os = new WriterOutputStream(sw); super.exportarStream(oplModel, os); stringBuilder.append(sw.getBuffer()); }
@Test public void testLoggin() throws IOException { final StringWriter sw = new StringWriter(); doReturn( new ServletOutputStream() { public void write(int b) throws IOException { sw.write(b); } }) .when(resp) .getOutputStream(); LoggingResponseWrapper lrw = new LoggingResponseWrapper(resp); assertNotNull(lrw); assertNotNull(lrw.getOutputStream()); lrw.getOutputStream().write("this is my body".getBytes()); assertEquals("this is my body", lrw.getResponseBody()); assertEquals("this is my body", sw.getBuffer().toString()); assertNotNull(lrw.getWriter()); }