Example #1
0
 private void checkCachedStream(Message m, OutputStream osOriginal, boolean enabled)
     throws Exception {
   XMLStreamWriter writer = null;
   if (enabled) {
     writer = m.getContent(XMLStreamWriter.class);
   } else {
     writer = (XMLStreamWriter) m.get(XMLStreamWriter.class.getName());
   }
   if (writer instanceof CachingXmlEventWriter) {
     CachingXmlEventWriter cache = (CachingXmlEventWriter) writer;
     if (cache.getEvents().size() != 0) {
       XMLStreamWriter origWriter = null;
       try {
         origWriter = StaxUtils.createXMLStreamWriter(osOriginal);
         for (XMLEvent event : cache.getEvents()) {
           StaxUtils.writeEvent(event, origWriter);
         }
       } finally {
         StaxUtils.close(origWriter);
       }
     }
     m.setContent(XMLStreamWriter.class, null);
     return;
   }
   if (enabled) {
     OutputStream os = m.getContent(OutputStream.class);
     if (os != osOriginal && os instanceof CachedOutputStream) {
       CachedOutputStream cos = (CachedOutputStream) os;
       if (cos.size() != 0) {
         cos.writeCacheTo(osOriginal);
       }
     }
   }
 }
Example #2
0
 protected Object unmarshalFromInputStream(
     Unmarshaller unmarshaller, InputStream is, Annotation[] anns, MediaType mt)
     throws JAXBException {
   // Try to create the read before unmarshalling the stream
   XMLStreamReader xmlReader = null;
   try {
     if (is == null) {
       Reader reader = getStreamHandlerFromCurrentMessage(Reader.class);
       if (reader == null) {
         LOG.severe("No InputStream, Reader, or XMLStreamReader is available");
         throw ExceptionUtils.toInternalServerErrorException(null, null);
       }
       xmlReader = StaxUtils.createXMLStreamReader(reader);
     } else {
       xmlReader = StaxUtils.createXMLStreamReader(is);
     }
     configureReaderRestrictions(xmlReader);
     return unmarshaller.unmarshal(xmlReader);
   } finally {
     try {
       StaxUtils.close(xmlReader);
     } catch (XMLStreamException e) {
       // Ignore
     }
   }
 }
  private void doFromSoapMessage(Message message, Object sm) {
    SOAPMessage m = (SOAPMessage) sm;
    MessageContentsList list = (MessageContentsList) message.getContent(List.class);
    if (list == null) {
      list = new MessageContentsList();
      message.setContent(List.class, list);
    }
    Object o = m;

    if (StreamSource.class.isAssignableFrom(type)) {
      try {
        try (CachedOutputStream out = new CachedOutputStream()) {
          XMLStreamWriter xsw = StaxUtils.createXMLStreamWriter(out);
          StaxUtils.copy(new DOMSource(m.getSOAPPart()), xsw);
          xsw.close();
          o = new StreamSource(out.getInputStream());
        }
      } catch (Exception e) {
        throw new Fault(e);
      }
    } else if (SAXSource.class.isAssignableFrom(type)) {
      o = new StaxSource(new W3CDOMStreamReader(m.getSOAPPart()));
    } else if (Source.class.isAssignableFrom(type)) {
      o = new DOMSource(m.getSOAPPart());
    }
    list.set(0, o);
  }
Example #4
0
 private byte[] getMessageBytes(Document doc) throws Exception {
   ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
   XMLStreamWriter byteArrayWriter = StaxUtils.createXMLStreamWriter(outputStream);
   StaxUtils.writeDocument(doc, byteArrayWriter, false);
   byteArrayWriter.flush();
   return outputStream.toByteArray();
 }
Example #5
0
  private SoapMessage makeInvocation(
      Map<String, String> outProperties, List<String> xpaths, Map<String, String> inProperties)
      throws Exception {
    Document doc = readDocument("wsse-request-clean.xml");

    WSS4JOutInterceptor ohandler = new WSS4JOutInterceptor();
    PhaseInterceptor<SoapMessage> handler = ohandler.createEndingInterceptor();

    SoapMessage msg = new SoapMessage(new MessageImpl());
    Exchange ex = new ExchangeImpl();
    ex.setInMessage(msg);

    SOAPMessage saajMsg = MessageFactory.newInstance().createMessage();
    SOAPPart part = saajMsg.getSOAPPart();
    part.setContent(new DOMSource(doc));
    saajMsg.saveChanges();

    msg.setContent(SOAPMessage.class, saajMsg);

    for (String key : outProperties.keySet()) {
      msg.put(key, outProperties.get(key));
    }

    handler.handleMessage(msg);

    doc = part;

    for (String xpath : xpaths) {
      assertValid(xpath, doc);
    }

    byte[] docbytes = getMessageBytes(doc);
    XMLStreamReader reader = StaxUtils.createXMLStreamReader(new ByteArrayInputStream(docbytes));

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    dbf.setValidating(false);
    dbf.setIgnoringComments(false);
    dbf.setIgnoringElementContentWhitespace(true);
    dbf.setNamespaceAware(true);

    DocumentBuilder db = dbf.newDocumentBuilder();
    db.setEntityResolver(new NullResolver());
    doc = StaxUtils.read(db, reader, false);

    WSS4JInInterceptor inHandler = new WSS4JInInterceptor();

    SoapMessage inmsg = new SoapMessage(new MessageImpl());
    ex.setInMessage(inmsg);
    inmsg.setContent(SOAPMessage.class, saajMsg);

    for (String key : inProperties.keySet()) {
      inHandler.setProperty(key, inProperties.get(key));
    }

    inHandler.handleMessage(inmsg);

    return inmsg;
  }
  protected String addOperationNode(
      NSStack nsStack,
      Message message,
      XMLStreamWriter xmlWriter,
      boolean output,
      BindingOperationInfo boi)
      throws XMLStreamException {
    String responseSuffix = output ? "Response" : "";
    String ns = boi.getName().getNamespaceURI();
    SoapBody body = null;
    if (output) {
      body = boi.getOutput().getExtensor(SoapBody.class);
    } else {
      body = boi.getInput().getExtensor(SoapBody.class);
    }
    if (body != null && !StringUtils.isEmpty(body.getNamespaceURI())) {
      ns = body.getNamespaceURI();
    }

    nsStack.add(ns);
    String prefix = nsStack.getPrefix(ns);
    StaxUtils.writeStartElement(
        xmlWriter, prefix, boi.getName().getLocalPart() + responseSuffix, ns);
    return ns;
  }
Example #7
0
  @Test
  public void testCustomSchemaWithImportJaxbContextPrefixes() throws Exception {
    WadlGenerator wg = new WadlGenerator();
    wg.setSchemaLocations(Collections.singletonList("classpath:/books.xsd"));

    ClassResourceInfo cri =
        ResourceUtils.createClassResourceInfo(BookStore.class, BookStore.class, true, true);
    Message m = mockMessage("http://localhost:8080/baz", "/bar", WadlGenerator.WADL_QUERY, cri);
    Response r = handleRequest(wg, m);
    checkResponse(r);
    Document doc = StaxUtils.read(new StringReader(r.getEntity().toString()));
    List<Element> grammarEls =
        DOMUtils.getChildrenWithName(doc.getDocumentElement(), WadlGenerator.WADL_NS, "grammars");
    assertEquals(1, grammarEls.size());
    List<Element> schemasEls =
        DOMUtils.getChildrenWithName(grammarEls.get(0), Constants.URI_2001_SCHEMA_XSD, "schema");
    assertEquals(1, schemasEls.size());
    assertEquals("http://books", schemasEls.get(0).getAttribute("targetNamespace"));
    List<Element> elementEls =
        DOMUtils.getChildrenWithName(schemasEls.get(0), Constants.URI_2001_SCHEMA_XSD, "element");
    assertEquals(1, elementEls.size());
    assertTrue(checkElement(elementEls, "books", "books"));

    List<Element> complexTypesEls =
        DOMUtils.getChildrenWithName(
            schemasEls.get(0), Constants.URI_2001_SCHEMA_XSD, "complexType");
    assertEquals(1, complexTypesEls.size());
    assertTrue(checkComplexType(complexTypesEls, "books"));

    List<Element> importEls =
        DOMUtils.getChildrenWithName(schemasEls.get(0), Constants.URI_2001_SCHEMA_XSD, "import");
    assertEquals(1, importEls.size());
    assertEquals(
        "http://localhost:8080/baz/book1.xsd", importEls.get(0).getAttribute("schemaLocation"));
  }
Example #8
0
 @Test
 public void testMultipleRootResources() throws Exception {
   WadlGenerator wg = new WadlGenerator();
   wg.setDefaultMediaType(WadlGenerator.WADL_TYPE.toString());
   ClassResourceInfo cri1 =
       ResourceUtils.createClassResourceInfo(BookStore.class, BookStore.class, true, true);
   ClassResourceInfo cri2 =
       ResourceUtils.createClassResourceInfo(Orders.class, Orders.class, true, true);
   List<ClassResourceInfo> cris = new ArrayList<ClassResourceInfo>();
   cris.add(cri1);
   cris.add(cri2);
   Message m = mockMessage("http://localhost:8080/baz", "", WadlGenerator.WADL_QUERY, cris);
   Response r = handleRequest(wg, m);
   assertEquals(
       WadlGenerator.WADL_TYPE.toString(),
       r.getMetadata().getFirst(HttpHeaders.CONTENT_TYPE).toString());
   String wadl = r.getEntity().toString();
   Document doc = StaxUtils.read(new StringReader(wadl));
   checkGrammars(
       doc.getDocumentElement(), "thebook", "books", "thebook2s", "thebook2", "thechapter");
   List<Element> els = getWadlResourcesInfo(doc, "http://localhost:8080/baz", 2);
   checkBookStoreInfo(els.get(0), "prefix1:thebook", "prefix1:thebook2", "prefix1:thechapter");
   Element orderResource = els.get(1);
   assertEquals("/orders", orderResource.getAttribute("path"));
 }
 protected void transformXWriter(Message message, XMLStreamWriter xWriter) {
   CachedWriter writer = new CachedWriter();
   XMLStreamWriter delegate = StaxUtils.createXMLStreamWriter(writer);
   XSLTStreamWriter wrapper = new XSLTStreamWriter(getXSLTTemplate(), writer, delegate, xWriter);
   message.setContent(XMLStreamWriter.class, wrapper);
   message.put(AbstractOutDatabindingInterceptor.DISABLE_OUTPUTSTREAM_OPTIMIZATION, Boolean.TRUE);
 }
Example #10
0
  protected XMLStreamWriter getStreamWriter(Object obj, OutputStream os, MediaType mt) {
    XMLStreamWriter writer = null;
    MessageContext mc = getContext();
    if (mc != null) {
      writer = mc.getContent(XMLStreamWriter.class);
      if (writer == null) {
        XMLOutputFactory factory = (XMLOutputFactory) mc.get(XMLOutputFactory.class.getName());
        if (factory != null) {
          try {
            writer = factory.createXMLStreamWriter(os);
          } catch (XMLStreamException e) {
            throw ExceptionUtils.toInternalServerErrorException(
                new RuntimeException("Cant' create XMLStreamWriter", e), null);
          }
        }
      }
      if (writer == null && getEnableStreaming()) {
        writer = StaxUtils.createXMLStreamWriter(os);
      }
    }

    if (writer == null && os == null) {
      writer = getStreamHandlerFromCurrentMessage(XMLStreamWriter.class);
    }
    return createTransformWriterIfNeeded(writer, os, true);
  }
 @Override
 protected Object unmarshalFromReader(
     Unmarshaller unmarshaller, XMLStreamReader reader, Annotation[] anns, MediaType mt)
     throws JAXBException {
   CachedOutputStream out = new CachedOutputStream();
   try {
     XMLStreamWriter writer = StaxUtils.createXMLStreamWriter(out);
     StaxUtils.copy(new StaxSource(reader), writer);
     writer.writeEndDocument();
     writer.flush();
     writer.close();
     return unmarshalFromInputStream(unmarshaller, out.getInputStream(), anns, mt);
   } catch (Exception ex) {
     throw ExceptionUtils.toBadRequestException(ex, null);
   }
 }
Example #12
0
 @Test
 public void testTwoSchemasSameNs() throws Exception {
   WadlGenerator wg = new WadlGenerator();
   wg.setApplicationTitle("My Application");
   wg.setNamespacePrefix("ns");
   ClassResourceInfo cri =
       ResourceUtils.createClassResourceInfo(TestResource.class, TestResource.class, true, true);
   Message m = mockMessage("http://localhost:8080/baz", "/", WadlGenerator.WADL_QUERY, cri);
   Response r = handleRequest(wg, m);
   checkResponse(r);
   Document doc = StaxUtils.read(new StringReader(r.getEntity().toString()));
   checkDocs(doc.getDocumentElement(), "My Application", "", "");
   List<Element> grammarEls =
       DOMUtils.getChildrenWithName(doc.getDocumentElement(), WadlGenerator.WADL_NS, "grammars");
   assertEquals(1, grammarEls.size());
   List<Element> schemasEls =
       DOMUtils.getChildrenWithName(grammarEls.get(0), Constants.URI_2001_SCHEMA_XSD, "schema");
   assertEquals(2, schemasEls.size());
   assertEquals("http://example.com/test", schemasEls.get(0).getAttribute("targetNamespace"));
   assertEquals("http://example.com/test", schemasEls.get(1).getAttribute("targetNamespace"));
   List<Element> reps =
       DOMUtils.findAllElementsByTagNameNS(
           doc.getDocumentElement(), WadlGenerator.WADL_NS, "representation");
   assertEquals(2, reps.size());
   assertEquals("ns1:testCompositeObject", reps.get(0).getAttribute("element"));
   assertEquals("ns1:testCompositeObject", reps.get(1).getAttribute("element"));
 }
Example #13
0
 private static String getXMLString(Element el) {
   try {
     return StaxUtils.toString(el);
   } catch (Throwable t) {
     // ignore
   }
   return "unknown content";
 }
  @Override
  protected void marshalToWriter(
      Marshaller ms, Object obj, XMLStreamWriter writer, Annotation[] anns, MediaType mt)
      throws Exception {
    CachedOutputStream out = new CachedOutputStream();
    marshalToOutputStream(ms, obj, out, anns, mt);

    StaxUtils.copy(new StreamSource(out.getInputStream()), writer);
  }
Example #15
0
 @Override
 public void handleMessage(Message message) throws Fault {
   try {
     XMLStreamWriter writer = message.getContent(XMLStreamWriter.class);
     StaxUtils.copy(reader, writer);
   } catch (XMLStreamException e) {
     throw new Fault("COULD_NOT_READ_XML_STREAM", LOG, e);
   }
 }
Example #16
0
 public EndpointReference readEndpointReference(Source eprInfoset) {
   try {
     Unmarshaller unmarshaller = getJAXBContext().createUnmarshaller();
     return (EndpointReference)
         unmarshaller.unmarshal(StaxUtils.createXMLStreamReader(eprInfoset));
   } catch (JAXBException e) {
     throw new WebServiceException(
         new Message("ERROR_UNMARSHAL_ENDPOINTREFERENCE", LOG).toString(), e);
   }
 }
  @Override
  protected Object unmarshalFromInputStream(
      Unmarshaller unmarshaller, InputStream is, Annotation[] anns, MediaType mt)
      throws JAXBException {
    try {

      Templates t = createTemplates(getInTemplates(anns, mt), inParamsMap, inProperties);
      if (t == null && supportJaxbOnly) {
        return super.unmarshalFromInputStream(unmarshaller, is, anns, mt);
      }

      if (unmarshaller.getClass().getName().contains("eclipse")) {
        // eclipse MOXy doesn't work properly with the XMLFilter/Reader thing
        // so we need to bounce through a DOM
        Source reader = new StaxSource(StaxUtils.createXMLStreamReader(is));
        DOMResult dom = new DOMResult();
        t.newTransformer().transform(reader, dom);
        return unmarshaller.unmarshal(dom.getNode());
      }
      XMLFilter filter = null;
      try {
        filter = factory.newXMLFilter(t);
      } catch (TransformerConfigurationException ex) {
        TemplatesImpl ti = (TemplatesImpl) t;
        filter = factory.newXMLFilter(ti.getTemplates());
        trySettingProperties(filter, ti);
      }
      XMLReader reader = new StaxSource(StaxUtils.createXMLStreamReader(is));
      filter.setParent(reader);
      SAXSource source = new SAXSource();
      source.setXMLReader(filter);
      if (systemId != null) {
        source.setSystemId(systemId);
      }
      return unmarshaller.unmarshal(source);
    } catch (TransformerException ex) {
      LOG.warning("Transformation exception : " + ex.getMessage());
      throw ExceptionUtils.toInternalServerErrorException(ex, null);
    }
  }
Example #18
0
  private void readHeaders(XMLStreamReader xmlReader, SoapMessage message)
      throws XMLStreamException {

    // read header portion of SOAP document into DOM
    SoapVersion version = message.getVersion();
    XMLStreamReader filteredReader = new PartialXMLStreamReader(xmlReader, version.getBody());
    Node nd = message.getContent(Node.class);
    W3CDOMStreamWriter writer = message.get(W3CDOMStreamWriter.class);
    Document doc = null;
    if (writer != null) {
      StaxUtils.copy(filteredReader, writer);
      doc = writer.getDocument();
    } else if (nd instanceof Document) {
      doc = (Document) nd;
      StaxUtils.readDocElements(doc, doc, filteredReader, false, false);
    } else {
      doc = StaxUtils.read(filteredReader);
      message.setContent(Node.class, doc);
    }

    // get the actual SOAP header
    Element element = doc.getDocumentElement();
    QName header = version.getHeader();
    List<Element> elemList =
        DOMUtils.findAllElementsByTagNameNS(
            element, header.getNamespaceURI(), header.getLocalPart());
    for (Element elem : elemList) {

      // set all child elements as headers for message transmission
      Element hel = DOMUtils.getFirstElement(elem);
      while (hel != null) {
        SoapHeader sheader = new SoapHeader(DOMUtils.getElementQName(hel), hel);
        message.getHeaders().add(sheader);
        hel = DOMUtils.getNextElement(hel);
      }
    }
  }
 @Override
 public void close() {
   Reader transformedReader = null;
   try {
     super.flush();
     transformedReader = XSLTUtils.transform(xsltTemplate, cachedWriter.getReader());
     StaxUtils.copy(new StreamSource(transformedReader), origXWriter);
   } catch (XMLStreamException e) {
     throw new Fault("STAX_COPY", LOG, e, e.getMessage());
   } catch (IOException e) {
     throw new Fault("GET_CACHED_INPUT_STREAM", LOG, e, e.getMessage());
   } finally {
     try {
       if (transformedReader != null) {
         transformedReader.close();
       }
       cachedWriter.close();
       StaxUtils.close(origXWriter);
       super.close();
     } catch (Exception e) {
       LOG.warning("Cannot close stream after transformation: " + e.getMessage());
     }
   }
 }
Example #20
0
 @POST
 @Path("depth-source")
 @Consumes({"application/xml"})
 public void postSourceBook(Source source) {
   try {
     StaxUtils.copy(source, new ByteArrayOutputStream());
   } catch (DepthExceededStaxException ex) {
     throw new WebApplicationException(413);
   } catch (XMLStreamException ex) {
     if (ex.getMessage().startsWith("Maximum Number")) {
       throw new WebApplicationException(413);
     }
   }
   throw new WebApplicationException(500);
 }
 private XMLStreamReader createXMLStreamReaderFromSOAPMessage(SOAPMessage soapMessage) {
   // responseMsg.setContent(SOAPMessage.class, soapMessage);
   XMLStreamReader xmlReader = null;
   try {
     DOMSource bodySource = new DOMSource(soapMessage.getSOAPPart().getEnvelope().getBody());
     xmlReader = StaxUtils.createXMLStreamReader(bodySource);
     xmlReader.nextTag();
     xmlReader.nextTag(); // move past body tag
   } catch (SOAPException e) {
     e.printStackTrace();
   } catch (XMLStreamException e) {
     e.printStackTrace();
   }
   return xmlReader;
 }
Example #22
0
 public synchronized Node getNode() {
   Node nd = super.getNode();
   if (nd == null) {
     try {
       InputSource src = new InputSource(resource.openStream());
       src.setSystemId(this.getSystemId());
       src.setPublicId(publicId);
       Document doc = StaxUtils.read(src);
       setNode(doc);
       nd = super.getNode();
     } catch (Exception ex) {
       throw new RuntimeException(ex);
     }
   }
   return nd;
 }
Example #23
0
  @Test
  public void testCustomSchemaJaxbContextPrefixes() throws Exception {
    WadlGenerator wg = new WadlGenerator();
    wg.setSchemaLocations(Collections.singletonList("classpath:/book1.xsd"));

    ClassResourceInfo cri =
        ResourceUtils.createClassResourceInfo(BookStore.class, BookStore.class, true, true);
    Message m =
        mockMessage("http://localhost:8080/baz", "/bookstore/1", WadlGenerator.WADL_QUERY, cri);
    Response r = handleRequest(wg, m);
    checkResponse(r);
    Document doc = StaxUtils.read(new StringReader(r.getEntity().toString()));
    checkGrammars(doc.getDocumentElement(), "thebook", "thebook2", "thechapter");
    List<Element> els = getWadlResourcesInfo(doc, "http://localhost:8080/baz", 1);
    checkBookStoreInfo(els.get(0), "prefix1:thebook", "prefix1:thebook2", "prefix1:thechapter");
  }
Example #24
0
 // Simulates a stream based processor or producer (e.g., file EP)
 public SOAPMessage invokeStream(InputStream in) {
   SOAPMessage response = null;
   try {
     Document doc = StaxUtils.read(in);
     if (doc.getElementsByTagNameNS(greetMe.getNamespaceURI(), sayHi.getLocalPart()).getLength()
         == 1) {
       response = sayHiResponse;
     } else if (doc.getElementsByTagNameNS(greetMe.getNamespaceURI(), greetMe.getLocalPart())
             .getLength()
         == 1) {
       response = greetMeResponse;
     }
   } catch (Exception ex) {
     ex.printStackTrace();
   }
   return response;
 }
Example #25
0
  @Test
  public void testExternalSchemaCustomPrefix() throws Exception {
    WadlGenerator wg = new WadlGenerator();
    wg.setExternalLinks(Collections.singletonList("http://books"));
    wg.setUseJaxbContextForQnames(false);

    ClassResourceInfo cri =
        ResourceUtils.createClassResourceInfo(BookStore.class, BookStore.class, true, true);
    Message m =
        mockMessage("http://localhost:8080/baz", "/bookstore/1", WadlGenerator.WADL_QUERY, cri);
    Response r = handleRequest(wg, m);
    checkResponse(r);
    Document doc = StaxUtils.read(new StringReader(r.getEntity().toString()));
    checkGrammarsWithLinks(doc.getDocumentElement(), Collections.singletonList("http://books"));
    List<Element> els = getWadlResourcesInfo(doc, "http://localhost:8080/baz", 1);
    checkBookStoreInfo(els.get(0), "p1:thesuperbook", "p1:thesuperbook2", "p1:thesuperchapter");
  }
Example #26
0
  public void handleMessage(Message message) throws Fault {
    Document doc = (Document) message.get(WSDLGetInterceptor.DOCUMENT_HOLDER);
    if (doc == null) {
      return;
    }
    message.remove(WSDLGetInterceptor.DOCUMENT_HOLDER);

    XMLStreamWriter writer = message.getContent(XMLStreamWriter.class);
    if (writer == null) {
      return;
    }
    message.put(Message.CONTENT_TYPE, "text/xml");
    try {
      StaxUtils.writeNode(doc, writer, true);
    } catch (XMLStreamException e) {
      throw new Fault(e);
    }
  }
Example #27
0
 @Test
 public void testSingleRootResource() throws Exception {
   WadlGenerator wg = new WadlGenerator();
   wg.setApplicationTitle("My Application");
   wg.setNamespacePrefix("ns");
   ClassResourceInfo cri =
       ResourceUtils.createClassResourceInfo(BookStore.class, BookStore.class, true, true);
   Message m =
       mockMessage("http://localhost:8080/baz", "/bookstore/1", WadlGenerator.WADL_QUERY, cri);
   Response r = handleRequest(wg, m);
   checkResponse(r);
   Document doc = StaxUtils.read(new StringReader(r.getEntity().toString()));
   checkDocs(doc.getDocumentElement(), "My Application", "", "");
   checkGrammars(
       doc.getDocumentElement(), "thebook", "books", "thebook2s", "thebook2", "thechapter");
   List<Element> els = getWadlResourcesInfo(doc, "http://localhost:8080/baz", 1);
   checkBookStoreInfo(els.get(0), "ns1:thebook", "ns1:thebook2", "ns1:thechapter", "ns1:books");
 }
Example #28
0
 protected Object doUnmarshal(
     Unmarshaller unmarshaller, Class<?> type, InputStream is, Annotation[] anns, MediaType mt)
     throws JAXBException {
   XMLStreamReader reader = getStreamReader(is, type, mt);
   if (reader != null) {
     try {
       return unmarshalFromReader(unmarshaller, reader, anns, mt);
     } catch (JAXBException e) {
       throw e;
     } finally {
       try {
         StaxUtils.close(reader);
       } catch (XMLStreamException e) {
         // Ignore
       }
     }
   }
   return unmarshalFromInputStream(unmarshaller, is, anns, mt);
 }
  @Override
  public void writeTo(
      T obj,
      Class<?> type,
      Type genericType,
      Annotation[] anns,
      MediaType m,
      MultivaluedMap<String, Object> headers,
      OutputStream os)
      throws IOException {
    if (type == null) {
      type = obj.getClass();
    }
    if (genericType == null) {
      genericType = type;
    }
    AegisContext context = getAegisContext(type, genericType);
    AegisType aegisType = context.getTypeMapping().getType(genericType);
    AegisWriter<XMLStreamWriter> aegisWriter = context.createXMLStreamWriter();
    try {
      W3CDOMStreamWriter w3cStreamWriter = new W3CDOMStreamWriter();
      XMLStreamWriter spyingWriter =
          new PrefixCollectingXMLStreamWriter(w3cStreamWriter, namespaceMap);
      spyingWriter.writeStartDocument();
      // use type qname as element qname?
      aegisWriter.write(obj, aegisType.getSchemaType(), false, spyingWriter, aegisType);
      spyingWriter.writeEndDocument();
      spyingWriter.close();
      Document dom = w3cStreamWriter.getDocument();
      // ok, now the namespace map has all the prefixes.

      XMLStreamWriter xmlStreamWriter = createStreamWriter(aegisType.getSchemaType(), os);
      xmlStreamWriter.writeStartDocument();
      StaxUtils.copy(dom, xmlStreamWriter);
      // Jettison needs, and StaxUtils.copy doesn't do it.
      xmlStreamWriter.writeEndDocument();
      xmlStreamWriter.flush();
      xmlStreamWriter.close();
    } catch (Exception e) {
      throw new WebApplicationException(e);
    }
  }
Example #30
0
  @Test
  public void testRootResourceWithSingleSlash() throws Exception {
    WadlGenerator wg = new WadlGenerator();
    ClassResourceInfo cri =
        ResourceUtils.createClassResourceInfo(
            BookStoreWithSingleSlash.class, BookStoreWithSingleSlash.class, true, true);
    Message m = mockMessage("http://localhost:8080/baz", "/", WadlGenerator.WADL_QUERY, cri);
    Response r = handleRequest(wg, m);
    checkResponse(r);
    Document doc = StaxUtils.read(new StringReader(r.getEntity().toString()));
    List<Element> rootEls = getWadlResourcesInfo(doc, "http://localhost:8080/baz", 1);
    assertEquals(1, rootEls.size());
    Element resource = rootEls.get(0);
    assertEquals("/", resource.getAttribute("path"));
    List<Element> resourceEls =
        DOMUtils.getChildrenWithName(resource, WadlGenerator.WADL_NS, "resource");
    assertEquals(1, resourceEls.size());
    assertEquals("book", resourceEls.get(0).getAttribute("path"));

    verifyParameters(resourceEls.get(0), 1, new Param("id", "template", "xs:int"));

    checkGrammars(doc.getDocumentElement(), "thebook", null, "thechapter");
  }