Example usage for javax.xml.bind JAXBException JAXBException

List of usage examples for javax.xml.bind JAXBException JAXBException

Introduction

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

Prototype

public JAXBException(Throwable exception) 

Source Link

Document

Construct a JAXBException with a linkedException.

Usage

From source file:org.dasein.cloud.azure.tests.compute.vm.AzureVmTest.java

@Test(expected = InternalException.class)
public void testRebootShouldThrowExceptionIfDeserializationFails() throws CloudException, InternalException {
    new MockUp<CloseableHttpClient>() {
        @Mock(invocations = 1)//w  ww  . j  ava  2 s  .c o  m
        public CloseableHttpResponse execute(HttpUriRequest request) throws JAXBException {
            throw new JAXBException("Deserialization failed");
        }
    };

    final AzureVM azureVM = new AzureVM(azureMock);
    new Expectations(AzureVM.class) {
        {
            azureVM.getVirtualMachine(VM_ID);
            result = getTestVirtualMachine();
        }
    };
    azureVM.reboot(VM_ID);
}

From source file:org.dasein.cloud.azure.tests.compute.vm.AzureVmTest.java

@Test(expected = InternalException.class)
public void testStopShouldThrowExceptionIfDeserializationFails() throws CloudException, InternalException {
    new MockUp<CloseableHttpClient>() {
        @Mock(invocations = 1)/*from www .  ja  v  a 2  s .c  o  m*/
        public CloseableHttpResponse execute(HttpUriRequest request) throws JAXBException {
            throw new JAXBException("Deserialization failed");
        }
    };

    final AzureVM azureVM = new AzureVM(azureMock);
    new Expectations(AzureVM.class) {
        {
            azureVM.getVirtualMachine(VM_ID);
            result = getTestVirtualMachine();
        }
    };
    azureVM.stop(VM_ID, true);
}

From source file:org.dasein.cloud.azure.tests.compute.vm.AzureVmTest.java

@Test(expected = InternalException.class)
public void testSuspendShouldThrowExceptionIfDeserializationFails() throws CloudException, InternalException {
    new MockUp<CloseableHttpClient>() {
        @Mock(invocations = 1)/*from w ww  .j a va 2s.  c om*/
        public CloseableHttpResponse execute(HttpUriRequest request) throws JAXBException {
            throw new JAXBException("Deserialization failed");
        }
    };

    final AzureVM azureVM = new AzureVM(azureMock);
    new Expectations(AzureVM.class) {
        {
            azureVM.getVirtualMachine(VM_ID);
            result = getTestVirtualMachine();
        }
    };
    azureVM.suspend(VM_ID);
}

From source file:org.docx4j.openpackaging.parts.JaxbXmlPart.java

/**
 * Marshal the content tree rooted at <tt>jaxbElement</tt> into a DOM tree.
 * //w  w w .j  a va2s  . c  o m
 * @param node
 *      DOM nodes will be added as children of this node.
 *      This parameter must be a Node that accepts children
 *      ({@link org.w3c.dom.Document},
 *      {@link  org.w3c.dom.DocumentFragment}, or
 *      {@link  org.w3c.dom.Element})
 * 
 * @throws JAXBException
 *      If any unexpected problem occurs during the marshalling.
 */
public void marshal(org.w3c.dom.Node node, Object namespacePrefixMapper) throws JAXBException {

    try {
        Marshaller marshaller = jc.createMarshaller();
        NamespacePrefixMapperUtils.setProperty(marshaller, namespacePrefixMapper);
        getContents();
        setMceIgnorable();
        marshaller.marshal(jaxbElement, node);

    } catch (Docx4JException e) {
        log.error(e.getMessage(), e);
        throw new JAXBException(e); // avoid change to method signature
    } catch (JAXBException e) {
        log.error(e.getMessage(), e);
        throw e;
    }
}

From source file:org.docx4j.openpackaging.parts.JaxbXmlPart.java

/**
* Marshal the content tree rooted at <tt>jaxbElement</tt> into an output
* stream/*from   w w w.  ja  v  a2 s . c  om*/
* 
* @param os
*            XML will be added to this stream.
* @param namespacePrefixMapper
*            namespacePrefixMapper
* 
* @throws JAXBException
*             If any unexpected problem occurs during the marshalling.
*/
public void marshal(java.io.OutputStream os, Object namespacePrefixMapper) throws JAXBException {

    try {
        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty("jaxb.formatted.output", true);

        NamespacePrefixMapperUtils.setProperty(marshaller, namespacePrefixMapper);

        log.debug("marshalling " + this.getClass().getName());
        getContents();
        //         if (jaxbElement==null) {
        //            log.error("No JAXBElement has been created for this part, yet!");
        //            throw new JAXBException("No JAXBElement has been created for this part, yet!");
        //         }
        setMceIgnorable();
        marshaller.marshal(jaxbElement, os);

    } catch (Docx4JException e) {
        log.error(e.getMessage(), e);
        throw new JAXBException(e); // avoid change to method signature
    } catch (JAXBException e) {
        log.error(e.getMessage(), e);
        throw e;
    }
}

From source file:org.docx4j.XmlUtils.java

public static Object unmarshal(InputStream is, JAXBContext jc) throws JAXBException {

    // Guard against XXE
    XMLInputFactory xif = XMLInputFactory.newInstance();
    xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
    xif.setProperty(XMLInputFactory.SUPPORT_DTD, false); // a DTD is merely ignored, its presence doesn't cause an exception
    XMLStreamReader xsr = null;/*  w  w  w. j  av  a 2 s  . c o  m*/
    try {
        xsr = xif.createXMLStreamReader(is);
    } catch (XMLStreamException e) {
        throw new JAXBException(e);
    }

    Object o = null;
    Unmarshaller u = jc.createUnmarshaller();

    JaxbValidationEventHandler eventHandler = new JaxbValidationEventHandler();
    //      if (is.markSupported()) {
    //         // Only fail hard if we know we can restart
    //         eventHandler.setContinue(false);
    //      }
    u.setEventHandler(eventHandler);
    try {
        o = u.unmarshal(xsr);
        return o;
    } catch (UnmarshalException ue) {

        if (ue.getLinkedException() != null && ue.getLinkedException().getMessage().contains("entity")) {

            /*
               Caused by: javax.xml.stream.XMLStreamException: ParseError at [row,col]:[10,19]
               Message: The entity "xxe" was referenced, but not declared.
                  at com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl.next(Unknown Source)
                  at com.sun.xml.internal.bind.v2.runtime.unmarshaller.StAXStreamConnector.bridge(Unknown Source)
                */
            log.error(ue.getMessage(), ue);
            throw ue;
        }

        if (is.markSupported()) {
            // When reading from zip, we use a ByteArrayInputStream,
            // which does support this.

            log.info("encountered unexpected content; pre-processing");
            eventHandler.setContinue(true);

            try {
                Templates mcPreprocessorXslt = JaxbValidationEventHandler.getMcPreprocessor();
                is.reset();
                JAXBResult result = XmlUtils.prepareJAXBResult(jc);
                XmlUtils.transform(new StreamSource(is), mcPreprocessorXslt, null, result);
                return //XmlUtils.unwrap(
                result.getResult();
            } catch (Exception e) {
                throw new JAXBException("Preprocessing exception", e);
            }

        } else {
            log.error(ue.getMessage(), ue);
            log.error(".. and mark not supported");
            throw ue;
        }
    }

}

From source file:org.kalypso.model.km.internal.binding.KMBindingUtils.java

public static KalininMiljukovGroupType load(final File file) throws JAXBException {
    final Unmarshaller unmarshaller = JC.createUnmarshaller();
    final Object object = unmarshaller.unmarshal(file);
    if (object instanceof JAXBElement) {
        final JAXBElement<?> object2 = (JAXBElement<?>) object;
        return (KalininMiljukovGroupType) object2.getValue();
    }/*from w  ww. j a  v a  2 s .c  o m*/

    throw new JAXBException("Unexpected root element: " + object); //$NON-NLS-1$
}

From source file:org.lib4j.xml.jaxb.XJCompiler.java

public static void compile(final Command command) throws JAXBException, MalformedURLException {
    if (command.getSchemas() == null || command.getSchemas().size() == 0)
        return;/*from w w w. j  a v  a2s.  c o  m*/

    final List<String> args = new ArrayList<>();
    args.add("java");
    if (command.classpath.size() > 0) {
        args.add("-cp");
        final StringBuilder cp = new StringBuilder();
        for (final File classpathFile : command.classpath)
            cp.append(File.pathSeparator).append(classpathFile.getAbsolutePath());

        args.add(cp.substring(1));
    }

    args.add(XJCFacade.class.getName());
    args.add("-Xannotate");
    if (command.isAddGeneratedAnnotation())
        args.add("-mark-generated");

    if (command.getCatalog() != null) {
        args.add(1, "-Dxml.catalog.ignoreMissing");
        args.add("-catalog");
        args.add(command.getCatalog().toURI().toURL().toExternalForm());
    }

    if (command.isEnableIntrospection())
        args.add("-enableIntrospection");

    if (command.isExtension())
        args.add("-extension");

    if (command.isLaxSchemaValidation())
        args.add("-nv");

    if (command.isNoGeneratedHeaderComments())
        args.add("-no-header");

    if (command.isNoPackageLevelAnnotations())
        args.add("-npa");

    if (command.isQuiet())
        args.add("-quiet");

    if (command.getTargetVersion() != null) {
        args.add("-target");
        args.add(command.getTargetVersion().version);
    }

    if (command.isVerbose())
        args.add("-verbose");

    if (command.getSourceType() != null)
        args.add("-" + command.getSourceType().type);

    if (command.getEncoding() != null) {
        args.add("-encoding");
        args.add(command.getEncoding());
    }

    if (command.getPackageName() != null) {
        args.add("-p");
        args.add(command.getPackageName());
    }

    try {
        if (command.getDestDir() != null) {
            args.add("-d");
            args.add(command.getDestDir().getAbsolutePath());

            if (!command.getDestDir().exists() && !command.getDestDir().mkdirs()) {
                throw new JAXBException(
                        "Unable to create output directory " + command.getDestDir().getAbsolutePath());
            }
            // FIXME: This does not work because the files that are written are only known by xjc, so I cannot
            // FIXME: stop this generator from overwriting them if owerwrite=false
            //        else if (command.isOverwrite()) {
            //          for (final File file : command.getDestDir().listFiles())
            //            Files.walk(file.toPath()).map(Path::toFile).filter(a -> a.getName().endsWith(".java")).sorted((o1, o2) -> o2.compareTo(o1)).forEach(File::delete);
            //        }
        }

        for (final URL schema : command.getSchemas()) {
            if (URLs.isFile(schema)) {
                final File file = new File(schema.getFile());
                if (!file.exists())
                    throw new FileNotFoundException(file.getAbsolutePath());

                args.add(file.getAbsolutePath());
            } else {
                try (final InputStream in = schema.openStream()) {
                    final File file = File.createTempFile(URLs.getName(schema), "");
                    args.add(file.getAbsolutePath());
                    file.deleteOnExit();
                    Files.write(file.toPath(), Streams.readBytes(in));
                }
            }

            args.add(schema.getFile());
        }

        if (command.getXJBs() != null) {
            for (final URL xjb : command.getXJBs()) {
                args.add("-b");
                if (URLs.isFile(xjb)) {
                    args.add(xjb.getFile());
                } else {
                    try (final InputStream in = xjb.openStream()) {
                        final File file = File.createTempFile(URLs.getName(xjb), "");
                        args.add(file.getAbsolutePath());
                        file.deleteOnExit();
                        Files.write(file.toPath(), Streams.readBytes(in));
                    }
                }
            }
        }

        if (command.isGenerateEpisode()) {
            final File metaInfDir = new File(command.getDestDir(),
                    "META-INF" + File.separator + "sun-jaxb.episode");
            if (!metaInfDir.getParentFile().mkdirs())
                throw new JAXBException("Unable to create output directory META-INF"
                        + metaInfDir.getParentFile().getAbsolutePath());

            args.add("-episode");
            args.add(metaInfDir.getAbsolutePath());
        }

        final Process process = new ProcessBuilder(args).inheritIO().redirectErrorStream(true).start();
        try (final Scanner scanner = new Scanner(process.getInputStream())) {
            while (scanner.hasNextLine())
                log(scanner.nextLine().trim());

            final StringBuilder lastLine = new StringBuilder();
            while (scanner.hasNextByte())
                lastLine.append(scanner.nextByte());

            if (lastLine.length() > 0)
                log(lastLine.toString());
        }

        final int exitCode = process.waitFor();
        if (exitCode != 0)
            throw new JAXBException(
                    "xjc finished with code: " + exitCode + "\n" + Collections.toString(args, " "));
    } catch (final IOException | InterruptedException e) {
        throw new JAXBException(e.getMessage(), e);
    }
}

From source file:org.mili.ant.PropertiesReplacerCLITest.java

/**
 * Test execute./* w w  w . j  ava 2 s . c om*/
 *
 * @throws Exception the exception
 */
@Test
public void testExecute() throws Exception {
    File f0 = new File("aaa");
    File f1 = new File("bbb");
    this.pr.replace(f0, f1);
    EasyMock.expectLastCall().times(1);
    EasyMock.replay(this.pr);
    try {
        PropertiesReplacerCLI o = new PropertiesReplacerCLI();
        o.execute(this.pr, new String[] { "-propfile", f0.getName(), "-propdesc", f1.getName() });
    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail("exception occured!");
    }
    EasyMock.reset(this.pr);
    this.pr.replace(f0, f1);
    EasyMock.expectLastCall().andThrow(new JAXBException("")).times(1);
    EasyMock.replay(this.pr);
    // jaxb exception
    try {
        PropertiesReplacerCLI o = new PropertiesReplacerCLI();
        o.execute(this.pr, new String[] { "-propfile", "aaa", "-propdesc", "bbb" });
        Assert.fail("exception expected!");
    } catch (JAXBException e) {
    }
    // parse exception
    try {
        PropertiesReplacerCLI o = new PropertiesReplacerCLI();
        o.execute(this.pr, new String[] { "-popel" });
        Assert.fail("exception expected!");
    } catch (ParseException e) {
    }
    // help
    try {
        PropertiesReplacerCLI o = new PropertiesReplacerCLI();
        o.execute(this.pr, new String[] { "-help" });
    } catch (Exception e) {
        Assert.fail("exception occured!");
    }
    // version
    try {
        PropertiesReplacerCLI o = new PropertiesReplacerCLI();
        o.execute(this.pr, new String[] { "-version" });
    } catch (Exception e) {
        Assert.fail("exception occured!");
    }
    // missing propfile
    try {
        PropertiesReplacerCLI o = new PropertiesReplacerCLI();
        o.execute(this.pr, new String[] { "-propdesc", "aaa" });
        Assert.fail("exception expected!");
    } catch (IllegalArgumentException e) {
    }
    // missing propdesc
    try {
        PropertiesReplacerCLI o = new PropertiesReplacerCLI();
        o.execute(this.pr, new String[] { "-propfile", "aaa" });
        Assert.fail("exception expected!");
    } catch (IllegalArgumentException e) {
    }

    EasyMock.verify(this.pr);
}

From source file:org.openhealthtools.openexchange.audit.IheAuditTrail.java

/** 
 * DICOM Supp95 message A1.3.15 (p. 36): User Authentication <p />
 * /* w w w .  ja  v a 2  s .  c o  m*/
 * This message records users logging into the system, as opposed to 
 * security alerts which are for node's authenticating themselves.  The single
 * event id is a login or logout, and whether it succeeded.  The user attempting
 * to authenticate is a required active participant.  The enterprise wide
 * authentication node (e.g. kerberos) is optional, but the actual authentication
 * node is mandatory though included by format and log.
 * 
  * @param user User authenticating.  Must not be null.
 * @param isLogin True if user is logging in false if logging out.
 * @param success Whether the loging was successful.
 */
protected void userAuthentication(ActiveParticipant user, AuditTypeCodes type, SuccessCode success)
        throws JAXBException {
    for (IMessageTransmitter messenger : messengers) {
        AuditObjectFactory factory = new AuditObjectFactory(messenger);
        factory.setEventIdType(
                new EventId(AuditEventIds.UserAuthentication, type, EventActionCode.Execute, success));
        if (user == null)
            user = getUser();
        if (user == null)
            throw new JAXBException("User not allowed to be null for authentication logging.");
        user.setRequestor(true);
        factory.addActiveParticipant(user);
        formatAndLog(messenger, factory, false, ActiveParticipantIds.Application, user.getAuditSourceType());
    }
}