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:io.wcm.caravan.io.http.impl.ribbon.RibbonHttpClientTest.java

@Before
public void setUp() {

    ArchaiusConfig.initialize();//  ww w.  j av  a2s.com
    context.registerInjectActivateService(new SimpleLoadBalancerFactory());
    context.registerInjectActivateService(new LoadBalancerCommandFactory());
    context.registerInjectActivateService(new HttpClientFactoryImpl());
    context.registerInjectActivateService(new ApacheHttpClient());
    client = context.registerInjectActivateService(new RibbonHttpClient());

    defectServer1Host = "localhost:" + defectServer1.port();
    defectServer2Host = "localhost:" + defectServer2.port();
    workingServerHost = "localhost:" + workingServer.port();

    workingServer.stubFor(get(urlEqualTo(HTTP_200_URI)).willReturn(aResponse()
            .withHeader("Content-Type", "text/plain;charset=" + CharEncoding.UTF_8).withBody("success")));
    workingServer.stubFor(
            get(urlEqualTo(HTTP_404_URI)).willReturn(aResponse().withStatus(HttpServletResponse.SC_NOT_FOUND)));

    defectServer1.stubFor(get(urlMatching(".*"))
            .willReturn(aResponse().withStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)));
    defectServer2.stubFor(get(urlMatching(".*"))
            .willReturn(aResponse().withStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)));
}

From source file:com.sastix.cms.server.utils.MultipartFileSender.java

public void serveResource() throws Exception {
    if (response == null || request == null) {
        return;//www  .  j a va 2  s . c om
    }

    Long length = Files.size(filepath);
    String fileName = filepath.getFileName().toString();
    FileTime lastModifiedObj = Files.getLastModifiedTime(filepath);

    if (StringUtils.isEmpty(fileName) || lastModifiedObj == null) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }
    long lastModified = LocalDateTime
            .ofInstant(lastModifiedObj.toInstant(), ZoneId.of(ZoneOffset.systemDefault().getId()))
            .toEpochSecond(ZoneOffset.UTC);

    // Validate request headers for caching ---------------------------------------------------

    // If-None-Match header should contain "*" or ETag. If so, then return 304.
    String ifNoneMatch = request.getHeader("If-None-Match");
    if (ifNoneMatch != null && HttpUtils.matches(ifNoneMatch, fileName)) {
        response.setHeader("ETag", fileName); // Required in 304.
        response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    // If-Modified-Since header should be greater than LastModified. If so, then return 304.
    // This header is ignored if any If-None-Match header is specified.
    long ifModifiedSince = request.getDateHeader("If-Modified-Since");
    if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModified) {
        response.setHeader("ETag", fileName); // Required in 304.
        response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    // Validate request headers for resume ----------------------------------------------------

    // If-Match header should contain "*" or ETag. If not, then return 412.
    String ifMatch = request.getHeader("If-Match");
    if (ifMatch != null && !HttpUtils.matches(ifMatch, fileName)) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    // If-Unmodified-Since header should be greater than LastModified. If not, then return 412.
    long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since");
    if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModified) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    // Validate and process range -------------------------------------------------------------

    // Prepare some variables. The full Range represents the complete file.
    Range full = new Range(0, length - 1, length);
    List<Range> ranges = new ArrayList<>();

    // Validate and process Range and If-Range headers.
    String range = request.getHeader("Range");
    if (range != null) {

        // Range header should match format "bytes=n-n,n-n,n-n...". If not, then return 416.
        if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) {
            response.setHeader("Content-Range", "bytes */" + length); // Required in 416.
            response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
            return;
        }

        String ifRange = request.getHeader("If-Range");
        if (ifRange != null && !ifRange.equals(fileName)) {
            try {
                long ifRangeTime = request.getDateHeader("If-Range"); // Throws IAE if invalid.
                if (ifRangeTime != -1) {
                    ranges.add(full);
                }
            } catch (IllegalArgumentException ignore) {
                ranges.add(full);
            }
        }

        // If any valid If-Range header, then process each part of byte range.
        if (ranges.isEmpty()) {
            for (String part : range.substring(6).split(",")) {
                // Assuming a file with length of 100, the following examples returns bytes at:
                // 50-80 (50 to 80), 40- (40 to length=100), -20 (length-20=80 to length=100).
                long start = Range.sublong(part, 0, part.indexOf("-"));
                long end = Range.sublong(part, part.indexOf("-") + 1, part.length());

                if (start == -1) {
                    start = length - end;
                    end = length - 1;
                } else if (end == -1 || end > length - 1) {
                    end = length - 1;
                }

                // Check if Range is syntactically valid. If not, then return 416.
                if (start > end) {
                    response.setHeader("Content-Range", "bytes */" + length); // Required in 416.
                    response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
                    return;
                }

                // Add range.
                ranges.add(new Range(start, end, length));
            }
        }
    }

    // Prepare and initialize response --------------------------------------------------------

    // Get content type by file name and set content disposition.
    String disposition = "inline";

    // If content type is unknown, then set the default value.
    // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp
    // To add new content types, add new mime-mapping entry in web.xml.
    if (contentType == null) {
        contentType = "application/octet-stream";
    } else if (!contentType.startsWith("image")) {
        // Else, expect for images, determine content disposition. If content type is supported by
        // the browser, then set to inline, else attachment which will pop a 'save as' dialogue.
        String accept = request.getHeader("Accept");
        disposition = accept != null && HttpUtils.accepts(accept, contentType) ? "inline" : "attachment";
    }
    LOG.debug("Content-Type : {}", contentType);
    // Initialize response.
    response.reset();
    response.setBufferSize(DEFAULT_BUFFER_SIZE);
    response.setHeader("Content-Type", contentType);
    response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\"");
    LOG.debug("Content-Disposition : {}", disposition);
    response.setHeader("Accept-Ranges", "bytes");
    response.setHeader("ETag", fileName);
    response.setDateHeader("Last-Modified", lastModified);
    response.setDateHeader("Expires", System.currentTimeMillis() + DEFAULT_EXPIRE_TIME);

    // Send requested file (part(s)) to client ------------------------------------------------

    // Prepare streams.
    try (InputStream input = new BufferedInputStream(Files.newInputStream(filepath));
            OutputStream output = response.getOutputStream()) {

        if (ranges.isEmpty() || ranges.get(0) == full) {

            // Return full file.
            LOG.debug("Return full file");
            response.setContentType(contentType);
            response.setHeader("Content-Range", "bytes " + full.start + "-" + full.end + "/" + full.total);
            response.setHeader("Content-Length", String.valueOf(full.length));
            Range.copy(input, output, length, full.start, full.length);

        } else if (ranges.size() == 1) {

            // Return single part of file.
            Range r = ranges.get(0);
            LOG.debug("Return 1 part of file : from ({}) to ({})", r.start, r.end);
            response.setContentType(contentType);
            response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total);
            response.setHeader("Content-Length", String.valueOf(r.length));
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

            // Copy single part range.
            Range.copy(input, output, length, r.start, r.length);

        } else {

            // Return multiple parts of file.
            response.setContentType("multipart/byteranges; boundary=" + MULTIPART_BOUNDARY);
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

            // Cast back to ServletOutputStream to get the easy println methods.
            ServletOutputStream sos = (ServletOutputStream) output;

            // Copy multi part range.
            for (Range r : ranges) {
                LOG.debug("Return multi part of file : from ({}) to ({})", r.start, r.end);
                // Add multipart boundary and header fields for every range.
                sos.println();
                sos.println("--" + MULTIPART_BOUNDARY);
                sos.println("Content-Type: " + contentType);
                sos.println("Content-Range: bytes " + r.start + "-" + r.end + "/" + r.total);

                // Copy single part range of multi part range.
                Range.copy(input, output, length, r.start, r.length);
            }

            // End with multipart boundary.
            sos.println();
            sos.println("--" + MULTIPART_BOUNDARY + "--");
        }
    }

}

From source file:com.wso2telco.workflow.api.WorkflowHistoryAPI.java

@GET
@Path("/subscribers")
@Produces(MediaType.APPLICATION_JSON)// w  w w .j a va  2 s . c om
public Response getAllSubscribers() {
    String jsonPayload;
    try {
        List<String> subscribers = SbHostObjectUtils.getAllSubscribers();
        jsonPayload = new Gson().toJson(subscribers);
    } catch (Exception e) {
        log.error(e);
        return Response.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).build();
    }
    return Response.status(HttpServletResponse.SC_OK).entity(jsonPayload).build();
}

From source file:fi.vm.kapa.identification.testservice.TestServiceAuthenticated.java

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

    Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);
    cfg.setDirectoryForTemplateLoading(new File("/opt/templates"));
    cfg.setDefaultEncoding("UTF-8");
    cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
    cfg.setLogTemplateExceptions(false);

    Map<String, String> values = new HashMap<>();
    putIfNotBlank(values, "KAPA_HETU", convertASCIItoUTF8(request.getHeader("nationalIdentificationNumber")));
    putIfNotBlank(values, "KAPA_ETUNIMET", convertASCIItoUTF8(request.getHeader("FirstName")));
    putIfNotBlank(values, "KAPA_SUKUNIMI", convertASCIItoUTF8(request.getHeader("sn")));
    putIfNotBlank(values, "KAPA_PERSON_IDENTIFIER", convertASCIItoUTF8(request.getHeader("PersonIdentifier")));
    putIfNotBlank(values, "KAPA_DATE_OF_BIRTH", convertASCIItoUTF8(request.getHeader("DateOfBirth")));
    putIfNotBlank(values, "KAPA_FAMILY_NAME", convertASCIItoUTF8(request.getHeader("FamilyName")));
    putIfNotBlank(values, "KAPA_KATU",
            convertASCIItoUTF8(request.getHeader("VakinainenKotimainenLahiosoiteS")));
    putIfNotBlank(values, "KAPA_POSTINUMERO",
            convertASCIItoUTF8(request.getHeader("VakinainenKotimainenLahiosoitePostinumero")));
    putIfNotBlank(values, "KAPA_PTP",
            convertASCIItoUTF8(request.getHeader("VakinainenKotimainenLahiosoitePostitoimipaikkaS")));
    putIfNotBlank(values, "KAPA_TOKEN", convertASCIItoUTF8(request.getHeader("authenticationToken")));

    Template output = cfg.getTemplate("tunnistautunut.ftlh");

    response.setCharacterEncoding("UTF-8");

    try {/*from   w ww .j  ava  2s.c om*/
        output.process(values, response.getWriter());
        response.setStatus(HttpServletResponse.SC_OK);
    } catch (TemplateException e) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }

    response.getWriter().flush();
    response.getWriter().close();
}

From source file:com.openmeap.admin.web.servlet.WebViewServlet.java

@SuppressWarnings("unchecked")
@Override/*from  w  w w .  j  a  v a2 s.c  o  m*/
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {

    logger.trace("in service");

    ModelManager mgr = getModelManager();
    GlobalSettings settings = mgr.getGlobalSettings();
    String validTempPath = settings.validateTemporaryStoragePath();
    if (validTempPath != null) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, validTempPath);
    }

    String pathInfo = request.getPathInfo();
    String[] pathParts = pathInfo.split("[/]");
    if (pathParts.length < 4) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    }
    String remove = pathParts[1] + "/" + pathParts[2] + "/" + pathParts[3];
    String fileRelative = pathInfo.replace(remove, "");

    String applicationNameString = URLDecoder.decode(pathParts[APP_NAME_INDEX], FormConstants.CHAR_ENC_DEFAULT);
    String archiveHash = URLDecoder.decode(pathParts[APP_VER_INDEX], FormConstants.CHAR_ENC_DEFAULT);

    Application app = mgr.getModelService().findApplicationByName(applicationNameString);
    ApplicationArchive arch = mgr.getModelService().findApplicationArchiveByHashAndAlgorithm(app, archiveHash,
            "MD5");

    String authSalt = app.getProxyAuthSalt();
    String authToken = URLDecoder.decode(pathParts[AUTH_TOKEN_INDEX], FormConstants.CHAR_ENC_DEFAULT);

    try {
        if (!AuthTokenProvider.validateAuthToken(authSalt, authToken)) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
        }
    } catch (DigestException e1) {
        throw new GenericRuntimeException(e1);
    }

    File fileFull = new File(
            arch.getExplodedPath(settings.getTemporaryStoragePath()).getAbsolutePath() + "/" + fileRelative);
    try {
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        String mimeType = fileNameMap.getContentTypeFor(fileFull.toURL().toString());
        response.setContentType(mimeType);
        response.setContentLength(Long.valueOf(fileFull.length()).intValue());

        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            //response.setStatus(HttpServletResponse.SC_FOUND);
            inputStream = new FileInputStream(fileFull);
            outputStream = response.getOutputStream();
            Utils.pipeInputStreamIntoOutputStream(inputStream, outputStream);
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
            response.getOutputStream().flush();
            response.getOutputStream().close();
        }
    } catch (FileNotFoundException e) {
        logger.error("Exception {}", e);
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    } catch (IOException ioe) {
        logger.error("Exception {}", ioe);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:com.liangc.hq.base.web.AvailabilityServlet.java

protected void sendErrorIcon(HttpServletRequest request, HttpServletResponse response) {
    try {//from  w  w w  .j a  va  2 s  .  c  o  m
        sendIcon(request, response, ICON_ERR_URL);
        return;
    } catch (Exception e) {
        log.debug("can't send error icon: ");
    }

    // if we made it this far, we can't even get the error icon
    // sent. bail out with an internal server error.

    try {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.flushBuffer();
    } catch (IOException e) {
        log.debug("can't commit server error response !? ");
    }
}

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

@Override
protected void doGet(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 {/* www  .j a v a2 s  .  c om*/
        if (profile != null && "guvnor".equals(profile)) {
            String uuid = request.getParameter("uuid");
            String packageName = taskService.getContainingPackage(uuid);
            FormRepresentation form = formService.getFormByUUID(packageName, uuid);
            json.addProperty("uuid", uuid);
            json.addProperty("packageName", packageName);
            if (form != null) {
                json.addProperty("formjson", encoder.encode(form));
            }
        } else {
            throw new Exception("Unknown profile for GET: " + 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.epam.wilma.extras.shortcircuit.ShortCircuitResponseInformationFileHandler.java

/**
 * Saves the map to a folder, to preserve it for later use.
 *
 * @param httpServletResponse is the response object
 * @return with the response body - that is a json info about the result of the call
 *///from w  w w  .j av  a2 s.  c  o  m
String savePreservedMessagesFromMap(String path, FileFactory fileFactory,
        FileOutputStreamFactory fileOutputStreamFactory, HttpServletResponse httpServletResponse) {
    String response = null;
    String filenamePrefix = "sc" + UniqueIdGenerator.getNextUniqueId() + "_";
    if (!SHORT_CIRCUIT_MAP.isEmpty()) {
        String[] keySet = SHORT_CIRCUIT_MAP.keySet().toArray(new String[SHORT_CIRCUIT_MAP.size()]);
        for (String entryKey : keySet) {
            ShortCircuitResponseInformation information = SHORT_CIRCUIT_MAP.get(entryKey);
            if (information != null) { //save only the cached files
                //save this into file, folder is in folder variable
                String filename = path + filenamePrefix + UniqueIdGenerator.getNextUniqueId() + ".json";
                File file = fileFactory.createFile(filename);
                try {
                    saveMapObject(fileOutputStreamFactory, file, entryKey, information);
                } catch (IOException e) {
                    String message = "Cache save failed at file: " + filename + ", with message: "
                            + e.getLocalizedMessage();
                    logger.info("ShortCircuit: " + message);
                    response = "{ \"resultsFailure\": \"" + message + "\" }";
                    httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    break;
                }
            }
        }
    }
    if (response == null) {
        String message = "Cache saved as: " + path + filenamePrefix + "*.json files";
        response = "{ \"resultsSuccess\": \"" + message + "\" }";
        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
        logger.info("ShortCircuit: " + message);
    }
    return response;
}

From source file:ge.taxistgela.servlet.RegistrationServlet.java

public void registerDriver(HttpServletRequest request, HttpServletResponse response) throws IOException {
    if (!verify(request, response))
        return;//from   w  w  w  .ja  va  2s  .  co m

    DriverManagerAPI driverManager = (DriverManagerAPI) request.getServletContext()
            .getAttribute(DriverManagerAPI.class.getName());
    CompanyManagerAPI companyManager = (CompanyManagerAPI) request.getServletContext()
            .getAttribute(CompanyManagerAPI.class.getName());

    DriverPreference driverPreference = new DriverPreference(-1, 0.1, 0.0);

    ErrorCode code = driverManager.insertDriverPreference(driverPreference);
    if (code.errorAccrued()) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    Car car = new Car(RandomStringUtils.randomAlphanumeric(7), "Untitled", 1900, false, 0);

    code = driverManager.insertCar(car);
    if (code.errorAccrued()) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }
    Integer companyID = null;
    if (request.getParameter("drivercompanyCode") != "") {
        companyID = companyManager.getCompanyIDByCode(request.getParameter("drivercompanyCode"));
        if (companyID == null) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }
    }

    Driver driver = new Driver(-1, request.getParameter("driverpersonalID"),
            request.getParameter("driveremail"), request.getParameter("driverpassword"), null,
            request.getParameter("driverfirstName"), request.getParameter("driverlastName"),
            getGender(request.getParameter("drivergender")), request.getParameter("driverphoneNumber"), car,
            filterSocialID(request.getParameter("driverfacebookId")),
            filterSocialID(request.getParameter("drivergoogleplusId")), 5.0, driverPreference, false, false,
            false);

    registerSuper(driverManager, driver, request, response);

    if (response.getStatus() == HttpServletResponse.SC_CREATED) {
        Company company = (Company) companyManager.getByID(companyID);
        driver = (Driver) driverManager.getByEmail(driver.getEmail());

        if (company != null && driver != null) {
            EmailSender.verifyCompany(driver, company);
        }
    }
}

From source file:eu.trentorise.smartcampus.mobility.controller.rest.OTPController.java

@RequestMapping(method = RequestMethod.GET, value = "/getroutes/{agencyId}")
public @ResponseBody void getRoutes(HttpServletResponse response, @PathVariable String agencyId)
        throws Exception {
    try {/*from  w w  w.j a v  a  2s  .  c o m*/
        //String address =  otpURL + OTP + "getroutes/" + agencyId;
        //String routes = HTTPConnector.doGet(address, null, null, MediaType.APPLICATION_JSON, "UTF-8");
        String routes = smartPlannerHelper.routes(agencyId);

        logger.info("-" + getUserId() + "~AppConsume~routes=" + agencyId);

        response.setContentType("application/json; charset=utf-8");
        response.getWriter().write(routes);

    } catch (ConnectorException e0) {
        response.setStatus(e0.getCode());
    } catch (Exception e) {
        e.printStackTrace();
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}