Search in sources :

Example 16 with Unmarshaller

use of javax.xml.bind.Unmarshaller in project jOOQ by jOOQ.

the class GenerationTool method load.

/**
     * Load a jOOQ codegen configuration file from an input stream
     */
public static Configuration load(InputStream in) throws IOException {
    // [#1149] If there is no namespace defined, add the default one
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    copyLarge(in, out);
    String xml = out.toString();
    // TODO [#1201] Add better error handling here
    xml = xml.replaceAll("<(\\w+:)?configuration xmlns(:\\w+)?=\"http://www.jooq.org/xsd/jooq-codegen-\\d+\\.\\d+\\.\\d+.xsd\">", "<$1configuration xmlns$2=\"" + Constants.NS_CODEGEN + "\">");
    xml = xml.replace("<configuration>", "<configuration xmlns=\"" + Constants.NS_CODEGEN + "\">");
    try {
        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        javax.xml.validation.Schema schema = sf.newSchema(GenerationTool.class.getResource("/xsd/" + Constants.XSD_CODEGEN));
        JAXBContext ctx = JAXBContext.newInstance(Configuration.class);
        Unmarshaller unmarshaller = ctx.createUnmarshaller();
        unmarshaller.setSchema(schema);
        unmarshaller.setEventHandler(new ValidationEventHandler() {

            @Override
            public boolean handleEvent(ValidationEvent event) {
                log.warn("Unmarshal warning", event.getMessage());
                return true;
            }
        });
        return (Configuration) unmarshaller.unmarshal(new StringReader(xml));
    } catch (Exception e) {
        throw new GeneratorException("Error while reading XML configuration", e);
    }
}
Also used : SchemaFactory(javax.xml.validation.SchemaFactory) ValidationEventHandler(javax.xml.bind.ValidationEventHandler) Configuration(org.jooq.util.jaxb.Configuration) JAXBContext(javax.xml.bind.JAXBContext) ByteArrayOutputStream(java.io.ByteArrayOutputStream) StringUtils.defaultString(org.jooq.tools.StringUtils.defaultString) SQLException(java.sql.SQLException) IOException(java.io.IOException) ValidationEvent(javax.xml.bind.ValidationEvent) StringReader(java.io.StringReader) Unmarshaller(javax.xml.bind.Unmarshaller)

Example 17 with Unmarshaller

use of javax.xml.bind.Unmarshaller in project jersey by jersey.

the class AbstractJaxbProvider method getUnmarshaller.

/**
     * Get the JAXB unmarshaller for the given class and media type.
     * <p>
     * In case this provider instance has been {@link #AbstractJaxbProvider(Providers, MediaType)
     * created with a fixed resolver media type}, the supplied media type argument will be ignored.
     * </p>
     *
     * @param type      Java type to be unmarshalled.
     * @param mediaType entity media type.
     * @return JAXB unmarshaller for the requested Java type, media type combination.
     * @throws JAXBException in case retrieving the unmarshaller fails with a JAXB exception.
     */
protected final Unmarshaller getUnmarshaller(Class type, MediaType mediaType) throws JAXBException {
    if (fixedResolverMediaType) {
        return getUnmarshaller(type);
    }
    final ContextResolver<Unmarshaller> unmarshallerResolver = jaxrsProviders.getContextResolver(Unmarshaller.class, mediaType);
    if (unmarshallerResolver != null) {
        Unmarshaller u = unmarshallerResolver.getContext(type);
        if (u != null) {
            return u;
        }
    }
    final JAXBContext ctx = getJAXBContext(type, mediaType);
    return (ctx == null) ? null : ctx.createUnmarshaller();
}
Also used : JAXBContext(javax.xml.bind.JAXBContext) Unmarshaller(javax.xml.bind.Unmarshaller)

Example 18 with Unmarshaller

use of javax.xml.bind.Unmarshaller in project hibernate-orm by hibernate.

the class XmlParserHelper method getJaxbRoot.

public <T> T getJaxbRoot(InputStream stream, Class<T> clazz, Schema schema) throws XmlParsingException {
    XMLEventReader staxEventReader;
    try {
        staxEventReader = createXmlEventReader(stream);
    } catch (XMLStreamException e) {
        throw new XmlParsingException("Unable to create stax reader", e);
    }
    ContextProvidingValidationEventHandler handler = new ContextProvidingValidationEventHandler();
    try {
        staxEventReader = new JpaNamespaceTransformingEventReader(staxEventReader);
        JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class);
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        unmarshaller.setSchema(schema);
        unmarshaller.setEventHandler(handler);
        return clazz.cast(unmarshaller.unmarshal(staxEventReader));
    } catch (JAXBException e) {
        StringBuilder builder = new StringBuilder();
        builder.append("Unable to perform unmarshalling at line number ");
        builder.append(handler.getLineNumber());
        builder.append(" and column ");
        builder.append(handler.getColumnNumber());
        builder.append(". Message: ");
        builder.append(handler.getMessage());
        throw new XmlParsingException(builder.toString(), e);
    }
}
Also used : XMLStreamException(javax.xml.stream.XMLStreamException) JAXBException(javax.xml.bind.JAXBException) XMLEventReader(javax.xml.stream.XMLEventReader) JAXBContext(javax.xml.bind.JAXBContext) Unmarshaller(javax.xml.bind.Unmarshaller)

Example 19 with Unmarshaller

use of javax.xml.bind.Unmarshaller in project openhab1-addons by openhab.

the class OpenWebIfCommunicator method executeRequest.

/**
     * Executes the http request and parses the returned stream.
     */
@SuppressWarnings("unchecked")
private <T> T executeRequest(OpenWebIfConfig config, String url, Class<T> clazz) throws IOException {
    HttpURLConnection con = null;
    try {
        logger.trace("Request [{}]: {}", config.getName(), url);
        con = (HttpURLConnection) new URL(url).openConnection();
        con.setConnectTimeout(CONNECTION_TIMEOUT);
        con.setReadTimeout(10000);
        if (config.hasLogin()) {
            String userpass = config.getUser() + ":" + config.getPassword();
            String basicAuth = "Basic " + DatatypeConverter.printBase64Binary(userpass.getBytes());
            con.setRequestProperty("Authorization", basicAuth);
        }
        if (con instanceof HttpsURLConnection) {
            HttpsURLConnection sCon = (HttpsURLConnection) con;
            TrustManager[] trustManager = new TrustManager[] { new SimpleTrustManager() };
            SSLContext context = SSLContext.getInstance("TLS");
            context.init(new KeyManager[0], trustManager, new SecureRandom());
            sCon.setSSLSocketFactory(context.getSocketFactory());
            sCon.setHostnameVerifier(new AllowAllHostnameVerifier());
        }
        StringWriter sw = new StringWriter();
        IOUtils.copy(con.getInputStream(), sw);
        con.disconnect();
        if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
            String response = sw.toString();
            logger.trace("Response: [{}]: {}", config.getName(), response);
            Unmarshaller um = JAXBContext.newInstance(clazz).createUnmarshaller();
            return (T) um.unmarshal(new StringReader(response));
        } else {
            throw new IOException(con.getResponseMessage());
        }
    } catch (JAXBException ex) {
        throw new IOException(ex.getMessage(), ex);
    } catch (GeneralSecurityException ex) {
        throw new IOException(ex.getMessage(), ex);
    } finally {
        if (con != null) {
            con.disconnect();
        }
    }
}
Also used : AllowAllHostnameVerifier(org.openhab.action.openwebif.internal.impl.ssl.AllowAllHostnameVerifier) JAXBException(javax.xml.bind.JAXBException) GeneralSecurityException(java.security.GeneralSecurityException) SimpleTrustManager(org.openhab.action.openwebif.internal.impl.ssl.SimpleTrustManager) SecureRandom(java.security.SecureRandom) SSLContext(javax.net.ssl.SSLContext) IOException(java.io.IOException) URL(java.net.URL) TrustManager(javax.net.ssl.TrustManager) SimpleTrustManager(org.openhab.action.openwebif.internal.impl.ssl.SimpleTrustManager) HttpURLConnection(java.net.HttpURLConnection) StringWriter(java.io.StringWriter) StringReader(java.io.StringReader) Unmarshaller(javax.xml.bind.Unmarshaller) HttpsURLConnection(javax.net.ssl.HttpsURLConnection)

Example 20 with Unmarshaller

use of javax.xml.bind.Unmarshaller in project openhab1-addons by openhab.

the class FritzahaWebserviceUpdateXmlCallback method execute.

/**
     * {@inheritDoc}
     */
@Override
public void execute(int status, String response) {
    super.execute(status, response);
    if (validRequest) {
        logger.trace("Received State response " + response + " for item " + itemName);
        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(DevicelistModel.class);
            Unmarshaller jaxbUM = jaxbContext.createUnmarshaller();
            DevicelistModel model = (DevicelistModel) jaxbUM.unmarshal(new StringReader(response));
            ArrayList<DeviceModel> list = model.getDevicelist();
            for (DeviceModel device : list) {
                if (device.getIdentifier().equals(this.deviceAin)) {
                    BigDecimal meterValueScaled = new BigDecimal(0);
                    switch(type) {
                        case POWER:
                            meterValueScaled = device.getPowermeter().getPower().scaleByPowerOfTen(-3);
                            break;
                        case ENERGY:
                            meterValueScaled = device.getPowermeter().getEnergy();
                            break;
                        case TEMPERATURE:
                            meterValueScaled = device.getTemperature().getCelsius().scaleByPowerOfTen(-1);
                            break;
                        default:
                            logger.warn("unknown meter type: " + type);
                            break;
                    }
                    logger.debug(device.toString());
                    webIface.postUpdate(itemName, new DecimalType(meterValueScaled));
                } else {
                    logger.trace("device " + device.getIdentifier() + " was not requested");
                }
            }
        } catch (JAXBException e) {
            logger.error(e.getLocalizedMessage(), e);
        }
    }
}
Also used : DeviceModel(org.openhab.binding.fritzaha.internal.model.DeviceModel) JAXBException(javax.xml.bind.JAXBException) StringReader(java.io.StringReader) DecimalType(org.openhab.core.library.types.DecimalType) JAXBContext(javax.xml.bind.JAXBContext) DevicelistModel(org.openhab.binding.fritzaha.internal.model.DevicelistModel) Unmarshaller(javax.xml.bind.Unmarshaller) BigDecimal(java.math.BigDecimal)

Aggregations

Unmarshaller (javax.xml.bind.Unmarshaller)292 JAXBContext (javax.xml.bind.JAXBContext)240 JAXBException (javax.xml.bind.JAXBException)97 InputStream (java.io.InputStream)91 Test (org.junit.Test)79 StringReader (java.io.StringReader)40 BaseTest (org.orcid.core.BaseTest)39 V2Convertible (org.orcid.core.version.V2Convertible)39 File (java.io.File)33 InputSource (org.xml.sax.InputSource)22 IOException (java.io.IOException)21 JAXBElement (javax.xml.bind.JAXBElement)18 Marshaller (javax.xml.bind.Marshaller)18 ByteArrayInputStream (java.io.ByteArrayInputStream)17 SAXSource (javax.xml.transform.sax.SAXSource)17 SAXParserFactory (javax.xml.parsers.SAXParserFactory)13 XMLInputFactory (javax.xml.stream.XMLInputFactory)13 XMLStreamException (javax.xml.stream.XMLStreamException)13 XMLStreamReader (javax.xml.stream.XMLStreamReader)13 Schema (javax.xml.validation.Schema)13