Search in sources :

Example 16 with XStreamException

use of com.thoughtworks.xstream.XStreamException in project GDSC-SMLM by aherbert.

the class PCPALMAnalysis method loadResult.

private boolean loadResult(XStream xs, String path) {
    FileInputStream fs = null;
    try {
        fs = new FileInputStream(path);
        CorrelationResult result = (CorrelationResult) xs.fromXML(fs);
        // Replace a result with the same id
        for (int i = 0; i < results.size(); i++) {
            if (results.get(i).id == result.id) {
                results.set(i, result);
                result = null;
                break;
            }
        }
        // Add to the results if we did not replace any
        if (result != null)
            results.add(result);
        return true;
    } catch (ClassCastException ex) {
        //ex.printStackTrace();
        IJ.log("Failed to load correlation result from file: " + path);
    } catch (XStreamException ex) {
        //ex.printStackTrace();
        IJ.log("Failed to load correlation result from file: " + path);
    } catch (Exception e) {
        IJ.log("Failed to load correlation result from file: " + path);
    } finally {
        if (fs != null) {
            try {
                fs.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return false;
}
Also used : XStreamException(com.thoughtworks.xstream.XStreamException) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) XStreamException(com.thoughtworks.xstream.XStreamException) IOException(java.io.IOException)

Example 17 with XStreamException

use of com.thoughtworks.xstream.XStreamException in project ddf by codice.

the class GmdTransformer method handleTransform.

private Metacard handleTransform(InputStream inputStream, String id) throws CatalogTransformerException {
    String xml;
    XstreamPathValueTracker pathValueTracker;
    try (TemporaryFileBackedOutputStream temporaryFileBackedOutputStream = new TemporaryFileBackedOutputStream()) {
        IOUtils.copy(inputStream, temporaryFileBackedOutputStream);
        byteArray = temporaryFileBackedOutputStream.asByteSource();
        try (InputStream xmlSourceInputStream = getSourceInputStream()) {
            xml = IOUtils.toString(xmlSourceInputStream);
        }
        argumentHolder.put(XstreamPathConverter.PATH_KEY, buildPaths());
        XMLStreamReader streamReader = xmlFactory.createXMLStreamReader(new StringReader(xml));
        HierarchicalStreamReader reader = new StaxReader(new QNameMap(), streamReader);
        pathValueTracker = (XstreamPathValueTracker) xstream.unmarshal(reader, null, argumentHolder);
        Metacard metacard = toMetacard(pathValueTracker, id);
        metacard.setAttribute(new AttributeImpl(Core.METADATA, xml));
        return metacard;
    } catch (XStreamException | XMLStreamException | IOException e) {
        throw new CatalogTransformerException(TRANSFORM_EXCEPTION_MSG, e);
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}
Also used : StaxReader(com.thoughtworks.xstream.io.xml.StaxReader) XMLStreamReader(javax.xml.stream.XMLStreamReader) TemporaryFileBackedOutputStream(org.codice.ddf.platform.util.TemporaryFileBackedOutputStream) InputStream(java.io.InputStream) AttributeImpl(ddf.catalog.data.impl.AttributeImpl) XstreamPathValueTracker(org.codice.ddf.spatial.ogc.csw.catalog.converter.XstreamPathValueTracker) CatalogTransformerException(ddf.catalog.transform.CatalogTransformerException) IOException(java.io.IOException) Metacard(ddf.catalog.data.Metacard) XStreamException(com.thoughtworks.xstream.XStreamException) XMLStreamException(javax.xml.stream.XMLStreamException) StringReader(java.io.StringReader) HierarchicalStreamReader(com.thoughtworks.xstream.io.HierarchicalStreamReader) QNameMap(com.thoughtworks.xstream.io.xml.QNameMap)

Example 18 with XStreamException

use of com.thoughtworks.xstream.XStreamException in project ddf by codice.

the class FeatureCollectionMessageBodyReaderWfs20 method readFrom.

@SuppressWarnings("unchecked")
@Override
public Wfs20FeatureCollection readFrom(Class<Wfs20FeatureCollection> clazz, Type type, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> headers, InputStream inStream) throws IOException, WebApplicationException {
    // Save original input stream for any exception message that might need to be
    // created and additional attributes
    String originalInputStream = IOUtils.toString(inStream, "UTF-8");
    LOGGER.debug("{}", originalInputStream);
    ClassLoader ccl = Thread.currentThread().getContextClassLoader();
    try {
        Thread.currentThread().setContextClassLoader(FeatureCollectionMessageBodyReaderWfs20.class.getClassLoader());
        //Fetch FeatureCollection attributes
        Unmarshaller unmarshaller = null;
        JAXBElement<FeatureCollectionType> wfsFeatureCollectionType = null;
        try {
            unmarshaller = JAXB_CONTEXT.createUnmarshaller();
            XMLInputFactory xmlInputFactory = XMLInputFactory.newFactory();
            xmlInputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
            xmlInputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
            xmlInputFactory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, false);
            XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(new StringReader(originalInputStream));
            wfsFeatureCollectionType = (JAXBElement<FeatureCollectionType>) unmarshaller.unmarshal(xmlStreamReader);
        } catch (ClassCastException e1) {
            LOGGER.debug("Exception unmarshalling {}, could be an OWS Exception Report from server.", e1.getMessage());
            // If an ExceptionReport is sent from the remote WFS site it will be sent with an
            // JAX-RS "OK" status, hence the ErrorResponse exception mapper will not fire.
            // Instead the ServiceExceptionReport will come here and be treated like a GetFeature
            // response, resulting in an XStreamException since ExceptionReport cannot be
            // unmarshalled. So this catch clause is responsible for catching that XStream
            // exception and creating a JAX-RS response containing the original stream
            // (with the ExceptionReport) and rethrowing it as a WebApplicationException,
            // which CXF will wrap as a ClientException that the WfsSource catches, converts
            // to a WfsException, and logs.
            ByteArrayInputStream bis = new ByteArrayInputStream(originalInputStream.getBytes(StandardCharsets.UTF_8));
            ResponseBuilder responseBuilder = Response.ok(bis);
            responseBuilder.type("text/xml");
            Response response = responseBuilder.build();
            throw new WebApplicationException(e1, response);
        } catch (JAXBException | XMLStreamException e1) {
            LOGGER.debug("Error in retrieving feature collection.", e1);
        } catch (RuntimeException | Error e) {
            LOGGER.debug("Error processing collection", e);
            throw e;
        }
        Wfs20FeatureCollection featureCollection = null;
        if (null != wfsFeatureCollectionType && null != wfsFeatureCollectionType.getValue()) {
            BigInteger numberReturned = wfsFeatureCollectionType.getValue().getNumberReturned();
            String numberMatched = wfsFeatureCollectionType.getValue().getNumberMatched();
            // Re-create the input stream (since it has already been read for potential
            // exception message creation)
            inStream = new ByteArrayInputStream(originalInputStream.getBytes("UTF-8"));
            try {
                featureCollection = (Wfs20FeatureCollection) xstream.fromXML(inStream);
                featureCollection.setNumberMatched(numberMatched);
                featureCollection.setNumberReturned(numberReturned);
            } catch (XStreamException e) {
                LOGGER.debug("Exception unmarshalling {}", e);
            } finally {
                IOUtils.closeQuietly(inStream);
            }
        }
        return featureCollection;
    } finally {
        Thread.currentThread().setContextClassLoader(ccl);
    }
}
Also used : FeatureCollectionType(net.opengis.wfs.v_2_0_0.FeatureCollectionType) XMLStreamReader(javax.xml.stream.XMLStreamReader) WebApplicationException(javax.ws.rs.WebApplicationException) JAXBException(javax.xml.bind.JAXBException) Wfs20FeatureCollection(org.codice.ddf.spatial.ogc.wfs.v2_0_0.catalog.common.Wfs20FeatureCollection) Response(javax.ws.rs.core.Response) XStreamException(com.thoughtworks.xstream.XStreamException) XMLStreamException(javax.xml.stream.XMLStreamException) ByteArrayInputStream(java.io.ByteArrayInputStream) StringReader(java.io.StringReader) BigInteger(java.math.BigInteger) Unmarshaller(javax.xml.bind.Unmarshaller) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) XMLInputFactory(javax.xml.stream.XMLInputFactory)

Example 19 with XStreamException

use of com.thoughtworks.xstream.XStreamException in project ddf by codice.

the class GetRecordsMessageBodyReader method readFrom.

@Override
public CswRecordCollection readFrom(Class<CswRecordCollection> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream inStream) throws IOException, WebApplicationException {
    CswRecordCollection cswRecords = null;
    Map<String, Serializable> resourceProperties = new HashMap<>();
    // Check if the server returned a Partial Content response (hopefully in response to a range header)
    String contentRangeHeader = httpHeaders.getFirst(HttpHeaders.CONTENT_RANGE);
    if (StringUtils.isNotBlank(contentRangeHeader)) {
        contentRangeHeader = StringUtils.substringBetween(contentRangeHeader.toLowerCase(), "bytes ", "-");
        long bytesSkipped = Long.parseLong(contentRangeHeader);
        resourceProperties.put(BYTES_SKIPPED, Long.valueOf(bytesSkipped));
    }
    // If the following HTTP header exists and its value is true, the input stream will contain
    // raw product data
    String productRetrievalHeader = httpHeaders.getFirst(CswConstants.PRODUCT_RETRIEVAL_HTTP_HEADER);
    if (productRetrievalHeader != null && productRetrievalHeader.equalsIgnoreCase("TRUE")) {
        String fileName = handleContentDispositionHeader(httpHeaders);
        cswRecords = new CswRecordCollection();
        cswRecords.setResource(new ResourceImpl(inStream, mediaType.toString(), fileName));
        cswRecords.setResourceProperties(resourceProperties);
        return cswRecords;
    }
    // Save original input stream for any exception message that might need to be
    // created
    String originalInputStream = IOUtils.toString(inStream, "UTF-8");
    LOGGER.debug("Converting to CswRecordCollection: \n {}", originalInputStream);
    // Re-create the input stream (since it has already been read for potential
    // exception message creation)
    inStream = new ByteArrayInputStream(originalInputStream.getBytes("UTF-8"));
    try {
        HierarchicalStreamReader reader = new XppReader(new InputStreamReader(inStream, StandardCharsets.UTF_8), XmlPullParserFactory.newInstance().newPullParser());
        cswRecords = (CswRecordCollection) xstream.unmarshal(reader, null, argumentHolder);
    } catch (XmlPullParserException e) {
        LOGGER.debug("Unable to create XmlPullParser, and cannot parse CSW Response.", e);
    } catch (XStreamException e) {
        // If an ExceptionReport is sent from the remote CSW site it will be sent with an
        // JAX-RS "OK" status, hence the ErrorResponse exception mapper will not fire.
        // Instead the ExceptionReport will come here and be treated like a GetRecords
        // response, resulting in an XStreamException since ExceptionReport cannot be
        // unmarshalled. So this catch clause is responsible for catching that XStream
        // exception and creating a JAX-RS response containing the original stream
        // (with the ExceptionReport) and rethrowing it as a WebApplicatioNException,
        // which CXF will wrap as a ClientException that the CswSource catches, converts
        // to a CswException, and logs.
        ByteArrayInputStream bis = new ByteArrayInputStream(originalInputStream.getBytes(StandardCharsets.UTF_8));
        ResponseBuilder responseBuilder = Response.ok(bis);
        responseBuilder.type("text/xml");
        Response response = responseBuilder.build();
        throw new WebApplicationException(e, response);
    } finally {
        IOUtils.closeQuietly(inStream);
    }
    return cswRecords;
}
Also used : Serializable(java.io.Serializable) InputStreamReader(java.io.InputStreamReader) WebApplicationException(javax.ws.rs.WebApplicationException) HashMap(java.util.HashMap) Response(javax.ws.rs.core.Response) XStreamException(com.thoughtworks.xstream.XStreamException) ResourceImpl(ddf.catalog.resource.impl.ResourceImpl) ByteArrayInputStream(java.io.ByteArrayInputStream) XppReader(com.thoughtworks.xstream.io.xml.XppReader) CswRecordCollection(org.codice.ddf.spatial.ogc.csw.catalog.common.CswRecordCollection) HierarchicalStreamReader(com.thoughtworks.xstream.io.HierarchicalStreamReader) XmlPullParserException(org.xmlpull.v1.XmlPullParserException) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder)

Example 20 with XStreamException

use of com.thoughtworks.xstream.XStreamException in project spacesettlers by amymcgovern.

the class PacifistHeuristicAsteroidCollectorTeamClient method initialize.

/**
 * Demonstrates one way to read in knowledge from a file
 */
@Override
public void initialize(Toroidal2DPhysics space) {
    asteroidToShipMap = new HashMap<UUID, Ship>();
    aimingForBase = new HashMap<UUID, Boolean>();
    XStream xstream = new XStream();
    xstream.alias("ExampleKnowledge", ExampleKnowledge.class);
    try {
        myKnowledge = (ExampleKnowledge) xstream.fromXML(new File(knowledgeFile));
    } catch (XStreamException e) {
        // if you get an error, handle it other than a null pointer because
        // the error will happen the first time you run
        myKnowledge = new ExampleKnowledge();
    }
}
Also used : XStreamException(com.thoughtworks.xstream.XStreamException) XStream(com.thoughtworks.xstream.XStream) Ship(spacesettlers.objects.Ship) UUID(java.util.UUID) File(java.io.File)

Aggregations

XStreamException (com.thoughtworks.xstream.XStreamException)24 IOException (java.io.IOException)13 XStream (com.thoughtworks.xstream.XStream)12 FileNotFoundException (java.io.FileNotFoundException)9 FileOutputStream (java.io.FileOutputStream)6 ByteArrayInputStream (java.io.ByteArrayInputStream)4 File (java.io.File)4 FileInputStream (java.io.FileInputStream)4 FitEngineConfiguration (gdsc.smlm.engine.FitEngineConfiguration)3 InputStream (java.io.InputStream)3 WebApplicationException (javax.ws.rs.WebApplicationException)3 Response (javax.ws.rs.core.Response)3 ResponseBuilder (javax.ws.rs.core.Response.ResponseBuilder)3 HierarchicalStreamReader (com.thoughtworks.xstream.io.HierarchicalStreamReader)2 StringReader (java.io.StringReader)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 XMLStreamException (javax.xml.stream.XMLStreamException)2 XMLStreamReader (javax.xml.stream.XMLStreamReader)2 SalesforceException (org.apache.camel.component.salesforce.api.SalesforceException)2 DomDriver (com.thoughtworks.xstream.io.xml.DomDriver)1