Example usage for javax.xml.bind Unmarshaller unmarshal

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

Introduction

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

Prototype

public Object unmarshal(javax.xml.stream.XMLEventReader reader) throws JAXBException;

Source Link

Document

Unmarshal XML data from the specified pull parser and return the resulting content tree.

Usage

From source file:br.gov.frameworkdemoiselle.behave.integration.alm.objects.util.GenerateXMLString.java

public static Testplan getTestPlanObject(HttpResponse response) throws IOException, JAXBException {

    Testplan plan = null;/*  w w  w. j av  a2 s .com*/
    StringBuffer xmlString = new StringBuffer();
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        InputStream instream = entity.getContent();
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
            String line = "";
            while ((line = reader.readLine()) != null) {
                xmlString.append(line);
            }
        } finally {
            instream.close();
        }
    }

    if (!xmlString.equals("")) {
        JAXBContext jaxbContext = JAXBContext.newInstance(Testplan.class);
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        StringReader reader = new StringReader(xmlString.toString());
        plan = (Testplan) unmarshaller.unmarshal(reader);
    }

    return plan;

}

From source file:com.maxl.java.aips2sqlite.Aips2Sqlite.java

static List<MedicalInformations.MedicalInformation> readAipsFile() {
    List<MedicalInformations.MedicalInformation> med_list = null;
    try {// w  w w .j a  v a  2s.  com
        JAXBContext context = JAXBContext.newInstance(MedicalInformations.class);

        // Validation
        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = sf.newSchema(new File(Constants.FILE_MEDICAL_INFOS_XSD));
        Validator validator = schema.newValidator();
        validator.setErrorHandler(new MyErrorHandler());

        // Marshaller
        /*
         * Marshaller ma = context.createMarshaller();
         * ma.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
         * MedicalInformations medi_infos = new MedicalInformations();
         * ma.marshal(medi_infos, System.out);
         */
        // Unmarshaller
        long startTime = System.currentTimeMillis();
        if (CmlOptions.SHOW_LOGS)
            System.out.print("- Unmarshalling Swissmedic xml... ");

        FileInputStream fis = new FileInputStream(new File(Constants.FILE_MEDICAL_INFOS_XML));
        Unmarshaller um = context.createUnmarshaller();
        MedicalInformations med_infos = (MedicalInformations) um.unmarshal(fis);
        med_list = med_infos.getMedicalInformation();

        long stopTime = System.currentTimeMillis();
        if (CmlOptions.SHOW_LOGS)
            System.out.println(med_list.size() + " medis in " + (stopTime - startTime) / 1000.0f + " sec");
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JAXBException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    }

    return med_list;
}

From source file:com.aionemu.gameserver.model.TribeRelationCheck.java

@BeforeClass
public static void init() throws Exception {
    File xml = new File("./data/static_data/tribe/tribe_relations.xml");
    Schema schema = null;/* w  w  w  . j  av  a2s .  c  o  m*/
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    TribeRelationsData tribeRelations = null;
    NpcData npcTemplates = null;

    try {
        schema = sf.newSchema(new File("./data/static_data/tribe/tribe_relations.xsd"));
        JAXBContext jc = JAXBContext.newInstance(TribeRelationsData.class);
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        unmarshaller.setSchema(schema);
        tribeRelations = (TribeRelationsData) unmarshaller.unmarshal(xml);

        xml = new File("./data/static_data/npcs/npc_templates.xml");
        schema = sf.newSchema(new File("./data/static_data/npcs/npcs.xsd"));
        jc = JAXBContext.newInstance(NpcData.class);
        unmarshaller = jc.createUnmarshaller();
        unmarshaller.setSchema(schema);
        npcTemplates = (NpcData) unmarshaller.unmarshal(xml);
    } catch (SAXException e1) {
        System.out.println(e1.getMessage());
    } catch (JAXBException e2) {
        System.out.println(e2.getMessage());
    }

    // Not interesting
    DataManager.NPC_SKILL_DATA = new NpcSkillData();
    DataManager.NPC_DATA = npcTemplates;
    DataManager.TRIBE_RELATIONS_DATA = tribeRelations;
    DataManager.ZONE_DATA = new DummyZoneData();
    DataManager.WORLD_MAPS_DATA = new DummyWorldMapData();

    Config.load();
    // AIConfig.ONCREATE_DEBUG = true;
    AIConfig.EVENT_DEBUG = true;
    ThreadConfig.THREAD_POOL_SIZE = 20;
    ThreadPoolManager.getInstance();

    AI2Engine.getInstance().load(null);

    /**
     * Comment out these lines in DAOManager.registerDAO() if not using DB: <tt> 
     * if (!dao.supports(getDatabaseName(),
     *       getDatabaseMajorVersion(), getDatabaseMinorVersion())) { return; } 
     * </tt>
     */
    DAOManager.init();

    world = World.getInstance();
    asmo = DummyPlayer.createAsmodian();
    asmoPosition = World.getInstance().createPosition(DummyWorldMapData.DEFAULT_MAP, 100f, 100f, 0f, (byte) 0,
            0);

    MapRegion asmoRegion = asmoPosition.getWorldMapInstance().getRegion(100f, 100f, 0);
    asmoRegion.getObjects().put(asmo.getObjectId(), asmo);
    asmoRegion.activate();
    asmo.setPosition(asmoPosition);

    ely = DummyPlayer.createElyo();
    elyPosition = World.getInstance().createPosition(DummyWorldMapData.DEFAULT_MAP, 200f, 200f, 0f, (byte) 0,
            0);
    MapRegion elyRegion = elyPosition.getWorldMapInstance().getRegion(200f, 200f, 0);
    elyRegion.getObjects().put(ely.getObjectId(), ely);
    elyRegion.activate();
    ely.setPosition(elyPosition);

    PacketBroadcaster.getInstance();
    DuelService.getInstance();
    PlayerMoveTaskManager.getInstance();
    MoveTaskManager.getInstance();
}

From source file:br.gov.frameworkdemoiselle.behave.integration.alm.objects.util.GenerateXMLString.java

public static Testcase getTestcaseObject(HttpResponse response) throws IOException, JAXBException {

    Testcase testcase = null;//from w w  w  . j ava  2s  .c om
    StringBuffer xmlString = new StringBuffer();
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        InputStream instream = entity.getContent();
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
            String line = "";
            while ((line = reader.readLine()) != null) {
                xmlString.append(line);
            }
        } finally {
            instream.close();
        }
    }

    if (!xmlString.equals("")) {
        JAXBContext jaxbContext = JAXBContext.newInstance(Testcase.class);
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        StringReader reader = new StringReader(xmlString.toString());
        testcase = (Testcase) unmarshaller.unmarshal(reader);
    }

    return testcase;

}

From source file:Main.java

/**
 * Converts the XML file specified into the specified POJO type
 * @param <T> the object type of the POJO
 * @param xmlfile the XML file to convert
 * @param classOfT the class of the POJO
 * @return the POJO object if conversion was successful
 * @throws JAXBException/*from   w w w .  jav  a 2  s  .c o  m*/
 * @throws XMLStreamException
 * @throws FileNotFoundException 
 */
public static <T> T convertToPojo(File xmlfile, Class<T> classOfT)
        throws JAXBException, XMLStreamException, FileNotFoundException {
    JAXBContext jaxbContext = JAXBContext.newInstance(classOfT);
    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();

    XMLInputFactory xif = XMLInputFactory.newFactory();
    // settings to prevent xxe // would be funny if this tool is itsef is vulnerable to xxe :D
    xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
    xif.setProperty(XMLInputFactory.SUPPORT_DTD, false);

    XMLStreamReader xsr = xif.createXMLStreamReader(new FileReader(xmlfile));
    T t = (T) jaxbUnmarshaller.unmarshal(xsr);//(xmlfile);

    return t;
}

From source file:ee.ria.xroad.common.hashchain.HashChainVerifier.java

@SuppressWarnings("unchecked")
private static HashChainType parseHashChain(InputStream xml) throws Exception {
    Unmarshaller unmarshaller = jaxbCtx.createUnmarshaller();
    JAXBElement<HashChainType> element = (JAXBElement<HashChainType>) unmarshaller.unmarshal(xml);

    HashChainValidator.validate(new JAXBSource(jaxbCtx, element));

    return element.getValue();
}

From source file:eu.squadd.reflections.mapper.ServiceModelTranslator.java

/**
 * JAXB object translation methods      
 *///from  w w  w . ja  va  2s  . c  o m

public static Object transformXmlObj2XmlObj(Class sourceClass, Class destClass, Object source) {
    try {
        JAXBContext sourceContext = JAXBContext.newInstance(sourceClass);
        JAXBSource jaxbSource = new JAXBSource(sourceContext, source);
        JAXBContext destContext = JAXBContext.newInstance(destClass);
        Unmarshaller unmarshaller = destContext.createUnmarshaller();
        return unmarshaller.unmarshal(jaxbSource);
    } catch (JAXBException ex) {
        System.err.println(ex.getMessage());
        return null;
    }
}

From source file:be.e_contract.dssp.client.SignResponseVerifier.java

/**
 * Checks the signature on the SignResponse browser POST message.
 * // ww w.ja v  a  2s . c o  m
 * @param signResponseMessage
 *            the SignResponse message.
 * @param session
 *            the session object.
 * @return the verification result object.
 * @throws JAXBException
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 * @throws MarshalException
 * @throws XMLSignatureException
 * @throws Base64DecodingException
 * @throws UserCancelException
 * @throws ClientRuntimeException
 * @throws SubjectNotAuthorizedException
 */
public static SignResponseVerificationResult checkSignResponse(String signResponseMessage,
        DigitalSignatureServiceSession session) throws JAXBException, ParserConfigurationException,
        SAXException, IOException, MarshalException, XMLSignatureException, Base64DecodingException,
        UserCancelException, ClientRuntimeException, SubjectNotAuthorizedException {
    if (null == session) {
        throw new IllegalArgumentException("missing session");
    }

    byte[] decodedSignResponseMessage;
    try {
        decodedSignResponseMessage = Base64.decode(signResponseMessage);
    } catch (Base64DecodingException e) {
        throw new SecurityException("no Base64");
    }
    // JAXB parsing
    JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class,
            be.e_contract.dssp.ws.jaxb.dss.async.ObjectFactory.class,
            be.e_contract.dssp.ws.jaxb.wsa.ObjectFactory.class,
            be.e_contract.dssp.ws.jaxb.wsu.ObjectFactory.class);
    Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
    SignResponse signResponse;
    try {
        signResponse = (SignResponse) unmarshaller
                .unmarshal(new ByteArrayInputStream(decodedSignResponseMessage));
    } catch (UnmarshalException e) {
        throw new SecurityException("no valid SignResponse XML");
    }

    // DOM parsing
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    InputStream signResponseInputStream = new ByteArrayInputStream(decodedSignResponseMessage);
    Document signResponseDocument = documentBuilder.parse(signResponseInputStream);

    // signature verification
    NodeList signatureNodeList = signResponseDocument
            .getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#", "Signature");
    if (signatureNodeList.getLength() != 1) {
        throw new SecurityException("requires 1 ds:Signature element");
    }
    Element signatureElement = (Element) signatureNodeList.item(0);
    SecurityTokenKeySelector keySelector = new SecurityTokenKeySelector(session.getKey());
    DOMValidateContext domValidateContext = new DOMValidateContext(keySelector, signatureElement);
    XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance("DOM");
    XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext);
    boolean validSignature = xmlSignature.validate(domValidateContext);
    if (false == validSignature) {
        throw new SecurityException("invalid ds:Signature");
    }

    // verify content
    String responseId = null;
    RelatesToType relatesTo = null;
    AttributedURIType to = null;
    TimestampType timestamp = null;
    String signerIdentity = null;
    AnyType optionalOutputs = signResponse.getOptionalOutputs();
    List<Object> optionalOutputsList = optionalOutputs.getAny();
    for (Object optionalOutputObject : optionalOutputsList) {
        LOG.debug("optional output object type: " + optionalOutputObject.getClass().getName());
        if (optionalOutputObject instanceof JAXBElement) {
            JAXBElement optionalOutputElement = (JAXBElement) optionalOutputObject;
            LOG.debug("optional output name: " + optionalOutputElement.getName());
            LOG.debug("optional output value type: " + optionalOutputElement.getValue().getClass().getName());
            if (RESPONSE_ID_QNAME.equals(optionalOutputElement.getName())) {
                responseId = (String) optionalOutputElement.getValue();
            } else if (optionalOutputElement.getValue() instanceof RelatesToType) {
                relatesTo = (RelatesToType) optionalOutputElement.getValue();
            } else if (TO_QNAME.equals(optionalOutputElement.getName())) {
                to = (AttributedURIType) optionalOutputElement.getValue();
            } else if (optionalOutputElement.getValue() instanceof TimestampType) {
                timestamp = (TimestampType) optionalOutputElement.getValue();
            } else if (optionalOutputElement.getValue() instanceof NameIdentifierType) {
                NameIdentifierType nameIdentifier = (NameIdentifierType) optionalOutputElement.getValue();
                signerIdentity = nameIdentifier.getValue();
            }
        }
    }

    Result result = signResponse.getResult();
    LOG.debug("result major: " + result.getResultMajor());
    LOG.debug("result minor: " + result.getResultMinor());
    if (DigitalSignatureServiceConstants.REQUESTER_ERROR_RESULT_MAJOR.equals(result.getResultMajor())) {
        if (DigitalSignatureServiceConstants.USER_CANCEL_RESULT_MINOR.equals(result.getResultMinor())) {
            throw new UserCancelException();
        }
        if (DigitalSignatureServiceConstants.CLIENT_RUNTIME_RESULT_MINOR.equals(result.getResultMinor())) {
            throw new ClientRuntimeException();
        }
        if (DigitalSignatureServiceConstants.SUBJECT_NOT_AUTHORIZED_RESULT_MINOR
                .equals(result.getResultMinor())) {
            throw new SubjectNotAuthorizedException(signerIdentity);
        }
    }
    if (false == DigitalSignatureServiceConstants.PENDING_RESULT_MAJOR.equals(result.getResultMajor())) {
        throw new SecurityException("invalid dss:ResultMajor");
    }

    if (null == responseId) {
        throw new SecurityException("missing async:ResponseID");
    }
    if (false == responseId.equals(session.getResponseId())) {
        throw new SecurityException("invalid async:ResponseID");
    }

    if (null == relatesTo) {
        throw new SecurityException("missing wsa:RelatesTo");
    }
    if (false == session.getInResponseTo().equals(relatesTo.getValue())) {
        throw new SecurityException("invalid wsa:RelatesTo");
    }

    if (null == to) {
        throw new SecurityException("missing wsa:To");
    }
    if (false == session.getDestination().equals(to.getValue())) {
        throw new SecurityException("invalid wsa:To");
    }

    if (null == timestamp) {
        throw new SecurityException("missing wsu:Timestamp");
    }
    AttributedDateTime expires = timestamp.getExpires();
    if (null == expires) {
        throw new SecurityException("missing wsu:Timestamp/wsu:Expires");
    }
    DateTime expiresDateTime = new DateTime(expires.getValue());
    DateTime now = new DateTime();
    if (now.isAfter(expiresDateTime)) {
        throw new SecurityException("wsu:Timestamp expired");
    }

    session.setSignResponseVerified(true);

    SignResponseVerificationResult signResponseVerificationResult = new SignResponseVerificationResult(
            signerIdentity);
    return signResponseVerificationResult;
}

From source file:net.ageto.gyrex.impex.console.internal.ImpexConsoleCommands.java

/**
 * Adds xml process configuration from file
 *
 * @param interpreter/*from   w  w w  .  j a v a2s.  com*/
 * @param context
 * @param processXmlFileName
 */
public static boolean addProcessFromFile(IRuntimeContext context, final String processXmlFileName) {
    final File processXmlFile = new File(processXmlFileName);
    if (!processXmlFile.isFile()) {
        System.err.println("ERROR: file does not exist " + processXmlFileName);
        return false;
    }

    ProcessConfig process = null;
    if (processXmlFileName != null) {

        try {
            JAXBContext jaxbContext;
            jaxbContext = JAXBContext.newInstance(ProcessConfig.class);
            final Unmarshaller u = jaxbContext.createUnmarshaller();
            // create process instance from xml
            process = (ProcessConfig) u.unmarshal(processXmlFile);

            process.getId();
        } catch (final JAXBException e) {
            System.err.println(e);
            return false;
        }
    }

    // store process into database
    final IProcessConfigManager processManager = context.get(IProcessConfigManager.class);
    processManager.persist(process);

    System.out.println(processXmlFileName + " file processed successfully.");

    return true;
}

From source file:org.apache.directory.fortress.core.rest.RestUtils.java

/**
 * Unmarshall the XML response into its associated Java objects.
 *
 * @param szResponse/*w w w  .  j  ava2 s.c  o m*/
 * @return FortResponse
 * @throws RestException
 */
public static FortResponse unmarshall(String szResponse) throws RestException {
    FortResponse response;
    try {
        // Create a JAXB context passing in the class of the object we want to marshal/unmarshal
        final JAXBContext context = cachedJaxbContext.getJaxbContext(FortResponse.class);

        // Create the unmarshaller, that will transform the XML back into an object
        final Unmarshaller unmarshaller = context.createUnmarshaller();
        response = (FortResponse) unmarshaller.unmarshal(new StringReader(szResponse));
    } catch (JAXBException je) {
        String error = "unmarshall caught JAXBException=" + je;
        throw new RestException(GlobalErrIds.REST_UNMARSHALL_ERR, error, je);
    }
    return response;
}