Example usage for javax.servlet.http HttpServletResponse SC_NOT_ACCEPTABLE

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

Introduction

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

Prototype

int SC_NOT_ACCEPTABLE

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

Click Source Link

Document

Status code (406) indicating that the resource identified by the request is only capable of generating response entities which have content characteristics not acceptable according to the accept headers sent in the request.

Usage

From source file:org.wso2.carbon.analytics.servlet.AnalyticsRecordStoreProcessor.java

public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String sessionId = req.getHeader(AnalyticsAPIConstants.SESSION_ID);
    if (sessionId == null || sessionId.trim().isEmpty()) {
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "No session id found, Please login first!");
    } else {//from  ww  w.  j a va  2  s  .  co  m
        try {
            ServiceHolder.getAuthenticator().validateSessionId(sessionId);
        } catch (AnalyticsAPIAuthenticationException e) {
            resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "No session id found, Please login first!");
        }
        String operation = req.getParameter(AnalyticsAPIConstants.OPERATION);
        boolean securityEnabled = Boolean
                .parseBoolean(req.getParameter(AnalyticsAPIConstants.ENABLE_SECURITY_PARAM));
        if (operation != null && operation.trim()
                .equalsIgnoreCase(AnalyticsAPIConstants.GET_RECORD_STORE_OF_TABLE_OPERATION)) {
            String tableName = req.getParameter(AnalyticsAPIConstants.TABLE_NAME_PARAM);
            if (!securityEnabled) {
                int tenantId = Integer.parseInt(req.getParameter(AnalyticsAPIConstants.TENANT_ID_PARAM));
                try {
                    String recordStore = ServiceHolder.getAnalyticsDataService()
                            .getRecordStoreNameByTable(tenantId, tableName);
                    resp.setStatus(HttpServletResponse.SC_OK);
                    PrintWriter responseWriter = resp.getWriter();
                    responseWriter.print(AnalyticsAPIConstants.RECORD_STORE_NAME
                            + AnalyticsAPIConstants.SEPARATOR + recordStore);
                } catch (AnalyticsException e) {
                    resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
                }
            } else {
                String username = req.getParameter(AnalyticsAPIConstants.USERNAME_PARAM);
                try {
                    String recordStore = ServiceHolder.getSecureAnalyticsDataService()
                            .getRecordStoreNameByTable(username, tableName);
                    resp.setStatus(HttpServletResponse.SC_OK);
                    PrintWriter responseWriter = resp.getWriter();
                    responseWriter.print(AnalyticsAPIConstants.RECORD_STORE_NAME
                            + AnalyticsAPIConstants.SEPARATOR + recordStore);
                } catch (AnalyticsException e) {
                    resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
                }
            }
        } else if (operation != null
                && operation.trim().equalsIgnoreCase(AnalyticsAPIConstants.LIST_RECORD_STORES_OPERATION)) {
            List<String> recordStores = ServiceHolder.getAnalyticsDataService().listRecordStoreNames();
            GenericUtils.serializeObject(recordStores, resp.getOutputStream());
            resp.setStatus(HttpServletResponse.SC_OK);
        } else {
            resp.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE,
                    "unsupported operation performed with get request!");
            log.error("unsupported operation performed : " + operation + " with get request!");
        }
    }
}

From source file:org.apache.hadoop.hdfs.qjournal.client.HttpImageUploadChannel.java

/**
 * Create an image upload channel, based on image txid and other metadata.
 *//*w w w . j a  v a 2 s  . co m*/
public void start() {
    try {
        if (init) {
            setErrorStatus("Cannot initialize multiple times", null);
            return;
        }
        init = true;
        HttpPost postRequest = setupRequest(new ByteArrayOutputStream(0));
        UploadImageParam.setHeaders(postRequest, journalId, namespaceInfoString, epoch, txid, 0, segmentId++,
                false);

        HttpClient httpClient = new DefaultHttpClient();
        HttpResponse response = httpClient.execute(postRequest);
        if (response.getStatusLine().getStatusCode() == HttpServletResponse.SC_NOT_ACCEPTABLE) {
            throwIOException("Error when starting upload to : " + uri + " status: "
                    + response.getStatusLine().toString());
        }

        // get the session id
        for (Header h : response.getAllHeaders()) {
            if (h.getName().equals("sessionId")) {
                sessionId = Long.parseLong(h.getValue());
                break;
            }
        }

        // we must have the session id
        if (sessionId < 0) {
            throw new IOException("Session id is missing");
        }
    } catch (Exception e) {
        setErrorStatus("Exception when starting upload channel for: " + uri, e);
    }
}

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 .ja v  a2 s. c  om

    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:org.wso2.carbon.analytics.servlet.AnalyticsRecordProcessor.java

/**
 * Get record count/*from   ww  w.j av a2  s.  co  m*/
 *
 * @param req  HttpRequest which has the required parameters to do the operation.
 * @param resp HttpResponse which returns the result of the intended operation.
 * @throws ServletException
 * @throws IOException
 */

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String sessionId = req.getHeader(AnalyticsAPIConstants.SESSION_ID);
    if (sessionId == null || sessionId.trim().isEmpty()) {
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "No session id found, Please login first!");
    } else {
        try {
            ServiceHolder.getAuthenticator().validateSessionId(sessionId);
        } catch (AnalyticsAPIAuthenticationException e) {
            resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "No session id found, Please login first!");
        }
        String operation = req.getParameter(AnalyticsAPIConstants.OPERATION);
        boolean securityEnabled = Boolean
                .parseBoolean(req.getParameter(AnalyticsAPIConstants.ENABLE_SECURITY_PARAM));
        if (operation != null
                && operation.trim().equalsIgnoreCase(AnalyticsAPIConstants.GET_RECORD_COUNT_OPERATION)) {
            int tenantIdParam = MultitenantConstants.INVALID_TENANT_ID;
            if (!securityEnabled)
                tenantIdParam = Integer.parseInt(req.getParameter(AnalyticsAPIConstants.TENANT_ID_PARAM));
            String userName = req.getParameter(AnalyticsAPIConstants.USERNAME_PARAM);
            String tableName = req.getParameter(AnalyticsAPIConstants.TABLE_NAME_PARAM);
            long timeFrom = Long.parseLong(req.getParameter(AnalyticsAPIConstants.TIME_FROM_PARAM));
            long timeTo = Long.parseLong(req.getParameter(AnalyticsAPIConstants.TIME_TO_PARAM));
            try {
                long recordCount;
                if (!securityEnabled)
                    recordCount = ServiceHolder.getAnalyticsDataService().getRecordCount(tenantIdParam,
                            tableName, timeFrom, timeTo);
                else
                    recordCount = ServiceHolder.getSecureAnalyticsDataService().getRecordCount(userName,
                            tableName, timeFrom, timeTo);
                PrintWriter outputWriter = resp.getWriter();
                outputWriter.append(AnalyticsAPIConstants.RECORD_COUNT).append(AnalyticsAPIConstants.SEPARATOR)
                        .append(String.valueOf(recordCount));
                resp.setStatus(HttpServletResponse.SC_OK);
            } catch (AnalyticsException e) {
                resp.sendError(HttpServletResponse.SC_EXPECTATION_FAILED, e.getMessage());
            }
        } else {
            resp.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE,
                    "unsupported operation performed with get request!");
            log.error("unsupported operation performed : " + operation + " with get request!");
        }
    }
}

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

protected JSONObject deleteRequestJSONObject(String urn, int returnCodeExpected) {
    Client client = Client.create();//from  w  w  w  .j a  v  a 2s  .  c  om
    WebResource webResource = client.resource("http://" + server + ":" + port + urn);
    ClientResponse response = webResource.accept("application/json").delete(ClientResponse.class);
    Assert.assertEquals(returnCodeExpected, response.getStatus());
    if (returnCodeExpected == HttpServletResponse.SC_NO_CONTENT
            || returnCodeExpected == HttpServletResponse.SC_NOT_ACCEPTABLE
            || returnCodeExpected == HttpServletResponse.SC_NOT_IMPLEMENTED) {
        return null;
    }

    String json = null;
    try {
        json = response.getEntity(String.class);
        return JSonTools.fromJson(json);
    } catch (JSONException e) {
        e.printStackTrace();
        Assert.fail("Problem with JSON [" + json + "] :" + e.getMessage());
    }
    return null;
}

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

@Test
public void test9DeleteLabel() {
    // Test new label creation
    JSONObject label = deleteRequestJSONObject(urn_labels + "/ch6", HttpServletResponse.SC_OK);
    testLabelCh6Bis(label);/*from  www.j  a  v  a2  s.  c  om*/

    label = deleteRequestJSONObject(urn_labels + "/label?id=ch7", HttpServletResponse.SC_NOT_ACCEPTABLE);
    Assert.assertNull(label);
}

From source file:org.wso2.carbon.analytics.servlet.AnalyticsTableProcessor.java

/**
 * Get the all tables for tenant or check table exists
 *
 * @param req HttpRequest which has the required parameters to do the operation.
 * @param resp HttpResponse which returns the result of the intended operation.
 * @throws ServletException//from w ww . j  a v  a2 s  .c o m
 * @throws IOException
 */
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String sessionId = req.getHeader(AnalyticsAPIConstants.SESSION_ID);
    if (sessionId == null || sessionId.trim().isEmpty()) {
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "No session id found, Please login first!");
    } else {
        try {
            ServiceHolder.getAuthenticator().validateSessionId(sessionId);
        } catch (AnalyticsAPIAuthenticationException e) {
            resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "No session id found, Please login first!");
        }
        String operation = req.getParameter(AnalyticsAPIConstants.OPERATION);
        boolean securityEnabled = Boolean
                .parseBoolean(req.getParameter(AnalyticsAPIConstants.ENABLE_SECURITY_PARAM));
        int tenantIdParam = MultitenantConstants.INVALID_TENANT_ID;
        if (!securityEnabled)
            tenantIdParam = Integer.parseInt(req.getParameter(AnalyticsAPIConstants.TENANT_ID_PARAM));
        String userName = req.getParameter(AnalyticsAPIConstants.USERNAME_PARAM);
        if (operation != null
                && operation.trim().equalsIgnoreCase(AnalyticsAPIConstants.TABLE_EXISTS_OPERATION)) {
            String tableName = req.getParameter(AnalyticsAPIConstants.TABLE_NAME_PARAM);
            try {
                boolean tableExists;
                if (!securityEnabled)
                    tableExists = ServiceHolder.getAnalyticsDataService().tableExists(tenantIdParam, tableName);
                else
                    tableExists = ServiceHolder.getSecureAnalyticsDataService().tableExists(userName,
                            tableName);
                PrintWriter output = resp.getWriter();
                output.append(AnalyticsAPIConstants.TABLE_EXISTS).append(AnalyticsAPIConstants.SEPARATOR)
                        .append(String.valueOf(tableExists));
                resp.setStatus(HttpServletResponse.SC_OK);
            } catch (AnalyticsException e) {
                resp.sendError(HttpServletResponse.SC_EXPECTATION_FAILED, e.getMessage());
            }
        } else if (operation != null
                && operation.trim().equalsIgnoreCase(AnalyticsAPIConstants.LIST_TABLES_OPERATION)) {
            try {
                List<String> tableNames;
                if (!securityEnabled)
                    tableNames = ServiceHolder.getAnalyticsDataService().listTables(tenantIdParam);
                else
                    tableNames = ServiceHolder.getSecureAnalyticsDataService().listTables(userName);
                resp.getOutputStream().write(GenericUtils.serializeObject(tableNames));
                resp.setStatus(HttpServletResponse.SC_OK);
            } catch (AnalyticsException e) {
                resp.sendError(HttpServletResponse.SC_EXPECTATION_FAILED, e.getMessage());
            }
        } else {
            resp.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE,
                    "unsupported operation performed with get request!");
            log.error("unsupported operation performed : " + operation + " with get request!");
        }
    }
}

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

@Test
public void test7OnStatus() {
    // Test to get a specific group
    JSONObject group = getRequestJSONObject("/house/groups/1?param=param");
    // Test group 1
    testGroup1Bis(group);//from  www .j  a  va 2s  .  c om

    group = getRequestJSONObject("/house/groups/group?id=10&param=param");
    // Test group 10
    testGroup10(group);

    putRequestJSONObject("/house/groups/1?param=param", createGroup1(), HttpServletResponse.SC_OK);
    putRequestJSONObject("/house/groups/group?id=1&param=param", createGroup1(), HttpServletResponse.SC_OK);

    postRequestJSONObject("/house/groups/1/21", createController21(), HttpServletResponse.SC_CREATED);
    JSONObject jo = getRequestJSONObject("/house/groups/1/controller?id=21&param=param");
    testController21(jo);

    jo = getRequestJSONObject("/house/groups/1/21?param=param");
    testController21(jo);

    testController21(jo);

    deleteRequestJSONObject("/house/groups/1?param=param", HttpServletResponse.SC_OK);
    deleteRequestJSONObject("/house/groups/group?id=1&param=param", HttpServletResponse.SC_NOT_ACCEPTABLE);
}

From source file:org.springframework.extensions.webscripts.WebScriptRequestImpl.java

public String getFormat() {
    if (this.format == null) {
        String format = null;//w  w w  . j a  v  a2 s  .  c om
        Match match = getServiceMatch();
        if (match != null && match.getKind() != Match.Kind.URI) {
            Description desc = match.getWebScript().getDescription();
            FormatStyle style = desc.getFormatStyle();

            // extract format from extension
            if (style == FormatStyle.extension || style == FormatStyle.any) {
                String pathInfo = getPathInfo();
                if (pathInfo != null) {
                    int extIdx = pathInfo.lastIndexOf('.');
                    if (extIdx != -1) {
                        // format extension is only valid as the last URL element 
                        int pathIdx = pathInfo.lastIndexOf('/');
                        if (pathIdx < extIdx) {
                            format = pathInfo.substring(extIdx + 1);
                        }
                    }
                }
            }

            // extract format from argument
            if (style == FormatStyle.argument || style == FormatStyle.any) {
                String argFormat = getParameter(ARG_FORMAT);
                if (argFormat != null) {
                    if (format != null && format.length() > 0) {
                        throw new WebScriptException("Format specified both in extension and format argument");
                    }
                    format = argFormat;
                }
            }

            // negotiate format, if necessary
            if (format == null || format.length() == 0) {
                String accept = getHeader(HEADER_ACCEPT);
                NegotiatedFormat[] negotiatedFormats = desc.getNegotiatedFormats();
                if (accept != null && negotiatedFormats != null) {
                    if (logger.isDebugEnabled())
                        logger.debug("Negotiating format for " + accept);

                    format = NegotiatedFormat.negotiateFormat(accept, negotiatedFormats);
                    if (format == null) {
                        throw new WebScriptException(HttpServletResponse.SC_NOT_ACCEPTABLE,
                                "Cannot negotiate appropriate response format for Accept: " + accept);
                    }
                }
            }

            // fallback to default
            if (format == null || format.length() == 0) {
                format = desc.getDefaultFormat();
            }
        }
        this.format = (format == null || format.length() == 0) ? "" : format;
    }
    return this.format;
}

From source file:org.apache.hadoop.hdfs.qjournal.server.TestJournalNodeImageUpload.java

private void tryUploading(ContentBody cb, String journalId, long sessionId, long segmentId, long epoch,
        boolean expectedError, boolean close) throws IOException {
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost postRequest = createRequest(httpAddress, cb);
    UploadImageParam.setHeaders(postRequest, journalId, FAKE_NSINFO.toColonSeparatedString(), epoch, 100,
            sessionId, segmentId, close);
    HttpResponse resp = httpClient.execute(postRequest);
    if (expectedError) {
        assertEquals(HttpServletResponse.SC_NOT_ACCEPTABLE, resp.getStatusLine().getStatusCode());
    }//from   w w w  .  j a v a2 s.  c  o  m
}