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:cf.spring.servicebroker.ServiceBrokerHandler.java

@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (!authenticator.authenticate(request, response)) {
        return;//from ww w  .j a  va2 s.  c  o m
    }
    ApiVersionValidator.validateApiVersion(request);
    try {
        response.setContentType(Constants.JSON_CONTENT_TYPE);
        final Matcher matcher = URI_PATTERN.matcher(request.getRequestURI());
        if (!matcher.matches()) {
            throw new NotFoundException("Resource not found");
        }
        final String instanceId = matcher.group(1);
        final String bindingId = matcher.group(3);
        if ("put".equalsIgnoreCase(request.getMethod())) {
            if (bindingId == null) {
                final ProvisionBody provisionBody = mapper.readValue(request.getInputStream(),
                        ProvisionBody.class);
                final String serviceId = provisionBody.getServiceId();
                final BrokerServiceAccessor accessor = getServiceAccessor(serviceId);
                final ProvisionRequest provisionRequest = new ProvisionRequest(UUID.fromString(instanceId),
                        provisionBody.getPlanId(), provisionBody.getOrganizationGuid(),
                        provisionBody.getSpaceGuid());
                final ProvisionResponse provisionResponse = accessor.provision(provisionRequest);
                if (provisionResponse.isCreated()) {
                    response.setStatus(HttpServletResponse.SC_CREATED);
                }
                mapper.writeValue(response.getOutputStream(), provisionResponse);
            } else {
                final BindBody bindBody = mapper.readValue(request.getInputStream(), BindBody.class);
                final String serviceId = bindBody.getServiceId();
                final BrokerServiceAccessor accessor = getServiceAccessor(serviceId);

                final BindRequest bindRequest = new BindRequest(UUID.fromString(instanceId),
                        UUID.fromString(bindingId), bindBody.applicationGuid, bindBody.getPlanId());
                final BindResponse bindResponse = accessor.bind(bindRequest);
                if (bindResponse.isCreated()) {
                    response.setStatus(HttpServletResponse.SC_CREATED);
                }
                mapper.writeValue(response.getOutputStream(), bindResponse);
            }
        } else if ("delete".equalsIgnoreCase(request.getMethod())) {
            final String serviceId = request.getParameter(SERVICE_ID_PARAM);
            final String planId = request.getParameter(PLAN_ID_PARAM);
            final BrokerServiceAccessor accessor = getServiceAccessor(serviceId);
            try {
                if (bindingId == null) {
                    // Deprovision
                    final DeprovisionRequest deprovisionRequest = new DeprovisionRequest(
                            UUID.fromString(instanceId), planId);
                    accessor.deprovision(deprovisionRequest);
                } else {
                    // Unbind
                    final UnbindRequest unbindRequest = new UnbindRequest(UUID.fromString(bindingId),
                            UUID.fromString(instanceId), planId);
                    accessor.unbind(unbindRequest);
                }
            } catch (MissingResourceException e) {
                response.setStatus(HttpServletResponse.SC_GONE);
            }
            response.getWriter().write("{}");
        } else {
            response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        }
    } catch (ConflictException e) {
        response.setStatus(HttpServletResponse.SC_CONFLICT);
        response.getWriter().write("{}");
    } catch (ServiceBrokerException e) {
        LOGGER.warn("An error occurred processing a service broker request", e);
        response.setStatus(e.getHttpResponseCode());
        mapper.writeValue(response.getOutputStream(), new ErrorBody(e.getMessage()));
    } catch (Throwable e) {
        LOGGER.error(e.getMessage(), e);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        mapper.writeValue(response.getOutputStream(), new ErrorBody(e.getMessage()));
    }
}

From source file:com.sap.dirigible.runtime.registry.RegistryServlet.java

@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {

    String repositoryPath = null;
    final String requestPath = request.getPathInfo();
    boolean deep = false;
    if (requestPath == null) {
        deep = true;/*ww  w.  j av  a2s .c o  m*/
    }
    final OutputStream out = response.getOutputStream();
    try {
        repositoryPath = extractRepositoryPath(request);
        final IEntity entity = getEntity(repositoryPath, request);
        byte[] data;
        if (entity != null) {
            if (entity instanceof IResource) {
                data = buildResourceData(entity, request, response);
            } else if (entity instanceof ICollection) {
                String collectionPath = request.getRequestURI().toString();
                String acceptHeader = request.getHeader(ACCEPT_HEADER);
                if (acceptHeader != null && acceptHeader.contains(JSON)) {
                    if (!collectionPath.endsWith(IRepository.SEPARATOR)) {
                        collectionPath += IRepository.SEPARATOR;
                    }
                    data = buildCollectionData(deep, entity, collectionPath);
                } else {
                    // welcome file support
                    IResource index = ((ICollection) entity).getResource(INDEX_HTML);
                    if (index.exists() && (collectionPath.endsWith(IRepository.SEPARATOR))) {
                        data = buildResourceData(index, request, response);
                    } else {
                        // listing of collections is forbidden
                        exceptionHandler(response, repositoryPath, HttpServletResponse.SC_FORBIDDEN,
                                LISTING_OF_FOLDERS_IS_FORBIDDEN);
                        return;
                    }
                }
            } else {
                exceptionHandler(response, repositoryPath, HttpServletResponse.SC_FORBIDDEN,
                        LISTING_OF_FOLDERS_IS_FORBIDDEN);
                return;
            }
        } else {
            exceptionHandler(response, repositoryPath, HttpServletResponse.SC_NOT_FOUND,
                    String.format("Resource at [%s] does not exist", requestPath));
            return;
        }

        if (entity instanceof IResource) {
            final IResource resource = (IResource) entity;
            String mimeType = null;
            String extension = ContentTypeHelper.getExtension(resource.getName());
            if ((mimeType = ContentTypeHelper.getContentType(extension)) != null) {
                response.setContentType(mimeType);
            } else {
                response.setContentType(resource.getContentType());
            }
        }
        sendData(out, data);
    } catch (final IllegalArgumentException ex) {
        exceptionHandler(response, repositoryPath, HttpServletResponse.SC_BAD_REQUEST, ex.getMessage());
    } catch (final MissingResourceException ex) {
        exceptionHandler(response, repositoryPath, HttpServletResponse.SC_NO_CONTENT, ex.getMessage());
    } catch (final RuntimeException ex) {
        exceptionHandler(response, repositoryPath, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                ex.getMessage());
    } finally {
        out.flush();
        out.close();
    }
}

From source file:org.apache.servicemix.http.security.HttpSecurityTest.java

public void testWSSecUnkownUser() throws Exception {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    FileUtil.copyInputStream(getClass().getResourceAsStream("request-uu.xml"), out);
    String request = out.toString();
    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod("http://localhost:8192/WSSec/");
    try {//w ww. ja va 2s.c  o m
        method.setDoAuthentication(true);
        method.setRequestEntity(new StringRequestEntity(request));
        int state = client.executeMethod(method);
        String str = method.getResponseBodyAsString();
        log.info(str);
        assertEquals(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, state);
        Element e = new SourceTransformer().toDOMElement(new StringSource(str));
        assertEquals("Envelope", e.getLocalName());
        e = (Element) e.getFirstChild();
        assertEquals("Body", e.getLocalName());
        e = (Element) e.getFirstChild();
        assertEquals("Fault", e.getLocalName());
    } finally {
        method.releaseConnection();
    }
}

From source file:com.app.inventario.controlador.Controlador.java

@RequestMapping(value = "/agregar-proveedor", method = RequestMethod.POST)
public @ResponseBody Map agregarProveedor(@ModelAttribute("proveedor") Proveedor proveedor,
        HttpServletRequest request, HttpServletResponse response) {
    Map map = new HashMap();
    try {//from   ww w  . jav  a 2  s . c  o m
        proveedorServicio.guardar(proveedor);
        response.setStatus(HttpServletResponse.SC_OK);
        map.put("Status", "OK");
        map.put("Message", "Agregado Correctamente");
    } catch (Exception ex) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        map.put("Status", "FAIL");
        map.put("Message", ex.getCause().getCause().getCause().getMessage());
    }
    return map;
}

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

private void registerSuper(SuperUserManager man, SuperDaoUser obj, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    SmsQueue smsQueue = (SmsQueue) request.getServletContext().getAttribute(SmsQueue.class.getName());

    if (man == null || smsQueue == null) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } else {//ww  w. j  a  v  a  2s. c o m

        ErrorCode errorCode = new ErrorCode();

        errorCode.union(man.register(obj));

        if (errorCode.errorNotAccrued()) {
            response.setStatus(HttpServletResponse.SC_CREATED);

            EmailSender.verifyEmail(obj);

            smsQueue.addSms(obj);

            return;
        }

        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.getWriter().print(errorCode.toJson());
    }
}

From source file:com.zimbra.cs.service.admin.StatsImageServlet.java

public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    AuthToken authToken = getAdminAuthTokenFromCookie(req, resp);
    if (authToken == null)
        return;//  w w  w .j a va  2  s  .c o  m

    String imgName = null;
    InputStream is = null;
    boolean imgAvailable = true;
    boolean localServer = false;
    boolean systemWide = false;

    String serverAddr = "";

    String noDefaultImg = req.getParameter("nodef");
    boolean noDefault = false;
    if (noDefaultImg != null && !noDefaultImg.equals("") && noDefaultImg.equals("1")) {
        noDefault = true;
    }
    String reqPath = req.getRequestURI();
    try {

        //check if this is the logger host, otherwise proxy the request to the logger host 
        String serviceHostname = Provisioning.getInstance().getLocalServer()
                .getAttr(Provisioning.A_zimbraServiceHostname);
        String logHost = Provisioning.getInstance().getConfig().getAttr(Provisioning.A_zimbraLogHostname);
        if (!serviceHostname.equalsIgnoreCase(logHost)) {
            StringBuffer url = new StringBuffer("https");
            url.append("://").append(logHost).append(':').append(LC.zimbra_admin_service_port.value());
            url.append(reqPath);
            String queryStr = req.getQueryString();
            if (queryStr != null)
                url.append('?').append(queryStr);

            // create an HTTP client with the same cookies
            HttpState state = new HttpState();
            try {
                state.addCookie(new org.apache.commons.httpclient.Cookie(logHost,
                        ZimbraCookie.COOKIE_ZM_ADMIN_AUTH_TOKEN, authToken.getEncoded(), "/", null, false));
            } catch (AuthTokenException ate) {
                throw ServiceException.PROXY_ERROR(ate, url.toString());
            }
            HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
            client.setState(state);
            GetMethod get = new GetMethod(url.toString());
            try {
                int statusCode = HttpClientUtil.executeMethod(client, get);
                if (statusCode != HttpStatus.SC_OK)
                    throw ServiceException.RESOURCE_UNREACHABLE(get.getStatusText(), null);

                resp.setContentType("image/gif");
                ByteUtil.copy(get.getResponseBodyAsStream(), true, resp.getOutputStream(), false);
                return;
            } catch (HttpException e) {
                throw ServiceException.RESOURCE_UNREACHABLE(get.getStatusText(), e);
            } catch (IOException e) {
                throw ServiceException.RESOURCE_UNREACHABLE(get.getStatusText(), e);
            } finally {
                get.releaseConnection();
            }
        }
    } catch (Exception ex) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Image not found");
        return;
    }
    try {

        if (reqPath == null || reqPath.length() == 0) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }

        if (mLog.isDebugEnabled())
            mLog.debug("received request to:(" + reqPath + ")");

        String reqParts[] = reqPath.split("/");

        String reqFilename = reqParts[3];
        imgName = LC.stats_img_folder.value() + File.separator + reqFilename;
        try {
            is = new FileInputStream(imgName);
        } catch (FileNotFoundException ex) {//unlikely case - only if the server's files are broken
            if (is != null)
                is.close();
            if (!noDefault) {
                imgName = LC.stats_img_folder.value() + File.separator + IMG_NOT_AVAIL;
                is = new FileInputStream(imgName);

            } else {
                resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Image not found");
                return;
            }
        }
    } catch (Exception ex) {
        if (is != null)
            is.close();

        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "FNF image File not found");
        return;
    }
    resp.setContentType("image/gif");
    ByteUtil.copy(is, true, resp.getOutputStream(), false);
}

From source file:de.xwic.appkit.core.remote.server.RemoteDataAccessServlet.java

/**
 * @param req//from w w  w .jav  a  2 s.com
 * @param resp
 * @throws IOException
 */
private void handleRequest(final HttpServletRequest req, final HttpServletResponse resp) throws IOException {
    //      This method can be called repeatedly to change the character encoding.
    //      This method has no effect if it is called after getWriter has been called or after
    //      the response has been committed.
    resp.setContentType("text/xml; charset=UTF-8");

    try {
        IParameterProvider pp = new ParameterProvider(req);

        // the API is taking its arguments from the URL and the parameters
        final String action = pp.getParameter(PARAM_ACTION);

        if (action == null || action.isEmpty()) {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Missing Parameters");
            return;
        }

        IRequestHandler handler = handlers.get(action);

        if (handler != null) {

            handler.handle(pp, resp);

        } else {
            // all responses will now basically be an XML document, so we can do some preparations
            PrintWriter pwOut = null;

            if (useCompression
                    && (action.equals(ACTION_GET_ENTITIES) || action.equals(ACTION_GET_COLLECTION))) {
                pwOut = new PrintWriter(new GZIPOutputStream(resp.getOutputStream()));
                resp.setHeader("Content-Encoding", "gzip");
            } else {
                pwOut = resp.getWriter();
            }

            String entityType = req.getParameter(PARAM_ENTITY_TYPE);
            assertValue(entityType, "Entity Type not specified");

            if (action.equals(ACTION_GET_ENTITY)) {
                handleGetEntity(entityType, req, resp, pwOut);

            } else if (action.equals(ACTION_GET_ENTITIES)) {
                handleGetEntities(entityType, req, resp, pwOut);

            } else if (action.equals(ACTION_UPDATE_ENTITY)) {
                handleUpdateEntity(entityType, req, resp, pwOut);

            } else if (action.equals(ACTION_GET_COLLECTION)) {
                handleGetCollection(entityType, req, resp, pwOut);

            } else if (action.equals(ACTION_DELETE) || action.equals(ACTION_SOFT_DELETE)) {
                handleDelete(entityType, req, resp, pwOut, action.equals(ACTION_SOFT_DELETE));

            } else {
                throw new IllegalArgumentException("Unknown action");
            }

            pwOut.flush();
            pwOut.close();
        }

    } catch (Exception e) {
        log.error(e.getMessage(), e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
    }

}

From source file:com.controlj.green.modstat.servlets.LongRunning.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {//w ww.ja  v a 2 s.  c o  m
        String actionString = req.getParameter(PARAM_ACTION);
        if (actionString == null || actionString.isEmpty()) {
            throw new ServletException("Missing parameter: action");
        }
        if (actionString.equals(ACTION_START)) {
            String processString = req.getParameter(PARAM_PROCESS);
            if (processString == null || processString.isEmpty()) {
                throw new ServletException("Missing parameter: process");
            }

            RunnableProgress oldWork = (RunnableProgress) req.getSession().getAttribute(ATTRIB_WORK);
            if (oldWork != null) {
                oldWork.interrupt();
            }
            /*
            if (processString.equals(PROCESS_TIMER)) {
                    
            TestWork work = new TestWork();
            req.getSession().setAttribute(ATTRIB_WORK, work);
            work.start();
            } else
            */
            if (processString.equals(PROCESS_MODSTAT)) {
                String idString = req.getParameter(PARAM_ID);
                if (idString == null || idString.isEmpty()) {
                    throw new ServletException("Missing parameter: id");
                }

                SystemConnection connection = null;
                try {
                    connection = DirectAccess.getDirectAccess().getUserSystemConnection(req);
                } catch (InvalidConnectionRequestException e) {
                    throw new ServletException("Error getting connection:" + e.getMessage());
                }
                RunnableProgress work;
                if (test) {
                    work = new TestWork(getFileInWebApp(TEST_SOURCE));
                } else {
                    work = new ModstatWork(connection, idString);
                }
                req.getSession().setAttribute(ATTRIB_WORK, work);
                work.start();
            } else {
                throw new ServletException("Unknown process:" + processString);
            }
        } else if (actionString.equals(ACTION_STATUS)) {
            RunnableProgress work = (RunnableProgress) req.getSession().getAttribute("work");
            JSONObject result = new JSONObject();
            resp.setContentType("application/json");
            String errorMessage = null;
            int percent = 0;
            boolean stopped = false;

            if (work == null) {
                throw new ServletException("Can't get status, nothing started");
            } else if (work.hasError()) {
                throw new ServletException(work.getError().getMessage());
            } else {
                if (work.isAlive()) {
                    percent = work.getProgress();
                } else {
                    percent = 100;
                    stopped = true;
                }
            }
            try {
                result.put("percent", percent);
                result.put("stopped", stopped);
                if (errorMessage != null) {
                    result.put("error", errorMessage);
                }

                result.write(resp.getWriter());
            } catch (JSONException e) {
                throw new ServletException("Error writing result:" + e.getMessage());
            }
        }
    } catch (ServletException e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        System.err.println("Add-On Error in " + AddOnInfo.getAddOnInfo().getName() + ":" + e.getMessage());
        e.printStackTrace(new PrintWriter(System.err));
    }
}

From source file:eu.trentorise.smartcampus.profileservice.controllers.rest.ExtendedProfileController.java

/**
 * Returns extended profile of an authenticate user given application and
 * profileId//from   www.j a v a 2s.c o  m
 * 
 * @param request
 * @param response
 * @param session
 * @param profileId
 * @return
 * @throws IOException
 * @throws ProfileServiceException
 */
@RequestMapping(method = RequestMethod.GET, value = "/extprofile/me/{profileId:.*}")
public @ResponseBody ExtendedProfile getMyExtendedProfile(HttpServletRequest request,
        HttpServletResponse response, HttpSession session, @PathVariable("profileId") String profileId)
        throws IOException, ProfileServiceException {
    try {
        String userId = getUserId();

        return storage.findExtendedProfile(userId, profileId);

    } catch (Exception e) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return null;
    }
}

From source file:org.dataconservancy.ui.api.CollectionController.java

@RequestMapping(value = "/{idpart}", method = RequestMethod.GET)
public void handleCollectionGetRequest(@RequestHeader(value = "Accept", required = false) String mimeType,
        @RequestHeader(value = "If-Match", required = false) String ifMatch,
        @RequestHeader(value = "If-None-Match", required = false) String ifNoneMatch,
        @RequestHeader(value = "If-Modified-Since", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Date modifiedSince,
        HttpServletRequest request, HttpServletResponse response)
        throws IOException, ArchiveServiceException, BizPolicyException, BizInternalException {

    // Check to see if the user is authenticated (TODO: Spring Security should be responsible for this)
    // Note that the fact that the user has to be authenticated, and further authorized, is a policy decision,
    // but the pattern for the Project and Person controllers is that the Controller has handled this.
    final Person authenticatedUser = getAuthenticatedUser();

    // Rudimentary Accept Header handling; accepted values are */*, application/*, application/xml,
    // application/octet-stream
    if (mimeType != null && !(mimeType.contains(APPLICATION_XML) || mimeType.contains(ACCEPT_WILDCARD)
            || mimeType.contains(ACCEPT_APPLICATION_WILDCARD) || mimeType.contains(ACCEPT_OCTET_STREAM))) {
        response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE,
                "Unacceptable value for 'Accept' header: '" + mimeType + "'");
        return;/* w w w .  j  a  v  a 2 s  .  c o m*/
    }

    // Resolve the Request URL to the ID of the Collection (in this case URL == ID)
    String collectionId = requestUtil.buildRequestUrl(request);

    if (collectionId == null || collectionId.trim().isEmpty()) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    // Get the Collection
    final Collection collection = getCollection(collectionId);

    // Calculate the ETag for the Collection, may be null.
    final String etag;
    if (collection != null) {
        etag = calculateEtag(collection);
    } else {
        etag = null;
    }

    // Handle the 'If-Match' header first; RFC 2616 14.24
    if (this.responseHeaderUtil.handleIfMatch(request, response, this.requestUtil, ifMatch, collection, etag,
            collectionId, "Collection")) {
        return;
    }

    final DateTime lastModified;
    if (collection != null) {
        lastModified = getLastModified(collection.getId());
    } else {
        lastModified = null;
    }

    // Handle the 'If-None-Match' header; RFC 2616 14.26
    if (this.responseHeaderUtil.handleIfNoneMatch(request, response, ifNoneMatch, collection, etag,
            collectionId, lastModified, modifiedSince)) {
        return;
    }

    if (collection == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // Handle the 'If-Modified-Since' header; RFC 2616 14.26
    if (this.responseHeaderUtil.handleIfModifiedSince(request, response, modifiedSince, lastModified)) {
        return;
    }

    // Check to see if the user is authorized
    if (!authzService.canRetrieveCollection(authenticatedUser, collection)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    // Compose the Business Object Package
    Bop businessPackage = new Bop();
    businessPackage.addCollection(collection);

    // Serialize the package to an output stream
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    bob.buildBusinessObjectPackage(businessPackage, out);
    out.close();

    this.responseHeaderUtil.setResponseHeaderFields(response, etag, out, lastModified);

    // Send the Response
    final ServletOutputStream servletOutputStream = response.getOutputStream();
    IOUtils.copy(new ByteArrayInputStream(out.toByteArray()), servletOutputStream);
    servletOutputStream.flush();
    servletOutputStream.close();
}