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.kohsuke.stapler.AcceptHeader.java

/**
 * Takes a list of supported mime-types and finds the best match for all the
 * media-ranges listed in header. The value of header must be a string that
 * conforms to the format of the HTTP Accept: header. The value of
 * 'supported' is a list of mime-types.//from  w w w  . j a  v a2  s .  c  o m
 *
 * <pre>
 * // Client: I prefer text/*, but if not I'm happy to take anything
 * // Server: I can serve you xbel or xml
 * // Result: let's serve you text/xml
 * new AcceptHeader("text/*;q=0.5, *;q=0.1").select("application/xbel+xml", "text/xml") => "text/xml"
 *
 * // Client: I want image, ideally PNG
 * // Server: I can give you plain text or XML
 * // Result: there's nothing to serve you here
 * new AcceptHeader("image/*;q=0.5, image/png;q=1").select("text/plain","text/xml") => null
 * </pre>
 *
 * @return null if none of the choices in {@code supported} is acceptable to the client.
 */
public String select(Iterable<String> supported) {
    float bestQ = 0;
    String best = null;

    for (String s : supported) {
        Atom a = match(s);
        if (a != null && a.q > bestQ) {
            bestQ = a.q;
            best = s;
        }
    }

    if (best == null)
        throw HttpResponses.error(HttpServletResponse.SC_NOT_ACCEPTABLE,
                "Requested MIME types '" + ranges + "' didn't match any of the available options " + supported);
    return best;
}

From source file:com.sun.faban.harness.webclient.RunUploader.java

/**
 * Post method to upload the run./*from  w w w.ja v  a 2s.  com*/
 * @param request The servlet request
 * @param response The servlet response
 * @throws ServletException If the servlet fails
 * @throws IOException If there is an I/O error
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String host = null;
    String key = null;
    boolean origin = false; // Whether the upload is to the original
    // run requestor. If so, key is needed.

    DiskFileUpload fu = new DiskFileUpload();
    // No maximum size
    fu.setSizeMax(-1);
    // maximum size that will be stored in memory
    fu.setSizeThreshold(4096);
    // the location for saving data that is larger than getSizeThreshold()
    fu.setRepositoryPath(Config.TMP_DIR);

    List fileItems = null;
    try {
        fileItems = fu.parseRequest(request);
    } catch (FileUploadException e) {
        throw new ServletException(e);
    }
    // assume we know there are two files. The first file is a small
    // text file, the second is unknown and is written to a file on
    // the server
    for (Iterator i = fileItems.iterator(); i.hasNext();) {
        FileItem item = (FileItem) i.next();
        String fieldName = item.getFieldName();
        if (item.isFormField()) {
            if ("host".equals(fieldName)) {
                host = item.getString();
            } else if ("key".equals(fieldName)) {
                key = item.getString();
            } else if ("origin".equals(fieldName)) {
                String value = item.getString();
                origin = Boolean.parseBoolean(value);
            }
            continue;
        }

        if (host == null) {
            logger.warning("Host not received on upload request!");
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            break;
        }

        // The host, origin, key info must be here before we receive
        // any file.
        if (origin) {
            if (Config.daemonMode != Config.DaemonModes.POLLEE) {
                logger.warning("Origin upload requested. Not pollee!");
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                break;
            }
            if (key == null) {
                logger.warning("Origin upload requested. No key!");
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                break;
            }
            if (!RunRetriever.authenticate(host, key)) {
                logger.warning("Origin upload requested. " + "Host/key mismatch: " + host + '/' + key + "!");
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                break;
            }
        }

        if (!"jarfile".equals(fieldName)) // ignore
            continue;

        String fileName = item.getName();

        if (fileName == null) // We don't process files without names
            continue;

        // Now, this name may have a path attached, dependent on the
        // source browser. We need to cover all possible clients...
        char[] pathSeparators = { '/', '\\' };
        // Well, if there is another separator we did not account for,
        // just add it above.

        for (int j = 0; j < pathSeparators.length; j++) {
            int idx = fileName.lastIndexOf(pathSeparators[j]);
            if (idx != -1) {
                fileName = fileName.substring(idx + 1);
                break;
            }
        }

        // Ignore all non-jarfiles.
        if (!fileName.toLowerCase().endsWith(".jar"))
            continue;
        File uploadFile = new File(Config.TMP_DIR, host + '.' + fileName);
        try {
            item.write(uploadFile);
        } catch (Exception e) {
            throw new ServletException(e);
        }
        File runTmp = unjarTmp(uploadFile);

        String runId = null;

        if (origin) {
            // Change origin file to know where this run came from.
            File metaInf = new File(runTmp, "META-INF");
            File originFile = new File(metaInf, "origin");
            if (!originFile.exists()) {
                logger.warning("Origin upload requested. Origin file" + "does not exist!");
                response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Origin file does not exist!");
                break;
            }

            RunId origRun;
            try {
                origRun = new RunId(readStringFromFile(originFile).trim());
            } catch (IndexOutOfBoundsException e) {
                response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE,
                        "Origin file error. " + e.getMessage());
                break;
            }

            runId = origRun.getBenchName() + '.' + origRun.getRunSeq();
            String localHost = origRun.getHostName();
            if (!localHost.equals(Config.FABAN_HOST)) {
                logger.warning("Origin upload requested. Origin host " + localHost
                        + " does not match this host " + Config.FABAN_HOST + '!');
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                break;
            }
            writeStringToFile(runTmp.getName(), originFile);
        } else {
            runId = runTmp.getName();
        }

        if (recursiveCopy(runTmp, new File(Config.OUT_DIR, runId))) {
            uploadFile.delete();
            recursiveDelete(runTmp);
        } else {
            logger.warning("Origin upload requested. Copy error!");
            response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE);
            break;
        }

        response.setStatus(HttpServletResponse.SC_CREATED);
        break;
    }
}

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

/**
 * This focuses on deleting the index data 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//ww w . j a v a2 s .  c  om
 * @throws IOException
 */
protected void doDelete(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.DELETE_INDICES_OPERATION)) {
            String tableName = req.getParameter(AnalyticsAPIConstants.TABLE_NAME_PARAM);
            try {
                if (!securityEnabled)
                    ServiceHolder.getAnalyticsDataService().clearIndexData(tenantId, tableName);
                else
                    ServiceHolder.getSecureAnalyticsDataService().clearIndexData(userName, tableName);
                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 delete request!");
            log.error("unsupported operation performed : " + operation + " with delete request!");
        }
    }
}

From source file:com.vcredit.lrh.microservice.gateway.api.redis.SecurityHandlerRedis.java

private void serverErrorRequest(HttpServletResponse httpServletResponse) throws IOException {
    JSONObject jSONObject = new JSONObject();
    PrintWriter pw = httpServletResponse.getWriter();
    httpServletResponse.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
    jSONObject.put("status", "error");
    jSONObject.put("code", HttpServletResponse.SC_NOT_ACCEPTABLE);
    jSONObject.put("message", "server error , please try again later...");
    pw.write(jSONObject.toJSONString());
    pw.flush();//  w w  w.jav a  2 s.c  o  m
}

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

/**
 * Get table schema.//from  w ww.  j av a 2  s  .  c  o  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));
        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.GET_SCHEMA_OPERATION)) {
            String tableName = req.getParameter(AnalyticsAPIConstants.TABLE_NAME_PARAM);
            try {
                AnalyticsSchema schema;
                if (!securityEnabled)
                    schema = ServiceHolder.getAnalyticsDataService().getTableSchema(tenantId, tableName);
                else
                    schema = ServiceHolder.getSecureAnalyticsDataService().getTableSchema(userName, tableName);
                resp.getOutputStream().write(GenericUtils.serializeObject(schema));
                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:org.wso2.carbon.analytics.servlet.AnalyticsRecordProcessor.java

/**
 * Put records// w  ww  .j  a va 2 s .c  o  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
 */
@SuppressWarnings("unchecked")
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));
        if (operation != null
                && operation.trim().equalsIgnoreCase(AnalyticsAPIConstants.PUT_RECORD_OPERATION)) {
            String username = req.getParameter(AnalyticsAPIConstants.USERNAME_PARAM);
            try {
                List<Record> records = (List<Record>) GenericUtils.deserializeObject(req.getInputStream());
                if (!securityEnabled)
                    ServiceHolder.getAnalyticsDataService().put(records);
                else
                    ServiceHolder.getSecureAnalyticsDataService().put(username, records);
                List<String> recordIds = new ArrayList<>();
                for (Record record : records) {
                    recordIds.add(record.getId());
                }
                resp.getOutputStream().write(GenericUtils.serializeObject(recordIds));
                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:eu.stratosphere.client.web.JobsServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // check, if we are doing the right request
    if (!ServletFileUpload.isMultipartContent(req)) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;// w  w w  .j a va  2  s  . c o  m
    }

    // create the disk file factory, limiting the file size to 20 MB
    DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
    fileItemFactory.setSizeThreshold(20 * 1024 * 1024); // 20 MB
    fileItemFactory.setRepository(tmpDir);

    String filename = null;

    // parse the request
    ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
    try {
        @SuppressWarnings("unchecked")
        Iterator<FileItem> itr = ((List<FileItem>) uploadHandler.parseRequest(req)).iterator();

        // go over the form fields and look for our file
        while (itr.hasNext()) {
            FileItem item = itr.next();
            if (!item.isFormField()) {
                if (item.getFieldName().equals("upload_jar_file")) {

                    // found the file, store it to the specified location
                    filename = item.getName();
                    File file = new File(destinationDir, filename);
                    item.write(file);
                    break;
                }
            }
        }
    } catch (FileUploadException ex) {
        resp.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Invalid Fileupload.");
        return;
    } catch (Exception ex) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "An unknown error occurred during the file upload.");
        return;
    }

    // write the okay message
    resp.sendRedirect(targetPage);
}

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

@Test
public void test10DeleteControllerFromLabel()
        throws ParseException, UnsupportedRestOperation, RestOperationException, MissingParameterRestOperation {
    // Test controller delete in a label
    JSONObject jo = deleteRequestJSONObject(urn_labels + "/ch1/controller?id=17", HttpServletResponse.SC_OK);
    testController17(jo);//from w ww  .jav  a 2s  .c  om

    // impossible to delete again the same controller
    deleteRequestJSONObject(urn_labels + "/ch1/17", HttpServletResponse.SC_NOT_ACCEPTABLE);

    // Test impossible to delete a controller not existing in a Group
    deleteRequestJSONObject(urn_labels + "/ch1/6", HttpServletResponse.SC_NOT_ACCEPTABLE);
    deleteRequestJSONObject(urn_labels + "/ch1/controller?id=6", HttpServletResponse.SC_NOT_ACCEPTABLE);
}

From source file:org.sakaiproject.nakamura.proxy.ICalProxyPostProcessor.java

/**
 * Checks that the response headers are OK. {@code false} is returned if the headers are
 * invalid and the {@code response} arg will have been populated with a suitable error
 * code and message. //from   w ww  .j  ava2 s .  com
 * 
 * @return {@code true} if the response is valid, {@code false} otherwise.
 */
private void validateResponseHeaders(ProxyResponse proxyResponse) throws ResponseFailedException {

    // Ensure the response's Content-Type is one of the ones we permit
    String contentType = getFirstHeaderValue(proxyResponse, "Content-Type");

    if (contentType == null || !ICAL_MIME_TYPES.contains(contentType.toLowerCase())) {

        throw new ResponseFailedException(HttpServletResponse.SC_NOT_ACCEPTABLE,
                String.format(
                        "Remote server responded with a Content-Type which is not "
                                + "permitted. Got: %s, expected one of: %s",
                        contentType, Joiner.on(", ").join(ICAL_MIME_TYPES)));
    }
}

From source file:com.telefonica.euro_iaas.paasmanager.rest.auth.OpenStackAuthenticationFilterTest.java

@Test
public void shouldReturn406WhenAcceptHeaderIsTextPlain() throws IOException, ServletException {
    // given/*from   w w w  . j  a v a2 s .  c  o m*/
    HttpServletRequest servletRequest = mock(HttpServletRequest.class);
    HttpServletResponse servletResponse = mock(HttpServletResponse.class);
    FilterChain filterChain = mock(FilterChain.class);
    when(servletRequest.getHeader(OpenStackAuthenticationFilter.HEADER_ACCEPT)).thenReturn("text/plain");

    // when
    openStackAuthenticationFilter.doFilter(servletRequest, servletResponse, filterChain);
    // then
    verify(servletResponse).sendError(eq(HttpServletResponse.SC_NOT_ACCEPTABLE), anyString());

}