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.fosstrak.epcis.repository.capture.CaptureOperationsServlet.java

/**
 * Implements the EPCIS capture operation. Takes HTTP POST request, extracts
 * the payload into an XML document, validates the document against the
 * EPCIS schema, and captures the EPCIS events given in the document. Errors
 * are caught and returned as simple plaintext messages via HTTP.
 * //from   ww  w . ja  va 2  s .com
 * @param req
 *            The HttpServletRequest.
 * @param rsp
 *            The HttpServletResponse.
 * @throws IOException
 *             If an error occurred while validating the request or writing
 *             the response.
 */
public void doPost(final HttpServletRequest req, final HttpServletResponse rsp)
        throws ServletException, IOException {
    LOG.info("EPCIS Capture Interface invoked.");
    InputStream is = null;

    // check if we have a POST request with form parameters
    if ("application/x-www-form-urlencoded".equalsIgnoreCase(req.getContentType())) {
        rsp.setContentType("text/plain");
        PrintWriter out = rsp.getWriter();
        // check if the 'event' or 'dbReset' form parameter are given
        String event = req.getParameter("event");
        String dbReset = req.getParameter("dbReset");
        if (event != null) {
            LOG.info("Found deprecated 'event=' parameter. Refusing to process request.");
            String msg = "Starting from version 0.2.2, the EPCIS repository does not accept the EPCISDocument in the HTTP POST form parameter 'event' anymore. Please provide the EPCISDocument as HTTP POST payload instead.";
            rsp.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
            out.println(msg);
        } else if (dbReset != null && dbReset.equalsIgnoreCase("true")) {
            doDbReset(rsp);
        }
        out.flush();
        out.close();
        return;
    } else {
        is = req.getInputStream();
    }

    // do the capture operation and handle exceptions
    String responseMsg = "";
    String detailedMsg = "";
    try {
        captureOperationsModule.doCapture(is, req.getUserPrincipal());
        rsp.setStatus(HttpServletResponse.SC_OK);
        responseMsg = "EPCIS capture request succeeded.";
    } catch (SAXException e) {
        responseMsg = "An error processing the XML document occurred.";
        detailedMsg = "Unable to parse incoming XML due to error: " + e.getMessage();
        LOG.info(detailedMsg);
        rsp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    } catch (InvalidFormatException e) {
        responseMsg = "An error parsing the XML contents occurred.";
        detailedMsg = "Unable to parse incoming EPCISDocument due to error: " + e.getMessage();
        LOG.info(detailedMsg);
        rsp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    } catch (final Exception e) {
        responseMsg = "An unexpected error occurred.";
        detailedMsg = "The repository is unable to handle the request due to an internal error.";
        LOG.error(responseMsg, e);
        rsp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }

    // dispatch the response
    req.setAttribute("responseMsg", responseMsg);
    req.setAttribute("detailedMsg", detailedMsg);
    RequestDispatcher dispatcher;
    String showCaptureForm = (String) req.getAttribute("showCaptureForm");
    if (showCaptureForm != null && "true".equals(showCaptureForm)) {
        dispatcher = getServletContext().getRequestDispatcher(PAGE_CAPTURE_FORM);
    } else {
        dispatcher = getServletContext().getRequestDispatcher(PAGE_CAPTURE_INTERFACE);
    }
    dispatcher.forward(req, rsp);
}

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

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {//from w  ww .j a  v a 2s  .co m
        List<String> deployNames = new ArrayList<String>();
        List<String> cantDeployNames = new ArrayList<String>();
        List<String> errDeployNames = new ArrayList<String>();
        List<String> invalidNames = new ArrayList<String>();
        List<String> errHeaders = new ArrayList<String>();
        List<String> errDetails = new ArrayList<String>();

        String user = null;
        String password = null;
        boolean clearConfig = false;
        boolean hasPermission = true;

        // Check whether we have to return text or html
        boolean acceptHtml = false;
        String acceptHeader = request.getHeader("Accept");
        if (acceptHeader != null && acceptHeader.indexOf("text/html") >= 0)
            acceptHtml = true;

        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);

        StringWriter messageBuffer = new StringWriter();
        PrintWriter messageWriter = new PrintWriter(messageBuffer);

        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 ("user".equals(fieldName)) {
                    user = item.getString();
                } else if ("password".equals(fieldName)) {
                    password = item.getString();
                } else if ("clearconfig".equals(fieldName)) {
                    String value = item.getString();
                    clearConfig = Boolean.parseBoolean(value);
                }
                continue;
            }

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

            String fileName = item.getName();

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

            if (Config.SECURITY_ENABLED) {
                if (Config.DEPLOY_USER == null || Config.DEPLOY_USER.length() == 0
                        || !Config.DEPLOY_USER.equals(user)) {
                    hasPermission = false;
                    break;
                }
                if (Config.DEPLOY_PASSWORD == null || Config.DEPLOY_PASSWORD.length() == 0
                        || !Config.DEPLOY_PASSWORD.equals(password)) {
                    hasPermission = false;
                    break;
                }
            }
            // 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")) {
                invalidNames.add(fileName);
                continue;
            }

            String deployName = fileName.substring(0, fileName.length() - 4);

            if (deployName.indexOf('.') > -1) {
                invalidNames.add(deployName);
                continue;
            }

            // Check if we can deploy benchmark or service.
            // If running or queued, we won't deploy benchmark.
            // If service being used by current run,we won't deploy service.
            if (!DeployUtil.canDeployBenchmark(deployName) || !DeployUtil.canDeployService(deployName)) {
                cantDeployNames.add(deployName);
                continue;
            }

            File uploadFile = new File(Config.BENCHMARK_DIR, fileName);
            if (uploadFile.exists())
                FileHelper.recursiveDelete(uploadFile);

            try {
                item.write(uploadFile);
            } catch (Exception e) {
                throw new ServletException(e);
            }

            try {
                DeployUtil.processUploadedJar(uploadFile, deployName);
            } catch (Exception e) {
                messageWriter.println("\nError deploying " + deployName + ".\n");
                e.printStackTrace(messageWriter);
                errDeployNames.add(deployName);
                continue;
            }
            deployNames.add(deployName);
        }

        if (clearConfig)
            for (String benchName : deployNames)
                DeployUtil.clearConfig(benchName);

        if (!hasPermission)
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        else if (cantDeployNames.size() > 0)
            response.setStatus(HttpServletResponse.SC_CONFLICT);
        else if (errDeployNames.size() > 0)
            response.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
        else if (invalidNames.size() > 0)
            response.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
        else if (deployNames.size() > 0)
            response.setStatus(HttpServletResponse.SC_CREATED);
        else
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);

        StringBuilder b = new StringBuilder();

        if (deployNames.size() > 0) {
            if (deployNames.size() > 1)
                b.append("Benchmarks/services ");
            else
                b.append("Benchmark/service ");

            for (int i = 0; i < deployNames.size(); i++) {
                if (i > 0)
                    b.append(", ");
                b.append((String) deployNames.get(i));
            }

            b.append(" deployed.");
            errHeaders.add(b.toString());
            b.setLength(0);
        }

        if (invalidNames.size() > 0) {
            if (invalidNames.size() > 1)
                b.append("Invalid deploy files ");
            else
                b.append("Invalid deploy file ");
            for (int i = 0; i < invalidNames.size(); i++) {
                if (i > 0)
                    b.append(", ");
                b.append((String) invalidNames.get(i));
            }
            b.append(". Deploy files must have .jar extension.");
            errHeaders.add(b.toString());
            b.setLength(0);
        }

        if (cantDeployNames.size() > 0) {
            if (cantDeployNames.size() > 1)
                b.append("Cannot deploy benchmarks/services ");
            else
                b.append("Cannot deploy benchmark/services ");
            for (int i = 0; i < cantDeployNames.size(); i++) {
                if (i > 0)
                    b.append(", ");
                b.append((String) cantDeployNames.get(i));
            }
            b.append(". Benchmark/services being used or " + "queued up for run.");
            errHeaders.add(b.toString());
            b.setLength(0);
        }

        if (errDeployNames.size() > 0) {
            if (errDeployNames.size() > 1) {
                b.append("Error deploying benchmarks/services ");
                for (int i = 0; i < errDeployNames.size(); i++) {
                    if (i > 0)
                        b.append(", ");
                    b.append((String) errDeployNames.get(i));
                }
            }

            errDetails.add(messageBuffer.toString());
            errHeaders.add(b.toString());
            b.setLength(0);
        }

        if (!hasPermission)
            errHeaders.add("Permission denied!");

        Writer writer = response.getWriter();
        if (acceptHtml)
            writeHtml(request, writer, errHeaders, errDetails);
        else
            writeText(writer, errHeaders, errDetails);
        writer.flush();
        writer.close();
    } catch (ServletException e) {
        logger.log(Level.SEVERE, e.getMessage(), e);
        throw e;
    } catch (IOException e) {
        logger.log(Level.SEVERE, e.getMessage(), e);
        throw e;
    } catch (Exception e) {
        logger.log(Level.SEVERE, e.getMessage(), e);
        throw new ServletException(e);
    }
}

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

/**
 * validate Accept Header//from   ww  w .  ja  v a2  s. com
 * 
 * @param request
 * @param response
 * @return
 * @throws IOException
 */
private boolean validateAcceptHeader(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    String headerAccept = request.getHeader(HEADER_ACCEPT);
    if (headerAccept != null) {
        headerAccept = headerAccept.toLowerCase();
        boolean someValidValue = headerAccept.equals("*/*") || headerAccept.equals("application/json")
                || headerAccept.equals("application/xml");

        if (!someValidValue) {
            response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE,
                    "'Accept' header should be application/xml or " + "application/json");
            return false;
        }
    }
    return true;
}

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

/**
 * delete records for range and given ids..
 *
 * @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 w  w  . j  a va  2 s  .  c  o  m*/
 * @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 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);
        if (operation != null
                && operation.trim().equalsIgnoreCase(AnalyticsAPIConstants.DELETE_RECORDS_RANGE_OPERATION)) {
            long timeFrom = Long.parseLong(req.getParameter(AnalyticsAPIConstants.TIME_FROM_PARAM));
            long timeTo = Long.parseLong(req.getParameter(AnalyticsAPIConstants.TIME_TO_PARAM));
            try {
                if (!securityEnabled)
                    ServiceHolder.getAnalyticsDataService().delete(tenantIdParam, tableName, timeFrom, timeTo);
                else
                    ServiceHolder.getSecureAnalyticsDataService().delete(userName, tableName, timeFrom, timeTo);
                resp.setStatus(HttpServletResponse.SC_OK);
            } catch (AnalyticsException e) {
                resp.sendError(HttpServletResponse.SC_EXPECTATION_FAILED, e.getMessage());
            }
        } else if (operation != null
                && operation.trim().equalsIgnoreCase(AnalyticsAPIConstants.DELETE_RECORDS_IDS_OPERATION)) {
            String jsonRecordIds = req.getParameter(AnalyticsAPIConstants.RECORD_IDS_PARAM);
            Type recordIdListType = new TypeToken<List<String>>() {
            }.getType();
            List<String> recordIds = new Gson().fromJson(jsonRecordIds, recordIdListType);
            try {
                if (!securityEnabled)
                    ServiceHolder.getAnalyticsDataService().delete(tenantIdParam, tableName, recordIds);
                else
                    ServiceHolder.getSecureAnalyticsDataService().delete(userName, tableName, 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 post request!");
        }
    }
}

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

/**
 * delete the table// ww w  .  j  a v a2  s . com
 *
 * @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 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_TABLE_OPERATION)) {
            String tableName = req.getParameter(AnalyticsAPIConstants.TABLE_NAME_PARAM);
            try {
                if (!securityEnabled)
                    ServiceHolder.getAnalyticsDataService().deleteTable(tenantId, tableName);
                else
                    ServiceHolder.getSecureAnalyticsDataService().deleteTable(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 post request!");
            log.error("unsupported operation performed : " + operation + " with post request!");
        }
    }
}

From source file:pt.ua.dicoogle.server.web.IndexerServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    // TODO validate user session credentials

    // get which action to take
    String actionStr = request.getParameter(PARAM_ACTION);

    // translate each action string to a action identification
    int action = ACTION_CODE_INVALID;
    if (actionStr != null) {
        if (actionStr.equalsIgnoreCase(ACTION_START_INDEXING))
            action = ACTION_CODE_START_INDEXING;
        else if (actionStr.equalsIgnoreCase(ACTION_STOP_INDEXING))
            action = ACTION_CODE_STOP_INDEXING;
        else if (actionStr.equalsIgnoreCase(ACTION_GET_STATUS))
            action = ACTION_CODE_GET_STATUS;
        else if (actionStr.equalsIgnoreCase(ACTION_SET_INDEXING_PATH))
            action = ACTION_CODE_SET_INDEXING_PATH;
        else if (actionStr.equalsIgnoreCase(ACTION_SET_ADVANCED_SETTINGS))
            action = ACTION_CODE_SET_ADVANCED_SETTINGS;
        else if (actionStr.equalsIgnoreCase(ACTION_GET_PATH_CONTENTS))
            action = ACTION_CODE_GET_PATH_CONTENTS;
    }//from ww w.  j a  va 2 s.  c om

    // response to each action accordingly
    // fix this!
    switch (action) {
    case ACTION_CODE_START_INDEXING:
        System.err.println("Started Indexing!!");

        Dicoogle dic = Dicoogle.getInstance();

        ServerDirectoryPath thepath = (ServerDirectoryPath) dic.getIndexingSettings()
                .get("Dicoogle Directory Monitorization");

        System.out.println("Indexing Home: " + thepath.getPath());
        File f = new File(thepath.getPath());
        URI uri = f.toURI();

        if (uri != null) {
            System.out.println("URI: " + uri.toString());
            List<Task<Report>> report = PluginController.getInstance().index(uri);
            System.out.println("Report Length: " + report.size());
            if (this.ongoingTasks == null)
                this.ongoingTasks = report;
            else
                System.out.println("More than one task in queue");
        } else
            System.out.println("Faulty");
        // send the client back the to previous page
        response.sendRedirect(Session.getLastVisitedURL(request));
        break;

    case ACTION_CODE_STOP_INDEXING:
        // idx.stopIndexing();
        // send the client back the to previous page

        // Cancelling all Tasks
        if (this.ongoingTasks != null) {
            for (Task<Report> t : this.ongoingTasks)
                t.cancel(true);
        }

        response.sendRedirect(Session.getLastVisitedURL(request));
        break;

    case ACTION_CODE_GET_STATUS:
        // get the XML document containing contents of the requested
        // directory path
        writeXMLToResponse(getIndexingStatus(), response, false);
        break;

    case ACTION_CODE_SET_INDEXING_PATH:
        String path = request.getParameter(ACTION_PARAM_PATH);
        if ((path == null) || (path.isEmpty())) {
            response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Invalid path parameter specified!");
            return;
        }

        // send the client back the to previous page
        response.sendRedirect(Session.getLastVisitedURL(request));
        break;

    case ACTION_CODE_SET_ADVANCED_SETTINGS:
        HashMap<String, String[]> advSettings = new HashMap<String, String[]>();

        // get all the settings and their values
        Enumeration<String> params = request.getParameterNames();
        while (params.hasMoreElements()) {
            String name = params.nextElement();
            // ignore the main params (the ones that go us here)
            if (name.equalsIgnoreCase(PARAM_ACTION))
                continue;
            String[] value = request.getParameterValues(name);
            advSettings.put(name, value);
        }

        // HashMap<String, Object> settings = idx.getSettings();
        // Services svcs = Services.getInstance();
        // svcs.processAdvancedSettings(settings, advSettings);

        // try to apply the settings
        /*
         * if (idx.trySettings(settings)){ idx.setSettings(settings);
         * svcs.saveSettings(); // send the client back the to previous page
         * response.sendRedirect(Session.getLastVisitedURL(request)); } else
         */
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid parameters!");
        break;

    case ACTION_CODE_GET_PATH_CONTENTS:
        path = request.getParameter(ACTION_PARAM_PATH);

        // get the XML document containing contents of the requested
        // directory path
        writeXMLToResponse(getPathContents(path), response, false);
        break;

    default:
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid action!");
        return;
    }
}

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

private void validateCalendar(Calendar calendar) throws ResponseFailedException {
    try {/*  w w  w. j  a va  2s. co  m*/
        calendar.validate(true);
    } catch (ValidationException e) {
        throw new ResponseFailedException(HttpServletResponse.SC_NOT_ACCEPTABLE,
                "Invalid Calendar Received: " + e.getMessage());
    }
}

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

@Test
public void test13OnStatus() {

    // Test to get a controller of type light!
    JSONObject jo = getRequestJSONObject(urn_labels + "/ch1/controller?id=12&param=param");
    testController12(jo);/*from   ww  w .  java 2 s .  c o  m*/

    jo = getRequestJSONObject(urn_labels + "/ch1/12?param=param");
    testController12(jo);

    jo = getRequestJSONObject(urn_groups + "/1/controller?id=16&param=param");
    Assert.assertNull(jo); // have been deleted

    jo = getRequestJSONObject(urn_groups + "/1/16?param=param");
    Assert.assertNull(jo); // have been deleted

    jo = getRequestJSONObject("/house/controllers/12?param=param");
    testController12(jo);

    jo = getRequestJSONObject("/house/controllers/controller?id=12&param=param");
    testController12(jo);

    jo = getRequestJSONObject("/house/controllers/12?param=param");
    testController12(jo);

    // Modification
    putRequestJSONObject("/house/controllers/12?status=On", createJsonController12(),
            HttpServletResponse.SC_OK);
    putRequestJSONObject("/house/controllers/controller?id=12&status=Off", createJsonController12(),
            HttpServletResponse.SC_OK);

    putRequestJSONObject(urn_groups + "/1/controller?id=12&param=param", createJsonController12(),
            HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    putRequestJSONObject(urn_groups + "/1/12?status=Off", createJsonController12(), HttpServletResponse.SC_OK);
    putRequestJSONObject(urn_labels + "/ch1/controller?id=12&status=Off", createJsonController12(),
            HttpServletResponse.SC_OK);
    putRequestJSONObject(urn_labels + "/ch1/12?status=Off", createJsonController12(),
            HttpServletResponse.SC_OK);
    putRequestJSONObject("/house/controllers/12?param=param", createJsonController12(),
            HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    putRequestJSONObject("/house/controllers/controller?id=12&status=Off", createJsonController12(),
            HttpServletResponse.SC_OK);
    putRequestJSONObject("/house/controllers/12?status=Off", createJsonController12(),
            HttpServletResponse.SC_OK);

    // creation
    postRequestJSONObject(urn_groups + "/1/controller?id=17&status=Off", createJsonController17(),
            HttpServletResponse.SC_CREATED);
    postRequestJSONObject(urn_groups + "/1/12?status=Off", createJsonController12(),
            HttpServletResponse.SC_NOT_ACCEPTABLE);
    postRequestJSONObject(urn_labels + "/ch1/controller?id=17&status=Off", createJsonController17(),
            HttpServletResponse.SC_CREATED);
    postRequestJSONObject(urn_labels + "/ch1/17?status=Off", createJsonController17(),
            HttpServletResponse.SC_NOT_ACCEPTABLE);
    postRequestJSONObject("/house/17?status=Off", createJsonController17(), HttpServletResponse.SC_BAD_REQUEST);
    postRequestJSONObject("/house/controllers/controller?id=12&status=Off", createJsonController17(),
            HttpServletResponse.SC_NOT_IMPLEMENTED);
    postRequestJSONObject("/house/controllers/12?status=Off", createJsonController17(),
            HttpServletResponse.SC_NOT_IMPLEMENTED);

    // Deletion
    deleteRequestJSONObject(urn_groups + "/1/controller?id=11&status=Off",
            HttpServletResponse.SC_NOT_ACCEPTABLE);
    deleteRequestJSONObject(urn_groups + "/1/11?status=Off", HttpServletResponse.SC_NOT_ACCEPTABLE);
    deleteRequestJSONObject(urn_labels + "/ch1/controller?id=12&status=Off", HttpServletResponse.SC_OK);
    deleteRequestJSONObject(urn_labels + "/ch1/12?status=Off", HttpServletResponse.SC_NOT_ACCEPTABLE);
    deleteRequestJSONObject("/house/controllers/12?status=Off", HttpServletResponse.SC_NOT_IMPLEMENTED);
    deleteRequestJSONObject("/house/controllers/controller?id=12&status=Off",
            HttpServletResponse.SC_NOT_IMPLEMENTED);
}

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

/**
 * Send a drill down request and get the results.
 *
 * @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  av a 2 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);
        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.DRILL_DOWN_SEARCH_OPERATION)) {
            doDrillDownSearch(req, resp, securityEnabled, tenantIdParam, userName);
        } else if (operation != null
                && operation.trim().equalsIgnoreCase(AnalyticsAPIConstants.DRILL_DOWN_SEARCH_COUNT_OPERATION)) {
            doDrillDownSearchCount(req, resp, securityEnabled, tenantIdParam, userName);
        } else if (operation != null && operation.trim()
                .equalsIgnoreCase(AnalyticsAPIConstants.DRILL_DOWN_SEARCH_CATEGORY_OPERATION)) {
            doDrillDownCategories(req, resp, securityEnabled, tenantIdParam, userName);
        } else if (operation != null && operation.trim()
                .equalsIgnoreCase(AnalyticsAPIConstants.DRILL_DOWN_SEARCH_RANGE_COUNT_OPERATION)) {
            doDrillDownRangeCount(req, resp, securityEnabled, tenantIdParam, userName);
        } else if (operation != null && operation.trim()
                .equalsIgnoreCase(AnalyticsAPIConstants.SEARCH_MULTITABLES_WITH_AGGREGATES_OPERATION)) {
            doSearchMultiTablesWithAggregates(req, resp, securityEnabled, tenantIdParam, userName);
        } 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.zimbra.cs.dav.service.DavServlet.java

@Override
public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ZimbraLog.clearContext();/*from  ww  w.  j  ava 2 s  . c  o  m*/
    addRemoteIpToLoggingContext(req);
    ZimbraLog.addUserAgentToContext(req.getHeader(DavProtocol.HEADER_USER_AGENT));

    //bug fix - send 400 for Range requests
    String rangeHeader = req.getHeader(DavProtocol.HEADER_RANGE);
    if (null != rangeHeader) {
        sendError(resp, HttpServletResponse.SC_BAD_REQUEST, "Range header not supported", null, Level.debug);
        return;
    }

    RequestType rtype = getAllowedRequestType(req);
    ZimbraLog.dav.debug("Allowable request types %s", rtype);

    if (rtype == RequestType.none) {
        sendError(resp, HttpServletResponse.SC_NOT_ACCEPTABLE, "Not an allowed request type", null,
                Level.debug);
        return;
    }

    logRequestInfo(req);
    Account authUser = null;
    DavContext ctxt;
    try {
        AuthToken at = AuthProvider.getAuthToken(req, false);
        if (at != null && (at.isExpired() || !at.isRegistered())) {
            at = null;
        }
        if (at != null && (rtype == RequestType.both || rtype == RequestType.authtoken)) {
            authUser = Provisioning.getInstance().get(AccountBy.id, at.getAccountId());
        } else if (at == null && (rtype == RequestType.both || rtype == RequestType.password)) {
            AuthUtil.AuthResult result = AuthUtil.basicAuthRequest(req, resp, true, this);
            if (result.sendErrorCalled) {
                logResponseInfo(resp);
                return;
            }
            authUser = result.authorizedAccount;
        }
        if (authUser == null) {
            try {
                sendError(resp, HttpServletResponse.SC_UNAUTHORIZED, "Authentication failed", null,
                        Level.debug);
            } catch (Exception e) {
            }
            return;
        }
        ZimbraLog.addToContext(ZimbraLog.C_ANAME, authUser.getName());
        ctxt = new DavContext(req, resp, authUser);
    } catch (AuthTokenException e) {
        sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "error getting authenticated user", e);
        return;
    } catch (ServiceException e) {
        sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "error getting authenticated user", e);
        return;
    }

    DavMethod method = sMethods.get(req.getMethod());
    if (method == null) {
        setAllowHeader(resp);
        sendError(resp, HttpServletResponse.SC_METHOD_NOT_ALLOWED, "Not an allowed method", null, Level.debug);
        return;
    }

    long t0 = System.currentTimeMillis();

    CacheStates cache = null;
    try {
        if (ZimbraLog.dav.isDebugEnabled()) {
            try {
                Upload upload = ctxt.getUpload();
                if (upload.getSize() > 0 && upload.getContentType().startsWith("text")) {
                    if (ZimbraLog.dav.isDebugEnabled()) {
                        StringBuilder logMsg = new StringBuilder("REQUEST\n").append(
                                new String(ByteUtil.readInput(upload.getInputStream(), -1, 20480), "UTF-8"));
                        ZimbraLog.dav.debug(logMsg.toString());
                    }
                }
            } catch (DavException de) {
                throw de;
            } catch (Exception e) {
                ZimbraLog.dav.debug("ouch", e);
            }
        }
        cache = checkCachedResponse(ctxt, authUser);
        if (!ctxt.isResponseSent() && !isProxyRequest(ctxt, method)) {

            method.checkPrecondition(ctxt);
            method.handle(ctxt);
            method.checkPostcondition(ctxt);
            if (!ctxt.isResponseSent()) {
                resp.setStatus(ctxt.getStatus());
            }
        }
        if (!ctxt.isResponseSent()) {
            logResponseInfo(resp);
        }
    } catch (DavException e) {
        if (e.getCause() instanceof MailServiceException.NoSuchItemException
                || e.getStatus() == HttpServletResponse.SC_NOT_FOUND)
            ZimbraLog.dav.info(ctxt.getUri() + " not found");
        else if (e.getStatus() == HttpServletResponse.SC_MOVED_TEMPORARILY
                || e.getStatus() == HttpServletResponse.SC_MOVED_PERMANENTLY)
            ZimbraLog.dav.info("sending redirect");

        try {
            if (e.isStatusSet()) {
                resp.setStatus(e.getStatus());
                if (e.hasErrorMessage())
                    e.writeErrorMsg(resp.getOutputStream());
                if (ZimbraLog.dav.isDebugEnabled()) {
                    ZimbraLog.dav.info("sending http error %d because: %s", e.getStatus(), e.getMessage(), e);
                } else {
                    ZimbraLog.dav.info("sending http error %d because: %s", e.getStatus(), e.getMessage());
                }
                if (e.getCause() != null)
                    ZimbraLog.dav.debug("exception: ", e.getCause());
            } else {
                sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "error handling method " + method.getName(), e);
            }
        } catch (IllegalStateException ise) {
            ZimbraLog.dav.debug("can't write error msg", ise);
        }
    } catch (ServiceException e) {
        if (e instanceof MailServiceException.NoSuchItemException) {
            sendError(resp, HttpServletResponse.SC_NOT_FOUND, ctxt.getUri() + " not found", null, Level.info);
            return;
        }
        sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "error handling method " + method.getName(), e);
    } catch (Exception e) {
        try {
            sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "error handling method " + method.getName(), e);
        } catch (Exception ex) {
        }
    } finally {
        long t1 = System.currentTimeMillis();
        ZimbraLog.dav.info("DavServlet operation " + method.getName() + " to " + req.getPathInfo() + " (depth: "
                + ctxt.getDepth().name() + ") finished in " + (t1 - t0) + "ms");
        if (cache != null)
            cacheCleanUp(ctxt, cache);
        ctxt.cleanup();
    }
}