Example usage for javax.xml.bind JAXBException toString

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

Introduction

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

Prototype

public String toString() 

Source Link

Document

Returns a short description of this JAXBException.

Usage

From source file:net.itransformers.idiscover.discoveryhelpers.xml.XmlDiscoveryHelper.java

public DiscoveredDeviceData parseDeviceRawData(
        net.itransformers.idiscover.api.models.node_data.RawDeviceData rawData, String[] discoveryTypes,
        Map<String, String> params) {

    byte[] data = rawData.getData();
    ByteArrayOutputStream deviceXmlOutputStream = new ByteArrayOutputStream();
    parseDeviceRawData(data, deviceXmlOutputStream, deviceType.getXslt(), params);

    ByteArrayInputStream is = new ByteArrayInputStream(deviceXmlOutputStream.toByteArray());
    logger.debug(Arrays.toString(deviceXmlOutputStream.toByteArray()));
    try {/*from w  w w.j a  v  a  2  s  . c om*/
        return JaxbMarshalar.unmarshal(DiscoveredDeviceData.class, is);
    } catch (JAXBException e) {
        System.err.println("Error unmarshal the xml:" + e.toString());
        System.err.println(new String(deviceXmlOutputStream.toByteArray()));
        return null;
    }
}

From source file:broadwick.Broadwick.java

/**
 * Read the configuration file from the configuration file.
 * <p>//from   w w  w.  j a  v a 2s .co m
 * @param logFacade  the LoggingFacade object used to log any messages.
 * @param configFile the name of the configuration file.
 */
private void readConfigFile(final LoggingFacade logFacade, final String configFile) {
    if (!configFile.isEmpty()) {
        final File cfg = new File(configFile);
        if (!cfg.exists()) {
            throw new BroadwickException("Configuration file [" + configFile + "] does not exist.");
        }
        try {
            // read the configuration file
            final JAXBContext jaxbContext = JAXBContext.newInstance(Constants.GENERATED_CONFIG_CLASSES_DIR);
            final Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            project = (Project) unmarshaller.unmarshal(cfg);

            // save the config file as a string for later use
            final StringWriter writer = new StringWriter();
            jaxbContext.createMarshaller().marshal(project, writer);
            configXml = writer.toString();

            // Validate the configuration file
            final ConfigValidator validator = new ConfigValidator(project);
            final ConfigValidationErrors validationErrors = validator.validate();

            // now set up the logger as defined in the config file, we want to do this
            // BEFORE writing the results of validation
            final Logs.File file = project.getLogs().getFile();
            if (file != null) {
                logFacade.addFileLogger(file.getName(), file.getLevel(), file.getPattern(), file.isOverwrite());
            }
            final Logs.Console console = project.getLogs().getConsole();
            if (console != null) {
                logFacade.addConsoleLogger(console.getLevel(), console.getPattern());
            }

            // Log any validation errors.
            if (validationErrors.getNumErrors() > 0) {
                log.error("Invalid configuration file.\n{}Correct any errors before continuing.",
                        validationErrors.getValidationErrors());
                project = validator.getValidatedProject();
            }

        } catch (JAXBException ex) {
            log.error("Could not read configuration file. {}", ex.toString());
            log.trace(com.google.common.base.Throwables.getStackTraceAsString(ex));
        }
    } else {
        throw new BroadwickException("No configuration file specified");
    }
}

From source file:cz.lbenda.dataman.db.DbConfig.java

/** Save session conf into File
 * @param writer writer to which is configuration saved */
public void save(Writer writer) throws IOException {
    cz.lbenda.dataman.schema.dataman.ObjectFactory of = new cz.lbenda.dataman.schema.dataman.ObjectFactory();
    SessionType st = storeToSessionType(null, null);
    try {//from   w w  w . j a v a 2s .  c om
        JAXBContext jc = JAXBContext.newInstance(cz.lbenda.dataman.schema.dataman.ObjectFactory.class);
        Marshaller m = jc.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        m.marshal(of.createSession(st), writer);
    } catch (JAXBException e) {
        LOG.error("Problem with write configuration: " + e.toString(), e);
        throw new RuntimeException("Problem with write configuration: " + e.toString(), e);
    }
}

From source file:cz.lbenda.dataman.db.DbConfig.java

/** Load configuration from given resource from input stream
 * @param reader reader from which is read configuration
 * @param readId flag which inform if newId will be reader from reader or is ignored */
public void load(@Nonnull Reader reader, boolean readId) {
    try {/* ww  w .  j  a  v a 2 s .c  o  m*/
        JAXBContext jc = JAXBContext.newInstance(cz.lbenda.dataman.schema.dataman.ObjectFactory.class);
        Unmarshaller u = jc.createUnmarshaller();
        //noinspection unchecked
        JAXBElement<SessionType> element = (JAXBElement<SessionType>) u.unmarshal(reader);
        //noinspection ConstantConditions
        if (element.getValue() instanceof SessionType) {
            fromSessionType(element.getValue(), readId);
        } else {
            LOG.error("The file doesn't contains single session config");
            throw new RuntimeException("The file doesn't contains single session config");
        }
    } catch (JAXBException e) {
        LOG.error("Problem with read configuration from XML: " + e.toString(), e);
        throw new RuntimeException("Problem with read configuration from XML: " + e.toString(), e);
    }
}

From source file:it.cnr.icar.eric.server.interfaces.rest.QueryManagerURLHandler.java

/** 
 * Process the QueryManager POST request and sends the response back to the client
 *
 *///from  w  w w  .j a  v a2 s . c om
void processPostRequest() throws IOException, RegistryException, InvalidRequestException,
        UnimplementedException, ObjectNotFoundException {
    try {
        PrintWriter out = response.getWriter();
        String xmlAdhocQueryRequest = request.getParameter("xmldoc");

        String message = xmlAdhocQueryRequest;
        //TODO: consider using unmarshall directly from BindingUtility
        StreamSource messageSS = new StreamSource(new StringReader(message));
        Unmarshaller unmarshaller = bu.getJAXBContext().createUnmarshaller();
        AdhocQueryRequest req = (AdhocQueryRequest) unmarshaller.unmarshal(messageSS);

        ServerRequestContext context = new ServerRequestContext("QueryManagerURLHandler.processPostRequest",
                req);
        context.setUser(currentUser);
        RegistryResponseType regResponse = QueryManagerFactory.getInstance().getQueryManager()
                .submitAdhocQuery(context);
        //            Marshaller marshaller = bu.rsFac.createMarshaller();
        Marshaller marshaller = bu.getJAXBContext().createMarshaller();
        marshaller.marshal(regResponse, out);
        out.close();

    } catch (JAXBException ex) {
        log.error(ex.toString(), ex);
        throw new RegistryException(ex);
    }
}

From source file:org.energyos.espi.thirdparty.web.AuthorizationController.java

@RequestMapping(value = Routes.THIRD_PARTY_OAUTH_CODE_CALLBACK, method = RequestMethod.GET)
public String authorization(String code, String state, ModelMap model, Principal principal,
        @RequestParam(value = "error", required = false) String error,
        @RequestParam(value = "error_description", required = false) String error_description,
        @RequestParam(value = "error_uri", required = false) String error_uri) {

    try {// w  w w. jav a  2s  . c o  m

        // Is /oauth/authorization response valid (i.e. is the "state"
        // element correct)?
        Authorization authorization = authorizationService.findByState(state);

        // Process valid /oauth/authorization response
        ApplicationInformation applicationInformation = authorization.getApplicationInformation();

        // Verify /oauth/authorization Endpoint process completed
        // successfully
        if (code != null) {
            try {

                // Update Authorization record with returned authorization
                // code for audit purposes
                authorization.setCode(code);
                authorization.setGrantType("authorization_code");
                authorization.setUpdated(new GregorianCalendar());
                authorizationService.merge(authorization);

                // Format /oauth/token Endpoint request
                String url = String.format("%s?redirect_uri=%s&code=%s&grant_type=authorization_code",
                        applicationInformation.getAuthorizationServerTokenEndpoint(),
                        applicationInformation.getRedirectUri(), code);

                // Build /oauth/token Endpoint request
                ClientRestTemplate restTemplate = templateFactory.newClientRestTemplate(
                        applicationInformation.getClientId(), applicationInformation.getClientSecret());

                // Issue /oauth/token Endpoint request
                AccessToken token = restTemplate.getForObject(url, AccessToken.class);

                // Process /oauth/token Endpoint response

                if (token.getAccessToken() != null) {
                    authorization.setAccessToken(token.getAccessToken());
                    authorization.setTokenType(token.getTokenType());
                    authorization.setExpiresIn(token.getExpiresIn());
                    authorization.setRefreshToken(token.getRefreshToken());
                    authorization.setScope(token.getScope());
                    authorization.setAuthorizationURI(token.getAuthorizationURI());
                    authorization.setResourceURI(token.getResourceURI());
                    authorization.setUpdated(new GregorianCalendar());
                    authorization.setStatus("1"); // Set authorization
                    // record status as
                    // "Active"
                    authorization.setState(null); // Clear State as a
                    // security measure

                    // Update authorization record with /oauth/token
                    // response data
                    authorizationService.merge(authorization);

                    // now do the initial import of the Authorized Resource,
                    // if it is
                    // not ready, then we will wait till we receive a Notify
                    // or the UX call for it.
                    // TODO: create a Subscription to work with if needed

                    RetailCustomer currentCustomer = currentCustomer(principal);

                    try {
                        usagePointRESTRepository.findAllByRetailCustomerId(currentCustomer.getId());

                    } catch (JAXBException e) {
                        // nothing there, so log the fact and move on. It
                        // will get imported later.
                        System.out.printf("\nThirdParty Import Exception: %s\n", e.toString());
                        e.printStackTrace();
                    }
                } else {

                    System.out.printf("\n/oauth/token Request did not return an access token\n");
                }

            } catch (HttpClientErrorException x) {

                // TODO: Extract error, error_description and error_uri from
                // JSON response. Currently recording null for all three
                // fields.

                // Update authorization record
                System.out.printf("\nHTTPClientException: %s\n", x.toString());

                authorization.setError(error);
                authorization.setErrorDescription(error_description);
                authorization.setErrorUri(error_uri);
                authorization.setUpdated(new GregorianCalendar());
                authorization.setStatus("2"); // Set authorization record
                // status as "Denied"
                authorization.setState(null); // Clear State as a security
                // measure
                authorizationService.merge(authorization);

                // TODO: Should the "message" differ based on the exception?
                throw new UserDeniedAuthorizationException("Unable to retrieve OAuth token", x);
            }
        } else {

            System.out.printf("\nOAuth2 authorization_request returned an error:\n");
            System.out.printf("Error:             " + error + "\n");
            System.out.printf("Error_description: " + error_description + "\n");
            System.out.printf("Error_uri:         " + error_uri + "\n");

            // Update authorization record with error response
            authorization.setError(error);
            authorization.setErrorDescription(error_description);
            authorization.setErrorUri(error_uri);
            authorization.setUpdated(new GregorianCalendar());
            authorization.setStatus("2"); // Set authorization record status
            // as "Denied"
            authorization.setState(null); // Clear State as a security
            // measure
            authorizationService.merge(authorization);

            throw new UserDeniedAuthorizationException("Error: " + error_description);

        }

    } catch (NoResultException | EmptyResultDataAccessException e) {

        // We received an invalid /oauth/authorization response
        // TODO: Log receipt of an invalid /oauth/authorization response
        return "/home";

    }

    return "redirect:/RetailCustomer/" + currentCustomer(principal).getId() + "/AuthorizationList";
}

From source file:org.restsql.core.impl.AbstractSqlResourceMetaData.java

/** Returns XML representation. */
@Override/*w  ww  . j a  v  a 2  s . c  o m*/
public String toXml() {
    // Build extended metadata for serialization if first time through
    if (!extendedMetadataIsBuilt) {
        parentTableName = getQualifiedTableName(parentTable);
        childTableName = getQualifiedTableName(childTable);
        joinTableName = getQualifiedTableName(joinTable);
        parentPlusExtTableNames = getQualifiedTableNames(parentPlusExtTables);
        childPlusExtTableNames = getQualifiedTableNames(childPlusExtTables);
        allReadColumnNames = getQualifiedColumnNames(allReadColumns);
        childReadColumnNames = getQualifiedColumnNames(childReadColumns);
        parentReadColumnNames = getQualifiedColumnNames(parentReadColumns);
        extendedMetadataIsBuilt = true;
    }

    try {
        final JAXBContext context = JAXBContext.newInstance(AbstractSqlResourceMetaData.class);
        final Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        final StringWriter writer = new StringWriter();
        marshaller.marshal(this, writer);
        return writer.toString();
    } catch (final JAXBException exception) {
        return exception.toString();
    }
}

From source file:com.intuit.tank.service.impl.v1.automation.AutomationServiceV1.java

/**
 * @{inheritDoc/*from w ww .  j a va 2  s .  c om*/
 */
@Override
public Response runAutomationJob(FormDataMultiPart formData) {
    AutomationRequest request = null;
    InputStream is = null;
    Map<String, List<FormDataBodyPart>> fields = formData.getFields();
    for (Entry<String, List<FormDataBodyPart>> entry : fields.entrySet()) {
        String formName = entry.getKey();
        LOG.info("Entry name: " + formName);
        for (FormDataBodyPart part : entry.getValue()) {
            MediaType mediaType = part.getMediaType();
            System.out.println("MediaType " + mediaType);
            if (MediaType.APPLICATION_XML_TYPE.equals(mediaType)
                    || MediaType.APPLICATION_JSON_TYPE.equals(mediaType)) {
                if ("automationRequest".equalsIgnoreCase(formName)) {
                    request = part.getEntityAs(AutomationRequest.class);
                } else {
                    is = part.getValueAs(InputStream.class);
                }
            } else if (MediaType.TEXT_PLAIN_TYPE.equals(mediaType)) {
                String s = part.getEntityAs(String.class);
                System.out.println("Plain Text Value: " + s);
                if ("xmlString".equalsIgnoreCase(formName)) {
                    try {
                        JAXBContext ctx = JAXBContext
                                .newInstance(AutomationRequest.class.getPackage().getName());
                        request = (AutomationRequest) ctx.createUnmarshaller().unmarshal(new StringReader(s));
                    } catch (JAXBException e) {
                        throw new RuntimeException(e);
                    }
                }
            } else if (MediaType.APPLICATION_OCTET_STREAM_TYPE.equals(mediaType)) {
                // get the file
                is = part.getValueAs(InputStream.class);
            }
        }
    }
    ResponseBuilder responseBuilder = Response.ok();
    if (request == null) {
        responseBuilder = Response.status(Status.BAD_REQUEST);
        responseBuilder.entity("Requests to run automation jobs must contain an AutomationRequest");
    } else {
        Script script = null;
        if (is != null) {
            try {
                ScriptProcessor scriptProcessor = new ServletInjector<ScriptProcessor>()
                        .getManagedBean(servletContext, ScriptProcessor.class);
                List<Integer> filterIds = getFilterList(request);
                script = new Script();
                script.setName(request.getScriptName());
                scriptProcessor.setScript(script);
                script.setProductName(request.getProductName());
                script.setCreator(TankConstants.TANK_USER_SYSTEM);
                List<ScriptStep> scriptSteps = scriptProcessor
                        .getScriptSteps(new BufferedReader(new InputStreamReader(is)), getFilters(filterIds));
                List<ScriptStep> newSteps = new ArrayList<ScriptStep>();
                for (ScriptStep step : scriptSteps) {
                    newSteps.add(step);
                }
                // script.setScriptSteps(newSteps);
                //
                // script.setScriptSteps(newSteps);
                script = new ScriptDao().saveOrUpdate(script);
                sendMsg(script, ModificationType.ADD);

            } catch (Exception e) {
                LOG.error("Error starting script: " + e, e);
                responseBuilder = Response.status(Status.INTERNAL_SERVER_ERROR);
                responseBuilder.entity("An External Script failed with Exception: " + e.toString());
            } finally {
                IOUtils.closeQuietly(is);
            }
        }
        // now send off to service
        Project p = getOrCreateProject(request);
        JobInstance job = addJobToQueue(p, request, script);
        LOG.info("Automation Job (" + job.getId() + ") requested with values: " + job);
        String jobId = Integer.toString(job.getId());

        JobController controller = new ServletInjector<JobController>().getManagedBean(servletContext,
                JobController.class);
        controller.startJob(jobId);
        responseBuilder = Response.ok();
        // add jobId to response
        responseBuilder.entity(jobId);
    }
    responseBuilder.cacheControl(ResponseUtil.getNoStoreCacheControl());
    return responseBuilder.build();

}

From source file:org.bibsonomy.rest.renderer.impl.JAXBRenderer.java

/**
 * Unmarshalls the document from the reader to the generated java
 * model./*from   ww  w .  java 2 s  .c o m*/
 * 
 * @return A BibsonomyXML object that contains the unmarshalled content
 * @throws InternServerException
 *             if the content can't be unmarshalled
 */
private BibsonomyXML parse(final Reader reader) throws InternServerException {
    // first: check the reader 
    this.checkReader(reader);
    try {
        // initialize JAXB context. We provide the classloader here because we experienced that under
        // certain circumstances (e.g. when used within JabRef as a JPF-Plugin), the wrong classloader is
        // used which has the following exception as consequence:
        //
        //   javax.xml.bind.JAXBException: "org.bibsonomy.rest.renderer.xml" doesnt contain ObjectFactory.class or jaxb.index
        //
        // (see also http://ws.apache.org/jaxme/apidocs/javax/xml/bind/JAXBContext.html)
        final JAXBContext jc = this.getJAXBContext();

        // create an Unmarshaller
        final Unmarshaller u = jc.createUnmarshaller();

        // set schema to validate input documents
        if (this.validateXMLInput) {
            u.setSchema(schema);
        }

        /*
         * unmarshal a xml instance document into a tree of Java content
         * objects composed of classes from the restapi package.
         */
        final JAXBElement<BibsonomyXML> xmlDoc = unmarshal(u, reader);
        return xmlDoc.getValue();
    } catch (final JAXBException e) {
        if (e.getLinkedException() != null && e.getLinkedException().getClass() == SAXParseException.class) {
            final SAXParseException ex = (SAXParseException) e.getLinkedException();
            throw new BadRequestOrResponseException("Error while parsing XML (Line " + ex.getLineNumber()
                    + ", Column " + ex.getColumnNumber() + ": " + ex.getMessage());
        }
        throw new InternServerException(e.toString());
    }
}

From source file:org.bibsonomy.rest.renderer.impl.JAXBRenderer.java

/**
 * Initializes java xml bindings, builds the document and then marshalls
 * it to the writer./*  ww w  . j a  va2  s  .com*/
 * 
 * @throws InternServerException
 *             if the document can't be marshalled
 */
private void serialize(final Writer writer, final BibsonomyXML xmlDoc) throws InternServerException {
    try {
        // initialize context for java xml bindings
        final JAXBContext jc = this.getJAXBContext();

        // buildup document model
        final JAXBElement<BibsonomyXML> webserviceElement = new ObjectFactory().createBibsonomy(xmlDoc);

        // create a marshaller
        final Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

        if (this.validateXMLOutput) {
            // validate the XML produced by the marshaller
            marshaller.setSchema(schema);
        }

        // marshal to the writer
        this.marshal(marshaller, webserviceElement, writer);
        // TODO log
        // log.debug("");
    } catch (final JAXBException e) {
        final Throwable linkedException = e.getLinkedException();
        if (present(linkedException) && linkedException.getClass() == SAXParseException.class) {
            final SAXParseException ex = (SAXParseException) linkedException;
            throw new BadRequestOrResponseException("Error while parsing XML (Line " + ex.getLineNumber()
                    + ", Column " + ex.getColumnNumber() + ": " + ex.getMessage());
        }
        throw new InternServerException(e.toString());
    }
}