Example usage for javax.xml.bind JAXBException getCause

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

Introduction

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

Prototype

@Override
    public Throwable getCause() 

Source Link

Usage

From source file:org.jasig.portlet.announcements.Importer.java

private void importTopics() {
    try {//w  w w  . j  ava2 s .co m
        JAXBContext jc = JAXBContext.newInstance(Topic.class);
        Unmarshaller unmarshaller = jc.createUnmarshaller();

        File[] files = dataDirectory.listFiles(new TopicImportFileFilter());

        if (files == null) {
            errors.add("Directory " + dataDirectory + " is not a valid directory");
        } else {

            for (File f : files) {
                log.info("Processing file " + f.toString());
                StreamSource xmlFile = new StreamSource(f.getAbsoluteFile());
                try {
                    JAXBElement<Topic> je1 = unmarshaller.unmarshal(xmlFile, Topic.class);
                    Topic topic = je1.getValue();

                    if (StringUtils.isBlank(topic.getTitle())) {
                        String msg = "Error parsing file " + f.toString() + "; did not get valid record:\n"
                                + topic.toString();
                        log.error(msg);
                        errors.add(msg);
                    } else {
                        announcementService.addOrSaveTopic(topic);
                        log.info("Successfully imported topic '" + topic.getTitle() + "'");
                    }
                } catch (JAXBException e) {
                    String msg = "JAXB exception " + e.getCause().getMessage() + " processing file "
                            + f.toString();
                    log.error(msg, e);
                    errors.add(msg + ". See stack trace");
                } catch (HibernateException e) {
                    String msg = "Hibernate exception " + e.getCause().getMessage() + " processing file "
                            + f.toString();
                    log.error(msg, e);
                    errors.add(msg + ". See stack trace");
                }
            }
        }
    } catch (JAXBException e) {
        String msg = "Fatal JAXBException in importTopics - no topics imported";
        log.fatal(msg, e);
        errors.add(msg + ".  See stack trace");
    }
}

From source file:de.iai.ilcd.services.DataStockResource.java

/**
 * Get list of data stocks/*from w w  w . ja v  a2  s .  c o m*/
 * 
 * @return an instance of javax.ws.rs.core.StreamingOutput
 */
@GET
@Produces("application/xml")
public StreamingOutput getDataStocks() {
    UserAccessBean user = new UserAccessBean();
    CommonDataStockDao stockDao = new CommonDataStockDao();
    List<AbstractDataStock> stocks = stockDao.getAllReadable(user.getUserObject());

    final DataStockListAdapter adapter = new DataStockListAdapter(stocks);
    return new StreamingOutput() {

        @Override
        public void write(OutputStream out) throws IOException, WebApplicationException {
            ServiceDAO dao = new ServiceDAO();
            dao.setRenderSchemaLocation(true);
            try {
                dao.marshal(adapter, out);
            } catch (JAXBException e) {
                if (e.getCause().getCause() instanceof SocketException) {
                    DataStockResource.LOGGER.warn("exception occurred during marshalling - " + e);
                } else {
                    DataStockResource.LOGGER.error("error marshalling data", e);
                }
            }
        }
    };

}

From source file:de.iai.ilcd.services.DataStockResource.java

/**
 * Get data sets of a specified data stock
 * //  www  . ja va2 s  .c  o m
 * @param uuid
 *            UUID of the data stock
 * @param dao
 *            the data access object to use for retrieving of the data sets
 * @param dsType
 *            the API data set type
 * @param startIndex
 *            start index of the list
 * @param pageSize
 *            page size of the list
 * @return created response
 */
private <E extends IDataSetListVO> Response getDataSets(final String uuid, final DataSetDao<?, E, ?> dao,
        final DatasetTypes dsType, final int startIndex, final int pageSize) {
    CommonDataStockDao dsDao = new CommonDataStockDao();
    IDataStockMetaData dsMeta = dsDao.getDataStockByUuid(uuid);

    if (dsMeta == null) {
        return Response.status(Status.NOT_FOUND).entity("Invalid data stock UUID").type("text/plain").build();
    }

    try {
        SecurityUtil.assertCanRead(dsMeta);

        IDataStockMetaData[] dsMetas = new IDataStockMetaData[] { dsMeta };

        final int totalCount = (int) dao.searchResultCount(null, true, dsMetas);
        final List<E> list = dao.search(null, true, dsMetas);

        final StreamingOutput sout = new StreamingOutput() {

            @Override
            public void write(OutputStream out) throws IOException, WebApplicationException {
                DataSetList resultList = new DataSetListAdapter(list);

                String baseUrl = ConfigurationService.INSTANCE.getNodeInfo().getBaseURL();

                // set xlink:href attribute for each dataset
                for (DataSetVO ds : resultList.getDataSet()) {
                    StringBuffer buf = new StringBuffer(baseUrl);
                    buf.append(dsType.getValue());
                    buf.append("/");
                    buf.append(ds.getUuidAsString());
                    ds.setHref(buf.toString());
                }

                resultList.setTotalSize(totalCount);
                resultList.setPageSize(pageSize);
                resultList.setStartIndex(startIndex);

                DatasetVODAO dao = new DatasetVODAO();

                try {
                    dao.marshal(resultList, out);
                } catch (JAXBException e) {
                    if (e.getCause().getCause() instanceof SocketException) {
                        DataStockResource.LOGGER.warn("exception occurred during marshalling - " + e);
                    } else {
                        DataStockResource.LOGGER.error("error marshalling data", e);
                    }
                }
            }
        };
        return Response.ok(sout).type("application/xml").build();
    } catch (AuthorizationException aEx) {
        return Response.status(Status.UNAUTHORIZED).entity(aEx.getMessage()).type("text/plain").build();
    }
}

From source file:eu.learnpad.cw.CWXwikiBridge.java

License:asdf

@Override
public void notifyRecommendations(String modelSetId, String simulationid, String userId, Recommendations rec)
        throws LpRestException {
    Writer recWriter = new StringWriter();
    JAXBContext jc;/*  ww  w  .  j  a v  a 2  s  .  c  o  m*/
    try {
        jc = JAXBContext.newInstance(Recommendations.class);
        jc.createMarshaller().marshal(rec, recWriter);
    } catch (JAXBException e) {
        throw new LpRestExceptionXWikiImpl(e.getMessage(), e.getCause());
    }

    String msg = "modelSetId : " + modelSetId + "\n" + "simulationid : " + simulationid + "\n" + "userId : "
            + userId + "\n" + "recommendations : " + rec.toString();

    logger.info(msg);

    CWXwikiBridge.recsStore.put(userId, simulationid, rec);
}

From source file:hydrograph.ui.propertywindow.widgets.customwidgets.schema.GridRowLoader.java

/**
 * The method exports schema rows from schema grid into schema file.
 * //w  w w  .j ava2s  . c  om
 */
public void exportXMLfromGridRowsWithoutMessage(List<GridRow> schemaGridRowList) {
    Schema schema = new Schema();
    fields = new Fields();

    try {
        if (StringUtils.isNotBlank(schemaFile.getPath())) {
            exportFile(schemaGridRowList, schema);
        } else {
            logger.error(Messages.EXPORT_XML_EMPTY_FILENAME);
            throw new Exception(Messages.EXPORT_XML_EMPTY_FILENAME);
        }
    } catch (JAXBException e) {
        showMessageBox(
                Messages.EXPORT_XML_ERROR + " -\n"
                        + ((e.getCause() != null) ? e.getLinkedException().getMessage() : e.getMessage()),
                "Error", SWT.ERROR);
        logger.error(Messages.EXPORT_XML_ERROR);
    } catch (Exception e) {
        showMessageBox(Messages.EXPORT_XML_ERROR + " -\n" + e.getMessage(), "Error", SWT.ERROR);
        logger.error(Messages.EXPORT_XML_ERROR);
    }

}

From source file:de.iai.ilcd.services.AbstractDataSetResource.java

/**
 * Create a streaming output for a list of data sets
 * /*  www.j  a va  2s. co  m*/
 * @param list
 *            the list with the data
 * @param totalCount
 *            the total count of result items (for pagination)
 * @param startIndex
 *            index of the first item in the passed list in the total data (for pagination)
 * @param pageSize
 *            pagination page size
 * @return output for the client (which will be marshaled via JAXB)
 */
protected StreamingOutput getStreamingOutputForDatasetListVOList(final List<? extends IDataSetListVO> list,
        final int totalCount, final int startIndex, final int pageSize) {
    return new StreamingOutput() {

        @Override
        public void write(OutputStream out) throws IOException, WebApplicationException {
            DataSetList resultList = new DataSetListAdapter(list);

            String baseUrl = ConfigurationService.INSTANCE.getNodeInfo().getBaseURL();

            // set xlink:href attribute for each dataset
            for (DataSetVO ds : resultList.getDataSet()) {
                StringBuffer buf = new StringBuffer(baseUrl);
                buf.append(AbstractDataSetResource.this.getURLSuffix(ds));
                buf.append("/");
                buf.append(ds.getUuidAsString());
                ds.setHref(buf.toString());
            }

            resultList.setTotalSize(totalCount);
            resultList.setPageSize(pageSize);
            resultList.setStartIndex(startIndex);

            DatasetVODAO dao = new DatasetVODAO();

            try {
                dao.marshal(resultList, out);
            } catch (JAXBException e) {
                if (e.getCause().getCause() instanceof SocketException) {
                    LOGGER.warn("exception occurred during marshalling - " + e);
                } else {
                    LOGGER.error("error marshalling data", e);
                }
            }
        }
    };
}

From source file:hydrograph.ui.propertywindow.widgets.customwidgets.schema.GridRowLoader.java

/**
 * The method exports schema rows from schema grid into schema file.
 * //from w w  w  .ja  v  a  2s. c om
 */
public void exportXMLfromGridRows(List<GridRow> schemaGridRowList) {
    Schema schema = new Schema();
    fields = new Fields();

    try {
        if (StringUtils.isNotBlank(schemaFile.getPath())) {

            if (!schemaFile.getName().contains(".")) {
                logger.error(Messages.EXPORT_XML_IMPROPER_EXTENSION);
                throw new Exception(Messages.EXPORT_XML_IMPROPER_EXTENSION);
            }

            if (!(schemaFile.getPath().endsWith(".schema")) && !(schemaFile.getPath().endsWith(".xml"))) {
                logger.error(Messages.EXPORT_XML_INCORRECT_FILE);
                throw new Exception(Messages.EXPORT_XML_INCORRECT_FILE);
            }

            exportFile(schemaGridRowList, schema);
            showMessageBox(Messages.EXPORTED_SCHEMA, "Information", SWT.ICON_INFORMATION);
        } else {
            logger.error(Messages.EXPORT_XML_EMPTY_FILENAME);
            throw new Exception(Messages.EXPORT_XML_EMPTY_FILENAME);
        }
    } catch (JAXBException e) {
        showMessageBox(
                Messages.EXPORT_XML_ERROR + " -\n"
                        + ((e.getCause() != null) ? e.getLinkedException().getMessage() : e.getMessage()),
                "Error", SWT.ERROR);
        logger.error(Messages.EXPORT_XML_ERROR);
    } catch (Exception e) {
        showMessageBox(Messages.EXPORT_XML_ERROR + " -\n" + e.getMessage(), "Error", SWT.ERROR);
        logger.error(Messages.EXPORT_XML_ERROR);
    }

}

From source file:de.iai.ilcd.services.AbstractDataSetResource.java

/**
 * Process uploaded XML as input stream//www.  ja va 2  s  .co  m
 * 
 * @param inputStream
 *            stream with XML
 * @param stockUuid
 *            UUID of the root stock to import to (or <code>null</code> for default
 * @return response for client
 */
private Response importXml(InputStream inputStream, String stockUuid) {
    try {
        final CommonDataStockDao dao = new CommonDataStockDao();
        AbstractDataStock ads;
        if (StringUtils.isBlank(stockUuid)) {
            ads = dao.getById(IDataStockMetaData.DEFAULT_DATASTOCK_ID);
        } else {
            ads = dao.getDataStockByUuid(stockUuid);
            if (!(ads instanceof RootDataStock)) {
                return Response.status(Response.Status.PRECONDITION_FAILED)
                        .entity("Data sets can only be imported into root data stocks!").type("text/plain")
                        .build();
            }
        }
        if (ads == null) {
            return Response.status(Response.Status.BAD_REQUEST).entity("Invalid root data stock UUID specified")
                    .type("text/plain").build();
        }
        SecurityUtil.assertCanImport(ads);

        PostResourceHelper postHelper = new PostResourceHelper();
        final Response resp = postHelper.importByFileUpload(this.modelType, inputStream, (RootDataStock) ads);
        if (resp.getStatus() != Status.OK.getStatusCode()) {
            return resp;
        } else {
            final DataStockVO dsVo = DataStockListAdapter.getServiceApiVo(ads);
            final StreamingOutput sout = new StreamingOutput() {

                @Override
                public void write(OutputStream out) throws IOException, WebApplicationException {
                    ServiceDAO sDao = new ServiceDAO();
                    try {
                        sDao.marshal(dsVo, out);
                    } catch (JAXBException e) {
                        if (e.getCause().getCause() instanceof SocketException) {
                            AbstractDataSetResource.LOGGER.warn("exception occurred during marshalling - " + e);
                        } else {
                            AbstractDataSetResource.LOGGER.error("error marshalling data", e);
                        }
                    }
                }
            };
            return Response.ok(sout).type("application/xml").build();
        }

    } catch (IllegalArgumentException e) {
        return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).type("text/plain").build();
    } catch (AuthorizationException e) {
        return Response.status(Response.Status.FORBIDDEN).entity(e.getMessage()).type("text/plain").build();
    }
}

From source file:net.emotivecloud.scheduler.drp4ost.DRP4OST.java

private OVFWrapper parse(String ovfXml) {
    OVFWrapper rv = null;/*  ww w.j ava 2s.  co m*/
    StringBuilder cause = new StringBuilder();

    try {
        rv = OVFWrapperFactory.parse(ovfXml);
    } catch (JAXBException e) {
        if (e instanceof PropertyException) {
            cause.append("Access to property failed: " + e.getErrorCode());
        } else if (e instanceof MarshalException) {
            cause.append("Marshalling failed: " + e.getLocalizedMessage());
        } else if (e instanceof UnmarshalException) {
            cause.append("Unmarshalling failed: " + e.getCause());
        } else if (e instanceof ValidationException) {
            cause.append("XML Validation failed: " + e.getErrorCode());
        } else {
            cause.append("Unespected " + e.getErrorCode());
            cause.append(e.getClass().getName());
            cause.append(": ");
        }

        cause.append(e.getMessage());

        throw new DRPOSTException(cause.toString(), e, StatusCodes.XML_PROBLEM);
    } catch (OVFException e) {
        cause.append("Problems parsing OVF file: ");
        cause.append(e.getMessage());

        throw new DRPOSTException(cause.toString(), e, StatusCodes.XML_PROBLEM);
    }
    return rv;
}

From source file:de.tu_dortmund.ub.api.paia.auth.PaiaAuthEndpoint.java

/**
 *
 * @param httpServletRequest/*from w  w w.  ja v a  2  s . co  m*/
 * @param httpServletResponse
 * @throws IOException
 */
private void authorize(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
        String format) throws IOException {

    httpServletResponse.setHeader("Access-Control-Allow-Origin",
            config.getProperty("Access-Control-Allow-Origin"));
    httpServletResponse.setHeader("Cache-Control", config.getProperty("Cache-Control"));

    ObjectMapper mapper = new ObjectMapper();

    // Error handling mit suppress_response_codes=true
    if (httpServletRequest.getParameter("suppress_response_codes") != null) {
        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
    }
    // Error handling mit suppress_response_codes=false (=default)
    else {
        httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }

    // Json fr Response body
    RequestError requestError = new RequestError();
    requestError.setError(
            this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED)));
    requestError.setCode(HttpServletResponse.SC_UNAUTHORIZED);
    requestError.setDescription(this.config
            .getProperty("error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED) + ".description"));
    requestError.setErrorUri(
            this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED) + ".uri"));

    // XML-Ausgabe mit JAXB
    if (format.equals("xml")) {

        try {

            JAXBContext context = JAXBContext.newInstance(RequestError.class);
            Marshaller m = context.createMarshaller();
            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

            // Write to HttpResponse
            httpServletResponse.setContentType("application/xml;charset=UTF-8");
            m.marshal(requestError, httpServletResponse.getWriter());

        } catch (JAXBException e) {
            this.logger.error(e.getMessage(), e.getCause());
            httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Internal Server Error: Error while rendering the results.");
        }
    }

    // JSON-Ausgabe mit Jackson
    if (format.equals("json")) {

        httpServletResponse.setContentType("application/json;charset=UTF-8");
        mapper.writeValue(httpServletResponse.getWriter(), requestError);
    }

    // html > redirect zu "PAIA auth - login" mit redirect_url = "PAIA auth - service"
    if (format.equals("html")) {

        httpServletResponse.setContentType("text/html;charset=UTF-8");

        String redirect_url = this.config.getProperty("service.base_url")
                + this.config.getProperty("service.endpoint.auth") + httpServletRequest.getPathInfo();
        if (httpServletRequest.getQueryString() != null && !httpServletRequest.getQueryString().equals("")) {
            redirect_url += "?" + httpServletRequest.getQueryString();
        }
        this.logger.info("redirect_url = " + redirect_url);

        //String login_url = "http://" + httpServletRequest.getServerName() + ":" + httpServletRequest.getServerPort() + this.config.getProperty("service.endpoint.auth") + "/login?redirect_url=" + redirect_url;
        String login_url = this.config.getProperty("service.base_url")
                + this.config.getProperty("service.endpoint.auth") + "/login?redirect_url=" + redirect_url;
        this.logger.info("login_url = " + login_url);

        httpServletResponse.sendRedirect(login_url);
    }
}