private void writeTitle(
     final XMLStreamWriter writer, final List<LanguageString> titles, final String name)
     throws XMLStreamException {
   if (titles != null && !titles.isEmpty()) {
     writeElement(writer, "Title", titles.get(0).getString());
   } else if (name != null) {
     writeElement(writer, "Title", name);
   }
 }
  @Override
  public ISORecord inspect(ISORecord record, Connection conn, SQLDialect dialect)
      throws MetadataInspectorException {

    ISORecord result = record;

    try {
      // create temporary sink for normalized XML
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      XMLStreamWriter writer = XMLOutputFactory.newInstance().createXMLStreamWriter(bos);
      writer = new NamespaceNormalizingXMLStreamWriter(writer, nsBindings);

      // create normalized copy
      XMLStreamReader reader = record.getAsXMLStream();
      XMLAdapter.writeElement(writer, reader);
      reader.close();
      writer.close();

      InputStream is = new ByteArrayInputStream(bos.toByteArray());
      XMLStreamReader xmlStream = XMLInputFactory.newInstance().createXMLStreamReader(is);
      result = new ISORecord(xmlStream);
    } catch (Throwable t) {
      LOG.error(
          "Namespace normalization failed. Proceeding with unnormalized record. Error: "
              + t.getMessage());
    }

    return result;
  }
Esempio n. 3
0
  /**
   * makes a {@link Document} out of a {@link XMLStreamReader}
   *
   * @param xmlStreamReader the xmlStreamRader to convert
   * @return the xmlStreamRader as {@link Document}
   * @throws FactoryConfigurationError
   * @throws XMLStreamException
   * @throws ParserConfigurationException
   * @throws IOException
   * @throws SAXException
   */
  public static Document getAsDocument(XMLStreamReader xmlStreamReader)
      throws XMLStreamException, FactoryConfigurationError, ParserConfigurationException,
          SAXException, IOException {
    StreamBufferStore store = new StreamBufferStore();
    XMLStreamWriter xmlWriter = null;
    try {
      xmlWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(store);
      xmlWriter.writeStartDocument();
      XMLAdapter.writeElement(xmlWriter, xmlStreamReader);
    } finally {
      if (xmlWriter != null) {
        try {
          xmlWriter.close();
        } catch (XMLStreamException e) {
          LOG.error("Unable to close xmlwriter.");
        }
      }
    }

    store.flush();
    DOMParser parser = new DOMParser();
    parser.parse(new InputSource(store.getInputStream()));
    Document doc = parser.getDocument();
    store.close();
    return doc;
  }
 private void writeMetadataUrls(final XMLStreamWriter writer, final List<MetadataUrl> list)
     throws XMLStreamException {
   if (list == null) {
     return;
   }
   for (final MetadataUrl url : list) {
     writer.writeStartElement("MetadataURL");
     if (url.getType() == null) {
       writer.writeAttribute("type", "TC211");
     } else {
       writer.writeAttribute("type", url.getType());
     }
     if (url.getFormat() == null) {
       writeElement(writer, "Format", "application/xml");
     } else {
       writeElement(writer, "Format", url.getFormat());
     }
     writeOnlineResource(writer, url.getUrl());
     writer.writeEndElement();
   }
 }
 private void writeKeywordList(
     final XMLStreamWriter writer, final List<Pair<List<LanguageString>, CodeType>> keywordList)
     throws XMLStreamException {
   if (keywordList != null && !keywordList.isEmpty()) {
     writer.writeStartElement("KeywordList");
     for (final Pair<List<LanguageString>, CodeType> kws : keywordList) {
       for (final LanguageString ls : kws.first) {
         // <!ELEMENT Keyword (#PCDATA) >
         writeElement(writer, "Keyword", ls.getString());
       }
     }
     writer.writeEndElement();
   }
 }
  @Override
  public void process(ProcessletInputs in, ProcessletOutputs out, ProcessletExecutionInfo info)
      throws ProcessletException {
    try {

      // validate against allowed values in process definition file
      URL processDefinitionUrl =
          this.getClass().getResource("/" + this.getClass().getSimpleName() + ".xml");

      // get validated data inputs or default values
      DataInputHandler dataInputHandler =
          new DataInputHandler(new File(processDefinitionUrl.toURI()));
      String srsName = dataInputHandler.getValidatedStringValue(in, "srsName");
      String filter = dataInputHandler.getValidatedStringValue(in, "filter");
      double x = DataInputHandler.getDoubleInputValue(in, "x");
      double y = DataInputHandler.getDoubleInputValue(in, "y");
      double z = DataInputHandler.getDoubleInputValue(in, "z");

      LOG.debug(
          String.format(
              "DataInputs: srsName: %s, poi: (%f, %f, %f), filter: %s", srsName, x, y, z, filter));

      responseValues = new ResponseValues();
      responseValues.clientSrsName = srsName;

      // transform non-AGEA coordinates to AGEA
      if (!srsName.equals("Mouse_AGEA_1.0")) {
        ABAServiceVO vo = getTransformPOI(srsName, x, y, z);
        if (vo.getTransformationXMLResponseString().startsWith("Error:")) {
          throw new OWSException(
              "Transformation Coordinates Error: ", vo.getTransformationXMLResponseString());
        }
        x = Double.parseDouble(vo.getTransformedCoordinateX());
        y = Double.parseDouble(vo.getTransformedCoordinateY());
        z = Double.parseDouble(vo.getTransformedCoordinateZ());
      }

      LOG.debug("X from Transformation Method: " + x);
      LOG.debug("Y from Transformation Method: " + y);
      LOG.debug("Z from Transformation Method: " + z);

      String srsFromClient = srsName;
      Point3d poiFromClient = new Point3d(x, y, z);

      // get plane; defaults to sagittal
      ImageSeriesPlane desiredPlane =
          filter.equals("maptype:coronal") ? ImageSeriesPlane.CORONAL : ImageSeriesPlane.SAGITTAL;

      // 1. get strong gene(s) at POI
      List<ABAGene> strongGenes = ABAUtil.retrieveStrongGenesAtAGEAPOI(x, y, z, NBR_STRONG_GENES);

      // make sure we have something
      if (strongGenes.size() == 0) {
        throw new OWSException(
            "No 'strong genes' found at " + "coordinates, hence no images to return.",
            ControllerException.NO_APPLICABLE_CODE);
      }

      if (LOG.isDebugEnabled()) {
        StringBuilder buf = new StringBuilder();
        for (ABAGene gene : strongGenes) {
          buf.append(gene.getGenesymbol()).append(", ");
        }
        LOG.debug("Strong genes: {}", buf.toString());
      }

      // 2. get image series'es for strong genes and desired plane
      List<ImageSeries> imageSerieses = new ArrayList<ImageSeries>();
      for (ABAGene gene : strongGenes) {
        ImageSeries imageSeries = retrieveImagesSeriesForGene(gene.getGenesymbol(), desiredPlane);
        if (imageSeries != null) {
          imageSerieses.add(imageSeries);
        }
      }

      // make sure we have something
      if (imageSerieses.size() == 0) {
        throw new OWSException(
            "No image series found for 'strong "
                + "genes' and desired plane, hence no images to "
                + "return.",
            ControllerException.NO_APPLICABLE_CODE);
      }

      if (LOG.isDebugEnabled()) {
        StringBuilder buf = new StringBuilder();
        for (ImageSeries is : imageSerieses) {
          buf.append(is.imageSeriesId).append(':');
          buf.append(is.imageSeriesPlane).append(", ");
        }
        LOG.debug("Image Serieses id:plane: {}", buf.toString());
      }

      Point3d poiForProximity = new Point3d(poiFromClient);

      // divide POI coords by 100
      Point3d poi100 = new Point3d();
      poi100.scale(0.01, poiForProximity);

      LOG.debug("POI for closest position (srs, xyz): {}, {}", srsFromClient, poi100.toString());

      // 3. get ......... for each image series
      for (ImageSeries imageSeries : imageSerieses) {

        // begin to add values to image
        Image image = new Image(imageSeries.imageSeriesId);

        // get atlas map
        // find closest point, get other values including position
        // add more (atlas map) values to image
        getClosestPosition(imageSeries, poi100, image);

        LOG.debug("Position: {}", image.abaImagePosition);

        // get best image id in image series based on position
        // add more (image elements) values to image
        // match position to find image in series, get imageid
        //  /image-series/images/image/position
        //  /image-series/images/image/imageid
        retrieveImageForPosition(imageSeries.imageSeriesId, image.abaImagePosition, image);

        LOG.debug("Image id: {}", image.imageId);

        // zoom level not applicable
        // image.zoomLevel = zoomLevel;

        // assemble aba view image uri
        image.imageURI = assembleImageURI(image.downloadImagePath, HI_RES, MIME);
        image.thumbnailurl = assembleImageURI(image.downloadImagePath, THUMB, MIME);

        LOG.debug("Image URI: {}", image.imageURI.toString());

        responseValues.images.add(image);
      } // for

      // ImagesResponseDocument 'is a' org.apache.xmlbeans.XmlObject
      //	'is a' org.apache.xmlbeans.XmlTokenSource
      ImagesResponseDocument document = completeResponse();

      if (LOG.isDebugEnabled()) {
        XmlOptions opt = (new XmlOptions()).setSavePrettyPrint();
        opt.setSaveSuggestedPrefixes(Utilities.SuggestedNamespaces());
        opt.setSaveNamespacesFirst();
        opt.setSaveAggressiveNamespaces();
        opt.setUseDefaultNamespace();
        LOG.debug("Xml:\n{}", document.xmlText(opt));
      }

      // 4. Send it
      // get reader on document
      XMLStreamReader reader = document.newXMLStreamReader();

      // get ComplexOutput object from ProcessletOutput...
      ComplexOutput complexOutput = (ComplexOutput) out.getParameter("Get2DImagesByPOIOutput");

      LOG.debug("Setting complex output (requested=" + complexOutput.isRequested() + ")");

      // ComplexOutput objects can be huge so stream it
      XMLStreamWriter writer = complexOutput.getXMLStreamWriter();
      XMLAdapter.writeElement(writer, reader);

      // transform any exceptions into ProcessletException wrapping
      // OWSException
    } catch (MissingParameterException e) {
      LOG.error(e.getMessage(), e);
      throw new ProcessletException(new OWSException(e));
    } catch (InvalidParameterValueException e) {
      LOG.error(e.getMessage(), e);
      throw new ProcessletException(new OWSException(e));
    } catch (InvalidDataInputValueException e) {
      LOG.error(e.getMessage(), e);
      throw new ProcessletException(e); // is already OWSException
    } catch (OWSException e) {
      LOG.error(e.getMessage(), e);
      throw new ProcessletException(e); // is already OWSException
    } catch (Throwable e) {
      String message = "Unexpected exception occurred: " + e.getMessage();
      LOG.error(message, e);
      throw new ProcessletException(
          new OWSException(message, e, ControllerException.NO_APPLICABLE_CODE));
    }
  }
Esempio n. 7
0
 /**
  * Copies an XML element (including all attributes and subnodes) from the given {@link
  * XMLStreamReader} to the given {@link XMLStreamWriter}.
  *
  * @param writer {@link XMLStreamWriter} that the xml is appended to
  * @param reader cursor must point at a <code>START_ELEMENT</code> event and points at the
  *     corresponding <code>END_ELEMENT</code> event afterwards
  * @throws XMLStreamException
  */
 public static void copy(XMLStreamWriter writer, XMLStreamReader reader)
     throws XMLStreamException {
   skipStartDocument(reader);
   XMLAdapter.writeElement(writer, reader);
 }
 private void writeAbstract(final XMLStreamWriter writer, final List<LanguageString> abstracts)
     throws XMLStreamException {
   if (abstracts != null && !abstracts.isEmpty()) {
     writeElement(writer, "Abstract", abstracts.get(0).getString());
   }
 }
 private void writeName(final XMLStreamWriter writer, final String name)
     throws XMLStreamException {
   if (name != null) {
     writeElement(writer, "Name", name);
   }
 }
  @Override
  public void process(ProcessletInputs in, ProcessletOutputs out, ProcessletExecutionInfo info)
      throws ProcessletException {

    try {

      WHSServiceVO vo = new WHSServiceVO();

      URL processDefinitionUrl =
          this.getClass().getResource("/" + this.getClass().getSimpleName() + ".xml");
      DataInputHandler dataInputHandler =
          new DataInputHandler(new File(processDefinitionUrl.toURI()));
      String srsName = dataInputHandler.getValidatedStringValue(in, "srsName");
      String x = String.valueOf(DataInputHandler.getDoubleInputValue(in, "x"));
      String y = String.valueOf(DataInputHandler.getDoubleInputValue(in, "y"));
      String z = String.valueOf(DataInputHandler.getDoubleInputValue(in, "z"));
      String tolerance = dataInputHandler.getValidatedStringValue(in, "tolerance");
      String filter = dataInputHandler.getValidatedStringValue(in, "filter");

      vo.setFromSRSCodeOne(srsName);
      vo.setFromSRSCode(srsName);
      // vo.setToSRSCodeOne(agea);
      // vo.setToSRSCode(agea);
      vo.setTolerance(tolerance);
      vo.setFilter(filter);

      if (vo.getFilter().toLowerCase().startsWith("filepath:")) {
        vo.setFilter(vo.getFilter().replaceAll("filePath:", ""));
      }

      LOG.debug("From SRS Code: {}", vo.getFromSRSCodeOne());
      LOG.debug("Filter: {}", vo.getFilter());

      // validate data inputs
      vo.setOriginalCoordinateX(x);
      vo.setOriginalCoordinateY(y);
      vo.setOriginalCoordinateZ(z);
      String transformedCoordinatesString = "";

      if (vo.getFromSRSCode().equalsIgnoreCase("image")) {
        vo.setTransformedCoordinateX(vo.getOriginalCoordinateX());
        vo.setTransformedCoordinateY(vo.getOriginalCoordinateY());
        vo.setTransformedCoordinateZ(vo.getOriginalCoordinateZ());
      } else if (vo.getFromSRSCode().equalsIgnoreCase(abaReference)) {
        vo.setTransformedCoordinateX(vo.getOriginalCoordinateX());
        vo.setTransformedCoordinateY(vo.getOriginalCoordinateY());
        vo.setTransformedCoordinateZ(vo.getOriginalCoordinateZ());
      } else {
        // Call getTransformationChain method here...
        // ABAVoxel
        vo.setOriginalCoordinateX(";x=" + vo.getOriginalCoordinateX());
        vo.setOriginalCoordinateY(";y=" + vo.getOriginalCoordinateY());
        vo.setOriginalCoordinateZ(";z=" + vo.getOriginalCoordinateZ());
        vo.setToSRSCode(abaReference);
        vo.setToSRSCodeOne(abaReference);

        // Construct GetTransformationChain URL
        // http://132.239.131.188:8080/atlas-ucsd?service=WPS&version=1.0.0&request=Execute&Identifier=GetTransformationChain&DataInputs=inputSrsName=Mouse_Paxinos_1.0;outputSrsName=Mouse_ABAreference_1.0;filter=Cerebellum

        // Start - FIXME - Uncomment below two lines and comment the
        // other three lines
        // String hostName = uri.getHost();
        // String portNumber = delimitor + uri.getPort();
        String delimitor = config.getValue("incf.deploy.port.delimitor");
        hostName = config.getValue("incf.deploy.host.name");
        portNumber = config.getValue("incf.aba.port.number");
        portNumber = delimitor + portNumber;
        // End - FIXME

        // central/atlas
        String servicePath =
            "/central/atlas?service=WPS&version=1.0.0&request=Execute&Identifier=GetTransformationChain&DataInputs=inputSrsName="
                + vo.getFromSRSCode()
                + ";outputSrsName="
                + vo.getToSRSCode()
                + ";filter=NONE";
        String transformationChainURL = "http://" + hostName + portNumber + servicePath;
        XMLUtilities xmlUtilities = new XMLUtilities();
        transformedCoordinatesString =
            xmlUtilities.coordinateTransformation(
                transformationChainURL,
                vo.getOriginalCoordinateX(),
                vo.getOriginalCoordinateY(),
                vo.getOriginalCoordinateZ());

        // Start - exception handling
        if (transformedCoordinatesString.startsWith("Error:")) {
          throw new OWSException("Transformed Coordinates Error: ", transformedCoordinatesString);
        }
        // End - exception handling
        WHSUtil util = new WHSUtil();
        String[] tempArray = util.getTabDelimNumbers(transformedCoordinatesString);
        vo.setTransformedCoordinateX(tempArray[0]);
        vo.setTransformedCoordinateY(tempArray[1]);
        vo.setTransformedCoordinateZ(tempArray[2]);
      }
      // End

      AnnotationResponseDocument document = completeResponse(vo);

      ArrayList errorList = new ArrayList();
      // opt.setErrorListener(errorList);
      // boolean isValid = document.validate(opt);

      // If the XML isn't valid, loop through the listener's contents,
      // printing contained messages.
      /*			if (!isValid) {
      				for (int i = 0; i < errorList.size(); i++) {
      					XmlError error = (XmlError) errorList.get(i);

      					LOG.debug("\n");
      					LOG.debug("Message: {}" , error.getMessage() + "\n");
      					LOG.debug("Location of invalid XML: {}"
      							, error.getCursorLocation().xmlText() + "\n");
      				}
      			}
      */

      ComplexOutput complexOutput = (ComplexOutput) out.getParameter("GetAnnotationsByPOIOutput");

      // get reader on document; reader --> writer
      XMLStreamReader reader = document.newXMLStreamReader();
      XMLStreamWriter writer = complexOutput.getXMLStreamWriter();
      XMLAdapter.writeElement(writer, reader);

    } catch (MissingParameterException e) {
      LOG.error(e.getMessage(), e);
      throw new ProcessletException(new OWSException(e));
    } catch (InvalidParameterValueException e) {
      LOG.error(e.getMessage(), e);
      throw new ProcessletException(new OWSException(e));
    } catch (Throwable e) {
      String message = "Unexpected exception occured";
      LOG.error(message, e);
      OWSException owsException =
          new OWSException(message, e, ControllerException.NO_APPLICABLE_CODE);
      throw new ProcessletException(owsException);
    }
  }