@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. 2
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;
  }
Esempio n. 3
0
  void parse(String layerName, XMLAdapter adapter, List<SLDStyleType> styles) {
    File stylesDir = new File(workspace.getLocation(), "styles");

    for (SLDStyleType sty : styles) {
      try {
        File file = new File(adapter.resolve(sty.getFile()).toURI());

        String namedLayer = sty.getNamedLayer();
        LOG.debug("Will read styles from SLD '{}', for named layer '{}'.", file, namedLayer);
        Map<String, String> map = new HashMap<String, String>();
        Map<String, Pair<File, URL>> legends = new HashMap<String, Pair<File, URL>>();
        Map<String, Boolean> glgUrls = new HashMap<String, Boolean>();
        extractFromSld(sty, adapter, stylesDir, layerName, legends, glgUrls, map);

        if (file.getParentFile().equals(stylesDir)) {
          handleSldFromStyleStore(file, namedLayer, map, layerName, legends, glgUrls);
        }

        handleExternalSld(file, namedLayer, layerName, map, legends, glgUrls);
      } catch (Throwable e) {
        LOG.trace("Stack trace", e);
        LOG.info(
            "Style file '{}' for layer '{}' could not be parsed: '{}'.",
            new Object[] {sty.getFile(), layerName, e.getLocalizedMessage()});
      }
    }
  }
Esempio n. 4
0
  private void extractFromSld(
      SLDStyleType sty,
      XMLAdapter adapter,
      File stylesDir,
      String layerName,
      Map<String, Pair<File, URL>> legends,
      Map<String, Boolean> glgUrls,
      Map<String, String> map)
      throws Throwable {
    String name = null, lastName = null;
    for (JAXBElement<?> elem : sty.getNameAndUserStyleAndLegendConfigurationFile()) {
      if (elem.getName().getLocalPart().equals("Name")) {
        name = elem.getValue().toString();
      } else if (elem.getName().getLocalPart().equals("LegendConfigurationFile")) {
        File legendFile = new File(adapter.resolve(elem.getValue().toString()).toURI());
        Style style = findStyle(legendFile, stylesDir, layerName);

        if (style != null) {
          if (name != null) {
            style.setName(name);
          }
          registry.putLegend(layerName, style, false);
        }
      } else if (elem.getName().getLocalPart().equals("LegendGraphicFile")) {
        LegendGraphicFile lgf = (LegendGraphicFile) elem.getValue();
        URL url = adapter.resolve(lgf.getValue());
        if (url.toURI().getScheme().equals("file")) {
          File legend = new File(url.toURI());
          legends.put(lastName, new Pair<File, URL>(legend, null));
        } else {
          legends.put(lastName, new Pair<File, URL>(null, url));
        }
        glgUrls.put(lastName, lgf.isOutputGetLegendGraphicUrl());
      } else if (elem.getName().getLocalPart().equals("UserStyle")) {
        if (name == null) {
          name = elem.getValue().toString();
        }
        LOG.debug(
            "Will load user style with name '{}', it will be known as '{}'.",
            elem.getValue(),
            name);
        map.put(elem.getValue().toString(), name);
        lastName = name;
        name = null;
      }
    }
  }
Esempio n. 5
0
  protected static Pair<Filter, ConstraintLanguage> parseConstraint(
      XMLAdapter adapter, OMElement omQueryElement) {
    Pair<Filter, ConstraintLanguage> pc = null;
    if (omQueryElement != null
        && new QName(CSWConstants.CSW_202_NS, "Constraint").equals(omQueryElement.getQName())) {
      Version versionConstraint =
          adapter.getRequiredNodeAsVersion(omQueryElement, new XPath("@version", nsContext));

      OMElement filterEl = omQueryElement.getFirstChildWithName(new QName(OGCNS, "Filter"));
      OMElement cqlTextEl = omQueryElement.getFirstChildWithName(new QName("", "CQLTEXT"));
      if ((filterEl != null) && (cqlTextEl == null)) {

        ConstraintLanguage constraintLanguage = ConstraintLanguage.FILTER;
        Filter constraint;
        try {
          // TODO remove usage of wrapper (necessary at the moment to work around problems
          // with AXIOM's

          XMLStreamReader xmlStream =
              new XMLStreamReaderWrapper(filterEl.getXMLStreamReaderWithoutCaching(), null);
          // skip START_DOCUMENT
          xmlStream.nextTag();

          if (versionConstraint.equals(new Version(1, 1, 0))) {

            constraint = Filter110XMLDecoder.parse(xmlStream);

          } else if (versionConstraint.equals(new Version(1, 0, 0))) {
            constraint = Filter100XMLDecoder.parse(xmlStream);
          } else {
            String msg =
                Messages.get(
                    "CSW_FILTER_VERSION_NOT_SPECIFIED",
                    versionConstraint,
                    Version.getVersionsString(new Version(1, 1, 0)),
                    Version.getVersionsString(new Version(1, 0, 0)));
            LOG.info(msg);
            throw new InvalidParameterValueException(msg);
          }
        } catch (XMLStreamException e) {
          String msg =
              "FilterParsingException: There went something wrong while parsing the filter expression, so please check this!";
          LOG.debug(msg);
          throw new XMLParsingException(adapter, filterEl, e.getMessage());
        }
        pc = new Pair<Filter, CSWConstants.ConstraintLanguage>(constraint, constraintLanguage);
      } else if ((filterEl == null) && (cqlTextEl != null)) {
        String msg = Messages.get("CSW_UNSUPPORTED_CQL_FILTER");
        LOG.info(msg);
        throw new NotImplementedError(msg);
      } else {
        String msg = Messages.get("CSW_MISSING_FILTER_OR_CQL");
        LOG.debug(msg);
        throw new InvalidParameterValueException(msg);
      }
    }
    return pc;
  }
 /**
  * @param datasource
  * @param adapter
  * @return a corresponding raster, null if files could not be fund
  */
 public static AbstractRaster fromDatasource(RasterDataSource datasource, XMLAdapter adapter) {
   if (datasource != null) {
     String defCRS = datasource.getCrs();
     CRS crs = null;
     if (defCRS != null) {
       crs = new CRS(defCRS);
     }
     RasterFileSetType directory = datasource.getRasterDirectory();
     RasterFileType file = datasource.getRasterFile();
     try {
       if (directory != null) {
         File rasterFiles = new File(adapter.resolve(directory.getValue()).getFile());
         boolean recursive = directory.isRecursive() == null ? false : directory.isRecursive();
         RasterIOOptions options = new RasterIOOptions();
         if (crs != null) {
           options.add(RasterIOOptions.CRS, crs.getName());
         }
         return buildTiledRaster(rasterFiles, directory.getFilePattern(), recursive, options);
       }
       if (file != null) {
         final File loc = new File(adapter.resolve(file.getValue()).getFile());
         AbstractRaster raster = loadRasterFromFile(loc);
         raster.setCoordinateSystem(crs);
         return raster;
       }
     } catch (MalformedURLException e) {
       if (directory != null) {
         LOG.warn(
             "Could not resolve the file {}, corresponding data will not be available.",
             directory.getValue());
       } else {
         LOG.warn(
             "Could not resolve the file {}, corresponding data will not be available.",
             file.getValue());
       }
     } catch (IOException e) {
       LOG.warn(
           "Could not load the file {}, corresponding data will not be available.",
           file.getValue());
     }
   }
   throw new NullPointerException("The configured raster datasource may not be null.");
 }
  @Override
  public GeoCouchFeatureStore create(URL configURL) throws ResourceInitException {

    GeoCouchFeatureStore fs = null;
    try {
      GeoCouchFeatureStoreConfig config =
          (GeoCouchFeatureStoreConfig)
              JAXBUtils.unmarshall(CONFIG_JAXB_PACKAGE, CONFIG_SCHEMA, configURL, workspace);

      XMLAdapter resolver = new XMLAdapter();
      resolver.setSystemId(configURL.toString());

      String srs = config.getStorageCRS();
      srs = srs.trim();
      ICRS crs = CRSManager.getCRSRef(srs);

      String couchUrl = config.getGeoCouchUrl();
      if (!couchUrl.endsWith("/")) {
        couchUrl += "/";
      }

      List<String> configSchemas = config.getGMLSchema();
      String[] schemas = new String[configSchemas.size()];
      int i = -1;
      for (String s : configSchemas) {
        schemas[++i] = resolver.resolve(s).toString();
      }

      GMLAppSchemaReader decoder = new GMLAppSchemaReader(null, null, schemas);
      AppSchema schema = decoder.extractAppSchema();

      fs = new GeoCouchFeatureStore(crs, schema, couchUrl);

    } catch (Throwable e) {

      String msg =
          "Error in feature store configuration file '" + configURL + "': " + e.getMessage();
      LOG.error(msg);
      throw new ResourceInitException(msg, e);
    }
    return fs;
  }
 /**
  * @param datasource
  * @param adapter
  * @return a corresponding raster
  */
 public static MultiResolutionRaster fromDatasource(
     MultiResolutionDataSource datasource, XMLAdapter adapter) {
   if (datasource != null) {
     String defCRS = datasource.getCrs();
     CRS crs = null;
     if (defCRS != null) {
       crs = new CRS(defCRS);
     }
     MultiResolutionRaster mrr = new MultiResolutionRaster();
     mrr.setCoordinateSystem(crs);
     for (Resolution resolution : datasource.getResolution()) {
       JAXBElement<? extends AbstractGeospatialDataSourceType> dsElement =
           resolution.getAbstractGeospatialDataSource();
       RasterDataSource ds = (RasterDataSource) dsElement.getValue();
       RasterFileSetType directory = ds.getRasterDirectory();
       File resolutionDir;
       try {
         resolutionDir = new File(adapter.resolve(directory.getValue()).getFile());
         RasterIOOptions options = new RasterIOOptions();
         if (crs != null) {
           options.add(RasterIOOptions.CRS, crs.getName());
         }
         AbstractRaster rasterLevel =
             buildTiledRaster(
                 resolutionDir, directory.getFilePattern(), directory.isRecursive(), options);
         // double res = RasterBuilder.getPixelResolution( resolution.getRes(), resolutionDir );
         mrr.addRaster(rasterLevel);
       } catch (MalformedURLException e) {
         LOG.warn(
             "Could not resolve the file {}, corresponding data will not be available.",
             directory.getValue());
       }
     }
     return mrr;
   }
   throw new NullPointerException("The configured multi resolution datasource may not be null.");
 }
  @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. 10
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);
 }
Esempio n. 11
0
  public static Query getQuery(OMElement omElement) {
    if (new QName(CSWConstants.CSW_202_NS, "Query").equals(omElement.getQName())) {
      XMLAdapter adapter = new XMLAdapter(omElement);
      SortProperty[] sortProps = null;
      Filter constraint = null;
      ReturnableElement elementSetName = null;
      String[] elementName = null;
      ConstraintLanguage constraintLanguage = null;

      List<OMElement> queryChildElements =
          adapter.getRequiredElements(omElement, new XPath("*", nsContext));

      String typeQuery =
          adapter.getNodeAsString(omElement, new XPath("./@typeNames", nsContext), "");

      if ("".equals(typeQuery)) {
        String msg =
            "ERROR in XML document: Required attribute \"typeNames\" in element \"Query\" is missing!";
        throw new MissingParameterException(msg);
      }

      String[] queryTypeNamesString = StringUtils.split(typeQuery, " ");
      QName[] queryTypeNames = new QName[queryTypeNamesString.length];
      int counterQName = 0;
      for (String s : queryTypeNamesString) {
        LOG.debug("Parsing typeName '" + s + "' of Query as QName. ");
        QName qname = adapter.parseQName(s, adapter.getRootElement());
        queryTypeNames[counterQName++] = qname;
      }
      elementName = adapter.getNodesAsStrings(omElement, new XPath("./csw:ElementName", nsContext));
      QName[] returnTypeNames = null;
      for (OMElement omQueryElement : queryChildElements) {

        // TODO mandatory exclusiveness between ElementSetName vs. ElementName not implemented yet
        if (new QName(CSWConstants.CSW_202_NS, "ElementSetName")
            .equals(omQueryElement.getQName())) {
          String elementSetNameString = omQueryElement.getText();
          elementSetName = ReturnableElement.determineReturnableElement(elementSetNameString);

          // elementSetNameTypeNames = getNodesAsQNames( omQueryElement, new XPath( "@typeNames",
          // nsContext ) );
          String typeElementSetName =
              adapter
                  .getNodeAsString(omQueryElement, new XPath("./@typeNames", nsContext), "")
                  .trim();
          String[] elementSetNameTypeNamesString = StringUtils.split(typeElementSetName, " ");
          returnTypeNames = new QName[elementSetNameTypeNamesString.length];
          for (int i = 0; i < elementSetNameTypeNamesString.length; i++) {
            returnTypeNames[i] = adapter.parseQName(elementSetNameTypeNamesString[i], omElement);
          }
        }
        Pair<Filter, ConstraintLanguage> parsedConstraint =
            parseConstraint(adapter, omQueryElement);
        if (parsedConstraint != null) {
          constraintLanguage = parsedConstraint.second;
          constraint = parsedConstraint.first;
        }

        if (new QName(OGCNS, "SortBy").equals(omQueryElement.getQName())) {

          List<OMElement> sortPropertyElements =
              adapter.getRequiredElements(omQueryElement, new XPath("ogc:SortProperty", nsContext));
          sortProps = new SortProperty[sortPropertyElements.size()];
          int counter = 0;
          for (OMElement sortPropertyEl : sortPropertyElements) {
            OMElement propNameEl =
                adapter.getRequiredElement(
                    sortPropertyEl, new XPath("ogc:PropertyName", nsContext));
            String sortOrder =
                adapter.getNodeAsString(
                    sortPropertyEl, new XPath("ogc:SortOrder", nsContext), "ASC");
            SortProperty sortProp =
                new SortProperty(
                    new ValueReference(
                        propNameEl.getText(), adapter.getNamespaceContext(propNameEl)),
                    sortOrder.equals("ASC"));
            sortProps[counter++] = sortProp;
          }
        }
      }
      return new Query(
          elementSetName,
          elementName,
          constraint,
          constraintLanguage,
          sortProps,
          queryTypeNames,
          returnTypeNames);
    }
    return null;
  }
Esempio n. 12
0
  @SuppressWarnings("boxing")
  private static GetFeature parse110(Map<String, String> kvpParams) throws Exception {

    StandardPresentationParams presentationParams =
        parseStandardPresentationParameters110(kvpParams);
    ResolveParams resolveParams = parseStandardResolveParameters110(kvpParams);

    // optional: 'NAMESPACE'
    Map<String, String> nsBindings = extractNamespaceBindings110(kvpParams);
    if (nsBindings == null) {
      nsBindings = Collections.emptyMap();
    }

    NamespaceBindings nsContext = new NamespaceBindings();
    if (nsBindings != null) {
      for (String key : nsBindings.keySet()) {
        nsContext.addNamespace(key, nsBindings.get(key));
      }
    }

    // optional: SRSNAME
    String srsName = kvpParams.get("SRSNAME");
    ICRS srs = null;
    if (srsName != null) {
      srs = CRSManager.getCRSRef(srsName);
    }

    // optional: 'PROPERTYNAME'
    String propertyStr = kvpParams.get("PROPERTYNAME");
    PropertyName[][] propertyNames = getPropertyNames(propertyStr, nsContext);

    // optional: SORTBY
    String sortbyStr = kvpParams.get("SORTBY");
    SortProperty[] sortBy = getSortBy(sortbyStr, nsContext);

    // optional: FEATUREVERSION
    String featureVersion = kvpParams.get("FEATUREVERSION");

    // mandatory: TYPENAME, but optional if FEATUREID is specified
    String typeStrList = kvpParams.get("TYPENAME");
    TypeName[] typeNames = getTypeNames(typeStrList, nsBindings);

    // optional: FEATUREID
    String featureIdStr = kvpParams.get("FEATUREID");
    String[] featureIds = null;
    if (featureIdStr != null) {
      featureIds = featureIdStr.split(",");
    }
    // optional: BBOX
    String bboxStr = kvpParams.get("BBOX");

    // optional: FILTER
    String filterStr = kvpParams.get("FILTER");

    // optional: 'PROPTRAVXLINKDEPTH'
    String propTravXlinkDepth = kvpParams.get("PROPTRAVXLINKDEPTH");
    String[][] ptxDepthAr = null;
    if (propTravXlinkDepth != null) {
      ptxDepthAr = parseParamList(propTravXlinkDepth);
    }

    // optional: 'PROPTRAVXLINKEXPIRY'
    String propTravXlinkExpiry = kvpParams.get("PROPTRAVXLINKEXPIRY");
    Integer[][] ptxExpAr = null;
    if (propTravXlinkExpiry != null) {
      ptxExpAr = parseParamListAsInts(propTravXlinkDepth);
    }

    propertyNames = getXLinkPropNames(propertyNames, ptxDepthAr, ptxExpAr);
    List<Query> queries = new ArrayList<Query>();

    if ((featureIdStr != null && bboxStr != null)
        || (featureIdStr != null && filterStr != null)
        || (bboxStr != null && filterStr != null)) {
      // TODO make new exception
      throw new Exception("The FEATUREID, BBOX and FILTER keywords are mutually exclusive!");
    }

    if (featureIdStr != null) {
      if (typeStrList == null && propertyNames == null) {
        queries.add(new FeatureIdQuery(null, null, featureVersion, srs, null, sortBy, featureIds));
      } else {
        for (int i = 0; i < featureIds.length; i++) {
          String[] fid = new String[] {featureIds[i]};
          TypeName[] typeName = new TypeName[0];
          if (typeStrList != null) {
            typeName = new TypeName[] {typeNames[i]};
          }
          PropertyName[] projectionClauses = null;
          if (propertyNames != null) {
            projectionClauses = propertyNames[i];
          }
          queries.add(
              new FeatureIdQuery(
                  null, typeName, featureVersion, srs, projectionClauses, sortBy, fid));
        }
      }
    } else if (bboxStr != null) {
      if (typeNames == null) {
        // TODO make new exception
        throw new Exception("The TYPENAME keyword is mandatory if BBOX is present!");
      }

      String[] coordList = bboxStr.split(",");

      // NOTE: Contradiction between spec and CITE tests (for omitted crsUri)
      // - WFS 1.1.0 spec, 14.3.3: coordinates should be in WGS84
      // - CITE tests, wfs:wfs-1.1.0-Basic-GetFeature-tc8.1: If no CRS reference is provided, a
      // service-defined
      // default value must be assumed.
      ICRS bboxCrs = null;
      if (coordList.length % 2 == 1) {
        bboxCrs = CRSManager.getCRSRef(coordList[coordList.length - 1]);
      }

      Envelope bbox = createEnvelope(bboxStr, bboxCrs);
      for (int i = 0; i < typeNames.length; i++) {
        TypeName typeName = typeNames[i];
        PropertyName[] projectionClauses = null;
        if (propertyNames != null) {
          projectionClauses = propertyNames[i];
        }
        queries.add(
            new BBoxQuery(
                null,
                new TypeName[] {typeName},
                featureVersion,
                srs,
                projectionClauses,
                sortBy,
                bbox));
      }
    } else if (filterStr != null || typeNames != null) {
      if (typeNames == null) {
        // TODO make new exception
        throw new Exception("The FILTER element requires the TYPENAME element");
      }

      int length = typeNames.length;

      String[] filters = getFilters(filterStr);

      for (int i = 0; i < length; i++) {
        Filter filter = null;
        if (filters != null) {

          StringReader sr = new StringReader(filters[i]);
          XMLAdapter adapter = new XMLAdapter(sr);
          XMLStreamReaderWrapper streamWrapper =
              new XMLStreamReaderWrapper(
                  adapter.getRootElement().getXMLStreamReaderWithoutCaching(),
                  adapter.getSystemId());
          try {
            streamWrapper.nextTag();
            filter = Filter110XMLDecoder.parse(streamWrapper);
          } catch (XMLParsingException e) {
            e.printStackTrace();
            // TODO raise exception
          } catch (XMLStreamException e) {
            e.printStackTrace();
            // TODO raise exception
          }
        }
        if (propertyNames != null) {
          queries.add(
              new FilterQuery(
                  null,
                  new TypeName[] {typeNames[i]},
                  featureVersion,
                  srs,
                  propertyNames[i],
                  sortBy,
                  filter));
        } else {
          queries.add(
              new FilterQuery(
                  null, new TypeName[] {typeNames[i]}, featureVersion, srs, null, sortBy, filter));
        }
      }
    }
    return new GetFeature(VERSION_110, null, presentationParams, resolveParams, queries);
  }
Esempio n. 13
0
  @SuppressWarnings("boxing")
  private static GetFeature parse100(Map<String, String> kvpParams, Map<String, String> nsMap)
      throws Exception {

    NamespaceBindings nsContext = new NamespaceBindings();
    if (nsMap != null) {
      for (String key : nsMap.keySet()) {
        nsContext.addNamespace(key, nsMap.get(key));
      }
    }

    StandardPresentationParams presentationParams =
        parseStandardPresentationParameters100(kvpParams);

    // optional: 'PROPERTYNAME'
    String propertyStr = kvpParams.get("PROPERTYNAME");
    PropertyName[][] propertyNames = getPropertyNames(propertyStr, nsContext);

    // optional: FEATUREVERSION
    String featureVersion = kvpParams.get("FEATUREVERSION");

    // mandatory: TYPENAME, but optional if FEATUREID is specified
    String typeStrList = kvpParams.get("TYPENAME");
    TypeName[] typeNames = getTypeNames100(typeStrList);

    // optional: FEATUREID
    String featureIdStr = kvpParams.get("FEATUREID");
    String[] featureIds = null;
    if (featureIdStr != null) {
      featureIds = featureIdStr.split(",");
    }
    // optional: BBOX
    String bboxStr = kvpParams.get("BBOX");

    // optional: FILTER
    String filterStr = kvpParams.get("FILTER");

    // optional: SRSNAME (not specified in WFS 1.0.0, deegree extension)
    String srsName = kvpParams.get("SRSNAME");
    ICRS srs = null;
    if (srsName != null) {
      srs = CRSManager.getCRSRef(srsName);
    }

    List<Query> queries = new ArrayList<Query>();

    if ((featureIdStr != null && bboxStr != null)
        || (featureIdStr != null && filterStr != null)
        || (bboxStr != null && filterStr != null)) {
      // TODO make new exception
      throw new Exception("The FEATUREID, BBOX and FILTER keywords are mutually exclusive!");
    }

    if (featureIdStr != null) {
      if (typeStrList == null && propertyNames == null) {
        queries.add(new FeatureIdQuery(null, null, featureVersion, srs, null, null, featureIds));
      } else {
        for (int i = 0; i < featureIds.length; i++) {
          String[] fids = new String[] {featureIds[i]};
          TypeName[] typeName = new TypeName[0];
          if (typeStrList != null) {
            typeName = new TypeName[] {typeNames[i]};
          }
          PropertyName[] projectionClauses = null;
          if (propertyNames != null) {
            if (propertyNames.length > 1) {
              projectionClauses = propertyNames[i];
            } else {
              projectionClauses = propertyNames[0];
            }
          }
          queries.add(
              new FeatureIdQuery(
                  null, typeName, featureVersion, srs, projectionClauses, null, fids));
        }
      }
    } else if (bboxStr != null) {
      if (typeNames == null) {
        // TODO make new exception
        throw new Exception("The TYPENAME keyword is mandatory if BBOX is present!");
      }

      String[] coordList = bboxStr.split(",");
      ICRS bboxCrs = null;
      if (coordList.length % 2 == 1) {
        bboxCrs = CRSManager.getCRSRef(coordList[coordList.length - 1]);
      }

      Envelope bbox = createEnvelope(bboxStr, bboxCrs);
      for (int i = 0; i < typeNames.length; i++) {
        TypeName typeName = typeNames[i];
        PropertyName[] projectionClauses = null;
        if (propertyNames != null) {
          projectionClauses = propertyNames[i];
        }
        queries.add(
            new BBoxQuery(
                null,
                new TypeName[] {typeName},
                featureVersion,
                srs,
                projectionClauses,
                null,
                bbox));
      }
    } else if (filterStr != null || typeNames != null) {
      if (typeNames == null) {
        // TODO make new exception
        throw new Exception("The FILTER element requires the TYPENAME element");
      }

      int length = typeNames.length;

      String[] filters = getFilters(filterStr);

      for (int i = 0; i < length; i++) {
        Filter filter = null;
        if (filters != null) {

          StringReader sr = new StringReader(filters[i]);
          XMLAdapter adapter = new XMLAdapter(sr);
          XMLStreamReaderWrapper streamWrapper =
              new XMLStreamReaderWrapper(
                  adapter.getRootElement().getXMLStreamReaderWithoutCaching(),
                  adapter.getSystemId());
          try {
            streamWrapper.nextTag();
            filter = Filter100XMLDecoder.parse(streamWrapper);
          } catch (XMLParsingException e) {
            e.printStackTrace();
            // TODO raise exception
          } catch (XMLStreamException e) {
            e.printStackTrace();
            // TODO raise exception
          }
        }
        if (propertyNames != null) {
          queries.add(
              new FilterQuery(
                  null,
                  new TypeName[] {typeNames[i]},
                  featureVersion,
                  srs,
                  propertyNames[i],
                  null,
                  filter));
        } else {
          queries.add(
              new FilterQuery(
                  null, new TypeName[] {typeNames[i]}, featureVersion, srs, null, null, filter));
        }
      }
    }
    return new GetFeature(VERSION_100, null, presentationParams, null, queries);
  }
  @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);
    }
  }