List of usage examples for javax.xml.stream XMLOutputFactory newInstance
public static XMLOutputFactory newInstance() throws FactoryConfigurationError
From source file:org.apache.axis2.transport.http.ListingAgent.java
public void processListService(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { String url;/*from w w w . j a v a 2 s . c om*/ try { url = req.getRequestURL().toString(); } catch (Throwable t) { log.info("Old Servlet API (Fallback to HttpServletRequest.getRequestURI) :" + t); url = req.getRequestURI(); } String serviceName = extractServiceName(url); HashMap services = configContext.getAxisConfiguration().getServices(); String query = req.getQueryString(); int wsdl2 = query.indexOf("wsdl2"); int wsdl = query.indexOf("wsdl"); int xsd = query.indexOf("xsd"); int policy = query.indexOf("policy"); if ((services != null) && !services.isEmpty()) { Object serviceObj = services.get(serviceName); if (serviceObj != null) { boolean isHttp = "http".equals(req.getScheme()); if (wsdl2 >= 0) { res.setContentType("text/xml"); String ip = extractHostAndPort(url, isHttp); String wsdlName = req.getParameter("wsdl2"); if (wsdlName != null && wsdlName.length() > 0) { InputStream in = ((AxisService) serviceObj).getClassLoader() .getResourceAsStream(DeploymentConstants.META_INF + "/" + wsdlName); if (in != null) { OutputStream out = res.getOutputStream(); out.write(IOUtils.getStreamAsByteArray(in)); out.flush(); out.close(); } else { res.sendError(HttpServletResponse.SC_NOT_FOUND); } } else { OutputStream out = res.getOutputStream(); ((AxisService) serviceObj).printWSDL2(out, ip); out.flush(); out.close(); } return; } else if (wsdl >= 0) { OutputStream out = res.getOutputStream(); res.setContentType("text/xml"); String ip = extractHostAndPort(url, isHttp); String wsdlName = req.getParameter("wsdl"); if (wsdlName != null && wsdlName.length() > 0) { AxisService axisServce = (AxisService) serviceObj; axisServce.printUserWSDL(out, wsdlName); out.flush(); out.close(); } else { ((AxisService) serviceObj).printWSDL(out, ip); out.flush(); out.close(); } return; } else if (xsd >= 0) { res.setContentType("text/xml"); int ret = ((AxisService) serviceObj).printXSD(res.getOutputStream(), req.getParameter("xsd")); if (ret == 0) { //multiple schemas are present and the user specified //no name - in this case we cannot possibly pump a schema //so redirect to the service root res.sendRedirect(""); } else if (ret == -1) { res.sendError(HttpServletResponse.SC_NOT_FOUND); } return; } else if (policy >= 0) { ExternalPolicySerializer serializer = new ExternalPolicySerializer(); serializer .setAssertionsToFilter(configContext.getAxisConfiguration().getLocalPolicyAssertions()); // check whether Id is set String idParam = req.getParameter("id"); if (idParam != null) { // Id is set Policy targetPolicy = findPolicy(idParam, (AxisService) serviceObj); if (targetPolicy != null) { XMLStreamWriter writer; try { OutputStream out = res.getOutputStream(); writer = XMLOutputFactory.newInstance().createXMLStreamWriter(out); res.setContentType("application/wspolicy+xml"); targetPolicy.serialize(writer); writer.flush(); } catch (XMLStreamException e) { throw new ServletException("Error occured when serializing the Policy", e); } catch (FactoryConfigurationError e) { throw new ServletException("Error occured when serializing the Policy", e); } } else { OutputStream out = res.getOutputStream(); res.setContentType("text/html"); String outStr = "<b>No policy found for id=" + idParam + "</b>"; out.write(outStr.getBytes()); } } else { PolicyInclude policyInclude = ((AxisService) serviceObj).getPolicyInclude(); Policy effecPolicy = policyInclude.getEffectivePolicy(); if (effecPolicy != null) { XMLStreamWriter writer; try { OutputStream out = res.getOutputStream(); writer = XMLOutputFactory.newInstance().createXMLStreamWriter(out); res.setContentType("application/wspolicy+xml"); effecPolicy.serialize(writer); writer.flush(); } catch (XMLStreamException e) { throw new ServletException("Error occured when serializing the Policy", e); } catch (FactoryConfigurationError e) { throw new ServletException("Error occured when serializing the Policy", e); } } else { OutputStream out = res.getOutputStream(); res.setContentType("text/html"); String outStr = "<b>No effective policy for " + serviceName + " servcie</b>"; out.write(outStr.getBytes()); } } return; } else { try { req.getSession().setAttribute(Constants.SINGLE_SERVICE, serviceObj); } catch (Throwable t) { log.info("Old Servlet API :" + t); } } } else { try { req.getSession().setAttribute(Constants.SINGLE_SERVICE, null); } catch (Throwable t) { log.info("Old Servlet API :" + t); } res.sendError(HttpServletResponse.SC_NOT_FOUND, url); } } renderView(LIST_SINGLE_SERVICE_JSP_NAME, req, res); }
From source file:org.apache.camel.converter.jaxb.FallbackTypeConverter.java
protected <T> T marshall(Class<T> type, Exchange exchange, Object value) throws JAXBException, XMLStreamException, FactoryConfigurationError { T answer = null;// ww w . j a v a 2 s . c o m if (parentTypeConverter != null) { // lets convert the object to a JAXB source and try convert that to // the required source JAXBContext context = createContext(value.getClass()); // must create a new instance of marshaller as its not thread safe Marshaller marshaller = context.createMarshaller(); Writer buffer = new StringWriter(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, isPrettyPrint() ? Boolean.TRUE : Boolean.FALSE); if (exchange != null && exchange.getProperty(Exchange.CHARSET_NAME, String.class) != null) { marshaller.setProperty(Marshaller.JAXB_ENCODING, exchange.getProperty(Exchange.CHARSET_NAME, String.class)); } if (needFiltering(exchange)) { XMLStreamWriter writer = XMLOutputFactory.newInstance().createXMLStreamWriter(buffer); FilteringXmlStreamWriter filteringWriter = new FilteringXmlStreamWriter(writer); marshaller.marshal(value, filteringWriter); } else { marshaller.marshal(value, buffer); } answer = parentTypeConverter.convertTo(type, buffer.toString()); } return answer; }
From source file:org.apache.camel.converter.jaxb.JaxbDataFormat.java
private FilteringXmlStreamWriter createFilteringWriter(OutputStream stream) throws XMLStreamException, FactoryConfigurationError { XMLStreamWriter writer = XMLOutputFactory.newInstance().createXMLStreamWriter(stream); FilteringXmlStreamWriter filteringWriter = new FilteringXmlStreamWriter(writer); return filteringWriter; }
From source file:org.apache.flex.compiler.config.Configuration.java
/** * @return Metadata XML string./*from w w w . j av a 2 s. c o m*/ */ private final String generateMetadata() { final XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance(); assert xmlOutputFactory != null : "Expect XMLOutputFactory implementation."; final StringWriter stringWriter = new StringWriter(); XMLStreamWriter xmlWriter = null; try { xmlWriter = new XMLFormatter(xmlOutputFactory.createXMLStreamWriter(stringWriter)); xmlWriter.writeStartDocument(); xmlWriter.writeStartElement("rdf", "RDF", RDF_URI); xmlWriter.setPrefix("rdf", RDF_URI); xmlWriter.writeNamespace("rdf", RDF_URI); // write rdf:Description xmlWriter.writeStartElement(RDF_URI, "Description"); xmlWriter.setPrefix("dc", DC_URI); xmlWriter.setPrefix(VersionInfo.COMPILER_NAMESPACE_PREFIX, VersionInfo.COMPILER_NAMESPACE_URI); xmlWriter.writeNamespace("dc", DC_URI); xmlWriter.writeNamespace(VersionInfo.COMPILER_NAMESPACE_PREFIX, VersionInfo.COMPILER_NAMESPACE_URI); // write dc:format xmlWriter.writeStartElement(DC_URI, "format"); xmlWriter.writeCharacters("application/x-shockwave-flash"); xmlWriter.writeEndElement(); if (isFlex()) { // write localizedTitles writeMap(xmlWriter, DC_URI, "description", localizedDescriptions); // write localizedDescription writeMap(xmlWriter, DC_URI, "title", localizedTitles); // write publisher writeCollection(xmlWriter, DC_URI, "publisher", publishers); // write creators writeCollection(xmlWriter, DC_URI, "creator", creators); // write contributor writeCollection(xmlWriter, DC_URI, "contributor", contributors); // write language writeCollection(xmlWriter, DC_URI, "language", langs); // write date writeDate(xmlWriter); } // write compiledBy writeCompiledBy(xmlWriter); // write xmlWriter.writeEndElement(); // Description xmlWriter.writeEndDocument(); } catch (XMLStreamException e) { return ""; } return stringWriter.toString(); }
From source file:org.apache.maven.dotnet.stylecop.StyleCopGenerator.java
/** * Generates the msbuild configuration for a project. * //from w w w .j ava2s .c o m * @param stream */ public void generate(OutputStream stream) { Project project = new Project(); // Properties used PropertyGroup propGroup = new PropertyGroup(); propGroup.setProjectRoot(toWindowsPath(projectRoot)); propGroup.setStyleCopRoot(toWindowsPath(styleCopRoot)); // StyleCop task definition UsingTask usingTask = new UsingTask(); usingTask.setAssemblyFile("$(StyleCopRoot)\\Microsoft.StyleCop.dll"); usingTask.setTaskName("StyleCopTask"); // StyleCop execution target Target target = new Target(); target.setName("CheckStyle"); StyleCopTask task = new StyleCopTask(); task.setFullPath(toWindowsPath(visualSolution)); task.setOutputFile(toWindowsPath(output)); task.setSettingsFile(toWindowsPath(settings)); task.setSourceFiles("@(SourceAnalysisFiles);@(CSFile)"); // Builds the creation item CreateItem createItem = new CreateItem(); createItem.setInclude("%(Project.RootDir)%(Project.Directory)**\\*.cs"); ItemOutput itemOutput = new ItemOutput(); itemOutput.setTaskParameter("Include"); itemOutput.setItemName("SourceAnalysisFiles"); createItem.setOutput(itemOutput); // ItemGroup group = new ItemGroup(); // Adds all the projects files for (File visualProject : visualProjects) { if (visualProject.isDirectory()) { group.addCsFiles(visualProject + "\\**\\*.cs"); } else { group.addProject(toWindowsPath(visualProject)); } } // Populates the task target.setItem(createItem); target.setStyleCopTask(task); // Finishes the project project.setUsingTask(usingTask); project.setPropertyGroup(propGroup); project.setDefaultTargets("CheckStyle"); project.setToolsVersion("3.5"); project.addItem(group); project.addTarget(target); XMLOutputFactory xof = XMLOutputFactory.newInstance(); StringWriter writer = new StringWriter(); XMLStreamWriter xtw = null; try { // Gets control of the generated namespaces xtw = xof.createXMLStreamWriter(writer); xtw.setNamespaceContext(new NamespaceContext() { @Override public Iterator getPrefixes(String arg0) { return null; } @Override public String getPrefix(String arg0) { if (STYLE_COP_NAMESPACE.equals(arg0)) { return "stylecop"; } return null; } @Override public String getNamespaceURI(String arg0) { return null; } }); // Establish a jaxb context JAXBContext jc = JAXBContext.newInstance(Project.class); // Get a marshaller Marshaller m = jc.createMarshaller(); // Enable formatted xml output m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // Marshal to system output: java to xml m.marshal(project, xtw); } catch (Exception e) { log.debug("Generation error", e); } String xmlContent = writer.toString(); // Due to a bug of missing feature in JAXB, I could not generate an XML file // having the default XML namespace // of stylecop (it defines the objects in a namespace that is not the // default). // The problem is that MSBuild is non fully XML compliant and requires the // stylecop namespace as being explicitely // the default one for the file. This is achived by hand-made replacement in // hte generated file, hoping for something // more robust later. String temp = StringUtils.replace(xmlContent, "xmlns=\"\"", "xmlns=\"" + STYLE_COP_NAMESPACE + "\""); String result = StringUtils.replace(temp, "stylecop:Project", "Project"); PrintWriter outputWriter = new PrintWriter(stream); outputWriter.print(result); outputWriter.flush(); }
From source file:org.apache.olingo.fit.utils.AbstractXMLUtilities.java
protected static XMLEventWriter getEventWriter(final OutputStream os) throws XMLStreamException { if (ofactory == null) { ofactory = XMLOutputFactory.newInstance(); }//from ww w .ja v a 2 s . co m return ofactory.createXMLEventWriter(os); }
From source file:org.apache.olingo.fit.utils.XMLUtilities.java
protected static XMLEventWriter getEventWriter(final OutputStream os) throws XMLStreamException { if (ofactory == null) { ofactory = XMLOutputFactory.newInstance(); }// w ww.j av a 2 s .c o m return ofactory.createXMLEventWriter(os, "UTF-8"); }
From source file:org.apache.synapse.mediators.builtin.ValidateMediator.java
public boolean mediate(SynapseContext synCtx) { ByteArrayInputStream baisFromSource = null; StringBuffer nsLocations = new StringBuffer(); try {/*from w ww.j a v a 2 s . c o m*/ // create a byte array output stream and serialize the source node into it ByteArrayOutputStream baosForSource = new ByteArrayOutputStream(); XMLStreamWriter xsWriterForSource = XMLOutputFactory.newInstance().createXMLStreamWriter(baosForSource); // save the list of defined namespaces for validation against the schema OMNode sourceNode = getValidateSource(synCtx.getSynapseMessage()); if (sourceNode instanceof OMElement) { Iterator iter = ((OMElement) sourceNode).getAllDeclaredNamespaces(); while (iter.hasNext()) { OMNamespace omNS = (OMNamespace) iter.next(); nsLocations.append(omNS.getName() + " " + getSchemaUrl()); } } sourceNode.serialize(xsWriterForSource); baisFromSource = new ByteArrayInputStream(baosForSource.toByteArray()); } catch (Exception e) { String msg = "Error accessing source element for validation : " + source; log.error(msg); throw new SynapseException(msg, e); } try { SAXParserFactory spFactory = SAXParserFactory.newInstance(); spFactory.setNamespaceAware(true); spFactory.setValidating(true); SAXParser parser = spFactory.newSAXParser(); parser.setProperty(VALIDATION, Boolean.TRUE); parser.setProperty(SCHEMA_VALIDATION, Boolean.TRUE); parser.setProperty(FULL_CHECKING, Boolean.TRUE); parser.setProperty(SCHEMA_LOCATION_NS, nsLocations.toString()); parser.setProperty(SCHEMA_LOCATION_NO_NS, getSchemaUrl()); Validator handler = new Validator(); parser.parse(baisFromSource, handler); if (handler.isValidationError()) { log.debug("Validation failed :" + handler.getSaxParseException().getMessage()); // super.mediate() invokes the "on-fail" sequence of mediators return super.mediate(synCtx); } } catch (Exception e) { String msg = "Error validating " + source + " against schema : " + schemaUrl + " : " + e.getMessage(); log.error(msg); throw new SynapseException(msg, e); } return true; }
From source file:org.apache.synapse.mediators.validate.ValidateMediator.java
public boolean mediate(MessageContext synCtx) { log.debug("ValidateMediator - Validate mediator mediate()"); ByteArrayInputStream baisFromSource = null; boolean shouldTrace = shouldTrace(synCtx.getTracingState()); if (shouldTrace) { trace.trace("Start : Validate mediator"); }// w w w . j av a2s . co m try { // create a byte array output stream and serialize the source node into it ByteArrayOutputStream baosForSource = new ByteArrayOutputStream(); XMLStreamWriter xsWriterForSource = XMLOutputFactory.newInstance().createXMLStreamWriter(baosForSource); // serialize the validation target and get an input stream into it OMNode validateSource = getValidateSource(synCtx); if (shouldTrace) { trace.trace("Validate Source : " + validateSource.toString()); } validateSource.serialize(xsWriterForSource); baisFromSource = new ByteArrayInputStream(baosForSource.toByteArray()); } catch (Exception e) { handleException("Error accessing source element for validation : " + source, e); } try { XMLReader reader = XMLReaderFactory.createXMLReader(); SAXSource saxSrc = new SAXSource(reader, new InputSource(baisFromSource)); synchronized (validatorLock) { // initialize schemas/Validator if required initialize(synCtx); // perform actual validation validator.validate(saxSrc); if (errorHandler.isValidationError()) { if (log.isDebugEnabled()) { log.debug("Validation of element returned by XPath : " + source + " failed against the given schemas with Message : " + errorHandler.getSaxParseException().getMessage() + " Executing 'on-fail' sequence"); log.debug("Failed message envelope : " + synCtx.getEnvelope()); } // super.mediate() invokes the "on-fail" sequence of mediators if (shouldTrace) { trace.trace("Validation failed. Invoking the \"on-fail\" " + "sequence of mediators"); } return super.mediate(synCtx); } } } catch (SAXException e) { handleException("Error validating " + source + " element" + e.getMessage(), e); } catch (IOException e) { handleException("Error validating " + source + " element" + e.getMessage(), e); } log.debug("validation of element returned by the XPath expression : " + source + " succeeded against the given schemas and the current message"); if (shouldTrace) { trace.trace("End : Validate mediator"); } return true; }
From source file:org.asimba.wa.integrationtest.saml2.model.AuthnRequest.java
/** * Get String with the SAML2 AuthnRequest message * @param format -1=plain, 1=base64/*from w w w . j a v a 2 s .c o m*/ * @return * @throws XMLStreamException * @throws IOException */ public String getRequest(int format) throws XMLStreamException, IOException { _logger.info("For ID: " + this._id); ByteArrayOutputStream baos = new ByteArrayOutputStream(); Deflater compresser = new Deflater(Deflater.BEST_COMPRESSION, true); DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(baos, compresser); StringWriter sw = new StringWriter(); XMLOutputFactory factory = XMLOutputFactory.newInstance(); XMLStreamWriter writer = null; // ugly but effective: if (format == base64) { writer = factory.createXMLStreamWriter(deflaterOutputStream); } else { writer = factory.createXMLStreamWriter(sw); } writer.writeStartElement("samlp", "AuthnRequest", "urn:oasis:names:tc:SAML:2.0:protocol"); writer.writeNamespace("samlp", "urn:oasis:names:tc:SAML:2.0:protocol"); writer.writeAttribute("ID", _id); writer.writeAttribute("Version", "2.0"); writer.writeAttribute("IssueInstant", this._issueInstant); writer.writeAttribute("ProtocolBinding", "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"); writer.writeAttribute("AssertionConsumerServiceURL", _acsUrl); writeIssuer(writer); writeNameIDPolicy(writer); writeRequestedAuthnContext(writer); writer.writeEndElement(); writer.flush(); if (format == base64) { deflaterOutputStream.close(); byte[] bain = baos.toByteArray(); byte[] encoded = Base64.encodeBase64(bain, false); String result = new String(encoded, Charset.forName("UTF-8")); return result; } else { return sw.toString(); } }