Example usage for javax.servlet ServletException ServletException

List of usage examples for javax.servlet ServletException ServletException

Introduction

In this page you can find the example usage for javax.servlet ServletException ServletException.

Prototype


public ServletException(Throwable rootCause) 

Source Link

Document

Constructs a new servlet exception when the servlet needs to throw an exception and include a message about the "root cause" exception that interfered with its normal operation.

Usage

From source file:com.berinchik.sip.FlexibleCommunicationServlet.java

@Override
public void service(ServletRequest req, ServletResponse resp) throws ServletException, IOException {

    try {//from   www.  j a  v a 2s.c  o m
        addUtilAttributesToAppSession(
                CommonUtils.getAppSession((SipServletMessage) req, (SipServletMessage) resp));
    } catch (SQLException ex) {
        logger.error("Unable to connect data source", ex);
        throw new ServletException("Server is down");
    }

    super.service(req, resp);
}

From source file:com.npower.dl.OMADownloadServlet.java

public void doDownloadDescriptor(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String requestUrl = request.getRequestURL().toString();
    String requestUri = request.getRequestURI();
    log.info("Download Service: Download Descriptor: url: " + requestUrl);
    log.info("Download Service: Download Descriptor: uri: " + requestUri);

    String downloadID = DownloadFactory.parserDownloadID(requestUri);

    log.info("Download Service: Request download ID: " + downloadID);

    DownloadFactory ddFactory = DownloadFactory.newInstance();
    DownloadDescriptor descriptor = ddFactory.getDownloadDescriptor(downloadID);

    try {/*from   www .j a v  a  2  s .  com*/
        String serverURL = DownloadFactory.getServerURL(requestUrl);
        String baseURL = serverURL + request.getContextPath() + "/dl";

        //String baseURL = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
        //                + request.getContextPath() + "/dl";

        descriptor.setDownloadURI(baseURL + "/" + DownloadFactory.OPERATION_DOWNLOAD);
        descriptor.setInstallNotifyURI(baseURL + "/" + DownloadFactory.OPERARION_INSTALL_NOTIFICATION);

        String content = descriptor.getContent();
        response.setContentType(descriptor.getContentType());
        response.setContentLength(content.length());

        OutputStream out = response.getOutputStream();
        out.write(content.getBytes("UTF-8"));
        out.flush();
        out.close();

        log.debug("Download Descriptor Content: " + content);
    } catch (Exception ex) {
        throw new ServletException(ex);
    } finally {
    }
}

From source file:it.greenvulcano.gvesb.debug.DebuggerServlet.java

/**
 * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 *///from w w  w .j a  va  2  s .c  om
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {

        StringBuffer sb = new StringBuffer();
        dump(request, sb);
        LOG.debug(sb.toString());

        DebugCommand debugOperation = Optional.ofNullable(request.getParameter("debugOperation"))
                .map(DebugCommand::valueOf).orElseThrow(IllegalArgumentException::new);

        PrintWriter writer = response.getWriter();

        Map<DebugKey, String> params = request.getParameterMap().keySet().stream().filter(KEYS::contains)
                .map(DebugKey::valueOf)
                .collect(Collectors.toMap(Function.identity(), k -> request.getParameter(k.name())));

        DebuggerObject dObj = gvDebugger.processCommand(debugOperation, params);

        if (dObj == null) {
            dObj = DebuggerObject.FAIL_DEBUGGER_OBJECT;
        }
        String debugOperationResponse = dObj.toXML();

        LOG.debug("Debug operation response: " + debugOperationResponse);
        writer.println(debugOperationResponse);
    } catch (IllegalArgumentException e) {
        LOG.error("Fail to process debug operation: missing or invalid value for parameter debugOperation");
        response.getWriter().println("Missing or invalid value for parameter debugOperation");
    } catch (Exception e) {
        LOG.error("Fail to process debug operation", e);
        throw new ServletException(e);
    }
}

From source file:fr.aliasource.webmail.server.export.ExportConversationImpl.java

/**
 * The actual business logic.//from ww w  . j  a  v a  2s . c  om
 * 
 * @param requ
 *            the request object
 * @param resp
 *            the response object
 * @throws IOException
 * @throws ServletException
 */
public void service(HttpServletRequest req, HttpServletResponse response) throws IOException, ServletException {
    logger.info("Export conversation called.");

    IAccount account = (IAccount) req.getSession().getAttribute("account");

    if (account == null) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
    String uri = req.getRequestURI();
    String convAndMessageIds = extractConversationIdFromRequestURI(uri);
    MessageId messageId = getMessageIdPart(convAndMessageIds);
    ConversationId conversationId = getConversationIdPart(convAndMessageIds);

    String folder = conversationId.getSourceFolder();

    logger.info("Conversation id: " + conversationId.getConversationId() + " folder: " + folder + " uri: " + uri
            + "Message id: " + messageId);

    Folder f = new Folder(folder, folder);
    ConversationReference cr = account.findConversation(conversationId);
    ClientMessage[] cm = null;
    if (messageId == null) {
        cm = account.fetchMessages(f, cr.getMessageIds());
    } else {
        cm = account.fetchMessages(f, Arrays.asList(messageId));
    }

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ConversationExporter exporter = new ConversationExporter(
            req.getContextPath() + "/minig/images/logo_print.jpg");
    try {
        if (req.getRequestURI().endsWith(".html")) {
            exporter.exportToHtml(account, cr, cm, baos);
            response.setContentType("text/html");
        } else {
            exporter.exportToPdf(account, cr, cm, baos);
            response.setContentType("application/pdf");
        }
    } catch (ConversationExporterException e) {
        logger.error("Cannot render conversation", e);
        throw new ServletException(e);
    }

    response.setHeader("Expires", "0");
    response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
    response.setHeader("Pragma", "public");

    response.setContentLength(baos.size());
    ServletOutputStream out = response.getOutputStream();
    baos.writeTo(out);
    out.flush();

}

From source file:org.openmeetings.servlet.outputhandler.ImportController.java

@RequestMapping(value = "/import.upload", method = RequestMethod.POST)
protected void service(HttpServletRequest request, HttpServletResponse httpServletResponse)
        throws ServletException {

    UploadInfo info = validate(request, true);
    try {/*  ww  w  . j av  a 2  s .  c  o m*/
        String moduleName = request.getParameter("moduleName");
        if (moduleName == null) {
            moduleName = "moduleName";
        }
        log.debug("moduleName: " + moduleName);
        InputStream is = info.file.getInputStream();

        if (moduleName.equals("users")) {
            log.error("Import Users");
            userImport.addUsersByDocument(is);

        } else if (moduleName.equals("language")) {
            log.error("Import Language");
            String language = request.getParameter("secondid");
            if (language == null) {
                language = "0";
            }
            Long language_id = Long.valueOf(language).longValue();
            log.debug("language_id: " + language_id);

            languageImport.addLanguageByDocument(language_id, is);
        }

        log.debug("Return And Close");

        LinkedHashMap<String, Object> hs = new LinkedHashMap<String, Object>();
        hs.put("user", usersDao.getUser(info.userId));
        hs.put("message", "library");
        hs.put("action", "import");

        log.debug("moduleName.equals(userprofile) ? " + moduleName);

        log.debug("moduleName.equals(userprofile) ! ");

        scopeApplicationAdapter.sendMessageWithClientByPublicSID(hs, info.publicSID);

    } catch (Exception er) {
        log.error("ERROR importing:", er);
        throw new ServletException(er);
    }
}

From source file:architecture.ee.web.servlet.ViewRendererServlet.java

protected void renderView(HttpServletRequest httpservletrequest, HttpServletResponse httpservletresponse)
        throws Exception {

    View view = resolvingView(httpservletrequest, httpservletresponse);
    if (view == null) {
        throw new ServletException("Could not complete render request: View is null");
    } else {//from   w  w  w.  ja  v a  2  s  .  co  m
        Map map = resolveModel(httpservletrequest, httpservletresponse);
        view.render(map, httpservletrequest, httpservletresponse);
        return;
    }
}

From source file:com.github.peholmst.springsecuritydemo.servlet.SpringApplicationServlet.java

@SuppressWarnings("unchecked")
@Override//from  w  w  w . ja  v a  2  s  . c o  m
public void init(ServletConfig servletConfig) throws ServletException {
    super.init(servletConfig);
    /*
     * Look up the name of the Vaadin application bean. The bean should be
     * either a prototype or have session scope.
     */
    applicationBean = servletConfig.getInitParameter("applicationBean");
    if (applicationBean == null) {
        if (logger.isErrorEnabled()) {
            logger.error("ApplicationBean not specified in servlet parameters");
        }
        throw new ServletException("ApplicationBean not specified in servlet parameters");
    }

    if (logger.isInfoEnabled()) {
        logger.info("Using applicationBean '" + applicationBean + "'");
    }

    /*
     * Fetch the Spring web application context
     */
    applicationContext = WebApplicationContextUtils.getWebApplicationContext(servletConfig.getServletContext());

    if (applicationContext.isSingleton(applicationBean)) {
        if (logger.isErrorEnabled()) {
            logger.error("ApplicationBean must not be a singleton");
        }
        throw new ServletException("ApplicationBean must not be a singleton");
    }
    if (!applicationContext.isPrototype(applicationBean) && logger.isWarnEnabled()) {
        logger.warn("ApplicationBean is not a prototype");
    }

    /*
     * Get the application class from the application context
     */
    applicationClass = (Class<? extends Application>) applicationContext.getType(applicationBean);
    if (logger.isDebugEnabled()) {
        logger.debug("Vaadin application class is [" + applicationClass + "]");
    }
    /*
     * Initialize the locale resolver
     */
    initLocaleResolver(applicationContext);
}

From source file:edu.fullerton.ldvservlet.Upload.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 *
 * @param request servlet request/* ww  w .j  ava2 s  . c  om*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    long startTime = System.currentTimeMillis();

    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new ServletException("This action requires a multipart form with a file attached.");
    }
    ServletSupport servletSupport;

    servletSupport = new ServletSupport();
    servletSupport.init(request, viewerConfig, false);

    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();

    // Configure a repository (to ensure a secure temp location is used)
    ServletContext servletContext = this.getServletConfig().getServletContext();
    File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
    factory.setRepository(repository);

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);

    ImageTable imageTable;
    String viewServletPath = request.getContextPath() + "/view";

    try {
        imageTable = new ImageTable(servletSupport.getDb());
    } catch (SQLException ex) {
        String ermsg = "Image upload: can't access the Image table: " + ex.getClass().getSimpleName() + " "
                + ex.getLocalizedMessage();
        throw new ServletException(ermsg);
    }
    try {
        HashMap<String, String> params = new HashMap<>();
        ArrayList<Integer> uploadedIds = new ArrayList<>();

        Page vpage = servletSupport.getVpage();
        vpage.setTitle("Image upload");
        try {
            servletSupport.addStandardHeader(version);
            servletSupport.addNavBar();
        } catch (WebUtilException ex) {
            throw new ServerException("Adding nav bar after upload", ex);
        }

        // Parse the request
        List<FileItem> items = upload.parseRequest(request);
        int cnt = items.size();
        for (FileItem item : items) {
            if (item.isFormField()) {
                String name = item.getFieldName();
                String value = item.getString();
                if (!value.isEmpty()) {
                    params.put(name, value);
                }
            }
        }
        for (FileItem item : items) {
            if (!item.isFormField()) {
                int imgId = addFile(item, params, vpage, servletSupport.getVuser().getCn(), imageTable);
                if (imgId != 0) {
                    uploadedIds.add(imgId);
                }
            }
        }
        if (!uploadedIds.isEmpty()) {
            showImages(vpage, uploadedIds, imageTable, viewServletPath);
        }
        servletSupport.showPage(response);
    } catch (FileUploadException ex) {
        Logger.getLogger(Upload.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:de.fhg.igd.vaadin.util.servlets.AutowiringApplicationServlet.java

/**
 * Get the containing Spring {@link WebApplicationContext}
 * This only works after the servlet has been initialized (via {@link #init init()}).
 *
 * @throws ServletException if the operation fails
 *//*w w w .  j  a  va 2  s . c om*/
protected final WebApplicationContext getWebApplicationContext() throws ServletException {
    if (webApplicationContext == null)
        throw new ServletException("can't retrieve WebApplicationContext before init() is invoked");
    return webApplicationContext;
}