Example usage for javax.servlet.http HttpServletResponse SC_NOT_IMPLEMENTED

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

Introduction

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

Prototype

int SC_NOT_IMPLEMENTED

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

Click Source Link

Document

Status code (501) indicating the HTTP server does not support the functionality needed to fulfill the request.

Usage

From source file:org.openrepose.filters.clientauth.openstack.OpenStackAuthenticationHandler.java

@Override
public FilterDirector processResponse(ReadableHttpServletResponse response) {
    LOG.debug("Handling service response in OpenStack auth filter.");
    final int responseStatus = response.getStatus();
    LOG.debug("Incoming response code is " + responseStatus);
    final FilterDirector myDirector = new FilterDirectorImpl();
    myDirector.setResponseStatusCode(responseStatus);
    myDirector.setFilterAction(FilterAction.PASS);

    /// The WWW Authenticate header can be used to communicate to the client
    // (since we are a proxy) how to correctly authenticate itself
    final String wwwAuthenticateHeader = response.getHeader(CommonHttpHeader.WWW_AUTHENTICATE.toString());

    switch (response.getStatus()) {
    // NOTE: We should only mutate the WWW-Authenticate header on a
    // 401 (unauthorized) or 403 (forbidden) response from the origin service
    case HttpServletResponse.SC_UNAUTHORIZED:
    case HttpServletResponse.SC_FORBIDDEN:
        // If in the case that the origin service supports delegated authentication
        // we should then communicate to the client how to authenticate with us
        if (delegatingMode) {
            myDirector.responseHeaderManager().appendHeader(CommonHttpHeader.WWW_AUTHENTICATE.toString(),
                    wwwAuthHeaderContents);
        } else {//from  ww  w . j  a va  2 s .  c o m
            // In the case where authentication has failed and we are not in delegating mode,
            //  this means that our own authentication with the origin service has failed
            // and must then be communicated as a 500 (internal server error) to the client
            myDirector.setResponseStatusCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
        break;
    case HttpServletResponse.SC_NOT_IMPLEMENTED:
        if (!StringUtils.isBlank(wwwAuthenticateHeader) && wwwAuthenticateHeader.contains(DELEGATED)) {
            myDirector.setResponseStatusCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            LOG.error(
                    "Repose authentication component is configured as delegetable but origin service does not support delegated mode.");
        } else {
            myDirector.setResponseStatusCode(HttpServletResponse.SC_NOT_IMPLEMENTED);
        }
        break;

    default:
        break;
    }

    LOG.debug("Outgoing response code is " + myDirector.getResponseStatusCode());
    return myDirector;
}

From source file:org.sakaiproject.lti2.LTI2Service.java

@SuppressWarnings("unchecked")
protected void doRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String ipAddress = request.getRemoteAddr();
    M_log.debug("LTI Service request from IP=" + ipAddress);

    String rpi = request.getPathInfo();
    String uri = request.getRequestURI();
    String[] parts = uri.split("/");
    if (parts.length < 4) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, null, "Incorrect url format", null);
        return;//from  w  w w.  ja  v a 2 s.  c o  m
    }
    String controller = parts[3];
    if (SVC_tc_profile.equals(controller) && parts.length == 5) {
        String profile_id = parts[4];
        getToolConsumerProfile(request, response, profile_id);
        return;
    } else if (SVC_tc_registration.equals(controller) && parts.length == 5) {
        String profile_id = parts[4];
        registerToolProviderProfile(request, response, profile_id);
        return;
    } else if (SVC_Result.equals(controller) && parts.length == 5) {
        String sourcedid = parts[4];
        handleResultRequest(request, response, sourcedid);
        return;
    } else if (SVC_Settings.equals(controller) && parts.length >= 6) {
        handleSettingsRequest(request, response, parts);
        return;
    }

    IMSJSONRequest jsonRequest = new IMSJSONRequest(request);
    if (jsonRequest.valid) {
        System.out.println(jsonRequest.getPostBody());
    }

    response.setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED);
    M_log.warn("Unknown request=" + uri);
    doErrorJSON(request, response, null, "Unknown request=" + uri, null);
}

From source file:org.occiware.mart.servlet.impl.ServletEntry.java

public HttpServletResponse buildInputDatas() {

    String contextRoot = serverURI.toString();
    LOGGER.debug("Context root : " + contextRoot);
    LOGGER.debug("URI relative path: " + path);

    // Load the parsers.
    // check content-type header.
    contentType = headers.getFirst(Constants.HEADER_CONTENT_TYPE);
    acceptType = headers.getFirst(Constants.HEADER_ACCEPT); // TODO : add support for uri-list combined with other type rendering.

    if (acceptType == null) {
        acceptType = contentType;/*from  www. j  av a  2  s  .c  o m*/
    }
    // Default values.
    if (contentType == null || contentType.isEmpty()) {
        contentType = Constants.MEDIA_TYPE_JSON;
    }
    if (acceptType == null || acceptType.isEmpty() || acceptType.equals("*/*")) {
        // Default to MEDIA_TYPE_JSON.
        acceptType = Constants.MEDIA_TYPE_JSON;
    }

    // Make it so that web browsers can get the json even when they don't have the proper header
    if (acceptType.equals(Constants.MEDIA_TYPE_HTML)) {
        acceptType = Constants.MEDIA_TYPE_JSON;
    }

    String username = "anonymous";
    LOGGER.info("Input parser implement: " + contentType);
    LOGGER.info("Output parser implement : " + acceptType);
    IRequestParser outputParser = ParserFactory.build(acceptType, username);

    try {
        occiResponse = new OCCIServletOutputResponse(acceptType, username, httpResponse, outputParser);
        username = validateAuth();

    } catch (AuthenticationException ex) {

        LOGGER.error(ex.getMessage());
        if (!occiResponse.hasExceptions()) {
            parseResponseAuthenticationFailed();
            occiResponse.setExceptionThrown(ex);
        }
        return occiResponse.getHttpResponse();
    }

    // Build inputparser and output parser.
    IRequestParser inputParser = ParserFactory.build(contentType, username);
    outputParser.setUsername(username);

    inputParser.setServerURI(serverURI);
    outputParser.setServerURI(serverURI);
    // Create occiRequest objects.
    occiResponse.setUsername(username);
    occiRequest = new OCCIServletInputRequest(occiResponse, contentType, username, httpRequest, headers,
            this.getRequestParameters(), inputParser);

    if (inputParser instanceof DefaultParser) {
        LOGGER.warn("No parser for content type : " + contentType);
        return occiResponse.parseMessage("content type : " + contentType + " not implemented.",
                HttpServletResponse.SC_NOT_IMPLEMENTED);
    }
    if (outputParser instanceof DefaultParser) {
        LOGGER.warn("No parser for accept type : " + acceptType);
        return occiResponse.parseMessage("accept type : " + contentType + " not implemented.",
                HttpServletResponse.SC_NOT_IMPLEMENTED);
    }

    // Get Client user agent to complain with http_protocol spec, control the occi version if set by client.
    boolean result = ServletUtils.checkClientOCCIVersion(headers);
    if (!result) {
        LOGGER.warn("Version is not compliant, max: OCCI v1.2");
        return occiResponse.parseMessage("The requested version is not implemented",
                HttpServletResponse.SC_NOT_IMPLEMENTED);
    }

    parseRequestParameters();

    // Define if the request is a users CRUD management request.
    userRequest = occiRequest.getRequestPath().startsWith(Constants.RESERVED_URI_LIST_USERS);
    if (userRequest && contentType.equals(Constants.MEDIA_TYPE_JSON)) {
        // if there is content, parse user profile in json format.
        try {
            occiRequest.parseUserInput();
        } catch (ParseUserException ex) {
            String msg = "Error while parsing input request: " + ex.getMessage();
            LOGGER.error(msg);

            return occiResponse.parseMessage(msg, HttpServletResponse.SC_BAD_REQUEST);
        }
    }

    // Parse OCCI worker datas content.
    try {

        if (!userRequest) {
            // Parse input query to data objects.
            occiRequest.parseInput();
        }
    } catch (ParseOCCIException ex) {
        String msg = "Error while parsing input request: " + ex.getMessage();
        LOGGER.error(msg);

        return occiResponse.parseMessage(msg, HttpServletResponse.SC_BAD_REQUEST);
    }

    return httpResponse;
}

From source file:com.orange.api.atmosdav.AtmosDavServlet.java

/**
 * Handles the special WebDAV methods.//w ww  . j  a v a2  s  .  c om
 */
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setHeader("Cache-Control", "no-cache"); //HTTP 1.1
    resp.setHeader("Pragma", "no-cache"); //HTTP 1.0
    resp.setDateHeader("Expires", 0); //prevents caching at the proxy server

    String method = req.getMethod();

    try {
        if (method.equals(METHOD_PROPFIND)) {
            doPropfind(req, resp);
        } else if (method.equals(METHOD_GET)) {
            doGet(req, resp);
        } else if (method.equals(METHOD_HEAD)) {
            doHead(req, resp);
        } else if (method.equals(METHOD_PUT)) {
            doPut(req, resp);
        } else if (method.equals(METHOD_PROPPATCH)) {
            doProppatch(req, resp);
        } else if (method.equals(METHOD_MKCOL)) {
            doMkcol(req, resp);
        } else if (method.equals(METHOD_COPY)) {
            doCopy(req, resp);
        } else if (method.equals(METHOD_MOVE)) {
            doMove(req, resp);
        } else if (method.equals(METHOD_LOCK)) {
            doLock(req, resp);
        } else if (method.equals(METHOD_UNLOCK)) {
            doUnlock(req, resp);
        } else if (method.equals(METHOD_POST)) {
            doPost(req, resp);
        } else if (method.equals(METHOD_DELETE)) {
            doDelete(req, resp);
        } else if (method.equals(METHOD_OPTIONS)) {
            doOptions(req, resp);
        } else if (method.equals(METHOD_TRACE)) {
            doTrace(req, resp);
        } else {
            resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED);
        }
    } catch (EsuException e) {
        if (e.getAtmosCode() == 1033) {
            resp.setHeader(WWW_AUTHENTICATE, WWW_AUTHENTICATE_VALUE);
            resp.sendError(resp.SC_UNAUTHORIZED);
        } else {
            if (e.getHttpCode() != 0) {
                StringBuffer err = new StringBuffer();

                err.append(e.getMessage());
                err.append("<BR />Atmos err code=");
                err.append(e.getAtmosCode());
                err.append("<BR />Http code=");
                err.append(e.getHttpCode());

                resp.sendError(e.getHttpCode(), err.toString());
            } else {
                resp.sendError(resp.SC_INTERNAL_SERVER_ERROR);
            }
        }
    }
    // Note super() is not called as we do not want some unexpected behaviour http servlets
}

From source file:org.opendaylight.iotdm.onem2m.protocols.http.Onem2mHttpProvider.java

public void handle(IotDMPluginRequest request, IotDMPluginResponse response) {
    HttpServletRequest httpRequest = ((IotDMPluginHttpRequest) request).getHttpRequest();
    HttpServletResponse httpResponse = ((IotDMPluginHttpResponse) response).getHttpResponse();

    Onem2mRequestPrimitiveClientBuilder clientBuilder = new Onem2mRequestPrimitiveClientBuilder();
    String headerValue;/*from  w w w .  j  a  v  a  2 s. co m*/

    clientBuilder.setProtocol(Onem2m.Protocol.HTTP);

    Onem2mStats.getInstance().inc(Onem2mStats.HTTP_REQUESTS);

    String contentType = httpRequest.getContentType();
    if (contentType == null)
        contentType = "json";
    contentType = contentType.toLowerCase();
    if (contentType.contains("json")) {
        clientBuilder.setContentFormat(Onem2m.ContentFormat.JSON);
    } else if (contentType.contains("xml")) {
        clientBuilder.setContentFormat(Onem2m.ContentFormat.XML);
    } else {
        httpResponse.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
        try {
            httpResponse.getWriter().println("Unsupported media type: " + contentType);
        } catch (IOException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/json;charset=utf-8");

        Onem2mStats.getInstance().inc(Onem2mStats.HTTP_REQUESTS_ERROR);
        return;
    }

    clientBuilder.setTo(Onem2m.translateUriToOnem2m(httpRequest.getRequestURI()));

    // pull fields out of the headers
    headerValue = httpRequest.getHeader(Onem2m.HttpHeaders.X_M2M_ORIGIN);
    if (headerValue != null) {
        clientBuilder.setFrom(headerValue);
    }
    headerValue = httpRequest.getHeader(Onem2m.HttpHeaders.X_M2M_RI);
    if (headerValue != null) {
        clientBuilder.setRequestIdentifier(headerValue);
    }
    headerValue = httpRequest.getHeader(Onem2m.HttpHeaders.X_M2M_NM);
    if (headerValue != null) {
        clientBuilder.setName(headerValue);
    }
    headerValue = httpRequest.getHeader(Onem2m.HttpHeaders.X_M2M_GID);
    if (headerValue != null) {
        clientBuilder.setGroupRequestIdentifier(headerValue);
    }
    headerValue = httpRequest.getHeader(Onem2m.HttpHeaders.X_M2M_RTU);
    if (headerValue != null) {
        clientBuilder.setResponseType(headerValue);
    }
    headerValue = httpRequest.getHeader(Onem2m.HttpHeaders.X_M2M_OT);
    if (headerValue != null) {
        clientBuilder.setOriginatingTimestamp(headerValue);
    }

    // the contentType string can have ty=val attached to it so we should handle this case
    Boolean resourceTypePresent = false;
    String contentTypeResourceString = parseContentTypeForResourceType(contentType);
    if (contentTypeResourceString != null) {
        resourceTypePresent = clientBuilder.parseQueryStringIntoPrimitives(contentTypeResourceString);
    }
    String method = httpRequest.getMethod().toLowerCase();
    // look in query string if didnt find it in contentType header
    if (!resourceTypePresent) {
        resourceTypePresent = clientBuilder.parseQueryStringIntoPrimitives(httpRequest.getQueryString());
    } else {
        clientBuilder.parseQueryStringIntoPrimitives(httpRequest.getQueryString());
    }
    if (resourceTypePresent && !method.contentEquals("post")) {
        httpResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        try {
            httpResponse.getWriter().println("Specifying resource type not permitted.");
        } catch (IOException e) {
            e.printStackTrace();
        }
        Onem2mStats.getInstance().inc(Onem2mStats.HTTP_REQUESTS_ERROR);
        return;
    }

    // take the entire payload text and put it in the CONTENT field; it is the representation of the resource
    String cn = request.getPayLoad();
    if (cn != null && !cn.contentEquals("")) {
        clientBuilder.setPrimitiveContent(cn);
    }

    switch (method) {
    case "get":
        clientBuilder.setOperationRetrieve();
        Onem2mStats.getInstance().inc(Onem2mStats.HTTP_REQUESTS_RETRIEVE);
        break;
    case "post":
        if (resourceTypePresent) {
            clientBuilder.setOperationCreate();
            Onem2mStats.getInstance().inc(Onem2mStats.HTTP_REQUESTS_CREATE);
        } else {
            clientBuilder.setOperationNotify();
            Onem2mStats.getInstance().inc(Onem2mStats.HTTP_REQUESTS_NOTIFY);
        }
        break;
    case "put":
        clientBuilder.setOperationUpdate();
        Onem2mStats.getInstance().inc(Onem2mStats.HTTP_REQUESTS_UPDATE);
        break;
    case "delete":
        clientBuilder.setOperationDelete();
        Onem2mStats.getInstance().inc(Onem2mStats.HTTP_REQUESTS_DELETE);
        break;
    default:
        httpResponse.setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED);
        try {
            httpResponse.getWriter().println("Unsupported method type: " + method);
        } catch (IOException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/json;charset=utf-8");
        //baseRequest.setHandled(true);
        Onem2mStats.getInstance().inc(Onem2mStats.HTTP_REQUESTS_ERROR);
        return;
    }

    // invoke the service request
    Onem2mRequestPrimitiveClient onem2mRequest = clientBuilder.build();
    ResponsePrimitive onem2mResponse = Onem2m.serviceOnenm2mRequest(onem2mRequest, onem2mService);

    // now place the fields from the onem2m result response back in the http fields, and send
    try {
        sendHttpResponseFromOnem2mResponse(httpResponse, onem2mResponse);
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:jetbrains.buildServer.server.rest.APIController.java

protected ModelAndView doHandle(final HttpServletRequest request, final HttpServletResponse response)
        throws Exception {
    if (ENABLE_DISABLING_CHECK) { //necessary until TW-16750 is fixed
        if (TeamCityProperties.getBoolean("rest.disable")) {
            response.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED,
                    "REST API is disabled on TeamCity server with 'rest.disable' internal property.");
            return null;
        }//ww w  . j  ava  2 s . c  om
    }
    final long requestStartProcessing = System.nanoTime();
    if (LOG.isDebugEnabled()) {
        LOG.debug("REST API request received: " + WebUtil.getRequestDump(request));
    }
    ensureInitialized();

    boolean runAsSystem = false;
    if (TeamCityProperties.getBoolean("rest.use.authToken")) {
        String authToken = request.getParameter("authToken");
        if (StringUtil.isNotEmpty(authToken) && StringUtil.isNotEmpty(getAuthToken())) {
            if (authToken.equals(getAuthToken())) {
                runAsSystem = true;
            } else {
                synchronized (this) {
                    Thread.sleep(10000); //to prevent bruteforcing
                }
                response.sendError(403, "Wrong authToken specified");
                return null;
            }
        }
    }

    final boolean runAsSystemActual = runAsSystem;
    // workaround for http://jetbrains.net/tracker/issue2/TW-7656
    jetbrains.buildServer.util.Util.doUnderContextClassLoader(getClass().getClassLoader(),
            new FuncThrow<Void, Exception>() {
                public Void apply() throws Exception {
                    // patching request
                    final HttpServletRequest actualRequest = new RequestWrapper(
                            patchRequest(request, "Accept", "overrideAccept"), myRequestPathTransformInfo);

                    if (runAsSystemActual) {
                        try {
                            LOG.debug("Executing request with system security level");
                            mySecurityContext.runAsSystem(new SecurityContextEx.RunAsAction() {
                                public void run() throws Throwable {
                                    myWebComponent.doFilter(actualRequest, response, null);
                                }
                            });
                        } catch (Throwable throwable) {
                            LOG.debug(throwable.getMessage(), throwable);
                            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                    throwable.getMessage());
                        }
                    } else {
                        myWebComponent.doFilter(actualRequest, response, null);
                    }
                    return null;
                }
            });

    if (LOG.isDebugEnabled()) {
        final long requestFinishProcessing = System.nanoTime();
        LOG.debug("REST API request processing finished in "
                + (requestFinishProcessing - requestStartProcessing) / 1000000 + " ms");
    }
    return null;
}

From source file:com.homesnap.webserver.ControllerRestAPITest.java

@Test
public void test12DeleteController() {
    deleteRequestJSONObject("/house/controllers/12", HttpServletResponse.SC_NOT_IMPLEMENTED);
    deleteRequestJSONObject("/house/controllers/controller?id=12", HttpServletResponse.SC_NOT_IMPLEMENTED);
    deleteRequestJSONObject("/house/controllers/12", HttpServletResponse.SC_NOT_IMPLEMENTED);
}

From source file:com.zimbra.cs.service.UserServletContext.java

protected void parseParams(HttpServletRequest request, AuthToken authToken)
        throws UserServletException, ServiceException {
    Provisioning prov = Provisioning.getInstance();

    String pathInfo = request.getPathInfo();
    if (pathInfo == null || pathInfo.equals("/") || pathInfo.equals("") || !pathInfo.startsWith("/"))
        throw new UserServletException(HttpServletResponse.SC_BAD_REQUEST,
                L10nUtil.getMessage(MsgKey.errInvalidPath, request));
    int pos = pathInfo.indexOf('/', 1);
    if (pos == -1)
        pos = pathInfo.length();//  w w w .ja v  a2 s .  c  o m
    if (pos < 1)
        throw new UserServletException(HttpServletResponse.SC_BAD_REQUEST,
                L10nUtil.getMessage(MsgKey.errInvalidPath, request));

    this.accountPath = pathInfo.substring(1, pos).toLowerCase();

    if (pos < pathInfo.length()) {
        this.itemPath = pathInfo.substring(pos + 1);
        if (itemPath.equals(""))
            itemPath = "/";
    } else {
        itemPath = "/";
    }
    this.extraPath = this.params.get(UserServlet.QP_NAME);
    this.format = FormatType.fromString(this.params.get(UserServlet.QP_FMT));
    String id = this.params.get(UserServlet.QP_ID);
    try {
        this.itemId = id == null ? null : new ItemId(id, (String) null);
    } catch (ServiceException e) {
        throw new UserServletException(HttpServletResponse.SC_BAD_REQUEST,
                L10nUtil.getMessage(MsgKey.errInvalidId, request));
    }

    String imap = this.params.get(UserServlet.QP_IMAP_ID);
    try {
        this.imapId = imap == null ? -1 : Integer.parseInt(imap);
    } catch (NumberFormatException nfe) {
        throw new UserServletException(HttpServletResponse.SC_BAD_REQUEST,
                L10nUtil.getMessage(MsgKey.errInvalidImapId, request));
    }

    if (this.format != null) {
        this.formatter = UserServlet.getFormatter(this.format);
        if (this.formatter == null) {
            throw new UserServletException(HttpServletResponse.SC_NOT_IMPLEMENTED,
                    L10nUtil.getMessage(MsgKey.errNotImplemented, request));
        } else {
            formatter.validateParams(this);
        }
    }

    // see if we can get target account or not
    if (itemId != null && itemId.getAccountId() != null) {
        targetAccount = prov.get(AccountBy.id, itemId.getAccountId(), authToken);
    } else if (accountPath.equals("~")) {
        // can't resolve this yet
    } else {
        if (accountPath.startsWith("~")) {
            accountPath = accountPath.substring(1);
        }
        targetAccount = prov.get(AccountBy.name, accountPath, authToken);
    }

    String listParam = this.params.get(UserServlet.QP_LIST);
    if (listParam != null && listParam.length() > 0) {
        String[] ids = listParam.split(",");
        requestedItems = new ArrayList<Item>();
        reqListIds = new int[ids.length];
        String proxyAcct = null;
        for (int i = 0; i < ids.length; ++i) {
            Item item = new Item(ids[i], targetAccount);
            requestedItems.add(item);
            reqListIds[i] = item.id;
            if (targetAccount != null && !targetAccount.getId().equals(item.acctId)) {
                if (proxyAcct != null && !proxyAcct.equals(item.acctId)) {
                    throw ServiceException.INVALID_REQUEST(
                            "Cross account multi list is not supported. already requested item from "
                                    + proxyAcct + " also found " + item.acctId + ":" + item.id,
                            null);
                } else if (proxyAcct == null) {
                    proxyAcct = item.acctId;
                }
            }
        }
        if (proxyAcct != null) {
            targetAccount = prov.get(AccountBy.id, proxyAcct, authToken);
        }
    }

    String dumpsterParam = params.get(UserServlet.QP_DUMPSTER);
    fromDumpster = (dumpsterParam != null && !dumpsterParam.equals("0")
            && !dumpsterParam.equalsIgnoreCase("false"));
}

From source file:com.aipo.container.protocol.AipoDataServiceServlet.java

@Override
protected void sendError(HttpServletResponse servletResponse, ResponseItem responseItem) throws IOException {
    int errorCode = responseItem.getErrorCode();
    Object response = responseItem.getResponse();
    if (errorCode < 0) {
        // Map JSON-RPC error codes into HTTP error codes as best we can
        // TODO: Augment the error message (if missing) with a default
        switch (errorCode) {
        case -32700:
        case -32602:
        case -32600:
            // Parse error, invalid params, and invalid request
            errorCode = HttpServletResponse.SC_BAD_REQUEST;
            break;
        case -32601:
            // Procedure doesn't exist
            errorCode = HttpServletResponse.SC_NOT_IMPLEMENTED;
            break;
        case -32603:
        default://from  ww  w .j a v a 2s  .  com
            // Internal server error, or any application-defined error
            errorCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
            break;
        }
    }

    String json = "{}";
    if (response != null && response instanceof JSONObject) {
        json = response.toString();
    } else {
        switch (errorCode) {
        case 400:
            json = AipoErrorCode.BAD_REQUEST.responseJSON().toString();
            break;
        case 401:
            json = AipoErrorCode.TOKEN_EXPIRED.responseJSON().toString();
            break;
        case 403:
            json = AipoErrorCode.INVALID_UER.responseJSON().toString();
            break;
        case 404:
            json = AipoErrorCode.NOT_FOUND.responseJSON().toString();
            break;
        case 500:
            json = AipoErrorCode.INTERNAL_ERROR.responseJSON().toString();
            break;
        case 501:
            json = AipoErrorCode.NOT_IMPLEMENTED.responseJSON().toString();
            break;
        case 502:
            json = AipoErrorCode.BAD_GATEWAY.responseJSON().toString();
            break;
        case 503:
            json = AipoErrorCode.SERVICE_UNAVAILABLE.responseJSON().toString();
            break;
        case 504:
            json = AipoErrorCode.GATEWAY_TIMEOUT.responseJSON().toString();
            break;
        default:
            json = AipoErrorCode.INTERNAL_ERROR.responseJSON().toString();
            errorCode = 500;
            break;
        }
    }

    servletResponse.setStatus(errorCode);
    servletResponse.setContentType("application/json; charset=utf8");
    OutputStream out = null;
    InputStream in = null;
    try {
        out = servletResponse.getOutputStream();
        in = new ByteArrayInputStream(json.getBytes("UTF-8"));
        int b;
        while ((b = in.read()) != -1) {
            out.write(b);
        }
        out.flush();
    } catch (Throwable t) {
        LOG.log(Level.WARNING, t.getMessage(), t);
    } finally {
        IOUtils.closeQuietly(out);
        IOUtils.closeQuietly(in);
    }
}

From source file:org.eclipse.orion.server.launching.LaunchingServlet.java

protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED);
}