@Put("xml")
  public String updateClinicConnectionDetails(DomRepresentation rep)
      throws IOException, SAXException {
    StringWriter xml = new StringWriter();
    XmlWriter xmlWriter = new XmlWriter(xml);

    ObjectOutputStream out;

    xmlWriter.startDocument();
    xmlWriter.setDataFormat(true);

    xmlWriter.startElement("response");

    Element dataNode = (Element) rep.getNode("//request/data");

    ClinicRequirements detachedInstance = null;
    try {
      if (dataNode != null) {
        xmlConverter.alias("data", ClinicRequirements.class);
        detachedInstance =
            clinicRequirementsBean.merge(
                (ClinicRequirements) xmlConverter.unmarshal(new DomReader(dataNode)));

        xmlWriter.dataElement("status", "0");
        xmlConverter.alias("record", ClinicRequirements.class);
        out = xmlConverter.createObjectOutputStream(xmlWriter.getWriter(), "data");
        out.writeObject(detachedInstance);
        out.close();
      } else // Sending error message
      {
        xmlWriter.dataElement("status", "-1");
        xmlWriter.dataElement("data", "Unable to update the Clinic Requirments! Please retry!");
      }
    } catch (Exception ex) {
      xmlWriter.dataElement("status", "-1");
      xmlWriter.dataElement("data", ex.getLocalizedMessage());
    }
    xmlWriter.endElement("response");
    xmlWriter.endDocument();

    return xml.toString();
  }
  @Test
  public void testUnmarshalParseXmlNamespaces() throws XmlPullParserException {

    XStream xstream = new XStream(new WstxDriver());
    xstream.setClassLoader(this.getClass().getClassLoader());

    xstream.registerConverter(new GetRecordsResponseConverter(mockProvider));
    xstream.alias("csw:GetRecordsResponse", CswRecordCollection.class);

    String xml =
        "<?xml version='1.0' encoding='UTF-8'?>"
            + "<csw:GetRecordsResponse "
            + "xmlns:dc=\"http://purl.org/dc/elements/1.1/\" "
            + "xmlns:dct=\"http://purl.org/dc/terms/\" "
            + "xmlns:ows=\"http://www.opengis.net/ows\" "
            + "xmlns:csw=\"http://www.opengis.net/cat/csw/2.0.2\" "
            + "version=\"2.0.2\"><csw:SearchStatus "
            + "timestamp=\"2014-11-11T10:53:32.152-06:00\"/>"
            + "<csw:SearchResults numberOfRecordsMatched=\"1\" "
            + "numberOfRecordsReturned=\"1\" nextRecord=\"0\" "
            + "recordSchema=\"http://www.opengis.net/cat/csw/2.0.2\">"
            + "<csw:Record>\n"
            + "<dc:identifier>0a2e1b1d2a3755e70a96d61e6bddbc5d</dc:identifier>"
            + "<dct:bibliographicCitation>0a2e1b1d2a3755e70a96d61e6bddbc5d</dct:bibliographicCitation>"
            + "<dc:title>US woman attacks Gauguin painting</dc:title>"
            + "<dct:alternative>US woman attacks Gauguin painting</dct:alternative>"
            + "<dc:type>video</dc:type><dc:date>2011-04-06T04:49:20.230-05:00</dc:date>"
            + "<dct:modified>2011-04-06T04:49:20.230-05:00</dct:modified>"
            + "<dct:created>2011-04-06T04:49:20.230-05:00</dct:created>"
            + "<dct:dateAccepted>2011-04-06T04:48:26.180-05:00</dct:dateAccepted>"
            + "<dct:dateCopyrighted>2011-04-06T04:48:26.180-05:00</dct:dateCopyrighted><"
            + "dct:dateSubmitted>2011-04-06T04:49:20.230-05:00</dct:dateSubmitted>"
            + "<dct:issued>2011-04-06T04:49:20.230-05:00</dct:issued>"
            + "<dc:publisher>ddf.distribution</dc:publisher>"
            + "<ows:BoundingBox crs=\"urn:x-ogc:def:crs:EPSG:6.11:4326\">\n"
            + "    <ows:LowerCorner>-50.5056430529222 84.0285103635943</ows:LowerCorner>"
            + "<ows:UpperCorner>-50.5056430529222 84.0285103635943</ows:UpperCorner>"
            + "</ows:BoundingBox></csw:Record><"
            + "/csw:SearchResults>"
            + "</csw:GetRecordsResponse>";
    InputStream inStream = IOUtils.toInputStream(xml);

    ArgumentCaptor<UnmarshallingContext> captor =
        ArgumentCaptor.forClass(UnmarshallingContext.class);

    HierarchicalStreamReader reader =
        new XppReader(
            new InputStreamReader(inStream), XmlPullParserFactory.newInstance().newPullParser());
    xstream.unmarshal(reader, null, null);
    IOUtils.closeQuietly(inStream);

    verify(mockProvider, times(1)).unmarshal(any(HierarchicalStreamReader.class), captor.capture());

    UnmarshallingContext context = captor.getValue();

    assertThat(context, notNullValue());
    assertThat(context.get(CswConstants.NAMESPACE_DECLARATIONS), is(Map.class));
    Map<String, String> namespaces = (Map) context.get(CswConstants.NAMESPACE_DECLARATIONS);
    assertThat(
        namespaces.get(
            CswConstants.XMLNS
                + CswConstants.NAMESPACE_DELIMITER
                + CswConstants.CSW_NAMESPACE_PREFIX),
        is(CswConstants.CSW_OUTPUT_SCHEMA));
    assertThat(
        namespaces.get(
            CswConstants.XMLNS
                + CswConstants.NAMESPACE_DELIMITER
                + CswConstants.DUBLIN_CORE_NAMESPACE_PREFIX),
        is(CswConstants.DUBLIN_CORE_SCHEMA));
    assertThat(
        namespaces.get(
            CswConstants.XMLNS
                + CswConstants.NAMESPACE_DELIMITER
                + CswConstants.DUBLIN_CORE_TERMS_NAMESPACE_PREFIX),
        is(CswConstants.DUBLIN_CORE_TERMS_SCHEMA));
    assertThat(
        namespaces.get(
            CswConstants.XMLNS
                + CswConstants.NAMESPACE_DELIMITER
                + CswConstants.OWS_NAMESPACE_PREFIX),
        is(CswConstants.OWS_NAMESPACE));
  }
Ejemplo n.º 3
0
  /**
   * Method responsible for handling incoming POSTs. It will parse the XML document and deserialize
   * it into a SeedRequest, then create a SeedTask and forward it to the thread pool executor.
   */
  public void doPost(Request req, Response resp) throws RestletException, IOException {
    String formatExtension = (String) req.getAttributes().get("extension");

    SeedRequest sr = null;

    XStream xs = xmlConfig.getConfiguredXStream(new XStream(new DomDriver()));
    try {
      if (formatExtension.equalsIgnoreCase("xml")) {
        String xml_body = req.getEntity().getText();
        log.debug("doPost, xml = " + xml_body);
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        ByteArrayInputStream xml_bs = new ByteArrayInputStream(xml_body.getBytes());
        Document doc = db.parse(xml_bs);
        Node rootNode = doc.getFirstChild();
        xs.alias("seedRequest", SeedRequest.class);
        sr = (SeedRequest) xs.unmarshal(new DomReader((Element) rootNode));
        log.debug("doPost, sr = " + sr.getLayerName());
      } else if (formatExtension.equalsIgnoreCase("json")) {
        sr = (SeedRequest) xs.fromXML(convertJson(req.getEntity().getText()));
      } else {
        throw new RestletException(
            "Format extension unknown or not specified: " + formatExtension,
            Status.CLIENT_ERROR_BAD_REQUEST);
      }
    } catch (Exception e) {
      log.error("Exception type = " + e.getClass().getName() + " msg = " + e.getMessage());
      e.printStackTrace();
      if (e.getCause() != null) {
        log.error("cause = " + e.getCause().getMessage());
      }
    }

    StringBuilder strBld = new StringBuilder();
    strBld.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
    String layerName = null;
    try {
      layerName = URLDecoder.decode((String) req.getAttributes().get("layer"), "UTF-8");
    } catch (UnsupportedEncodingException uee) {
      log.error("Exception type = " + uee.getClass().getName() + " msg = " + uee.getMessage());
      throw new RestletException(uee.getMessage(), Status.SERVER_ERROR_INTERNAL);
    }

    log.debug(
        "layerName = "
            + layerName
            + " sr.GridSetId = "
            + sr.getGridSetId()
            + " type = "
            + sr.getType());
    GWCTask[] tasks = null;
    try {
      TileLayer tl = null;
      try {
        tl = seeder.findTileLayer(layerName);
      } catch (GeoWebCacheException e) {
        strBld.append("<GeoWebCacheException>");
        strBld.append(e.getMessage());
        strBld.append("</GeoWebCacheException>");
        resp.setEntity(strBld.toString(), MediaType.TEXT_XML);
        throw new RestletException(e.getMessage(), Status.SERVER_ERROR_INTERNAL);
      }

      TileRange tr = TileBreeder.createTileRange(sr, tl);

      tasks = seeder.createTasks(tr, tl, sr.getType(), sr.getThreadCount(), sr.getFilterUpdate());

      seeder.dispatchTasks(tasks);
      // Give the thread executor a chance to run
      try {
        Thread.sleep(500);
      } catch (InterruptedException e) {
        // Ok, no worries
      }

    } catch (IllegalArgumentException e) {
      log.error("IllegalArgumentException occured: " + e.getMessage());
      throw new RestletException(e.getMessage(), Status.CLIENT_ERROR_BAD_REQUEST);
    } catch (GeoWebCacheException e) {
      log.error("GeoWebCacheException occured: " + e.getMessage());
      throw new RestletException(e.getMessage(), Status.SERVER_ERROR_INTERNAL);
    }

    strBld.append("<Tasks>");
    if (tasks.length == 0) {
      log.debug("No running tasks");
    }
    for (int i = 0; i < tasks.length; i++) {
      if (i > 0) {
        strBld.append(",");
      }
      strBld.append(tasks[i].getDbId());
    }
    strBld.append("</Tasks>\n");
    log.debug("post response = " + strBld.toString());
    resp.setEntity(strBld.toString(), MediaType.TEXT_XML);
  }