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:eu.city4ageproject.delivery.HTTPService.java

/**{@inheritDoc} */
@Override/*ww w . j av  a  2s  .  c om*/
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    if (req.getContentType() != null && req.getContentType().toLowerCase().contains("application/json")
    //            && req.getCharacterEncoding() != null
    //            && req.getCharacterEncoding().toLowerCase().contains("utf")
    //            && req.getCharacterEncoding().toLowerCase().contains("8")
    ) {
        ServletInputStream is = req.getInputStream();
        String request = IOUtils.toString(is, "UTF-8");
        try {
            DeliveryRequest drequest = gsonBuilder.create().fromJson(request, DeliveryRequest.class);
            if (drequest.getPilotID() != null && !drequest.getPilotID().isEmpty()
                    && drequest.getUserID() != null && !drequest.getUserID().isEmpty()
                    && drequest.getIntervention() != null) {
                //connect to uAAL
                if (delivery.sendIntervention(drequest))
                    resp.setStatus(HttpServletResponse.SC_ACCEPTED);
                else
                    resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                return;
            }

            //TODO get parameters into the Actual delivery
        } catch (JsonSyntaxException e) {
            e.printStackTrace();

        }
        resp.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
        PrintStream ps = new PrintStream(resp.getOutputStream());
        ps.print("Request not acceptable.\n cotnent is not compliant to schema.");
    } else {
        resp.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
        resp.setContentType("text/html");
        resp.setCharacterEncoding("UTF-8");
        PrintStream ps = new PrintStream(resp.getOutputStream());
        ps.print("Request not acceptable.<br> " + "Content-Type: application/json <br>"
        //               +" Content-Encoding: UTF-8"
        );
    }
}

From source file:com.fpmislata.banco.presentacion.CreditoController.java

@RequestMapping(value = { "/Credito/{idCuentaBancaria}" }, method = RequestMethod.POST)
public void insert(HttpServletRequest httpRequest, HttpServletResponse httpServletResponse,
        @PathVariable("idCuentaBancaria") int idCuentaBancaria, @RequestBody String json)
        throws JsonProcessingException {
    try {/*from  www.j a  v a 2s  . c o  m*/
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        Credito credito = (Credito) objectMapper.readValue(json, Credito.class);

        CuentaBancaria cuentaBancaria = cuentaBancariaDAO.read(idCuentaBancaria);
        credito.setCuentaBancaria(cuentaBancaria);
        credito.setFecha(new Date());

        boolean ok = creditoDAO.comprobarCredito(credito.getCuentaBancaria().getUsuario());

        if (ok) {
            // ======================= Credito ============================= //

            creditoDAO.insert(credito);

            // ======================= Movimiento ============================= //
            MovimientoBancario movimientoBancario = new MovimientoBancario();

            movimientoBancario.setConcepto("Credito Bitbank");
            movimientoBancario.setFecha(new Date());
            movimientoBancario.setImporte(credito.getImporte());
            movimientoBancario.setTipoMovimientoBancario(TipoMovimientoBancario.Haber);
            movimientoBancario.setCuentaBancaria(credito.getCuentaBancaria());

            movimientoBancarioDAO.insert(movimientoBancario);
            noCache(httpServletResponse);
            httpServletResponse.setStatus(HttpServletResponse.SC_NO_CONTENT);
        } else {
            noCache(httpServletResponse);
            httpServletResponse.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
        }

    } catch (ConstraintViolationException cve) {
        List<BussinesMessage> errorList = new ArrayList();
        ObjectMapper jackson = new ObjectMapper();
        System.out.println("No se ha podido insertar la Cuenta Bancaria debido a los siguientes errores:");
        for (ConstraintViolation constraintViolation : cve.getConstraintViolations()) {
            String datos = constraintViolation.getPropertyPath().toString();
            String mensage = constraintViolation.getMessage();

            BussinesMessage bussinesMessage = new BussinesMessage(datos, mensage);
            errorList.add(bussinesMessage);
        }
        String jsonInsert = jackson.writeValueAsString(errorList);
        noCache(httpServletResponse);
        httpServletResponse.setStatus(httpServletResponse.SC_BAD_REQUEST);
    } catch (Exception ex) {
        noCache(httpServletResponse);
        httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        httpServletResponse.setContentType("text/plain; charset=UTF-8");
        try {
            noCache(httpServletResponse);
            ex.printStackTrace(httpServletResponse.getWriter());
        } catch (Exception ex1) {
            noCache(httpServletResponse);
        }
    }
}

From source file:org.nuxeo.ecm.platform.oauth2.openid.web.OAuth2CallbackHandlerServlet.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {

    // Getting the "error" URL parameter
    String error = req.getParameter(ERROR_URL_PARAM_NAME);

    // / Checking if there was an error such as the user denied access
    if (error != null && error.length() > 0) {
        resp.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "There was an error: \"" + error + "\".");
        return;/*from ww  w. jav a  2 s.c  o  m*/
    }

    // Getting the "code" URL parameter
    String code = req.getParameter(CODE_URL_PARAM_NAME);

    // Checking conditions on the "code" URL parameter
    if (code == null || code.isEmpty()) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "There was an error: \"" + error + "\".");
        return;
    }

    String path = req.getRequestURI().split(URL_MAPPING + "/")[1];
    String[] parts = path.split("/");
    String serviceProviderName = parts[0];

    NuxeoOAuth2ServiceProvider provider;
    try {
        provider = getServiceProvider(serviceProviderName);

        if (provider == null) {
            resp.sendError(HttpServletResponse.SC_NOT_FOUND,
                    "No service provider called: \"" + serviceProviderName + "\".");
            return;
        }

        AuthorizationCodeFlow flow = provider.getAuthorizationCodeFlow(HTTP_TRANSPORT, JSON_FACTORY);

        String redirectUri = req.getRequestURL().toString();

        Principal principal = req.getUserPrincipal();

        HttpResponse response = flow.newTokenRequest(code).setRedirectUri(redirectUri).executeUnparsed();
        TokenResponse tokenResponse = response.parseAs(TokenResponse.class);

        // Validate the token
        String accessToken = tokenResponse.getAccessToken();

        HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(new HttpRequestInitializer() {
            @Override
            public void initialize(HttpRequest request) throws IOException {
                request.setParser(new JsonObjectParser(JSON_FACTORY));
            }
        });

        GenericUrl url = new GenericUrl("https://www.googleapis.com/oauth2/v1/tokeninfo");
        url.set("access_token", accessToken);

        HttpRequest request = requestFactory.buildGetRequest(url);
        response = request.execute();

        // TODO - get the email
        String email = "nelson.silva@gmail.com";

        UserManager manager = Framework.getLocalService(UserManager.class);

        Map<String, Serializable> query = new HashMap<String, Serializable>();
        query.put(manager.getUserEmailField(), email);

        DocumentModelList users = manager.searchUsers(query, null);

        if (users.isEmpty()) {
            resp.sendError(HttpServletResponse.SC_NOT_FOUND, "No user found with email: \"" + email + "\".");
        }

        DocumentModel user = users.get(0);
        String userId = (String) user.getPropertyValue(manager.getUserIdField());

        Framework.loginAs(userId);
        LoginContext loginContext = NuxeoAuthenticationFilter.loginAs(userId);
        loginContext.login();

        resp.sendRedirect(req.getContextPath());
    } catch (Exception e) {
        log.error("Error while processing OAuth2 Callback", e);
    }

}

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

@Test
public void test02CreateControllerFromLabel() {
    // Test controller add in a label
    postRequestJSONObject(urn_labels + "/ch1", createJsonLabel("Chambre 1", "ch1"),
            HttpServletResponse.SC_CREATED);
    JSONObject jo = postRequestJSONObject(urn_labels + "/ch1/controller?id=11", createJsonController11(),
            HttpServletResponse.SC_CREATED);
    testController11(jo);//from   w w  w  .j  a  v a 2s .co  m

    jo = postRequestJSONObject(urn_labels + "/ch1/controller?id=17", createJsonController17(),
            HttpServletResponse.SC_CREATED);
    testController17(jo);

    jo = postRequestJSONObject(urn_labels + "/ch1/controller?id=12", createJsonController12(),
            HttpServletResponse.SC_CREATED);
    testController12(jo);

    // impossible to add again the same controller
    postRequestJSONObject(urn_labels + "/ch1/61", createJsonController61(),
            HttpServletResponse.SC_NOT_ACCEPTABLE);

    // Test impossible to create a new controller not existing in a Group
    postRequestJSONObject(urn_labels + "/ch1/61", createJsonController61(),
            HttpServletResponse.SC_NOT_ACCEPTABLE);
    postRequestJSONObject(urn_labels + "/ch1/controller?id=61", createJsonController61(),
            HttpServletResponse.SC_NOT_ACCEPTABLE);
}

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

protected JSONObject postRequestJSONObject(String urn, String body, int returnCodeExpected) {
    Client client = Client.create();/*w w w. j  a va  2  s  . c om*/
    WebResource webResource = client.resource("http://" + server + ":" + port + urn);

    String json = null;
    try {
        ClientResponse response = webResource.accept("application/json").post(ClientResponse.class, body);
        Assert.assertEquals(returnCodeExpected, response.getStatus());
        if (returnCodeExpected == HttpServletResponse.SC_NOT_IMPLEMENTED
                || returnCodeExpected == HttpServletResponse.SC_NOT_ACCEPTABLE
                || returnCodeExpected == HttpServletResponse.SC_BAD_REQUEST) {
            return null;
        }

        json = response.getEntity(String.class);
        return JSonTools.fromJson(json);

    } catch (JSONException e) {
        e.printStackTrace();
        Assert.fail("Problem with JSON [" + json + "] :" + e.getMessage());
    }
    Assert.fail("Problem when call [" + urn + "].");
    return null;
}

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

@Test
public void test8OnStatus() {

    // Test to get a specific label
    JSONObject label = getRequestJSONObject("/house/labels/ch6?param=param");
    // Test label Ch1
    testLabelCh6Bis(label);/*from  w w w  .  j ava2s .com*/

    label = getRequestJSONObject("/house/labels/label?id=ch7&param=param");
    // Test label Ch1
    testLabelCh7Bis(label);

    putRequestJSONObject("/house/labels/ch1?param=param", createJsonController17(),
            HttpServletResponse.SC_NOT_ACCEPTABLE); // Ch1 not existing!
    putRequestJSONObject("/house/labels/label?id=ch1&param=param", createJsonController17(),
            HttpServletResponse.SC_NOT_ACCEPTABLE);

    postRequestJSONObject("/house/labels/ch7?param=param", createJsonLabelCh7(),
            HttpServletResponse.SC_NOT_ACCEPTABLE);
    postRequestJSONObject("/house/labels/label?id=ch7&param=param", createJsonLabelCh7(),
            HttpServletResponse.SC_NOT_ACCEPTABLE);

    deleteRequestJSONObject("/house/labels/ch7?param=param", HttpServletResponse.SC_OK);
    deleteRequestJSONObject("/house/labels/label?id=ch7&param=param", HttpServletResponse.SC_NOT_ACCEPTABLE);
}

From source file:org.dataconservancy.dcs.access.http.QueryServlet.java

@SuppressWarnings("unchecked")
private void search(HttpServletRequest req, HttpServletResponse resp, OutputStream os) throws IOException {

    String query = req.getParameter("q");

    if (query == null) {
        query = ServletUtil.getResource(req);
    }/*  ww w .  j  a v  a2  s . c  om*/

    if (query == null) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "No query specified");
        return;
    }

    int offset = 0;
    int max = DEFAULT_MAX_MATCHES;

    if (req.getParameter("offset") != null) {
        try {
            offset = Integer.parseInt(req.getParameter("offset"));
        } catch (NumberFormatException e) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Bad offset param");
            return;
        }
    }

    if (req.getParameter("max") != null) {
        try {
            max = Integer.parseInt(req.getParameter("max"));
        } catch (NumberFormatException e) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Bad max param");
            return;
        }
    }

    if (offset < 0) {
        offset = 0;
    }

    if (max < 0) {
        max = DEFAULT_MAX_MATCHES;
    }

    if (max > MAX_MATCHES_UPPER_BOUND) {
        max = MAX_MATCHES_UPPER_BOUND;
    }

    ResultFormat fmt = ResultFormat.find(req);

    if (fmt == null) {
        resp.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Unknown response format requested");
        return;
    }

    resp.setContentType(fmt.mimeType());

    List<String> params = new ArrayList<String>();

    for (Object o : Collections.list(req.getParameterNames())) {
        String name = (String) o;

        if (name.startsWith("_")) {
            params.add(name.substring(1));
            params.add(req.getParameter(name));
        }
    }

    QueryResult<DcsEntity> result;

    try {
        result = config.dcpQueryService().query(query, offset, max, params.toArray(new String[] {}));
    } catch (QueryServiceException e) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Error running query: " + e.getMessage());
        return;
    }

    resp.setHeader("X-TOTAL-MATCHES", "" + result.getTotal());

    if (os == null) {
        return;
    }

    for (QueryMatch<DcsEntity> match : result.getMatches()) {
        DcsEntity entity = match.getObject();

        if (entity instanceof DcsFile) {
            DcsFile file = (DcsFile) entity;

            file.setSource(config.publicDatastreamUrl() + ServletUtil.encodeURLPath(file.getId()));
        }
    }

    if (fmt == ResultFormat.JSON || fmt == ResultFormat.JAVASCRIPT) {
        String jsoncallback = req.getParameter("callback");

        if (jsoncallback != null) {
            os.write(jsoncallback.getBytes("UTF-8"));
            os.write('(');
        }

        jsonbuilder.toXML(result, os);

        if (jsoncallback != null) {
            os.write(')');
        }
    } else if (fmt == ResultFormat.DCP) {
        ResearchObject dcp = new ResearchObject();

        for (QueryMatch<DcsEntity> match : result.getMatches()) {
            dcp = new SeadUtil().add(dcp, match.getObject());
        }

        dcpbuilder.buildSip(dcp, os);
    }
}

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

/**
 * set schema// w w  w .j  a va2 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 doPost(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 tenantId = MultitenantConstants.INVALID_TENANT_ID;
        if (!securityEnabled)
            tenantId = Integer.parseInt(req.getParameter(AnalyticsAPIConstants.TENANT_ID_PARAM));
        String userName = req.getParameter(AnalyticsAPIConstants.USERNAME_PARAM);
        if (operation != null
                && operation.trim().equalsIgnoreCase(AnalyticsAPIConstants.SET_SCHEMA_OPERATION)) {
            String tableName = req.getParameter(AnalyticsAPIConstants.TABLE_NAME_PARAM);
            Object analyticsSchemeObj = GenericUtils.deserializeObject(req.getInputStream());
            if (analyticsSchemeObj != null && analyticsSchemeObj instanceof AnalyticsSchema) {
                AnalyticsSchema schema = (AnalyticsSchema) analyticsSchemeObj;
                try {
                    if (!securityEnabled)
                        ServiceHolder.getAnalyticsDataService().setTableSchema(tenantId, tableName, schema);
                    else
                        ServiceHolder.getSecureAnalyticsDataService().setTableSchema(userName, tableName,
                                schema);
                    resp.setStatus(HttpServletResponse.SC_OK);
                } catch (AnalyticsException e) {
                    resp.sendError(HttpServletResponse.SC_EXPECTATION_FAILED, e.getMessage());
                }
            } else {
                resp.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE,
                        "unexpected content passed with the request! " + "Expected analytics schema but found "
                                + analyticsSchemeObj);
            }
        } 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.wso2.carbon.analytics.servlet.AnalyticsRecordReadProcessor.java

/**
 * Read the record record count// w w w. j  av a  2 s . c om
 *
 * @param req  HttpRequest which has the required parameters to do the operation.
 * @param resp HttpResponse which returns the result of the intended operation.
 * @throws javax.servlet.ServletException
 * @throws java.io.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_RANGE_RECORD_GROUP_OPERATION)) {
            doGetRangeRecordGroupOperation(securityEnabled, req, resp);
        } else if (operation != null
                && operation.trim().equalsIgnoreCase(AnalyticsAPIConstants.GET_IDS_RECORD_GROUP_OPERATION)) {
            doIdsRecordGroup(securityEnabled, req, resp);
        } else if (operation != null && operation.trim()
                .equalsIgnoreCase(AnalyticsAPIConstants.GET_RECORDS_WITH_KEY_VALUES_OPERATION)) {
            doGetRecordWithKeyValues(securityEnabled, req, resp);
        } else if (operation != null
                && operation.trim().equalsIgnoreCase(AnalyticsAPIConstants.READ_RECORD_OPERATION)) {
            doReadRecords(req, resp);
        } else {
            resp.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE,
                    "unsupported operation performed with get request!");
            log.error("unsupported operation performed : " + operation + " with post request!");
        }
    }
}

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

/**
 * This focuses on changing the wait time for indexing for the given table.
 *
 * @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 ww  w  .  j a  v a2 s .co m*/
 * @throws IOException
 */
protected void doPost(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);
        if (operation != null
                && operation.trim().equalsIgnoreCase(AnalyticsAPIConstants.WAIT_FOR_INDEXING_OPERATION)) {
            long maxWait = Integer.parseInt(req.getParameter(AnalyticsAPIConstants.MAX_WAIT_PARAM));
            String tableName = req.getParameter(AnalyticsAPIConstants.TABLE_NAME_PARAM);
            if (tableName != null && !tableName.trim().isEmpty()) {
                int tenantId = Integer.parseInt(req.getParameter(AnalyticsAPIConstants.TENANT_ID_PARAM));
                boolean securityEnabled = Boolean
                        .parseBoolean(req.getParameter(AnalyticsAPIConstants.ENABLE_SECURITY_PARAM));
                String username = req.getParameter(AnalyticsAPIConstants.USERNAME_PARAM);
                try {
                    if (!securityEnabled) {
                        ServiceHolder.getAnalyticsDataService().waitForIndexing(tenantId, tableName, maxWait);
                    } else {
                        ServiceHolder.getSecureAnalyticsDataService().waitForIndexing(username, tableName,
                                maxWait);
                    }
                    resp.setStatus(HttpServletResponse.SC_OK);
                } catch (AnalyticsException e) {
                    resp.sendError(HttpServletResponse.SC_EXPECTATION_FAILED, e.getMessage());
                }
            } else {
                try {
                    ServiceHolder.getAnalyticsDataService().waitForIndexing(maxWait);
                    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 post request!");
            log.error("unsupported operation performed : " + operation + " with post request!");
        }
    }
}