Example usage for javax.xml.bind Unmarshaller setSchema

List of usage examples for javax.xml.bind Unmarshaller setSchema

Introduction

In this page you can find the example usage for javax.xml.bind Unmarshaller setSchema.

Prototype

public void setSchema(javax.xml.validation.Schema schema);

Source Link

Document

Specify the JAXP 1.3 javax.xml.validation.Schema Schema object that should be used to validate subsequent unmarshal operations against.

Usage

From source file:com.mondora.chargify.controller.ChargifyAdapter.java

protected Object parse(Class clazz, InputStream inputStream) throws ChargifyException {
    byte[] in = null;
    try {// w  ww.j a v a2 s .c o  m
        JAXBContext context = JAXBContext.newInstance(clazz);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        unmarshaller.setSchema(null);
        if (logger.isTraceEnabled()) {
            try {
                in = readByteStream(inputStream);
                logger.trace("Response input " + new String(in));

                inputStream = new ByteArrayInputStream(in);
            } catch (IOException e) {
            }
        }
        Object xmlObject = clazz.cast(unmarshaller.unmarshal(inputStream));
        return xmlObject;
    } catch (JAXBException e) {
        if (logger.isTraceEnabled())
            logger.trace(e.getMessage(), e);
        if (logger.isInfoEnabled())
            logger.info(e.getMessage());
        throw new ChargifyException("Unparsable Entity " + new String(in));
    }
}

From source file:com.aionemu.gameserver.dataholders.SpawnsData2.java

public synchronized boolean saveSpawn(Player admin, VisibleObject visibleObject, boolean delete)
        throws IOException {
    SpawnTemplate spawn = visibleObject.getSpawn();
    Spawn oldGroup = DataManager.SPAWNS_DATA2.getSpawnsForNpc(visibleObject.getWorldId(), spawn.getNpcId());

    File xml = new File("./data/static_data/spawns/" + getRelativePath(visibleObject));
    SpawnsData2 data = null;// w  ww  .  ja  va2  s. com
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = null;
    JAXBContext jc = null;
    boolean addGroup = false;

    try {
        schema = sf.newSchema(new File("./data/static_data/spawns/spawns.xsd"));
        jc = JAXBContext.newInstance(SpawnsData2.class);
    } catch (Exception e) {
        // ignore, if schemas are wrong then we even could not call the command;
    }

    FileInputStream fin = null;
    if (xml.exists()) {
        try {
            fin = new FileInputStream(xml);
            Unmarshaller unmarshaller = jc.createUnmarshaller();
            unmarshaller.setSchema(schema);
            data = (SpawnsData2) unmarshaller.unmarshal(fin);
        } catch (Exception e) {
            log.error(e.getMessage());
            PacketSendUtility.sendMessage(admin, "Could not load old XML file!");
            return false;
        } finally {
            if (fin != null) {
                fin.close();
            }
        }
    }

    if (oldGroup == null || oldGroup.isCustom()) {
        if (data == null) {
            data = new SpawnsData2();
        }

        oldGroup = data.getSpawnsForNpc(visibleObject.getWorldId(), spawn.getNpcId());
        if (oldGroup == null) {
            oldGroup = new Spawn(spawn.getNpcId(), spawn.getRespawnTime(), spawn.getHandlerType());
            addGroup = true;
        }
    } else {
        if (data == null) {
            data = DataManager.SPAWNS_DATA2;
        }
        // only remove from memory, will be added back later
        allSpawnMaps.get(visibleObject.getWorldId()).remove(spawn.getNpcId());
        addGroup = true;
    }

    SpawnSpotTemplate spot = new SpawnSpotTemplate(visibleObject.getX(), visibleObject.getY(),
            visibleObject.getZ(), visibleObject.getHeading(), visibleObject.getSpawn().getRandomWalk(),
            visibleObject.getSpawn().getWalkerId(), visibleObject.getSpawn().getWalkerIndex());
    boolean changeX = visibleObject.getX() != spawn.getX();
    boolean changeY = visibleObject.getY() != spawn.getY();
    boolean changeZ = visibleObject.getZ() != spawn.getZ();
    boolean changeH = visibleObject.getHeading() != spawn.getHeading();
    if (changeH && visibleObject instanceof Npc) {
        Npc npc = (Npc) visibleObject;
        if (!npc.isAtSpawnLocation() || !npc.isInState(CreatureState.NPC_IDLE) || changeX || changeY
                || changeZ) {
            // if H changed, XSD validation fails, because it may be negative; thus, reset it back
            visibleObject.setXYZH(null, null, null, spawn.getHeading());
            changeH = false;
        }
    }

    SpawnSpotTemplate oldSpot = null;
    for (SpawnSpotTemplate s : oldGroup.getSpawnSpotTemplates()) {
        if (s.getX() == spot.getX() && s.getY() == spot.getY() && s.getZ() == spot.getZ()
                && s.getHeading() == spot.getHeading()) {
            if (delete || !StringUtils.equals(s.getWalkerId(), spot.getWalkerId())) {
                oldSpot = s;
                break;
            } else {
                return false; // nothing to change
            }
        } else if (changeX && s.getY() == spot.getY() && s.getZ() == spot.getZ()
                && s.getHeading() == spot.getHeading()
                || changeY && s.getX() == spot.getX() && s.getZ() == spot.getZ()
                        && s.getHeading() == spot.getHeading()
                || changeZ && s.getX() == spot.getX() && s.getY() == spot.getY()
                        && s.getHeading() == spot.getHeading()
                || changeH && s.getX() == spot.getX() && s.getY() == spot.getY() && s.getZ() == spot.getZ()) {
            oldSpot = s;
            break;
        }
    }

    if (oldSpot != null) {
        oldGroup.getSpawnSpotTemplates().remove(oldSpot);
    }
    if (!delete) {
        oldGroup.addSpawnSpot(spot);
    }
    oldGroup.setCustom(true);

    SpawnMap map = null;
    if (data.templates == null) {
        data.templates = new ArrayList<SpawnMap>();
        map = new SpawnMap(spawn.getWorldId());
        data.templates.add(map);
    } else {
        map = data.templates.get(0);
    }

    if (addGroup) {
        map.addSpawns(oldGroup);
    }

    FileOutputStream fos = null;
    try {
        xml.getParentFile().mkdir();
        fos = new FileOutputStream(xml);
        Marshaller marshaller = jc.createMarshaller();
        marshaller.setSchema(schema);
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(data, fos);
        DataManager.SPAWNS_DATA2.templates = data.templates;
        DataManager.SPAWNS_DATA2.afterUnmarshal(null, null);
        DataManager.SPAWNS_DATA2.clearTemplates();
        data.clearTemplates();
    } catch (Exception e) {
        log.error(e.getMessage());
        PacketSendUtility.sendMessage(admin, "Could not save XML file!");
        return false;
    } finally {
        if (fos != null) {
            fos.close();
        }
    }
    return true;
}

From source file:at.gv.egiz.slbinding.SLUnmarshaller.java

/**
 * @param source a StreamSource wrapping a Reader (!) for the marshalled Object
 * @return the unmarshalled Object// w  w  w .j a  v  a2 s.  c o m
 * @throws XMLStreamException
 * @throws JAXBException
 */
public Object unmarshal(StreamSource source) throws XMLStreamException, JAXBException {
    Reader inputReader = source.getReader();

    /* Validate XML against XXE, XEE, and SSRF
     * 
     * This pre-validation step is required because com.sun.xml.stream.sjsxp-1.0.2 XML stream parser library does not 
     * support all XML parser features to prevent these types of attacks  
     */
    if (inputReader instanceof InputStreamReader) {
        try {
            //create copy of input stream
            InputStreamReader isReader = (InputStreamReader) inputReader;
            String encoding = isReader.getEncoding();
            byte[] backup = IOUtils.toByteArray(isReader, encoding);

            //validate input stream
            DOMUtils.validateXMLAgainstXXEAndSSRFAttacks(new ByteArrayInputStream(backup));

            //create new inputStreamReader for reak processing
            inputReader = new InputStreamReader(new ByteArrayInputStream(backup), encoding);

        } catch (XMLStreamException e) {
            log.error("XML data validation FAILED with msg: " + e.getMessage(), e);
            throw new XMLStreamException("XML data validation FAILED with msg: " + e.getMessage(), e);

        } catch (IOException e) {
            log.error("XML data validation FAILED with msg: " + e.getMessage(), e);
            throw new XMLStreamException("XML data validation FAILED with msg: " + e.getMessage(), e);

        }

    } else {
        log.error("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
        log.error(
                "Reader is not of type InputStreamReader -> can not make a copy of the InputStream --> extended XML validation is not possible!!! ");
        log.error("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");

    }

    /* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
     * parse XML with original functionality
     * 
     * This code implements the the original mocca XML processing by using 
     *  com.sun.xml.stream.sjsxp-1.0.2 XML stream parser library. Currently, this library is required to get full 
     *  security-layer specific XML processing. However, this lib does not fully support XXE, XEE and SSRF
     *  prevention mechanisms (e.g.: XMLInputFactory.SUPPORT_DTD flag is not used)    
     * 
     * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
     */
    XMLInputFactory inputFactory = XMLInputFactory.newInstance();

    //disallow DTD and external entities
    inputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
    inputFactory.setProperty("javax.xml.stream.isSupportingExternalEntities", false);

    XMLEventReader eventReader = inputFactory.createXMLEventReader(inputReader);
    RedirectEventFilter redirectEventFilter = new RedirectEventFilter();
    XMLEventReader filteredReader = inputFactory.createFilteredReader(eventReader, redirectEventFilter);

    Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
    ReportingValidationEventHandler validationEventHandler = new ReportingValidationEventHandler();
    unmarshaller.setEventHandler(validationEventHandler);

    unmarshaller.setListener(new RedirectUnmarshallerListener(redirectEventFilter));
    unmarshaller.setSchema(slSchema);

    Object object;
    try {
        log.trace("Before unmarshal().");
        object = unmarshaller.unmarshal(filteredReader);
        log.trace("After unmarshal().");
    } catch (UnmarshalException e) {
        if (log.isDebugEnabled()) {
            log.debug("Failed to unmarshal security layer message.", e);
        } else {
            log.info("Failed to unmarshal security layer message."
                    + (e.getMessage() != null ? " " + e.getMessage() : ""));
        }

        if (validationEventHandler.getErrorEvent() != null) {
            ValidationEvent errorEvent = validationEventHandler.getErrorEvent();
            if (e.getLinkedException() == null) {
                e.setLinkedException(errorEvent.getLinkedException());
            }
        }
        throw e;
    }

    return object;

}

From source file:com.netxforge.oss2.core.xml.JaxbUtils.java

/**
 * Get a JAXB unmarshaller for the given object.  If no JAXBContext is provided,
 * JAXBUtils will create and cache a context for the given object.
 * @param obj The object type to be unmarshaled.
 * @param jaxbContext An optional JAXB context to create the unmarshaller from.
 * @param validate TODO/*from   w  ww  .  j a  v a 2s  .  c o  m*/
 * @return an Unmarshaller
 */
public static Unmarshaller getUnmarshallerFor(final Object obj, final JAXBContext jaxbContext,
        boolean validate) {
    final Class<?> clazz = (Class<?>) (obj instanceof Class<?> ? obj : obj.getClass());

    Unmarshaller unmarshaller = null;

    Map<Class<?>, Unmarshaller> unmarshallers = m_unMarshallers.get();
    if (jaxbContext == null) {
        if (unmarshallers == null) {
            unmarshallers = new WeakHashMap<Class<?>, Unmarshaller>();
            m_unMarshallers.set(unmarshallers);
        }
        if (unmarshallers.containsKey(clazz)) {
            LogUtils.tracef(clazz, "found unmarshaller for %s", clazz);
            unmarshaller = unmarshallers.get(clazz);
        }
    }

    if (unmarshaller == null) {
        try {
            final JAXBContext context;
            if (jaxbContext == null) {
                context = getContextFor(clazz);
            } else {
                context = jaxbContext;
            }
            unmarshaller = context.createUnmarshaller();
        } catch (final JAXBException e) {
            throw EXCEPTION_TRANSLATOR.translate("creating XML marshaller", e);
        }
    }

    LogUtils.tracef(clazz, "created unmarshaller for %s", clazz);

    if (validate) {
        final Schema schema = getValidatorFor(clazz);
        if (schema == null) {
            LogUtils.tracef(clazz, "Validation is enabled, but no XSD found for class %s",
                    clazz.getSimpleName());
        }
        unmarshaller.setSchema(schema);
    }
    if (jaxbContext == null)
        unmarshallers.put(clazz, unmarshaller);

    return unmarshaller;
}

From source file:cz.cas.lib.proarc.common.workflow.profile.WorkflowProfiles.java

private Unmarshaller getUnmarshaller() throws JAXBException {
    JAXBContext jctx = JAXBContext.newInstance(WorkflowDefinition.class);
    Unmarshaller unmarshaller = jctx.createUnmarshaller();
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    URL schemaUrl = WorkflowDefinition.class.getResource("workflow.xsd");
    Schema schema = null;/*from   w ww . j av a2s. c  o m*/
    try {
        schema = sf.newSchema(new StreamSource(schemaUrl.toExternalForm()));
    } catch (SAXException ex) {
        throw new JAXBException("Missing schema workflow.xsd!", ex);
    }
    unmarshaller.setSchema(schema);
    ValidationEventCollector errors = new ValidationEventCollector() {

        @Override
        public boolean handleEvent(ValidationEvent event) {
            super.handleEvent(event);
            return true;
        }

    };
    unmarshaller.setEventHandler(errors);
    return unmarshaller;
}

From source file:org.anodyneos.jse.cron.CronDaemon.java

public CronDaemon(InputSource source) throws JseException {

    Schedule schedule;/*w  ww. j a  v  a 2  s  .  co m*/

    // parse source
    try {

        JAXBContext jc = JAXBContext.newInstance("org.anodyneos.jse.cron.config");
        Unmarshaller u = jc.createUnmarshaller();
        //Schedule
        Source schemaSource = new StreamSource(Thread.currentThread().getContextClassLoader()
                .getResourceAsStream("org/anodyneos/jse/cron/cron.xsd"));

        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = sf.newSchema(schemaSource);
        u.setSchema(schema);
        ValidationEventCollector vec = new ValidationEventCollector();
        u.setEventHandler(vec);

        JAXBElement<?> rootElement;
        try {
            rootElement = ((JAXBElement<?>) u.unmarshal(source));
        } catch (UnmarshalException ex) {
            if (!vec.hasEvents()) {
                throw ex;
            } else {
                for (ValidationEvent ve : vec.getEvents()) {
                    ValidationEventLocator vel = ve.getLocator();
                    log.error("Line:Col[" + vel.getLineNumber() + ":" + vel.getColumnNumber() + "]:"
                            + ve.getMessage());
                }
                throw new JseException("Validation failed for source publicId='" + source.getPublicId()
                        + "'; systemId='" + source.getSystemId() + "';");
            }
        }

        schedule = (Schedule) rootElement.getValue();

        if (vec.hasEvents()) {
            for (ValidationEvent ve : vec.getEvents()) {
                ValidationEventLocator vel = ve.getLocator();
                log.warn("Line:Col[" + vel.getLineNumber() + ":" + vel.getColumnNumber() + "]:"
                        + ve.getMessage());
            }
        }

    } catch (JseException e) {
        throw e;
    } catch (Exception e) {
        throw new JseException("Cannot parse " + source + ".", e);
    }

    SpringHelper springHelper = new SpringHelper();

    ////////////////
    //
    // Configure Spring and Create Beans
    //
    ////////////////

    TimeZone defaultTimeZone;

    if (schedule.isSetTimeZone()) {
        defaultTimeZone = getTimeZone(schedule.getTimeZone());
    } else {
        defaultTimeZone = TimeZone.getDefault();
    }

    if (schedule.isSetSpringContext() && schedule.getSpringContext().isSetConfig()) {
        for (Config config : schedule.getSpringContext().getConfig()) {
            springHelper.addXmlClassPathConfigLocation(config.getClassPathResource());
        }
    }

    for (org.anodyneos.jse.cron.config.JobGroup jobGroup : schedule.getJobGroup()) {
        for (Job job : jobGroup.getJob()) {
            if (job.isSetBeanRef()) {
                if (job.isSetBean() || job.isSetClassName()) {
                    throw new JseException("Cannot set bean or class attribute for job when beanRef is set.");
                } // else config ok
            } else {
                if (!job.isSetClassName()) {
                    throw new JseException("must set either class or beanRef for job.");
                }
                GenericBeanDefinition beanDef = new GenericBeanDefinition();
                MutablePropertyValues propertyValues = new MutablePropertyValues();

                if (!job.isSetBean()) {
                    job.setBean(UUID.randomUUID().toString());
                }

                if (springHelper.containsBean(job.getBean())) {
                    throw new JseException(
                            "Bean name already used; overriding not allowed here: " + job.getBean());
                }

                beanDef.setBeanClassName(job.getClassName());

                for (Property prop : job.getProperty()) {
                    String value = null;
                    if (prop.isSetSystemProperty()) {
                        value = System.getProperty(prop.getSystemProperty());
                    }
                    if (null == value) {
                        value = prop.getValue();
                    }

                    propertyValues.addPropertyValue(prop.getName(), value);
                }

                beanDef.setPropertyValues(propertyValues);
                springHelper.registerBean(job.getBean(), beanDef);
                job.setBeanRef(job.getBean());
            }
        }
    }

    springHelper.init();

    ////////////////
    //
    // Configure Timer Services
    //
    ////////////////

    for (org.anodyneos.jse.cron.config.JobGroup jobGroup : schedule.getJobGroup()) {

        String jobGroupName;
        JseTimerService service = new JseTimerService();

        timerServices.add(service);

        if (jobGroup.isSetName()) {
            jobGroupName = jobGroup.getName();
        } else {
            jobGroupName = UUID.randomUUID().toString();
        }

        if (jobGroup.isSetMaxConcurrent()) {
            service.setMaxConcurrent(jobGroup.getMaxConcurrent());
        }

        for (Job job : jobGroup.getJob()) {

            TimeZone jobTimeZone = defaultTimeZone;

            if (job.isSetTimeZone()) {
                jobTimeZone = getTimeZone(job.getTimeZone());
            } else {
                jobTimeZone = defaultTimeZone;
            }

            Object obj;

            Date notBefore = null;
            Date notAfter = null;

            if (job.isSetNotBefore()) {
                notBefore = job.getNotBefore().toGregorianCalendar(jobTimeZone, null, null).getTime();
            }
            if (job.isSetNotAfter()) {
                notAfter = job.getNotAfter().toGregorianCalendar(jobTimeZone, null, null).getTime();
            }

            CronSchedule cs = new CronSchedule(job.getSchedule(), jobTimeZone, job.getMaxIterations(),
                    job.getMaxQueue(), notBefore, notAfter);

            obj = springHelper.getBean(job.getBeanRef());
            log.info("Adding job " + jobGroup.getName() + "/" + job.getName() + " using bean "
                    + job.getBeanRef());
            if (obj instanceof CronJob) {
                ((CronJob) obj).setCronContext(new CronContext(jobGroupName, job.getName(), cs));
            }
            if (obj instanceof JseDateAwareJob) {
                service.createTimer((JseDateAwareJob) obj, cs);
            } else if (obj instanceof Runnable) {
                service.createTimer((Runnable) obj, cs);
            } else {
                throw new JseException("Job must implement Runnable or JseDateAwareJob");
            }
        }
    }
}

From source file:org.apache.taverna.scufl2.translator.t2flow.T2FlowParser.java

public Unmarshaller getUnmarshaller() {
    Unmarshaller u = unmarshaller.get();
    if (!isValidating() && u.getSchema() != null) {
        u.setSchema(null);
    } else if (isValidating() && u.getSchema() == null) {
        // Load and set schema to validate against
        Schema schema;/*from  w  ww. j a v  a 2  s.  c o m*/
        try {
            SchemaFactory schemaFactory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
            List<URI> schemas = getAdditionalSchemas();
            URL t2flowExtendedXSD = T2FlowParser.class.getResource(T2FLOW_EXTENDED_XSD);
            schemas.add(t2flowExtendedXSD.toURI());

            List<Source> schemaSources = new ArrayList<>();
            for (URI schemaUri : schemas)
                schemaSources.add(new StreamSource(schemaUri.toASCIIString()));
            Source[] sources = schemaSources.toArray(new Source[schemaSources.size()]);
            schema = schemaFactory.newSchema(sources);
        } catch (SAXException e) {
            throw new RuntimeException("Can't load schemas", e);
        } catch (URISyntaxException | NullPointerException e) {
            throw new RuntimeException("Can't find schemas", e);
        }
        u.setSchema(schema);
    }
    return u;
}

From source file:alter.vitro.vgw.service.query.SimpleQueryHandler.java

/**
 * Method processQuery://  w  w w  .j  a v  a  2 s .c o m
 * <p/>
 *
 * @param queryXMLStr The XML query Message to be processed
 * @return 0, if OK, -1 if not. If OK, it will have generated and forwarded the  XML Response Message
 *         to the sender of the query
 *         TODO: here the code is blocking...  But this will eventually be replaced by a VSN controller within the VGW
 */
public int processQuery(String queryXMLStr) {
    // a usernode query is the object for the expected query from a user application
    UserNodeQuery query = new UserNodeQuery(queryXMLStr);

    if (query.getQueryId() == 0 || query.getSrc().isEmpty() || query.getQuery().isEmpty()) {
        // DEBUG:
        //System.out.println("Not a query!!!");
        if (queryXMLStr == null) {
            queryXMLStr = "";
        }
        logger.error("Not a valid query!!!::" + queryXMLStr);
        return -1;
    }

    UserNodeResponse response;

    //System.out.println("Processing query...");
    //System.out.println(queryXMLStr);
    logger.debug("Processing query or command...");
    //logger.debug(queryXMLStr);

    if (query.isSpecialCommand()) {
        // special cases (this could be a static method "isSpecialQueryId)
        if (query.getQueryId() == UserNodeQuery.SPECIAL_ENABLE_NODES_COMMAND_ID) {
            //
            // CASE OF ENABLE/DISABLE NODES MESSAGE
            //
            logger.debug("Handling ENABLE-DISABLE Message!");
            try {
                InputStream stream;
                stream = new ByteArrayInputStream(query.getQuery().getBytes());
                // create a JAXBContext capable of handling classes generated into package
                javax.xml.bind.JAXBContext jaxbContext = javax.xml.bind.JAXBContext
                        .newInstance("alter.vitro.vgw.service.query.xmlmessages.enablednodessynch.fromvsp");
                // create an Unmarshaller
                javax.xml.bind.Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
                if (enDisFromVSPschema == null) {
                    logger.error("Could not acquire schema info for en-dis: fromvsp.xsd");
                    return -1;
                }
                unmarshaller.setSchema(enDisFromVSPschema);

                // unmarshal an instance document into a tree of Java content
                // objects composed of classes from the package.
                // TODO: fixing the xsd not to reference types of elements outside the elements will clear up the unmarshaller
                EnableNodesReqType recvdQuery = (EnableNodesReqType) ((JAXBElement) unmarshaller
                        .unmarshal(stream)).getValue();

                //preliminary check to see if we have other types of queries
                if (recvdQuery.getMessageType().trim()
                        .compareToIgnoreCase(UserNodeQuery.COMMAND_TYPE_ENABLENODES) == 0) {
                    // start preparing the response
                    String msgToSend = ResourceAvailabilityService.getInstance()
                            .createSynchConfirmationForVSP(recvdQuery);
                    if (msgToSend != null || !msgToSend.trim().isEmpty()) {
                        //send the confirmation message with the right header
                        StringBuilder toAddHeaderBld = new StringBuilder();
                        // based on a UserNodeResponse structure we should have a queryId (which here is the messageType again, as src which should be the VSPCore, and a body)
                        toAddHeaderBld.append(UserNodeResponse.COMMAND_TYPE_ENABLENODES_RESP);
                        toAddHeaderBld.append(UserNodeResponse.headerSpliter);
                        toAddHeaderBld.append(VitroGatewayService.getVitroGatewayService()
                                .getAssignedGatewayUniqueIdFromReg());

                        toAddHeaderBld.append(UserNodeResponse.headerSpliter);
                        toAddHeaderBld.append(msgToSend);
                        msgToSend = toAddHeaderBld.toString();
                        sendResponse(msgToSend);
                    } else {
                        logger.debug("No message to send for enable disable list confirmation");
                    }
                    logger.debug("Successfully Handled ENABLE-DISABLE Message!");
                    logger.debug(ResourceAvailabilityService.getInstance().printDevicesAndEnabledStatus());
                } else {
                    // DEBUG
                    logger.debug("Error: Invalid command type received!" + recvdQuery.getMessageType().trim());
                }

            } catch (javax.xml.bind.JAXBException je) {
                logger.error("JaxBException in processQuery method", je);
                return -1;
            } catch (Exception eall) {
                logger.error("General Exception in processQuery method", eall);
                return -1;
            }
        } else if (query.getQueryId() == UserNodeQuery.SPECIAL_EQUIV_LIST_SYNCH_COMMAND_ID) {
            //
            // CASE OF SYNCH EQUIV LISTS MESSAGE
            //
            logger.debug("Handling SYNCH EQUIV LISTS MESSAGE!");
            try {
                InputStream stream;
                stream = new ByteArrayInputStream(query.getQuery().getBytes());
                // create a JAXBContext capable of handling classes generated into package
                javax.xml.bind.JAXBContext jaxbContext = javax.xml.bind.JAXBContext
                        .newInstance("alter.vitro.vgw.service.query.xmlmessages.equivlistsynch.fromvsp");
                // create an Unmarshaller
                javax.xml.bind.Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
                if (equivSynchFromVSPschema == null) {
                    logger.error("Could not acquire schema info for equiv synch: fromvsp.xsd");
                    return -1;
                }
                unmarshaller.setSchema(equivSynchFromVSPschema);

                // unmarshal an instance document into a tree of Java content
                // objects composed of classes from the package.
                // TODO: fixing the xsd not to reference types of elements outside the elements will clear up the unmarshaller
                EquivListNodesReqType recvdQuery = (EquivListNodesReqType) ((JAXBElement) unmarshaller
                        .unmarshal(stream)).getValue();

                //preliminary check to see if we have other types of queries
                if (recvdQuery.getMessageType().trim()
                        .compareToIgnoreCase(UserNodeQuery.COMMAND_TYPE_EQUIV_LIST_SYNCH) == 0) {
                    // start preparing the response
                    //response = new UserNodeResponse();
                    // TODO:
                    // return processAggregateQuery(new QueryAggrMsg(recvdQuery), query.getQueryId(),response);
                    String msgToSend = ContinuationOfProvisionService.getInstance()
                            .createSynchConfirmationForVSP(recvdQuery);
                    if (msgToSend != null || !msgToSend.trim().isEmpty()) {
                        //send the confirmation message with the right header
                        StringBuilder toAddHeaderBld = new StringBuilder();
                        // based on a UserNodeResponse structure we should have a queryId (which here is the messageType again, as src which should be the VSPCore, and a body)
                        toAddHeaderBld.append(UserNodeResponse.COMMAND_TYPE_EQUIV_LIST_SYNCH_RESP);
                        toAddHeaderBld.append(UserNodeResponse.headerSpliter);
                        toAddHeaderBld.append(VitroGatewayService.getVitroGatewayService()
                                .getAssignedGatewayUniqueIdFromReg());

                        toAddHeaderBld.append(UserNodeResponse.headerSpliter);
                        toAddHeaderBld.append(msgToSend);
                        msgToSend = toAddHeaderBld.toString();
                        sendResponse(msgToSend);
                    } else {
                        logger.debug("No message to send for equiv list confirmation");
                    }
                    logger.debug("Successfully Handled SYNCH EQUIV LISTS Message!");
                    logger.debug(
                            ContinuationOfProvisionService.getInstance().printEquivListsAndReplacementLists());
                } else {
                    // DEBUG
                    logger.debug("Error: Invalid command type received!" + recvdQuery.getMessageType().trim());
                }
            } catch (javax.xml.bind.JAXBException je) {
                logger.error("JaxBException in processQuery method", je);
                return -1;
            } catch (Exception eall) {
                logger.error("General Exception in processQuery method", eall);
                return -1;
            }
        }
    } else {

        // Parse the message from the query string.
        // find what kind of message we are dealing with, and process it accordingly
        //
        try {
            InputStream stream;
            stream = new ByteArrayInputStream(query.getQuery().getBytes());
            // create a JAXBContext capable of handling classes generated into package
            javax.xml.bind.JAXBContext jaxbContext = javax.xml.bind.JAXBContext
                    .newInstance("alter.vitro.vgw.service.query.xmlmessages.aggrquery");
            // create an Unmarshaller
            javax.xml.bind.Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            if (schema == null) {
                logger.error("Could not acquire schema info for: PublicQueryAggrMsg.xsd");
                return -1;
            }
            unmarshaller.setSchema(schema);

            // unmarshal an instance document into a tree of Java content
            // objects composed of classes from the package.
            // TODO: fixing the xsd not to reference types of elements outside the elements will clear up the unmarshaller
            MyQueryAggrType recvdQuery = (MyQueryAggrType) ((JAXBElement) unmarshaller.unmarshal(stream))
                    .getValue();

            //preliminary check to see if we have other types of queries
            if (recvdQuery.getMessageType().trim().equals(QueryAggrMsg.getThisMsgType())) {
                // start preparing the response
                response = new UserNodeResponse();
                return processAggregateQuery(new QueryAggrMsg(recvdQuery), query.getQueryId(), response);
            } else {
                // DEBUG
                logger.debug("Error: Invalid query type received!" + recvdQuery.getMessageType().trim());
            }
        } catch (javax.xml.bind.JAXBException je) {
            logger.error("JaxBException in processQuery method", je);
            return -1;
        } catch (Exception eall) {
            logger.error("General Exception in processQuery method", eall);
            return -1;
        }
    }
    return 0;
}

From source file:nl.ordina.bag.etl.xml.XMLMessageBuilder.java

@SuppressWarnings("unchecked")
public T handle(Schema schema, InputStream is, Class<T> clazz) throws JAXBException {
    if (is == null)
        return null;
    Unmarshaller unmarshaller = context.createUnmarshaller();
    if (schema != null)
        unmarshaller.setSchema(schema);
    Object o = clazz == null ? unmarshaller.unmarshal(is) : unmarshaller.unmarshal(new StreamSource(is), clazz);
    if (o instanceof JAXBElement<?>)
        return ((JAXBElement<T>) o).getValue();
    else/*  ww w . j av a2  s.  com*/
        return (T) o;
}

From source file:nl.ordina.bag.etl.xml.XMLMessageBuilder.java

@SuppressWarnings("unchecked")
public T handle(Schema schema, Reader r, Class<T> clazz) throws JAXBException {
    if (r == null)
        return null;
    Unmarshaller unmarshaller = context.createUnmarshaller();
    if (schema != null)
        unmarshaller.setSchema(schema);
    Object o = clazz == null ? unmarshaller.unmarshal(r) : unmarshaller.unmarshal(new StreamSource(r), clazz);
    if (o instanceof JAXBElement<?>)
        return ((JAXBElement<T>) o).getValue();
    else//from   w w  w  .  j  a  va 2  s. c o  m
        return (T) o;
}