org.apache.xmlbeans.XmlException Java Examples

The following examples show how to use org.apache.xmlbeans.XmlException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GetDataAvailabilityXmlEncoder.java    From arctic-sea with Apache License 2.0 6 votes vote down vote up
@Override
protected XmlObject create(GetDataAvailabilityResponse response)
        throws EncodingException {
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        EncodingContext ctx = EncodingContext.empty()
                .with(EncoderFlags.ENCODER_REPOSITORY, getEncoderRepository())
                .with(XmlEncoderFlags.XML_OPTIONS, (Supplier<XmlOptions>) this::getXmlOptions);
        if (GetDataAvailabilityConstants.NS_GDA.equals(response.getResponseFormat())) {
            new GetDataAvailabilityStreamWriter(ctx, baos, response.getDataAvailabilities()).write();
        } else if (GetDataAvailabilityConstants.NS_GDA_20.equals(response.getResponseFormat())) {
            new GetDataAvailabilityV20StreamWriter(ctx, baos, response.getDataAvailabilities()).write();
        }
        XmlObject encodedObject = XmlObject.Factory.parse(baos.toString("UTF8"));
        XmlHelper.validateDocument(encodedObject, EncodingException::new);
        return encodedObject;
    } catch (XMLStreamException | XmlException | UnsupportedEncodingException ex) {
        throw new EncodingException("Error encoding response", ex);
    }
}
 
Example #2
Source File: ShapefileMappingGenerator.java    From GeoTriples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws ClassNotFoundException, InstantiationException,
		IllegalAccessException, ClassCastException, FileNotFoundException, XmlException, IOException {
	if (args.length < 3) {
		System.err.println("Please give arguments, eg <shapefile> <outputfile> <baseiri> [out-ontologyfile]");
		System.exit(1);
	}
	// XMLMappingGenerator m=new XMLMappingGenerator("TF7.xsd" ,
	// "personal.xml" , "http://ex.com/" , true);
	boolean arg_gfeatures = false;
	for (String arg: args){
		if (arg.equals("-gfeatures")){
			arg_gfeatures = true;
		}
	}
	ShapefileMappingGenerator m = new ShapefileMappingGenerator(args[0], args[1], args[2],
			(args.length > 3) ? args[3] : null, arg_gfeatures);
	m.run();
}
 
Example #3
Source File: HydroMetadataHandler.java    From SensorWebClient with GNU General Public License v2.0 6 votes vote down vote up
private void executeFoiTasks(Map<String, FutureTask<OperationResult>> getFoiAccessTasks, SOSMetadata metadata) throws InterruptedException,
        ExecutionException,
        XmlException,
        IOException,
        OXFException {
    int counter;
    counter = getFoiAccessTasks.size();
    LOGGER.debug("Sending {} GetFeatureOfInterest requests", counter);
    for (String procedureID : getFoiAccessTasks.keySet()) {
        LOGGER.debug("Sending #{} GetFeatureOfInterest request for procedure '{}'", counter--, procedureID);
        FutureTask<OperationResult> futureTask = getFoiAccessTasks.get(procedureID);
        AccessorThreadPool.execute(futureTask);
        try {
            OperationResult opRes = futureTask.get(metadata.getTimeout(), MILLISECONDS);
            GetFeatureOfInterestParser getFoiParser = new GetFeatureOfInterestParser(opRes, metadata);
            getFoiParser.createFeatures();
        }
        catch (TimeoutException e) {
            LOGGER.error("Timeout occured.", e);
        }
    }
}
 
Example #4
Source File: XMLMappingGeneratorTrans.java    From GeoTriples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws ClassNotFoundException,
		InstantiationException, IllegalAccessException, ClassCastException,
		FileNotFoundException, XmlException, IOException {
	if (args.length < 4) {
		System.err
				.println("Please give arguments, eg <xsdfile> <xmlfile> <outputfile> <baseiri> <rootelement> <basepath> <namespaces> [<true or false> for generating classes for elements without type name]");
		System.exit(1);
	}
	// XMLMappingGenerator m=new XMLMappingGenerator("TF7.xsd" ,
	// "personal.xml" , "http://ex.com/" , true);
	boolean arg_gfeatures = false;
	for (String arg: args){
		if (arg.equals("-gfeatures")){
			arg_gfeatures = true;
		}
	}
	XMLMappingGeneratorTrans m = new XMLMappingGeneratorTrans(args[0], args[1],
			args[2], args[3], args[4], args[5], args[6],
			(args.length > 7) ? Boolean.valueOf(args[7]) : false,
			(args.length > 8) ? args[8] : null, (args.length > 9) ? args[9]
					: null, arg_gfeatures);
	m.run();
}
 
Example #5
Source File: GetResultTemplateResponseEncoder.java    From arctic-sea with Apache License 2.0 6 votes vote down vote up
private void encodeResultStructure(GetResultTemplateResponse t, ObjectNode json)
        throws EncodingException {
    ObjectNode jrs = json.putObject(JSONConstants.RESULT_STRUCTURE);
    SweAbstractDataComponent structure;
    SosResultStructure rs = t.getResultStructure();
    if (rs.isDecoded()) {
        structure = t.getResultStructure().get().get();
    } else {
        try {
            XmlNamespaceDecoderKey key =
                    new XmlNamespaceDecoderKey(SweConstants.NS_SWE_20, SweAbstractDataComponent.class);
            Decoder<SweAbstractDataComponent, XmlObject> decoder = this.decoderRepository.getDecoder(key);
            if (decoder == null) {
                throw new NoDecoderForKeyException(key);
            }
            structure = decoder.decode(XmlObject.Factory.parse(rs.getXml().get()));
        } catch (XmlException | DecodingException ex) {
            throw new EncodingException(ex);
        }
    }
    if (structure instanceof SweDataRecord) {
        encodeSweDataRecord(structure, jrs);
    } else {
        LOG.warn("Unsupported structure: {}", structure == null ? null : structure.getClass());
    }
}
 
Example #6
Source File: XmlBeansMarshaller.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Convert the given XMLBeans exception to an appropriate exception from the
 * {@code org.springframework.oxm} hierarchy.
 * <p>A boolean flag is used to indicate whether this exception occurs during marshalling or
 * unmarshalling, since XMLBeans itself does not make this distinction in its exception hierarchy.
 * @param ex XMLBeans Exception that occured
 * @param marshalling indicates whether the exception occurs during marshalling ({@code true}),
 * or unmarshalling ({@code false})
 * @return the corresponding {@code XmlMappingException}
 */
protected XmlMappingException convertXmlBeansException(Exception ex, boolean marshalling) {
	if (ex instanceof XMLStreamValidationException) {
		return new ValidationFailureException("XMLBeans validation exception", ex);
	}
	else if (ex instanceof XmlException || ex instanceof SAXException) {
		if (marshalling) {
			return new MarshallingFailureException("XMLBeans marshalling exception",  ex);
		}
		else {
			return new UnmarshallingFailureException("XMLBeans unmarshalling exception", ex);
		}
	}
	else {
		// fallback
		return new UncategorizedMappingException("Unknown XMLBeans exception", ex);
	}
}
 
Example #7
Source File: WnsUtil.java    From SensorWebClient with GNU General Public License v2.0 6 votes vote down vote up
protected static XmlObject readXmlResponse(HttpResponse response) throws IOException {
    InputStream content = response.getEntity().getContent();
    StringBuilder sb = new StringBuilder();
    try {
        String line = "";
        BufferedReader reader = new BufferedReader(new InputStreamReader(content));
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        return XmlObject.Factory.parse(sb.toString());
    }
    catch (XmlException e) {
        LOGGER.error("Failed to parse WNS response: {}", sb.toString(), e);
        return XmlObject.Factory.newInstance();
    }
}
 
Example #8
Source File: CapabilitiesTypeDecoder.java    From arctic-sea with Apache License 2.0 6 votes vote down vote up
private SosObservationOffering parseOffering(AbstractContentsType.Offering offering) {
    SosObservationOffering observationOffering = new SosObservationOffering();
    if (offering.getDomNode().hasChildNodes()) {
        final Node node = XmlHelper.getNodeFromNodeList(offering.getDomNode().getChildNodes());
        try {
            ObservationOfferingPropertyType offeringType = ObservationOfferingPropertyType.Factory.parse(node);
            ObservationOfferingType obsOffPropType = offeringType.getObservationOffering();
            observationOffering.setOffering(parseOffering(obsOffPropType));
            observationOffering.setProcedures(parseProcedure(obsOffPropType));
            observationOffering.setProcedureDescriptionFormat(parseProcedureDescriptionFormat(obsOffPropType));
            observationOffering.setObservableProperties(parseObservableProperties(obsOffPropType));
            observationOffering.setRelatedFeatures(parseRelatedFeatures(obsOffPropType));
            observationOffering.setObservedArea(parseObservedArea(obsOffPropType));
            observationOffering.setPhenomenonTime(parsePhenomenonTime(obsOffPropType));
            observationOffering.setResultTime(parseResultTime(obsOffPropType));
            observationOffering.setResponseFormats(parseResponseFormats(obsOffPropType));
            observationOffering.setObservationTypes(parseObservationTypes(obsOffPropType));
            observationOffering.setFeatureOfInterestTypes(parseFeatureOfInterestTypes(obsOffPropType));
            observationOffering.setExtensions(parseOfferingExtension(obsOffPropType));
        } catch (XmlException | DecodingException ex) {
            LOGGER.error(ex.getLocalizedMessage(), ex);
        }
    }
    return observationOffering;
}
 
Example #9
Source File: SOSConnector.java    From SensorWebClient with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Replace special characters.
 *
 * @param xmlObject
 *        the xml object
 * @return the xml object
 */
private XmlObject replaceSpecialCharacters(XmlObject xmlObject) {
    String tempStr = xmlObject.toString();
    tempStr = tempStr.replace("Ä", "Ae");
    tempStr = tempStr.replace("Ö", "Oe");
    tempStr = tempStr.replace("Ü", "Ue");
    tempStr = tempStr.replace("ä", "ae");
    tempStr = tempStr.replace("ö", "oe");
    tempStr = tempStr.replace("ü", "ue");
    tempStr = tempStr.replace("ß", "ss");
    tempStr = tempStr.replace("´", "'");
    tempStr = tempStr.replace("`", "'");
    try {
        return XmlObject.Factory.parse(tempStr);
    }
    catch (XmlException e) {
        LOGGER.error("Error while replacing special characters: " + e.getMessage());
    }
    return null;
}
 
Example #10
Source File: ShapefileMappingGenerator.java    From GeoTriples with Apache License 2.0 6 votes vote down vote up
public ShapefileMappingGenerator(String shapefilefilename, String outputfile, String baseiri,
			String ontologyOutputFile, boolean in_gfeatures) throws ClassNotFoundException, InstantiationException, IllegalAccessException,
					ClassCastException, FileNotFoundException, XmlException, IOException {
		super(baseiri,outputfile);
//		System.out.println("shapefilefilename=" + shapefilefilename);
//		System.out.println("outputfile=" + outputfile);
//		System.out.println("baseiri" + baseiri);
		this.pathToShapefile = new File(shapefilefilename).getAbsolutePath();
		this.gfeatures= in_gfeatures;

//		System.out.println("ontologyOutputFile=" + ontologyOutputFile);
		

		
		if (ontologyOutputFile != null) {
			this.ontologyOutputFile = new File(ontologyOutputFile);
			ontology = new OntologyGenerator(true, baseURI);
		}
	}
 
Example #11
Source File: SosDecoderv20Test.java    From arctic-sea with Apache License 2.0 6 votes vote down vote up
@Test
public void should_decode_boolean_swesExtensions()
        throws XmlException, OwsExceptionReport, DecodingException {
    final GetObservationDocument doc =
            GetObservationDocument.Factory.parse("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
                    + "<sos:GetObservation service=\"SOS\" version=\"2.0.0\"\n"
                    + "    xmlns:sos=\"http://www.opengis.net/sos/2.0\"\n"
                    + "    xmlns:swe=\"http://www.opengis.net/swe/2.0\"\n"
                    + "    xmlns:swes=\"http://www.opengis.net/swes/2.0\">\n" + "    <swes:extension>\n"
                    + "        <swe:Boolean definition=\"MergeObservationsIntoDataArray\">\n"
                    + "            <swe:value>true</swe:value>\n" + "        </swe:Boolean>\n"
                    + "    </swes:extension>\n" + "</sos:GetObservation>");

    final OwsServiceCommunicationObject decodedObject = decoder.decode(doc);

    assertThat(decodedObject, instanceOf(GetObservationRequest.class));

    final GetObservationRequest request = (GetObservationRequest) decodedObject;
    assertThat(request.getBooleanExtension("MergeObservationsIntoDataArray"), is(TRUE));
}
 
Example #12
Source File: PowerPointOOXMLDocument.java    From olat with Apache License 2.0 6 votes vote down vote up
private void extractContent(final StringBuilder buffy, final XMLSlideShow xmlSlideShow) throws IOException, XmlException {
    final XSLFSlide[] slides = xmlSlideShow.getSlides();
    for (final XSLFSlide slide : slides) {
        final CTSlide rawSlide = slide._getCTSlide();
        final CTSlideIdListEntry slideId = slide._getCTSlideId();

        final CTNotesSlide notes = xmlSlideShow._getXSLFSlideShow().getNotes(slideId);
        final CTCommentList comments = xmlSlideShow._getXSLFSlideShow().getSlideComments(slideId);

        extractShapeContent(buffy, rawSlide.getCSld().getSpTree());

        if (comments != null) {
            for (final CTComment comment : comments.getCmArray()) {
                buffy.append(comment.getText()).append(' ');
            }
        }

        if (notes != null) {
            extractShapeContent(buffy, notes.getCSld().getSpTree());
        }
    }
}
 
Example #13
Source File: GetResultTemplateResponseEncoder.java    From arctic-sea with Apache License 2.0 6 votes vote down vote up
private ResultStructure createResultStructure(SosResultStructure resultStructure)
        throws EncodingException {
    // TODO move encoding to SWECommonEncoder
    final DataRecordDocument dataRecordDoc;
    if (resultStructure.isEncoded()) {
        try {
            dataRecordDoc = DataRecordDocument.Factory.parse(resultStructure.getXml().get());
        } catch (XmlException ex) {
            throw unsupportedResultStructure(ex);
        }
    } else {
        XmlObject xml = encodeSwe(EncodingContext.of(XmlBeansEncodingFlags.DOCUMENT), resultStructure.get().get());
        if (xml instanceof DataRecordDocument) {
            dataRecordDoc = (DataRecordDocument) xml;
        } else {
            throw unsupportedResultStructure();
        }
    }
    ResultStructure xbResultStructure = ResultStructure.Factory.newInstance(getXmlOptions());
    xbResultStructure.addNewAbstractDataComponent().set(dataRecordDoc.getDataRecord());
    XmlHelper.substituteElement(xbResultStructure.getAbstractDataComponent(), dataRecordDoc.getDataRecord());
    return xbResultStructure;
}
 
Example #14
Source File: GetResultTemplateResponseEncoder.java    From arctic-sea with Apache License 2.0 6 votes vote down vote up
private ResultEncoding createResultEncoding(SosResultEncoding resultEncoding)
        throws EncodingException {
    // TODO move encoding to SWECommonEncoder
    final TextEncodingDocument xbEncoding;
    if (resultEncoding.isEncoded()) {
        try {
            xbEncoding = TextEncodingDocument.Factory.parse(resultEncoding.getXml().get());
        } catch (XmlException ex) {
            throw unsupportedResultEncoding(ex);
        }
    } else {
        XmlObject xml = encodeSwe(EncodingContext.of(XmlBeansEncodingFlags.DOCUMENT), resultEncoding.get().get());
        if (xml instanceof TextEncodingDocument) {
            xbEncoding = (TextEncodingDocument) xml;
        } else {
            throw unsupportedResultEncoding();
        }

    }
    ResultEncoding xbResultEncoding = ResultEncoding.Factory.newInstance(getXmlOptions());
    xbResultEncoding.addNewAbstractEncoding().set(xbEncoding.getTextEncoding());
    XmlHelper.substituteElement(xbResultEncoding.getAbstractEncoding(), xbEncoding.getTextEncoding());
    return xbResultEncoding;
}
 
Example #15
Source File: SensorMLEncoderv20.java    From arctic-sea with Apache License 2.0 6 votes vote down vote up
@Override
public XmlObject encode(Object objectToEncode, EncodingContext additionalValues)
        throws EncodingException {
    XmlObject encodedObject = null;
    try {
        if (objectToEncode instanceof AbstractSensorML) {
            AbstractSensorML description = (AbstractSensorML) objectToEncode;
            if (description.isSetXml()) {
                encodedObject = XmlObject.Factory.parse(((AbstractSensorML) objectToEncode).getXml());
                addValuesToXmlObject(encodedObject, (AbstractSensorML) objectToEncode);
                encodedObject = checkForAdditionalValues(encodedObject, additionalValues);
            } else {
                encodedObject = encodeDescription(description, additionalValues);
            }
        } else {
            throw new UnsupportedEncoderInputException(this, objectToEncode);
        }
    } catch (XmlException xmle) {
        throw new EncodingException(xmle);
    }
    // check if all gml:id are unique
    XmlHelper.makeGmlIdsUnique(encodedObject.getDomNode());
    XmlHelper.validateDocument(encodedObject, EncodingException::new);
    return encodedObject;
}
 
Example #16
Source File: TrajectoryObservationTypeEncoderTest.java    From arctic-sea with Apache License 2.0 6 votes vote down vote up
private OmObservation createObservation() throws DecodingException, XmlException, IOException {
    DateTime now = new DateTime(DateTimeZone.UTC);
    TimeInstant resultTime = new TimeInstant(now);
    TrajectoryObservation observation = new TrajectoryObservation();
    observation.setObservationID("123");
    OmObservationConstellation observationConstellation = new OmObservationConstellation();
    observationConstellation
            .setFeatureOfInterest(new SamplingFeature(new CodeWithAuthority("feature", CODE_SPACE)));
    OmObservableProperty observableProperty = new OmObservableProperty(OBSERVABLE_PROPERTY);
    observationConstellation.setObservableProperty(observableProperty);
    observationConstellation.addOffering(OFFERING);
    Process procedure = createProcessFromFile();
    observationConstellation.setProcedure(procedure);
    observation.setObservationConstellation(observationConstellation);
    observation.setResultTime(resultTime);
    return observation;
}
 
Example #17
Source File: OrchestratorActivity.java    From mdw with Apache License 2.0 6 votes vote down vote up
protected boolean allSubProcessCompleted() throws ActivityException, XmlException {
    ServicePlan plan = getServicePlan();
    ServiceSummary summary = getServiceSummary(false);
    ServiceSummary currentSummary = summary.findCurrent(getActivityInstanceId());
    if (currentSummary == null)
        currentSummary = summary;
    for (Microservice service : plan.getServices()) {
        for (MicroserviceInstance instance : currentSummary.getMicroservices(service.getName()).getInstances()) {
            if (!instance.getStatus().equals(WorkStatus.STATUSNAME_COMPLETED)
                    && !instance.getStatus().equals(WorkStatus.STATUSNAME_CANCELED)) {
                return false;
            }
        }
    }
    return true;
}
 
Example #18
Source File: FesDecoderv20.java    From arctic-sea with Apache License 2.0 6 votes vote down vote up
/**
 * Parse XML expression array
 *
 * @param expressionArray
 *            XML expression array
 * @param comparisonFilter
 *            SOS comparison filter
 * @throws DecodingException
 *             if an error occurs
 */
private void parseExpressions(XmlObject[] expressionArray, ComparisonFilter comparisonFilter)
        throws DecodingException {
    for (XmlObject xmlObject : expressionArray) {
        if (isValueReferenceExpression(xmlObject)) {
            try {
                comparisonFilter.setValueReference(parseValueReference(xmlObject));
            } catch (XmlException xmle) {
                throw valueReferenceParsingException(xmle);
            }
        } else if (xmlObject instanceof LiteralType) {
            // TODO is this the best way?
            comparisonFilter.setValue(parseLiteralValue((LiteralType) xmlObject));
        }
    }
}
 
Example #19
Source File: SweCommonEncoderv20.java    From arctic-sea with Apache License 2.0 6 votes vote down vote up
private AbstractEncodingType createAbstractEncoding(SweAbstractEncoding encoding)
        throws EncodingException {
    if (encoding instanceof SweTextEncoding) {
        return createTextEncoding((SweTextEncoding) encoding);
    }

    try {
        String xml = encoding.getXml();
        if (xml != null && !xml.isEmpty()) {
            XmlObject xmlObject = XmlObject.Factory.parse(xml, getXmlOptions());
            if (xmlObject instanceof AbstractEncodingType) {
                return (AbstractEncodingType) xmlObject;
            }
        }
        throw new EncodingException("AbstractEncoding can not be encoded!");
    } catch (XmlException e) {
        throw new EncodingException("Error while encoding AbstractEncoding!", e);
    }
}
 
Example #20
Source File: FesDecoderv20.java    From arctic-sea with Apache License 2.0 6 votes vote down vote up
/**
 * Parse XML propertyIsBetween element
 *
 * @param comparisonOpsType
 *            XML propertyIsBetween element
 * @return SOS comparison filter
 * @throws DecodingException
 *             If an error occurs of the filter is not supported
 */
private ComparisonFilter parsePropertyIsBetweenFilter(PropertyIsBetweenType comparisonOpsType)
        throws DecodingException {
    ComparisonFilter comparisonFilter = new ComparisonFilter();
    comparisonFilter.setOperator(ComparisonOperator.PropertyIsBetween);
    try {
        comparisonFilter.setValueReference(parseValueReference(comparisonOpsType.getExpression()));
    } catch (XmlException xmle) {
        throw valueReferenceParsingException(xmle);
    }
    if (comparisonOpsType.getLowerBoundary().getExpression() instanceof LiteralType) {
        comparisonFilter
                .setValue(parseLiteralValue((LiteralType) comparisonOpsType.getLowerBoundary().getExpression()));
    }
    if (comparisonOpsType.getUpperBoundary().getExpression() instanceof LiteralType) {
        comparisonFilter.setValueUpper(
                parseLiteralValue((LiteralType) comparisonOpsType.getUpperBoundary().getExpression()));
    }
    return comparisonFilter;
}
 
Example #21
Source File: Soap12Decoder.java    From arctic-sea with Apache License 2.0 6 votes vote down vote up
private OwsServiceCommunicationObject getBodyContent(EnvelopeDocument doc) throws DecodingException {
    Body body = doc.getEnvelope().getBody();
    try {
        Node domNode = body.getDomNode();
        if (domNode.hasChildNodes()) {
            NodeList childNodes = domNode.getChildNodes();
            for (int i = 0; i < childNodes.getLength(); i++) {
                Node node = childNodes.item(i);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    XmlObject content = XmlObject.Factory.parse(node);
                    // fix problem with invalid prefix in xsi:type value for
                    // om:result, e.g. OM_SWEArrayObservation or
                    // gml:ReferenceType
                    Map<?, ?> namespaces = XmlHelper.getNamespaces(doc.getEnvelope());
                    fixNamespaceForXsiType(content, namespaces);
                    XmlHelper.fixNamespaceForXsiType(content, SweConstants.QN_DATA_ARRAY_PROPERTY_TYPE_SWE_200);
                    return decodeXmlElement(content);
                }
            }
        }
        return decodeXmlElement(body);
    } catch (XmlException xmle) {
        throw new DecodingException("Error while parsing SOAP body element!", xmle);
    }
}
 
Example #22
Source File: CacheRegistration.java    From mdw with Apache License 2.0 6 votes vote down vote up
/**
 * Load all the cache objects when the server starts
 */
private void preloadCaches() throws IOException, XmlException {
    Map<String,Properties> caches = getPreloadCacheSpecs();
    for (String cacheName : caches.keySet()) {
        Properties cacheProps = caches.get(cacheName);
        String cacheClassName = cacheProps.getProperty("ClassName");
        logger.info(" - loading cache " + cacheName);
        CacheService cachingObj = getCacheInstance(cacheClassName, cacheProps);
        if (cachingObj != null) {
            long before = System.currentTimeMillis();
            if (cachingObj instanceof PreloadableCache) {
                ((PreloadableCache)cachingObj).loadCache();
            }
            synchronized(allCaches) {
                allCaches.put(cacheName, cachingObj);
            }
            logger.debug("    - " + cacheName + " loaded in " + (System.currentTimeMillis() - before) + " ms");
        }
        else {
            logger.warn("Caching Class is  invalid. Name-->"+cacheClassName);
        }
    }
}
 
Example #23
Source File: PhenomenonFilteredHydroMetadataHandler.java    From SensorWebClient with GNU General Public License v2.0 5 votes vote down vote up
private Collection<SosTimeseries> executeGDATasks(Map<String, FutureTask<OperationResult>> getDataAvailabilityTasks,
                                                   SOSMetadata metadata, Collection<SosTimeseries> observingTimeseries) throws InterruptedException,
         ExecutionException,
         TimeoutException,
         XmlException,
         IOException {
     int counter = getDataAvailabilityTasks.size();
     LOGGER.debug("Sending " + counter + " GetDataAvailability requests");
     Collection<SosTimeseries> timeseries = new ArrayList<SosTimeseries>();
     for (String phenomenon : getDataAvailabilityTasks.keySet()) {
         LOGGER.debug("Sending #{} GetDataAvailability request for phenomenon " + phenomenon,
                      counter--);
         FutureTask<OperationResult> futureTask = getDataAvailabilityTasks.get(phenomenon);
         AccessorThreadPool.execute(futureTask);
         OperationResult result = null;
try {
	result = futureTask.get(SERVER_TIMEOUT, MILLISECONDS);
} catch (Exception e) {
	LOGGER.error("Get no result for GetDataAvailability with parameter constellation: " + phenomenon + "!");
}
         if (result == null) {
             LOGGER.error("Get no result for GetDataAvailability with parameter constellation: " + phenomenon + "!");
         } else {
         	XmlObject result_xb = XmlObject.Factory.parse(result.getIncomingResultAsStream());
             timeseries.addAll(getAvailableTimeseries(result_xb, phenomenon, metadata, observingTimeseries));
         }
     }
     return timeseries;
 }
 
Example #24
Source File: ListenerHelper.java    From mdw with Apache License 2.0 5 votes vote down vote up
private XmlObject parseXmlBean(String request) {
    CodeTimer timer = new CodeTimer("ListenerHelper.parseXmlBean()", true);
    try {
        XmlObject xmlBean = XmlObject.Factory.parse(request, new XmlOptions());
        timer.stopAndLogTiming("");
        return xmlBean;
    }
    catch (XmlException ex) {
        logger.error(ex.getMessage(), ex);
        timer.stopAndLogTiming("unparseable");
        return null;
    }
}
 
Example #25
Source File: EeaSosConnectorTest.java    From SensorWebClient with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testGetPointOfSamplingFeatureType() throws XmlException, FactoryException {
    SFSamplingFeatureType feature = sfSamplingFeature.getSFSamplingFeature();
    Point parsedPoint = sosConnector.getPointOfSamplingFeatureType(feature, referenceHelper);
    // <gml:Point gml:id="BETR701-point-location">
    //  <gml:pos srsName="http://www.opengis.net/def/crs/EPSG/0/4326">3.729 51.058</gml:pos>
    // </gml:Point>
    assertThat(parsedPoint.getX(), closeTo(3.729, ALLOWED_DELTA));
    assertThat(parsedPoint.getY(), closeTo(51.058, ALLOWED_DELTA));
}
 
Example #26
Source File: AllowableTaskActions.java    From mdw with Apache License 2.0 5 votes vote down vote up
public static List<TaskAction> getMyTasksBulkActions() throws IOException, XmlException {
    if (myTasksBulkActions == null) {
        myTasksBulkActions = new ArrayList<TaskAction>();
        for (AllowableAction allowableAction : getTaskActions().getBulkTaskActions().getAssignedBulkActions().getAllowableActionList()) {
            TaskAction taskAction = convertToJsonable(allowableAction);
            if (!myTasksBulkActions.contains(taskAction))
                myTasksBulkActions.add(taskAction);
        }
    }
    return myTasksBulkActions;
}
 
Example #27
Source File: TestCaseRun.java    From mdw with Apache License 2.0 5 votes vote down vote up
List<ProcessInstance> loadProcess(TestCaseProcess[] processes, Asset expectedResults) throws TestException {
    processInstances = null;
    if (isLoadTest())
        throw new TestException("Not supported for load tests");
    try {
        List<Process> processVos = new ArrayList<>();
        if (isVerbose())
            log.println("loading runtime data for processes:");
        for (TestCaseProcess process : processes) {
            if (isVerbose())
                log.println("  - " + process.getLabel());
            processVos.add(process.getProcess());
        }
        processInstances = loadResults(processVos, expectedResults, processes[0]);
        return processInstances;
    }
    catch (Exception ex) {
        String msg = ex.getMessage() == null ? "" : ex.getMessage().trim();
        if (msg.startsWith("<")) {
            // xml message
            try {
                MDWStatusMessageDocument statusMsgDoc = MDWStatusMessageDocument.Factory.parse(msg);
                msg = statusMsgDoc.getMDWStatusMessage().getStatusMessage();
            }
            catch (XmlException xmlEx) {
                // not an MDW status message -- just escape XML
                msg = StringEscapeUtils.escapeXml(msg);
            }
        }
        throw new TestException(msg, ex);
    }
}
 
Example #28
Source File: OmEncoderv20Test.java    From arctic-sea with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldEncodeFeatureInObservationTemplate()
        throws EncodingException, InvalidSridException, ParseException, XmlException, IOException {
    //
    SamplingFeature featureOfInterest = new SamplingFeature(new CodeWithAuthority(featureIdentifier));
    featureOfInterest.setIdentifier(featureIdentifier);
    featureOfInterest.setName(new CodeType(featureName));
    featureOfInterest.setFeatureType(SfConstants.SAMPLING_FEAT_TYPE_SF_SAMPLING_POINT);
    featureOfInterest.setGeometry(JTSHelper.createGeometryFromWKT("POINT (30 10)" , 4326));
    //
    SensorML procedure = new SensorML();
    procedure.setIdentifier(procedureIdentifier);
    //
    OmObservationConstellation observationTemplate = new OmObservationConstellation();
    observationTemplate.setObservationType(OmConstants.OBS_TYPE_MEASUREMENT);
    observationTemplate.setObservableProperty(new OmObservableProperty(observedProperty));
    observationTemplate.setProcedure(procedure);
    observationTemplate.setFeatureOfInterest(featureOfInterest);
    //
    OMObservationType omObservation = (OMObservationType) omEncoderv20.encode(observationTemplate);
    //
    assertThat(omObservation.getType().getHref(), Is.is(OmConstants.OBS_TYPE_MEASUREMENT));
    assertThat(omObservation.getPhenomenonTime().isNil(), Is.is(false));
    assertThat(omObservation.getPhenomenonTime().isSetNilReason(), Is.is(true));
    assertThat(omObservation.getPhenomenonTime().getNilReason(), Is.is("template"));
    assertThat(omObservation.getResultTime().isNil(), Is.is(false));
    assertThat(omObservation.getResultTime().isSetNilReason(), Is.is(true));
    assertThat(omObservation.getResultTime().getNilReason(), Is.is("template"));
    assertThat(omObservation.getProcedure().isNil(), Is.is(false));
    assertThat(omObservation.getProcedure().getHref(), Is.is(procedureIdentifier));
    assertThat(omObservation.getObservedProperty().isNil(), Is.is(false));
    assertThat(omObservation.getObservedProperty().getHref(), Is.is(observedProperty));
    assertThat(omObservation.getFeatureOfInterest(), Matchers.notNullValue());
    XmlObject xmlObject = XmlObject.Factory.parse(omObservation.getFeatureOfInterest().newInputStream());
    assertThat(xmlObject, Matchers.instanceOf(SFSamplingFeatureDocument.class));
    SFSamplingFeatureType feature = ((SFSamplingFeatureDocument) xmlObject).getSFSamplingFeature();
    assertThat(feature.getIdentifier().getStringValue(), Is.is(featureIdentifier));
    assertThat(feature.getNameArray().length, Is.is(1));
    assertThat(feature.getNameArray(0).getStringValue(), Is.is(featureName));
}
 
Example #29
Source File: GetFeatureOfInterestXmlStreamWriterTest.java    From arctic-sea with Apache License 2.0 5 votes vote down vote up
@Test
public void testMetadataEncoding() throws XmlException, XMLStreamException, IOException, EncodingException {
    try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
        GetFeatureOfInterestXmlStreamWriter encoder = new GetFeatureOfInterestXmlStreamWriter(baos,
                EncodingContext.of(EncoderFlags.ENCODER_REPOSITORY, encoderRepository), createResponse());
        encoder.write();
        XmlObject encode = XmlObject.Factory.parse(new String(baos.toByteArray()));
        assertThat(encode, instanceOf(GetFeatureOfInterestResponseDocument.class));
        GetFeatureOfInterestResponseDocument gord = (GetFeatureOfInterestResponseDocument) encode;
        assertThat(gord.getGetFeatureOfInterestResponse() != null, is(true));
        checkMetadataResponse(gord.getGetFeatureOfInterestResponse().getExtensionArray());
    }
}
 
Example #30
Source File: SoapHttpTestRunner.java    From microcks with Apache License 2.0 5 votes vote down vote up
@Override
protected int extractTestReturnCode(Service service, Operation operation, Request request,
												ClientHttpResponse httpResponse, String responseContent){
	int code = TestReturn.SUCCESS_CODE;

	// Checking HTTP return code: delegating to super class.
	code = super.extractTestReturnCode(service, operation, request, httpResponse, responseContent);
	// If test is already a failure (40x code), no need to pursue...
	if (TestReturn.FAILURE_CODE == code){
		return code;
	}

	try{
		// Validate Soap message body according to operation output part.
		List<XmlError> errors = SoapMessageValidator.validateSoapMessage(
              operation.getOutputName(), service.getXmlNS(), responseContent, resourceUrl
                    +  UriUtils.encodeFragment(service.getName(), "UTF-8") + "-" + service.getVersion() + ".wsdl", true
        );

		if (!errors.isEmpty()){
			log.debug("Soap validation errors found " + errors.size() + ", marking test as failed.");
			return TestReturn.FAILURE_CODE;
		}
	} catch (XmlException e) {
		log.debug("XmlException while validating Soap response message", e);
		return TestReturn.FAILURE_CODE;
	}
	return code;
}