Example usage for javax.xml.bind JAXBContext createUnmarshaller

List of usage examples for javax.xml.bind JAXBContext createUnmarshaller

Introduction

In this page you can find the example usage for javax.xml.bind JAXBContext createUnmarshaller.

Prototype

public abstract Unmarshaller createUnmarshaller() throws JAXBException;

Source Link

Document

Create an Unmarshaller object that can be used to convert XML data into a java content tree.

Usage

From source file:com.ikon.util.impexp.RepositoryImporter.java

/**
 * Import document.//from ww w  .ja  v  a  2 s  . c  om
 */
private static ImpExpStats importDocument(String token, File fs, String fldPath, String fileName, File fDoc,
        String metadata, boolean history, Writer out, InfoDecorator deco)
        throws IOException, RepositoryException, DatabaseException, PathNotFoundException,
        AccessDeniedException, ExtensionException, AutomationException {
    FileInputStream fisContent = new FileInputStream(fDoc);
    MetadataAdapter ma = MetadataAdapter.getInstance(token);
    DocumentModule dm = ModuleManager.getDocumentModule();
    ImpExpStats stats = new ImpExpStats();
    int size = fisContent.available();
    Document doc = new Document();
    Gson gson = new Gson();
    boolean api = false;

    try {
        // Metadata
        if (!metadata.equals("none")) {
            boolean isJsonFile = metadata.equals("JSON");
            // Read serialized document metadata
            File jsFile = null;
            if (isJsonFile)
                jsFile = new File(fDoc.getPath() + Config.EXPORT_METADATA_EXT);
            else
                jsFile = new File(fDoc.getPath() + ".xml");

            log.info("Document Metadata File: {}", jsFile.getPath());

            if (jsFile.exists() && jsFile.canRead()) {
                FileReader fr = new FileReader(jsFile);
                DocumentMetadata dmd = null;

                //for json file metadata
                if (isJsonFile)
                    dmd = gson.fromJson(fr, DocumentMetadata.class);
                else {
                    JAXBContext jaxbContext = JAXBContext.newInstance(DocumentMetadata.class);

                    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
                    dmd = (DocumentMetadata) jaxbUnmarshaller.unmarshal(fr);
                }

                doc.setPath(fldPath + "/" + fileName);
                dmd.setPath(doc.getPath());
                IOUtils.closeQuietly(fr);
                log.info("Document Metadata: {}", dmd);

                if (history && containsHistoryFiles(fs, fileName)) {
                    File[] vhFiles = fs.listFiles(new RepositoryImporter.VersionFilenameFilter(fileName));
                    List<File> listFiles = Arrays.asList(vhFiles);
                    Collections.sort(listFiles, FilenameVersionComparator.getInstance());
                    boolean first = true;

                    for (File vhf : vhFiles) {
                        String vhfName = vhf.getName();
                        int idx = vhfName.lastIndexOf('#', vhfName.length() - 2);
                        String verName = vhfName.substring(idx + 2, vhfName.length() - 1);
                        FileInputStream fis = new FileInputStream(vhf);
                        File jsVerFile = new File(vhf.getPath() + Config.EXPORT_METADATA_EXT);
                        log.info("Document Version Metadata File: {}", jsVerFile.getPath());

                        if (jsVerFile.exists() && jsVerFile.canRead()) {
                            FileReader verFr = new FileReader(jsVerFile);
                            VersionMetadata vmd = gson.fromJson(verFr, VersionMetadata.class);
                            IOUtils.closeQuietly(verFr);

                            if (first) {
                                dmd.setVersion(vmd);
                                size = fis.available();
                                ma.importWithMetadata(dmd, fis);
                                first = false;
                            } else {
                                log.info("Document Version Metadata: {}", vmd);
                                size = fis.available();
                                ma.importWithMetadata(doc.getPath(), vmd, fis);
                            }
                        } else {
                            log.warn("Unable to read metadata file: {}", jsVerFile.getPath());
                        }

                        IOUtils.closeQuietly(fis);
                        FileLogger.info(BASE_NAME, "Created document ''{0}'' version ''{1}''", doc.getPath(),
                                verName);
                        log.info("Created document '{}' version '{}'", doc.getPath(), verName);
                    }
                } else {
                    // Apply metadata
                    ma.importWithMetadata(dmd, fisContent);
                    FileLogger.info(BASE_NAME, "Created document ''{0}''", doc.getPath());
                    log.info("Created document '{}'", doc.getPath());
                }
            } else {
                log.warn("Unable to read metadata file: {}", jsFile.getPath());
                api = true;
            }
        } else {
            api = true;
        }

        if (api) {
            doc.setPath(fldPath + "/" + fileName);

            // Version history
            if (history) {
                File[] vhFiles = fs.listFiles(new RepositoryImporter.VersionFilenameFilter(fileName));
                List<File> listFiles = Arrays.asList(vhFiles);
                Collections.sort(listFiles, FilenameVersionComparator.getInstance());
                boolean first = true;

                for (File vhf : vhFiles) {
                    String vhfName = vhf.getName();
                    int idx = vhfName.lastIndexOf('#', vhfName.length() - 2);
                    String verName = vhfName.substring(idx + 2, vhfName.length() - 1);
                    FileInputStream fis = new FileInputStream(vhf);

                    if (first) {
                        dm.create(token, doc, fis);
                        first = false;
                    } else {
                        dm.checkout(token, doc.getPath());
                        dm.checkin(token, doc.getPath(), fis, "Imported from administration");
                    }

                    IOUtils.closeQuietly(fis);
                    FileLogger.info(BASE_NAME, "Created document ''{0}'' version ''{1}''", doc.getPath(),
                            verName);
                    log.info("Created document '{}' version '{}'", doc.getPath(), verName);
                }
            } else {
                dm.create(token, doc, fisContent);
                FileLogger.info(BASE_NAME, "Created document ''{0}''", doc.getPath());
                log.info("Created document ''{}''", doc.getPath());
            }
        }

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), null));
            out.flush();
        }

        // Stats
        stats.setSize(stats.getSize() + size);
        stats.setDocuments(stats.getDocuments() + 1);
    } catch (UnsupportedMimeTypeException e) {
        log.warn("UnsupportedMimeTypeException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "UnsupportedMimeType"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "UnsupportedMimeTypeException ''{0}''", doc.getPath());
    } catch (FileSizeExceededException e) {
        log.warn("FileSizeExceededException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "FileSizeExceeded"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "FileSizeExceededException ''{0}''", doc.getPath());
    } catch (UserQuotaExceededException e) {
        log.warn("UserQuotaExceededException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "UserQuotaExceeded"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "UserQuotaExceededException ''{0}''", doc.getPath());
    } catch (VirusDetectedException e) {
        log.warn("VirusWarningException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "VirusWarningException"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "VirusWarningException ''{0}''", doc.getPath());
    } catch (ItemExistsException e) {
        log.warn("ItemExistsException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "ItemExists"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "ItemExistsException ''{0}''", doc.getPath());
    } catch (LockException e) {
        log.warn("LockException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "Lock"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "LockException ''{0}''", doc.getPath());
    } catch (VersionException e) {
        log.warn("VersionException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "Version"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "VersionException ''{0}''", doc.getPath());
    } catch (JsonParseException e) {
        log.warn("JsonParseException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "Json"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "JsonParseException ''{0}''", doc.getPath());
    } catch (JAXBException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(fisContent);
    }

    return stats;
}

From source file:com.tremolosecurity.openunison.util.OpenUnisonUtils.java

private static TremoloType loadTremoloType(String unisonXMLFile) throws Exception {
    JAXBContext jc = JAXBContext.newInstance("com.tremolosecurity.config.xml");
    Unmarshaller unmarshaller = jc.createUnmarshaller();
    FileInputStream in = new FileInputStream(unisonXMLFile);

    Object obj = unmarshaller.unmarshal(in);

    JAXBElement<TremoloType> cfg = (JAXBElement<TremoloType>) obj;
    return cfg.getValue();
}

From source file:com.tremolosecurity.openunison.util.OpenUnisonUtils.java

private static TremoloType loadTremoloType(String unisonXMLFile, CommandLine cmd, Options options)
        throws Exception {
    JAXBContext jc = JAXBContext.newInstance("com.tremolosecurity.config.xml");
    Unmarshaller unmarshaller = jc.createUnmarshaller();
    InputStream in = null;//from  ww  w  . jav  a 2  s.c o m

    String envFile = cmd.getOptionValue("envFile");
    if (envFile != null) {
        BufferedReader fin = new BufferedReader(new InputStreamReader(new FileInputStream(envFile)));
        String line = null;
        while ((line = fin.readLine()) != null) {
            String name = line.substring(0, line.indexOf('='));
            String val = line.substring(line.indexOf('=') + 1);
            System.setProperty(name, val);
        }

        String withProps = OpenUnisonConfigLoader.generateOpenUnisonConfig(unisonXMLFile);
        in = new ByteArrayInputStream(withProps.getBytes("UTF-8"));

    } else {
        in = new FileInputStream(unisonXMLFile);
    }

    Object obj = unmarshaller.unmarshal(in);

    JAXBElement<TremoloType> cfg = (JAXBElement<TremoloType>) obj;
    return cfg.getValue();
}

From source file:com.mycompany.dao.report.XMLReport.java

@Override
public void generate() throws JAXBException {
    JAXBContext jaxbContext = JAXBContext.newInstance(Books.class);
    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
    Books books = (Books) jaxbUnmarshaller.unmarshal(new File(fileName));

    for (Iterator<Book> iterator = books.getBooks().iterator(); iterator.hasNext();) {
        Book book = iterator.next();
        if (book.getQuantity() != 0) {
            // Remove the current element from the iterator and the list.
            iterator.remove();/*w  w w  .  j a va 2  s .  c  o  m*/
        }
    }

    Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
    jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    jaxbMarshaller.marshal(books, new File(fileName2));

}

From source file:jails.http.converter.xml.AbstractJaxb2HttpMessageConverter.java

/**
 * Creates a new {@link Unmarshaller} for the given class.
 *
 * @param clazz the class to create the unmarshaller for
 * @return the {@code Unmarshaller}/*  w  ww  . ja va 2  s .  c om*/
 * @throws HttpMessageConversionException in case of JAXB errors
 */
protected final Unmarshaller createUnmarshaller(Class clazz) throws JAXBException {
    try {
        JAXBContext jaxbContext = getJaxbContext(clazz);
        return jaxbContext.createUnmarshaller();
    } catch (JAXBException ex) {
        throw new HttpMessageConversionException(
                "Could not create Unmarshaller for class [" + clazz + "]: " + ex.getMessage(), ex);
    }
}

From source file:com.kurtraschke.wsf.gtfsrealtime.services.WSFVesselLocationService.java

public WSFVesselLocationService() throws JAXBException {
    JAXBContext jc = JAXBContext.newInstance(ArrayOfVesselLocationResponse.class);
    _um = jc.createUnmarshaller();
}

From source file:org.hisp.dhis.dxf2.importsummary.ImportSummaryTest.java

@Test
public void unMarshallImportSummary() throws Exception {
    ClassPathResource resource = new ClassPathResource("importSummary.xml");
    JAXBContext jaxbContext = JAXBContext.newInstance(ImportSummary.class);

    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
    ImportSummary importSummary = (ImportSummary) jaxbUnmarshaller.unmarshal(resource.getInputStream());
    assertEquals(3, importSummary.getDataValueCount().getImported());
    assertEquals(0, importSummary.getDataValueCount().getUpdated());
    assertEquals(1, importSummary.getDataValueCount().getIgnored());
}

From source file:com.wso2telco.core.mnc.resolver.ConfigLoader.java

/**
 * Inits the mcc config.//  w w  w  . j  a va2 s  . com
 *
 * @return the MCC configuration
 * @throws JAXBException the JAXB exception
 */
private MCCConfiguration initMccConfig() throws JAXBException {
    String configPath = CarbonUtils.getCarbonConfigDirPath() + File.separator + "MobileCountryConfig.xml";
    File file = new File(configPath);
    JAXBContext ctx = JAXBContext.newInstance(MCCConfiguration.class);
    Unmarshaller um = ctx.createUnmarshaller();
    return (MCCConfiguration) um.unmarshal(file);
}

From source file:org.jasig.portlet.campuslife.dao.MockDataService.java

@Override
public void afterPropertiesSet() throws Exception {
    try {//from w  w w.  j av a  2 s.  co m
        JAXBContext jaxbContext = JAXBContext.newInstance(getPackageName());
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        this.data = (T) unmarshaller.unmarshal(feed.getInputStream());
    } catch (IOException e) {
        log.error("Failed to read mock data", e);
    } catch (JAXBException e) {
        log.error("Failed to unmarshall mock data", e);
    }
}

From source file:cz.muni.fi.editor.typemanager.TypeServiceImpl.java

public TypeServiceImpl() throws JAXBException {
    JAXBContext context = JAXBContext.newInstance(Type.class);
    this.unmarshaller = context.createUnmarshaller();
    this.marshaller = context.createMarshaller();
    this.marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
}