List of usage examples for java.io StringWriter getBuffer
public StringBuffer getBuffer()
From source file:ddf.catalog.transformer.xml.XmlResponseQueueTransformer.java
@Override public BinaryContent transform(SourceResponse response, Map<String, Serializable> args) throws CatalogTransformerException { try {//from w w w. ja va 2s. c o m Writer stringWriter = new StringWriter(BUFFER_SIZE); stringWriter.append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"); MetacardPrintWriter writer = new MetacardPrintWriter(stringWriter); writer.startNode("metacards"); for (Map.Entry<String, String> nsRow : NAMESPACE_MAP.entrySet()) { writer.addAttribute(nsRow.getKey(), nsRow.getValue()); } if (response.getResults() != null && !response.getResults().isEmpty()) { StringWriter metacardContent = fjp.invoke(new MetacardForkTask( ImmutableList.copyOf(response.getResults()), fjp, geometryTransformer, threshold)); writer.setRawValue(metacardContent.getBuffer().toString()); } writer.endNode(); // metacards ByteArrayInputStream bais = new ByteArrayInputStream(stringWriter.toString().getBytes()); return new BinaryContentImpl(bais, MIME_TYPE); } catch (Exception e) { LOGGER.info("Failed Query response transformation", e); throw new CatalogTransformerException("Failed Query response transformation"); } }
From source file:Repackage.java
StringBuffer readFile(File f) throws IOException { InputStream in = new FileInputStream(f); Reader r = new InputStreamReader(in); StringWriter w = new StringWriter(); copy(r, w);/*from w w w. ja va 2 s . co m*/ w.close(); r.close(); in.close(); return w.getBuffer(); }
From source file:com.nanyou.framework.jdbc.sql.dynamic.DynamicSql.java
private void processBodyChildren(SqlTagContext ctx, Object parameterObject, Iterator localChildren, PrintWriter out) {//from ww w .java 2s . c om while (localChildren.hasNext()) { SqlChild child = (SqlChild) localChildren.next(); if (child instanceof SqlText) { SqlText sqlText = (SqlText) child; String sqlStatement = sqlText.getText(); out.println(sqlStatement); } else if (child instanceof SqlTag) { SqlTag tag = (SqlTag) child; SqlTagHandler handler = tag.getHandler(); int response = SqlTagHandler.INCLUDE_BODY; do { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); response = handler.doStartFragment(ctx, tag, parameterObject); if (response != SqlTagHandler.SKIP_BODY) { processBodyChildren(ctx, parameterObject, tag.getChildren(), pw); pw.flush(); pw.close(); StringBuffer body = sw.getBuffer(); response = handler.doEndFragment(ctx, tag, parameterObject, body); handler.doPrepend(ctx, tag, parameterObject, body); if (response != SqlTagHandler.SKIP_BODY) { if (body.length() > 0) { out.println(body.toString()); } } } } while (response == SqlTagHandler.REPEAT_BODY); ctx.popRemoveFirstPrependMarker(tag); if (ctx.peekIterateContext() != null && ctx.peekIterateContext().getTag() == tag) { ctx.setAttribute(ctx.peekIterateContext().getTag(), null); ctx.popIterateContext(); } } } }
From source file:nz.co.senanque.sandbox.ObjectTest.java
@Test public void test1() throws Exception { @SuppressWarnings("unused") Object en = IndustryType.fromValue("Ag"); ValidationSession validationSession = m_validationEngine.createSession(); // create a customer Customer customer = m_customerDAO.createCustomer(); validationSession.bind(customer);// w w w .ja v a 2 s. c o m Invoice invoice = new Invoice(); invoice.setDescription("test invoice"); invoice.setTestBoolean(true); customer.getInvoices().add(invoice); boolean exceptionFound = false; try { customer.setName("ttt"); } catch (ValidationException e) { exceptionFound = true; } assertTrue(exceptionFound); final ObjectMetadata customerMetadata = validationSession.getMetadata(customer); @SuppressWarnings("unused") final FieldMetadata customerTypeMetadata = customerMetadata.getFieldMetadata(Customer.CUSTOMERTYPE); // assertFalse(customerTypeMetadata.isActive()); // assertFalse(customerTypeMetadata.isReadOnly()); // assertFalse(customerTypeMetadata.isRequired()); customer.setName("aaaab"); exceptionFound = false; try { customer.setCustomerType("B"); } catch (Exception e) { exceptionFound = true; } // assertTrue(exceptionFound); exceptionFound = false; try { customer.setCustomerType("XXX"); } catch (Exception e) { exceptionFound = true; } assertTrue(exceptionFound); customer.setBusiness(IndustryType.AG); customer.setAmount(new Double(500.99)); final long id = m_customerDAO.save(customer); log.info("{}", id); // fetch customer back customer = m_customerDAO.getCustomer(id); @SuppressWarnings("unused") final int invoiceCount = customer.getInvoices().size(); validationSession.bind(customer); invoice = new Invoice(); ValidationUtils.setDefaults(invoice); invoice.setDescription("test invoice2"); invoice.setTestBoolean(true); customer.getInvoices().add(invoice); assertEquals("xyz", invoice.getTestDefault()); assertEquals("Ag", invoice.getTestEnumDefault().value()); m_customerDAO.save(customer); // fetch customer again customer = m_customerDAO.getCustomer(id); customer.toString(); final Invoice inv0 = customer.getInvoices().get(0); assertTrue(inv0.isTestBoolean()); validationSession.bind(customer); final Invoice inv = customer.getInvoices().get(0); assertTrue(inv.isTestBoolean()); customer.getInvoices().remove(inv); //ObjectMetadata metadata = validationSession.getMetadata(customer); ObjectMetadata metadata = customer.getMetadata(); assertEquals("this is a description", metadata.getFieldMetadata(Customer.NAME).getDescription()); assertEquals("ABC", metadata.getFieldMetadata(Customer.NAME).getPermission()); @SuppressWarnings("unused") List<ChoiceBase> choices = metadata.getFieldMetadata(Customer.BUSINESS).getChoiceList(); // assertEquals(1,choices.size()); List<ChoiceBase> choices2 = metadata.getFieldMetadata(Customer.CUSTOMERTYPE).getChoiceList(); // assertEquals(1,choices2.size()); choices2 = metadata.getFieldMetadata(Customer.CUSTOMERTYPE).getChoiceList(); // assertEquals(1,choices2.size()); for (ChoiceBase choice : choices2) { System.out.println(choice.getDescription()); } customer.setName("aab"); choices2 = metadata.getFieldMetadata(Customer.CUSTOMERTYPE).getChoiceList(); // assertEquals(6,choices2.size()); // Convert customer to XML QName qname = new QName("http://www.example.org/sandbox", "Session"); JAXBElement<Session> sessionJAXB = new JAXBElement<Session>(qname, Session.class, new Session()); sessionJAXB.getValue().getCustomers().add(customer); //??This fails to actually add StringWriter marshallWriter = new StringWriter(); Result marshallResult = new StreamResult(marshallWriter); m_marshaller.marshal(sessionJAXB, marshallResult); marshallWriter.flush(); String result = marshallWriter.getBuffer().toString().trim(); String xml = result.replaceAll("\\Qhttp://www.example.org/sandbox\\E", "http://www.example.org/sandbox"); log.info("{}", xml); // Convert customer back to objects SAXBuilder builder = new SAXBuilder(); org.jdom.Document resultDOM = builder.build(new StringReader(xml)); @SuppressWarnings("unchecked") JAXBElement<Session> request = (JAXBElement<Session>) m_unmarshaller.unmarshal(new JDOMSource(resultDOM)); validationSession = m_validationEngine.createSession(); validationSession.bind(request.getValue()); assertEquals(3, validationSession.getProxyCount()); List<Customer> customers = request.getValue().getCustomers(); assertEquals(1, customers.size()); assertTrue(customers.get(0).getInvoices().get(0).isTestBoolean()); customers.clear(); assertEquals(1, validationSession.getProxyCount()); request.toString(); validationSession.close(); }
From source file:org.apache.accumulo.core.file.rfile.MultiThreadedRFileTest.java
@SuppressFBWarnings(value = "INFORMATION_EXPOSURE_THROUGH_AN_ERROR_MESSAGE", justification = "information put into error message is safe and used for testing") @Test//from w w w . j a v a 2 s. co m public void testMultipleReaders() throws IOException { final List<Throwable> threadExceptions = Collections.synchronizedList(new ArrayList<Throwable>()); Map<String, MutableInt> messages = new HashMap<>(); Map<String, String> stackTrace = new HashMap<>(); final TestRFile trfBase = new TestRFile(conf); writeData(trfBase); trfBase.openReader(); try { validate(trfBase); final TestRFile trfBaseCopy = trfBase.deepCopy(); validate(trfBaseCopy); // now start up multiple RFile deepcopies int maxThreads = 10; String name = "MultiThreadedRFileTestThread"; ThreadPoolExecutor pool = new ThreadPoolExecutor(maxThreads + 1, maxThreads + 1, 5 * 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>(), new NamingThreadFactory(name)); pool.allowCoreThreadTimeOut(true); try { Runnable runnable = () -> { try { TestRFile trf = trfBase; synchronized (trfBaseCopy) { trf = trfBaseCopy.deepCopy(); } validate(trf); } catch (Throwable t) { threadExceptions.add(t); } }; for (int i = 0; i < maxThreads; i++) { pool.submit(runnable); } } finally { pool.shutdown(); try { pool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { e.printStackTrace(); } } for (Throwable t : threadExceptions) { String msg = t.getClass() + " : " + t.getMessage(); if (!messages.containsKey(msg)) { messages.put(msg, new MutableInt(1)); } else { messages.get(msg).increment(); } StringWriter string = new StringWriter(); PrintWriter writer = new PrintWriter(string); t.printStackTrace(writer); writer.flush(); stackTrace.put(msg, string.getBuffer().toString()); } } finally { trfBase.closeReader(); trfBase.close(); } for (String message : messages.keySet()) { LOG.error(messages.get(message) + ": " + message); LOG.error(stackTrace.get(message)); } assertTrue(threadExceptions.isEmpty()); }
From source file:de.griffel.confluence.plugins.plantuml.PlantUmlMacro.java
private String render(final String umlBlock, final PageContext pageContext, final PlantUmlMacroParams macroParams, final PlantUmlPreprocessor preprocessor) throws IOException, UnauthorizedDownloadResourceException, DownloadResourceNotFoundException { final FileFormat fileFormat = macroParams.getFileFormat(pageContext); final List<String> config = new PlantUmlConfigBuilder().build(macroParams); final MySourceStringReader reader = new MySourceStringReader(new Defines(), umlBlock, config); final StringBuilder sb = new StringBuilder(); if (preprocessor.hasExceptions()) { sb.append("<span class=\"error\">"); for (PreprocessingException exception : preprocessor.getExceptions()) { sb.append("<span class=\"error\">"); sb.append("plantuml: "); sb.append(exception.getDetails()); sb.append("</span><br/>"); }//from w ww . j a va2 s. c o m sb.append("</span>"); } while (reader.hasNext()) { final DownloadResourceWriter resourceWriter = writeableDownloadResourceManager.getResourceWriter( AuthenticatedUserThreadLocal.getUsername(), "plantuml", fileFormat.getFileSuffix()); final ImageInfo imageInfo = reader.renderImage(resourceWriter.getStreamForWriting(), fileFormat); final ImageMap cmap = imageInfo.getImageMap(); if (cmap.isValid()) { sb.append(cmap.toHtmlString()); } if (umlBlock.matches(PlantUmlPluginInfo.PLANTUML_VERSION_INFO_REGEX)) { sb.append(new PlantUmlPluginInfo(pluginAccessor, i18NBeanFactory.getI18NBean()).toHtmlString()); } final DownloadResourceInfo resourceInfo; if (macroParams.getExportName() != null && !preprocessor.hasExceptions()) { resourceInfo = attachImage(pageContext.getEntity(), macroParams, imageInfo, fileFormat, resourceWriter); } else { resourceInfo = new DefaultDownloadResourceInfo(writeableDownloadResourceManager, resourceWriter); } if (FileFormat.SVG == fileFormat) { final StringWriter sw = new StringWriter(); IOUtils.copy(resourceInfo.getStreamForReading(), sw); sb.append(sw.getBuffer()); } else /* PNG */ { sb.append("<span class=\"image-wrap\" style=\"").append(macroParams.getAlignment().getCssStyle()) .append("\">"); sb.append("<img"); if (cmap.isValid()) { sb.append(" usemap=\"#"); sb.append(cmap.getId()); sb.append("\""); } sb.append(" src='"); sb.append(resourceInfo.getDownloadPath()); sb.append("'"); sb.append(macroParams.getImageStyle()); sb.append("/>"); sb.append("</span>"); } } if (macroParams.isDebug()) { sb.append("<div class=\"puml-debug\">"); sb.append("<pre>"); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); HexDump.dump(umlBlock.getBytes("UTF-8"), 0, baos, 0); sb.append(baos.toString()); // HexDump class writer bytes with JVM default encoding sb.append("</pre>"); sb.append("</div>"); } return sb.toString(); }
From source file:org.hexlogic.CooptoPluginFactory.java
@Override public QueryResult findAll(String type, String query) { log.debug("running findAll() with type=" + type + " and query=" + query + "."); QueryResult qr = new QueryResult(); if (type.equals(DockerNode.TYPE)) { try {/*from w w w . j av a2 s .c o m*/ // try to load from EndpointConfiguration if empty if (nodes.isEmpty()) { log.warn("Unable to find " + type + " in cache."); this.rebuildCache(); } else { log.debug("Found " + type + " in cache."); } // try to find in cache - must be in synchronized block synchronized (nodes) { Iterator<DockerNode> itr = nodes.iterator(); while (itr.hasNext()) { DockerNode node = itr.next(); if (node != null) { qr.addElement(node); } } } } catch (Exception e) { final StringWriter sw = new StringWriter(); final PrintWriter pw = new PrintWriter(sw, true); e.printStackTrace(pw); log.error("Error: " + sw.getBuffer().toString()); } } else if (type.equals(DockerImage.TYPE)) { try { // try to find in cache - must be in synchronized block synchronized (nodes) { Iterator<DockerNode> itr = nodes.iterator(); while (itr.hasNext()) { DockerNode node = itr.next(); if (node != null) { List<DockerImage> children = node.getImages(); qr.addElements(children); } } } log.debug("Found children: " + qr); } catch (Exception e) { final StringWriter sw = new StringWriter(); final PrintWriter pw = new PrintWriter(sw, true); e.printStackTrace(pw); log.error("Error: " + sw.getBuffer().toString()); } } else if (type.equals(DockerContainer.TYPE)) { try { // try to find in cache - must be in synchronized block synchronized (nodes) { Iterator<DockerNode> itr = nodes.iterator(); while (itr.hasNext()) { DockerNode node = itr.next(); if (node != null) { List<DockerContainer> container = node.getContainers(); qr.addElements(container); } } } log.debug("Found children: " + qr); } catch (Exception e) { final StringWriter sw = new StringWriter(); final PrintWriter pw = new PrintWriter(sw, true); e.printStackTrace(pw); log.error("Error: " + sw.getBuffer().toString()); } } return qr; }
From source file:a1deployer.Axis1Deployer.java
public void deploy(DeploymentFileData deploymentFileData) throws DeploymentException { log.info("Deploying - " + deploymentFileData.getName()); ClassLoader threadClassLoader = Thread.currentThread().getContextClassLoader(); try {// w ww .j av a 2 s. co m File file = deploymentFileData.getFile(); File parentFile = file.getParentFile(); ClassLoader classLoader = Utils.getClassLoader(configCtx.getAxisConfiguration().getSystemClassLoader(), parentFile); Thread.currentThread().setContextClassLoader(classLoader); FileProvider config = new FileProvider(deploymentFileData.getAbsolutePath()); AxisServer server = new AxisServer(config); WSDLSupplier supplier = new A1WSDLSupplier(server); config.getDeployedServices(); // ensure everything's set up WSDDService[] services = config.getDeployment().getServices(); AxisServiceGroup serviceGroup = new AxisServiceGroup(); serviceGroup.addParameter("service.axis1.server", server); for (int i = 0; i < services.length; i++) { ServiceDesc service = services[i].getServiceDesc(); log.info("Deploying Axis1 service -- " + service.getName()); AxisService axisService; org.apache.axis.MessageContext mc = new MessageContext(server); String wsdlString; try { mc.setTargetService(service.getName()); mc.setProperty(MessageContext.TRANS_URL, REPLACEME); server.generateWSDL(mc); Document wsdlDoc = (Document) mc.getProperty("WSDL"); wsdlString = DOM2Writer.nodeToString(wsdlDoc, true); } catch (Exception e) { log.error(e); continue; } try { ByteArrayInputStream bis = new ByteArrayInputStream(wsdlString.getBytes()); WSDL11ToAxisServiceBuilder builder = new WSDL11ToAxisServiceBuilder(bis); axisService = builder.populateService(); axisService.getEndpoints().clear(); axisService.setBindingName(null); axisService.setEndpointName(null); } catch (Exception e) { String serviceName = service.getName(); if (REPLACEME.equals(service.getDefaultNamespace())) { service.setDefaultNamespace(null); } log.info("Couldn't process WSDL for Axis1 service '" + serviceName + "', defaulting to passthrough mode."); // Couldn't process WSDL (RPC/enc?), so set up passthrough axisService = new AxisService(serviceName); // Ensure dispatch works. axisService.addParameter("supportSingleOperation", Boolean.TRUE); // Add WSDL supplier axisService.addParameter("WSDLSupplier", supplier); AxisOperation op = new InOutAxisOperation(new QName("invokeAxis1Service")); op.setDocumentation("This operation is a 'passthrough' for all operations in " + "an RPC/encoded Axis1 service."); axisService.addOperation(op); } axisService.setName(service.getName()); axisService.setClassLoader(classLoader); // Put all the parameters from the A1 service into the A2 service Hashtable params = services[i].getParametersTable(); Enumeration paramKeys = params.keys(); while (paramKeys.hasMoreElements()) { String key = (String) paramKeys.nextElement(); axisService.addParameter(key, params.get(key)); } Axis1InOutMessageReceiver receiver = new Axis1InOutMessageReceiver(); AxisConfiguration axisConfig = configCtx.getAxisConfiguration(); PhasesInfo phaseInfo = axisConfig.getPhasesInfo(); for (Iterator ops = axisService.getOperations(); ops.hasNext();) { AxisOperation op = (AxisOperation) ops.next(); op.setMessageReceiver(receiver); phaseInfo.setOperationPhases(op); } // axisService.addMessageReceiver(WSDL2Constants.MEP_URI_IN_OUT, // new Axis1InOutMessageReceiver()); // Add service type axisService.addParameter("serviceType", "axis1_service"); axisService.setFileName(deploymentFileData.getFile().toURL()); axisService.addParameterObserver(new Axis1ParameterObserver(service)); serviceGroup.addService(axisService); } serviceGroup.setServiceGroupName(deploymentFileData.getName()); configCtx.getAxisConfiguration().addServiceGroup(serviceGroup); } catch (ConfigurationException e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); // If we get here, we couldn't start the AxisServer, so create a faulty service configCtx.getAxisConfiguration().getFaultyServices().put(deploymentFileData.getFile().getAbsolutePath(), sw.getBuffer().toString()); throw new DeploymentException(e); } catch (AxisFault e) { throw new DeploymentException(e); } catch (MalformedURLException e) { throw new DeploymentException(e); } finally { if (threadClassLoader != null) { Thread.currentThread().setContextClassLoader(threadClassLoader); } } }
From source file:org.hexlogic.CooptoPluginFactory.java
@Override public Object find(InventoryRef ref) { log.debug("running find() with id=" + ref.getId() + " and type=" + ref.getType() + "."); if (ref.isOfType(DockerNode.TYPE)) { try {/*from ww w.j av a 2 s. c o m*/ for (int i = 0; i < 2; i++) { // try to find in cache - must be in synchronized block synchronized (nodes) { Iterator<DockerNode> itr = nodes.iterator(); while (itr.hasNext()) { DockerNode node = itr.next(); log.debug("Checking cache. Current node: " + node.getId() + "."); if (node.getId().equals(ref.getId())) { log.debug("Found node '" + ref.getId() + "' in cache."); return node; } } } // if not found in cache, refresh and try again one more time if (i < 1) { log.warn("Unable to find node '" + ref.getId() + "' in cache."); this.rebuildCache(); } else { log.warn("Unable to find node '" + ref.getId() + "' after reloading cache."); } } } catch (Exception e) { final StringWriter sw = new StringWriter(); final PrintWriter pw = new PrintWriter(sw, true); e.printStackTrace(pw); log.error("Error: " + sw.getBuffer().toString()); } } else if (ref.isOfType(DockerImage.TYPE)) { try { // try to find in cache - must be in synchronized block synchronized (nodes) { Iterator<DockerNode> itr = nodes.iterator(); while (itr.hasNext()) { DockerNode node = itr.next(); DockerImage image = node.getImage(ref.getId()); if (image != null) { log.debug("Found " + ref.getType() + " '" + ref.getId() + "' in cache."); return image; } } } // getImage will also run reloadImages on it's node if not found, thus we don't have to handle that here. If it's not returned by getImage, it dosn't exist. log.warn("Unable to find " + ref.getType() + " '" + ref.getId() + "'."); //TODO dunno what should be returned if the item was not found. currently we end up with a [EMPTY_NODE] item in the inventory, even after we already called notifyDeleted in order to inform the inventory about the deleted object } catch (Exception e) { final StringWriter sw = new StringWriter(); final PrintWriter pw = new PrintWriter(sw, true); e.printStackTrace(pw); log.error("Error: " + sw.getBuffer().toString()); } } else if (ref.isOfType(DockerContainer.TYPE)) { try { // try to find in cache - must be in synchronized block synchronized (nodes) { Iterator<DockerNode> itr = nodes.iterator(); while (itr.hasNext()) { DockerNode node = itr.next(); DockerContainer container = node.getContainer(ref.getId()); if (container != null) { log.debug("Found " + ref.getType() + " '" + ref.getId() + "' in cache."); return container; } } } // getContainer will also run reloadContainers on it's node if not found, thus we don't have to handle that here. If it's not returned by getContainer, it dosn't exist. log.warn("Unable to find " + ref.getType() + " '" + ref.getId() + "'."); //TODO dunno what should be returned if the item was not found. currently we end up with a [EMPTY_NODE] item in the inventory, even after we already called notifyDeleted in order to inform the inventory about the deleted object } catch (Exception e) { final StringWriter sw = new StringWriter(); final PrintWriter pw = new PrintWriter(sw, true); e.printStackTrace(pw); log.error("Error: " + sw.getBuffer().toString()); } } return null; }
From source file:com.cloudera.flume.reporter.ReportEvent.java
/** * Returns event as HTML string//from w w w . j av a 2 s . c o m */ public String toHtml() { StringWriter sw = new StringWriter(); try { toHtml(sw); } catch (IOException e) { LOG.error("String writer should never throw IOException", e); return null; } return sw.getBuffer().toString(); }