Example usage for javax.servlet.http HttpServletResponse SC_INTERNAL_SERVER_ERROR

List of usage examples for javax.servlet.http HttpServletResponse SC_INTERNAL_SERVER_ERROR

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse SC_INTERNAL_SERVER_ERROR.

Prototype

int SC_INTERNAL_SERVER_ERROR

To view the source code for javax.servlet.http HttpServletResponse SC_INTERNAL_SERVER_ERROR.

Click Source Link

Document

Status code (500) indicating an error inside the HTTP server which prevented it from fulfilling the request.

Usage

From source file:controller.TemasNivel1RestController.java

/**
*
* @param id/* ww w . j  ava  2 s  .com*/
* @param request
* @param response
* @return XML
*/
@RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = "application/xml")
public String getByIdXML(@PathVariable("id") int id, HttpServletRequest request, HttpServletResponse response) {

    TemasNivel1DAO tabla = new TemasNivel1DAO();
    XStream XML;
    TemasNivel1 elemento;
    try {
        elemento = tabla.selectById(id);
        if (elemento == null) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            Error e = new Error();
            e.setTypeAndDescription("Warning", "No existe el elemeto solicitado con id:" + id);
            XML = new XStream();
            XML.alias("message", Error.class);
            return XML.toXML(e);
        }
    } catch (HibernateException ex) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        Error e = new Error();
        e.setTypeAndDescription("errorServerError", ex.getMessage());
        XML = new XStream();
        XML.alias("message", Error.class);
        return XML.toXML(e);
    }

    XML = new XStream();
    XML.alias("Tema-Nivel-1", TemasNivel1.class);
    response.setStatus(HttpServletResponse.SC_OK);
    return XML.toXML(elemento);
}

From source file:controller.TemasNivel3RestController.java

/**
*
* @param id/*from w  w  w . java  2 s  .  c o  m*/
* @param request
* @param response
* @return XML
*/
@RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = "application/xml")
public String getByIdXML(@PathVariable("id") int id, HttpServletRequest request, HttpServletResponse response) {

    TemasNivel3DAO tabla = new TemasNivel3DAO();
    XStream XML;
    TemasNivel3 elemento;
    try {
        elemento = tabla.selectById(id);
        if (elemento == null) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            Error e = new Error();
            e.setTypeAndDescription("Warning", "No existe el elemeto solicitado con id:" + id);
            XML = new XStream();
            XML.alias("message", Error.class);
            return XML.toXML(e);
        }
    } catch (HibernateException ex) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        Error e = new Error();
        e.setTypeAndDescription("errorServerError", ex.getMessage());
        XML = new XStream();
        XML.alias("message", Error.class);
        return XML.toXML(e);
    }

    XML = new XStream();
    XML.alias("Tema-Nivel-3", TemasNivel3.class);
    response.setStatus(HttpServletResponse.SC_OK);
    return XML.toXML(elemento);
}

From source file:net.sf.sripathi.ws.mock.servlet.MockServlet.java

/**
 * The service operation generated the mocked response for the input SOAP request message.
 *//*from  www .  ja  va  2s  .c o  m*/
@Override
public void service(HttpServletRequest req, HttpServletResponse resp) {

    long startTime = System.currentTimeMillis();

    try {
        String tmp = req.getRequestURI().substring((req.getContextPath() + "/mock/").length());
        String[] tmps = tmp.split("/");

        String domainName = tmps[0];

        Domain domain = DomainFactory.getInstance().getDomain(domainName);

        String soapResp = null;
        String soapReq = "";
        if (tmps.length != 3) {
            soapResp = SoapUtil.getSoapFault("NOT_A_VALID_URL", "URL " + req.getRequestURI() + " is not valid");
        } else if (domain == null) {
            soapResp = SoapUtil.getSoapFault("NOT_A_VALID_PROFILE", "Domain " + domainName + " is not valid");
            LOGGER.error(soapResp);
        } else {
            String serviceName = tmps[2];

            Service service = domain.getService(serviceName);

            if (service == null) {
                soapResp = SoapUtil.getSoapFault("NOT_A_VALID_SERVICE",
                        "Service " + serviceName + " is not valid");
                LOGGER.error(soapResp);
            } else {
                LOGGER.info("Request received for service - " + serviceName + " on domain - " + domainName);
                InputStream is = req.getInputStream();

                soapReq = new String(IOUtils.toByteArray(is));

                this.getLogger(domainName, serviceName).info("Request - " + soapReq);
                try {
                    Scenario scenario = service.getMockResponse(soapReq);
                    soapResp = scenario.getResponse();

                    if (scenario.getDelayInMilliSec() > 0) {
                        long curTime = System.currentTimeMillis();
                        long diff = curTime - startTime;
                        if (diff < scenario.getDelayInMilliSec()) {
                            Thread.sleep(scenario.getDelayInMilliSec() - diff);
                        }
                    }

                } catch (MockException me) {
                    soapResp = SoapUtil.getSoapFault("UNABLE_TO_PROCESS_REQ", me.getMessage());
                }
                this.getLogger(domainName, serviceName).info("Mock Response - " + soapResp);
            }
        }

        if (soapReq.contains(javax.xml.soap.SOAPConstants.URI_NS_SOAP_1_2_ENVELOPE)) {
            resp.setContentType(javax.xml.soap.SOAPConstants.SOAP_1_2_CONTENT_TYPE);
        } else {
            resp.setContentType(javax.xml.soap.SOAPConstants.SOAP_1_1_CONTENT_TYPE);
        }

        if (soapResp != null && soapResp.indexOf("Fault>") != -1 && soapResp.indexOf("faultcode>") != -1
                && soapResp.indexOf("faultstring>") != -1) {
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }

        resp.getOutputStream().write(soapResp.getBytes());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.eureka.v1_0.account.information.api.AccountInformationController.java

@ResponseBody
@RequestMapping(method = RequestMethod.POST, consumes = MediaType.TEXT_XML_VALUE, produces = MediaType.TEXT_XML_VALUE, value = "/resetpassword")
public ResetPasswordResponse resetPassword(@RequestBody ResetPasswordRequest resetPasswordRequest,
        HttpServletRequest request, HttpServletResponse response) {
    if (resetPasswordRequest != null) {
        try {/*from  ww  w .j  av  a2  s.co  m*/
            witLoggerService.debug(JaxbHandler.toXml(resetPasswordRequest));
            ResetPasswordResponse resetPasswordResponse = this.accountInformationApiService
                    .resetPassword(resetPasswordRequest);
            if (resetPasswordResponse != null) {
                witLoggerService.debug(JaxbHandler.toXml(resetPasswordResponse));
                response.setStatus(HttpServletResponse.SC_OK);
                return resetPasswordResponse;
            } else {
                response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
            }
        } catch (Exception ex) {
            witLoggerService.warn(ex);
            ex.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    return null;
}

From source file:com.lp.webapp.cc.CCOrderResponseServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse response)
        throws ServletException, IOException {

    ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
    upload.setSizeMax(maxUploadSize);//from  w w  w.  j a v a2 s  . com

    if (!ServletFileUpload.isMultipartContent(req)) {
        myLogger.info("Received request without form/multipart data. Aborting.");
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    FileItem file = null;

    try {
        List<FileItem> files = upload.parseRequest(req);
        if (files.size() != 1) {
            response.setStatus(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
            return;
        }

        file = files.get(0);
        processOrder(req, response, file);
    } catch (FileUploadException e) {
        myLogger.error("Upload exception: ", e);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    } catch (Exception e) {
        myLogger.error("Processing file exception: ", e);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

        saveXmlFile(file);
    }
}

From source file:com.ephesoft.gxt.uploadbatch.server.UploadBatchImageServlet.java

private void uploadFile(HttpServletRequest req, HttpServletResponse resp, BatchSchemaService batchSchemaService,
        String currentBatchUploadFolderName) throws IOException {

    PrintWriter printWriter = resp.getWriter();
    File tempFile = null;//from  w  w w.jav a 2 s .  c om
    InputStream instream = null;
    OutputStream out = null;
    String uploadBatchFolderPath = batchSchemaService.getUploadBatchFolder();
    String uploadFileName = "";
    if (ServletFileUpload.isMultipartContent(req)) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

        uploadFileName = "";
        String uploadFilePath = "";
        List<FileItem> items;
        try {
            items = upload.parseRequest(req);

            for (FileItem item : items) {
                if (!item.isFormField()) { // && "uploadFile".equals(item.getFieldName())) {
                    uploadFileName = item.getName();
                    if (uploadFileName != null) {
                        uploadFileName = uploadFileName
                                .substring(uploadFileName.lastIndexOf(File.separator) + 1);
                    }
                    uploadFilePath = uploadBatchFolderPath + File.separator + currentBatchUploadFolderName
                            + File.separator + uploadFileName;

                    try {
                        instream = item.getInputStream();
                        tempFile = new File(uploadFilePath);

                        out = new FileOutputStream(tempFile);
                        byte buf[] = new byte[1024];
                        int len;
                        while ((len = instream.read(buf)) > 0) {
                            out.write(buf, 0, len);
                        }
                    } catch (FileNotFoundException e) {
                        log.error("Unable to create the upload folder." + e, e);
                        printWriter.write("Unable to create the upload folder.Please try again.");
                        tempFile.delete();
                        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                "unable to upload. please see server logs for more details.");
                    } catch (IOException e) {
                        log.error("Unable to read the file." + e, e);
                        printWriter.write("Unable to read the file.Please try again.");
                        tempFile.delete();
                        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                "unable to upload. please see server logs for more details.");
                    } finally {
                        if (out != null) {
                            out.close();
                        }
                        if (instream != null) {
                            instream.close();
                        }
                    }
                }
            }
        } catch (FileUploadException e) {
            log.error("Unable to read the form contents." + e, e);
            printWriter.write("Unable to read the form contents.Please try again.");
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "unable to upload. please see server logs for more details.");
        }

    } else {
        log.error("Request contents type is not supported.");
        printWriter.write("Request contents type is not supported.");
    }
    printWriter.write("currentBatchUploadFolderName:" + currentBatchUploadFolderName);
    printWriter.append("|");

    printWriter.append("fileName:").append(uploadFileName);
    printWriter.append("|");

    printWriter.flush();
}

From source file:csiro.pidsvc.servlet.controller.java

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
 *     response)/*from  www  .  jav  a2  s  .co m*/
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setDateHeader("Expires", 0);
    response.addHeader("Cache-Control",
            "no-cache,no-store,private,must-revalidate,max-stale=0,post-check=0,pre-check=0");

    String cmd = request.getParameter("cmd");
    if (cmd == null || cmd.isEmpty())
        return;

    ManagerJson mgr = null;
    try {
        mgr = new ManagerJson();

        _logger.info("Processing \"{}\" command -> {}?{}.", cmd, request.getRequestURL(),
                request.getQueryString());
        if (cmd.matches("(?i)^(?:full|partial)_export$")) {
            int mappingId = Literals.toInt(request.getParameter("mapping_id"), -1);
            String mappingPath = request.getParameter("mapping_path");
            String outputFormat = request.getParameter("format");
            String serializedConfig = mappingId > 0 ? mgr.exportMapping(mappingId)
                    : (mappingId == 0 ? mgr.exportCatchAllMapping(cmd.startsWith("full"))
                            : mgr.exportMapping(mappingPath, cmd.startsWith("full")));

            // Check output format.
            outputFormat = outputFormat != null && outputFormat.matches("(?i)^xml$") ? "xml" : "psb";

            returnAttachment(response,
                    "mapping." + (cmd.startsWith("full") ? "full" : "partial") + "."
                            + _sdfBackupStamp.format(new Date()) + "." + outputFormat,
                    outputFormat, serializedConfig);
        } else if (cmd.matches("(?i)^(?:full|partial)_backup$")) {
            String includeDeprecated = request.getParameter("deprecated");
            String includeConditionSets = request.getParameter("conditionsets");
            String includeLookupMaps = request.getParameter("lookup");
            String outputFormat = request.getParameter("format");
            String serializedConfig = mgr.backupDataStore(cmd.startsWith("full"),
                    includeDeprecated != null && includeDeprecated.equalsIgnoreCase("true"),
                    includeConditionSets == null || includeConditionSets.equalsIgnoreCase("true"),
                    includeLookupMaps == null || includeLookupMaps.equalsIgnoreCase("true"));

            // Check output format.
            outputFormat = outputFormat != null && outputFormat.matches("(?i)^xml$") ? "xml" : "psb";

            returnAttachment(response,
                    "backup." + (cmd.startsWith("full") ? "full" : "partial") + "."
                            + _sdfBackupStamp.format(new Date()) + "." + outputFormat,
                    outputFormat, serializedConfig);
        } else if (cmd.matches("(?i)export_lookup$")) {
            String ns = request.getParameter("ns");
            String outputFormat = request.getParameter("format");
            String serializedConfig = mgr.exportLookup(ns);

            // Check output format.
            outputFormat = outputFormat != null && outputFormat.matches("(?i)^xml$") ? "xml" : "psl";

            returnAttachment(response, "lookup." + (ns == null ? "backup." : "")
                    + _sdfBackupStamp.format(new Date()) + "." + outputFormat, outputFormat, serializedConfig);
        } else if (cmd.matches("(?i)export_condition_set$")) {
            String name = request.getParameter("name");
            String outputFormat = request.getParameter("format");
            String serializedConfig = mgr.exportConditionSet(name);

            // Check output format.
            outputFormat = outputFormat != null && outputFormat.matches("(?i)^xml$") ? "xml" : "psb";

            returnAttachment(
                    response, "conditionSet." + (name == null ? "backup." : "")
                            + _sdfBackupStamp.format(new Date()) + "." + outputFormat,
                    outputFormat, serializedConfig);
        }
    } catch (Exception e) {
        _logger.error(e);
        Http.returnErrorCode(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
    } finally {
        if (mgr != null)
            mgr.close();
    }
}

From source file:dk.netarkivet.viewerproxy.WebProxy.java

/**
 * Generate an appropriate error response when a URI generates an exception. If this fails, it is logged, but
 * otherwise ignored.//from  ww  w.j  av a  2  s. co m
 *
 * @param uri The URI attempted read that could not be found
 * @param response The Response object to write the error response into.
 * @param e the exception generated by the URI
 */
private void createErrorResponse(URI uri, Response response, Throwable e) {
    try {
        // first write a header telling the browser to expect text/html
        response.addHeaderField(CONTENT_TYPE_NAME, CONTENT_TYPE_VALUE);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        // Now flush an errorscreen to the browser
        OutputStream browserOut = response.getOutputStream();
        browserOut.write((HTML_HEADER + "Internal server error for: " + uri + "\n<pre>"
                + ExceptionUtils.getStackTrace(e) + "</pre>" + HTML_FOOTER).getBytes());
        browserOut.flush();
        log.warn("Exception for : " + uri, e);
    } catch (Exception e1) {
        log.warn("Error writing error response to browser " + "for '" + uri + "' with exception "
                + ExceptionUtils.getStackTrace(e) + ". Giving up!", e1);
    }
    // Do not close stream! That is left to the servlet.
}

From source file:org.jbpm.formbuilder.server.EmbedingServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String profile = request.getParameter("profile");
    String usr = request.getParameter("usr");
    String pwd = request.getParameter("pwd");
    TaskDefinitionService taskService = createTaskService(request, usr, pwd);
    FormDefinitionService formService = createFormService(request, usr, pwd);
    FormRepresentationEncoder encoder = FormEncodingFactory.getEncoder();
    JsonObject json = new JsonObject();
    json.addProperty("embedded", profile);
    try {/*from  w  w w  .j ava 2 s.c  om*/
        if (profile != null && "designer".equals(profile)) {
            String userTask = request.getParameter("userTask");
            String processName = request.getParameter("processName");
            String bpmn2Process = IOUtils.toString(request.getReader());
            TaskRef task = taskService.getBPMN2Task(bpmn2Process, processName, userTask);
            if (task != null) {
                //get associated form if it exists
                FormRepresentation form = formService.getAssociatedForm(task.getPackageName(), task);
                if (form != null) {
                    json.addProperty("formjson", encoder.encode(form));
                }
                json.add("task", toJsonObject(task));
                json.addProperty("packageName", task.getPackageName());
            }
        } else {
            throw new Exception("Unknown profile for POST: " + profile);
        }
        request.setAttribute("jsonData", new Gson().toJson(json));
        request.getRequestDispatcher("/FormBuilder.jsp").forward(request, response);
    } catch (TaskServiceException e) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Problem getting task from guvnor");
    } catch (FormServiceException e) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Problem reading form from guvnor");
    } catch (FormEncodingException e) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Problem encoding form");
    } catch (Exception e) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    }
}

From source file:com.google.nigori.server.NigoriServlet.java

/**
 * Send an SC_OK and and empty body//from   w  ww  .j a v a  2s .c  om
 * 
 * @param resp
 * @throws ServletException
 */
private void emptyBody(HttpServletResponse resp) throws ServletException {
    try {
        resp.setContentType(MessageLibrary.MIMETYPE_JSON);
        resp.setStatus(HttpServletResponse.SC_OK);
        resp.flushBuffer();
    } catch (IOException ioe) {
        throw new ServletException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Error attempting to write status OK message after successfully handling a PutRequest");
    }
}