Example usage for javax.servlet.http HttpServletResponse SC_EXPECTATION_FAILED

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

Introduction

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

Prototype

int SC_EXPECTATION_FAILED

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

Click Source Link

Document

Status code (417) indicating that the server could not meet the expectation given in the Expect request header.

Usage

From source file:com.eureka.v1_0.kyc.information.api.KycInformationApiController.java

@ResponseBody
@RequestMapping(method = RequestMethod.POST, consumes = MediaType.TEXT_XML_VALUE, produces = MediaType.TEXT_XML_VALUE, value = "/removecontactinformation")
public RemoveContactInformationResponse removeContactInformation(
        RemoveContactInformationRequest removeContactInformationRequest, HttpServletRequest request,
        HttpServletResponse response) {//from   w w w . j a  va 2  s  .  com
    if (removeContactInformationRequest != null) {
        try {
            witLoggerService.debug(JaxbHandler.toXml(removeContactInformationRequest));
            RemoveContactInformationResponse removeContactInformationResponse = this.kycInformationApiService
                    .removeContactInformation(removeContactInformationRequest);
            if (removeContactInformationResponse != null) {
                witLoggerService.debug(JaxbHandler.toXml(removeContactInformationResponse));
                response.setStatus(HttpServletResponse.SC_OK);
                return removeContactInformationResponse;
            } else {
                response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
            }
        } catch (Exception ex) {
            witLoggerService.warn(ex);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    return null;
}

From source file:com.eureka.v1_0.kyc.information.api.KycInformationApiController.java

@ResponseBody
@RequestMapping(method = RequestMethod.POST, consumes = MediaType.TEXT_XML_VALUE, produces = MediaType.TEXT_XML_VALUE, value = "/updatecontactinformation")
public UpdateContactInformationResponse updateContactInformation(
        UpdateContactInformationRequest updateContactInformationRequest, HttpServletRequest request,
        HttpServletResponse response) {// w ww.  jav  a 2s.  co m
    if (updateContactInformationRequest != null) {
        try {
            witLoggerService.debug(updateContactInformationRequest);
            UpdateContactInformationResponse updateContactInformationResponse = this.kycInformationApiService
                    .updateContactInformation(updateContactInformationRequest);
            if (updateContactInformationResponse != null) {
                witLoggerService.debug(JaxbHandler.toXml(updateContactInformationResponse));
                response.setStatus(HttpServletResponse.SC_OK);
                return updateContactInformationResponse;
            } else {
                response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
            }
        } catch (Exception ex) {
            witLoggerService.warn(ex);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    return null;
}

From source file:org.alfresco.web.app.servlet.UploadContentServlet.java

/**
 * @see javax.servlet.http.HttpServlet#doPut(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *///from w w  w.  j  a  v a2  s  .  c o  m
protected void doPut(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    if (logger.isDebugEnabled() == true) {
        String queryString = req.getQueryString();
        logger.debug("Authenticating request to URL: " + req.getRequestURI()
                + ((queryString != null && queryString.length() > 0) ? ("?" + queryString) : ""));
    }

    AuthenticationStatus status = servletAuthenticate(req, res, false);
    if (status == AuthenticationStatus.Failure || status == AuthenticationStatus.Guest) {
        res.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;
    }

    // Tokenise the URI
    String uri = req.getRequestURI();
    uri = uri.substring(req.getContextPath().length());
    StringTokenizer t = new StringTokenizer(uri, "/");
    int tokenCount = t.countTokens();

    t.nextToken(); // skip servlet name

    // get or calculate the noderef and filename to download as
    NodeRef nodeRef = null;
    String filename = null;
    QName propertyQName = null;

    if (tokenCount == 2) {
        // filename is the only token
        filename = t.nextToken();
    } else if (tokenCount == 4 || tokenCount == 5) {
        // assume 'workspace' or other NodeRef based protocol for remaining URL
        // elements
        StoreRef storeRef = new StoreRef(t.nextToken(), t.nextToken());
        String id = t.nextToken();
        // build noderef from the appropriate URL elements
        nodeRef = new NodeRef(storeRef, id);

        if (tokenCount == 5) {
            // filename is last remaining token
            filename = t.nextToken();
        }

        // get qualified of the property to get content from - default to
        // ContentModel.PROP_CONTENT
        propertyQName = ContentModel.PROP_CONTENT;
        String property = req.getParameter(ARG_PROPERTY);
        if (property != null && property.length() != 0) {
            propertyQName = QName.createQName(property);
        }
    } else {
        logger.debug("Upload URL did not contain all required args: " + uri);
        res.sendError(HttpServletResponse.SC_EXPECTATION_FAILED);
        return;
    }

    // get the services we need to retrieve the content
    ServiceRegistry serviceRegistry = getServiceRegistry(getServletContext());
    ContentService contentService = serviceRegistry.getContentService();
    PermissionService permissionService = serviceRegistry.getPermissionService();
    MimetypeService mimetypeService = serviceRegistry.getMimetypeService();
    NodeService nodeService = serviceRegistry.getNodeService();

    InputStream is = req.getInputStream();
    BufferedInputStream inputStream = new BufferedInputStream(is);

    // Sort out the mimetype
    String mimetype = req.getParameter(ARG_MIMETYPE);
    if (mimetype == null || mimetype.length() == 0) {
        mimetype = MIMETYPE_OCTET_STREAM;
        if (filename != null) {
            MimetypeService mimetypeMap = serviceRegistry.getMimetypeService();
            int extIndex = filename.lastIndexOf('.');
            if (extIndex != -1) {
                String ext = filename.substring(extIndex + 1);
                mimetype = mimetypeService.getMimetype(ext);
            }
        }
    }

    // Get the encoding
    String encoding = req.getParameter(ARG_ENCODING);
    if (encoding == null || encoding.length() == 0) {
        // Get the encoding
        ContentCharsetFinder charsetFinder = mimetypeService.getContentCharsetFinder();
        Charset charset = charsetFinder.getCharset(inputStream, mimetype);
        encoding = charset.name();
    }

    // Get the locale
    Locale locale = I18NUtil.parseLocale(req.getParameter(ARG_LOCALE));
    if (locale == null) {
        locale = I18NUtil.getContentLocale();
        if (nodeRef != null) {
            ContentData contentData = (ContentData) nodeService.getProperty(nodeRef, propertyQName);
            if (contentData != null) {
                locale = contentData.getLocale();
            }
        }
    }

    if (logger.isDebugEnabled()) {
        if (nodeRef != null) {
            logger.debug("Found NodeRef: " + nodeRef.toString());
        }
        logger.debug("For property: " + propertyQName);
        logger.debug("File name: " + filename);
        logger.debug("Mimetype: " + mimetype);
        logger.debug("Encoding: " + encoding);
        logger.debug("Locale: " + locale);
    }

    // Check that the user has the permissions to write the content
    if (permissionService.hasPermission(nodeRef, PermissionService.WRITE_CONTENT) == AccessStatus.DENIED) {
        if (logger.isDebugEnabled() == true) {
            logger.debug("User does not have permissions to wrtie content for NodeRef: " + nodeRef.toString());
        }

        if (logger.isDebugEnabled()) {
            logger.debug("Returning 403 Forbidden error...");
        }

        res.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    // Try and get the content writer
    ContentWriter writer = contentService.getWriter(nodeRef, propertyQName, true);
    if (writer == null) {
        if (logger.isDebugEnabled() == true) {
            logger.debug("Content writer cannot be obtained for NodeRef: " + nodeRef.toString());
        }
        res.sendError(HttpServletResponse.SC_EXPECTATION_FAILED);
        return;
    }

    // Set the mimetype, encoding and locale
    writer.setMimetype(mimetype);
    writer.setEncoding(encoding);
    if (locale != null) {
        writer.setLocale(locale);
    }

    // Stream the content into the repository
    writer.putContent(inputStream);

    if (logger.isDebugEnabled() == true) {
        logger.debug("Content details: " + writer.getContentData().toString());
    }

    // Set return status
    res.getWriter().write(writer.getContentData().toString());
    res.flushBuffer();

    if (logger.isDebugEnabled() == true) {
        logger.debug("UploadContentServlet done");
    }
}

From source file:org.apache.click.ClickServlet.java

/**
 * Provides an Ajax exception handler. Exceptions are wrapped inside a
 * <tt>div</tt> element and streamed back to the browser. The response status
 * is set to an {@link javax.servlet.http.HttpServletResponse#SC_INTERNAL_SERVER_ERROR HTTP 500 error}
 * which allows the JavaScript that initiated the Ajax request to handle
 * the error as appropriate.//from   w  w  w . ja  v a  2 s  .  c  om
 * <p/>
 * If Click is running in <tt>development</tt> modes the exception stackTrace
 * will be rendered, in <tt>production</tt> modes an error message is
 * rendered.
 * <p/>
 * Below is an example error response:
 *
 * <pre class="prettyprint">
 * &lt;div id='errorReport' class='errorReport'&gt;
 * The application encountered an unexpected error.
 * &lt;/div&gt;
 * </pre>
 *
 * @param request the servlet request
 * @param response the servlet response
 * @param isPost determines whether the request is a POST
 * @param exception the error causing exception
 * @param pageClass the page class with the error
 */
protected void handleAjaxException(HttpServletRequest request, HttpServletResponse response, boolean isPost,
        Throwable exception, Class<? extends Page> pageClass) {

    // If an exception occurs during an Ajax request, stream
    // the exception instead of creating an ErrorPage
    PrintWriter writer = null;
    try {
        String returnJson = "";
        BizException bizException = null;
        if (exception instanceof BizException) {
            bizException = (BizException) exception;
        } else if (exception.getCause() instanceof BizException) {
            bizException = (BizException) exception.getCause();
        } else {
            bizException = null;
        }
        if (bizException != null) {
            if (!bizException.isAjaxRequest()) {
                //ajax
                response.setContentType("text/html;charset=GBK");
                writer = getPrintWriter(response);
                response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
                returnJson = ClickUtil.creaReturnJSON(bizException);
            } else {
                //ajax                 
                response.setContentType("text/json;charset=GBK");
                writer = getPrintWriter(response);
                response.setStatus(HttpServletResponse.SC_OK);
                returnJson = ClickUtil.creaReturnJSON(bizException);
            }
        } else {
            // 
            response.setContentType("text/html;charset=GBK");
            writer = getPrintWriter(response);
            response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
            returnJson = "{\"statusCode\":\"300\", \"message\":\"-" + exception.getMessage()
                    + "\"}";
        }
        writer.write(returnJson);
    } catch (Throwable error) {
        logger.error(error.getMessage(), error);
        throw new RuntimeException(error);
    } finally {
        if (writer != null) {
            writer.flush();
        }
    }
    if (exception instanceof BizException && exception != null
            && ((BizException) exception).getCode() == BizException.AJAXEND) {
        logger.debug("ajax request success end");
    } else {
        logger.error("handleException: ", exception);
    }
}

From source file:org.apache.qpid.server.management.plugin.servlet.rest.SaslServlet.java

@Override
protected void doPostWithSubjectAndActor(final HttpServletRequest request, final HttpServletResponse response)
        throws IOException {
    checkSaslAuthEnabled(request);//from   w w w. j av a2s  . c o m

    try {
        response.setContentType("application/json");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);

        HttpSession session = request.getSession();

        String mechanism = request.getParameter("mechanism");
        String id = request.getParameter("id");
        String saslResponse = request.getParameter("response");

        SubjectCreator subjectCreator = getSubjectCreator(request);

        if (mechanism != null) {
            if (id == null) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Creating SaslServer for mechanism: " + mechanism);
                }
                SaslServer saslServer = subjectCreator.createSaslServer(mechanism, request.getServerName(),
                        null/*TODO*/);
                evaluateSaslResponse(request, response, session, saslResponse, saslServer, subjectCreator);
            } else {
                response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
                session.removeAttribute(ATTR_ID);
                session.removeAttribute(ATTR_SASL_SERVER);
                session.removeAttribute(ATTR_EXPIRY);
            }
        } else {
            if (id != null) {
                if (id.equals(session.getAttribute(ATTR_ID))
                        && System.currentTimeMillis() < (Long) session.getAttribute(ATTR_EXPIRY)) {
                    SaslServer saslServer = (SaslServer) session.getAttribute(ATTR_SASL_SERVER);
                    evaluateSaslResponse(request, response, session, saslResponse, saslServer, subjectCreator);
                } else {
                    response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
                    session.removeAttribute(ATTR_ID);
                    session.removeAttribute(ATTR_SASL_SERVER);
                    session.removeAttribute(ATTR_EXPIRY);
                }
            } else {
                response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
                session.removeAttribute(ATTR_ID);
                session.removeAttribute(ATTR_SASL_SERVER);
                session.removeAttribute(ATTR_EXPIRY);
            }
        }
    } catch (IOException e) {
        LOGGER.error("Error processing SASL request", e);
        throw e;
    } catch (RuntimeException e) {
        LOGGER.error("Error processing SASL request", e);
        throw e;
    }
}

From source file:org.mortbay.servlet.LLabsMultiPartFilter.java

/**
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
 *      javax.servlet.ServletResponse, javax.servlet.FilterChain)
 *///from  w  w  w.  j  av  a2 s .c o  m
@SuppressWarnings("unchecked")
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    logger.info("Received uploadRequest:" + request);
    if (Log.isDebugEnabled())
        Log.debug(getClass().getName() + ">>> Received Request");

    HttpServletRequest srequest = (HttpServletRequest) request;
    if (srequest.getContentType() == null || !srequest.getContentType().startsWith("multipart/form-data")) {
        chain.doFilter(request, response);
        return;
    }
    if (ServletFileUpload.isMultipartContent(srequest)) {
        // Parse the request

        List<File> tempFiles = new ArrayList<File>();
        try {

            MultiMap params = new MultiMap();

            logger.info("Parsing Request");

            List<DiskFileItem> fileItems = uploadHandler.parseRequest(srequest);

            logger.info("Done Parsing Request, got FileItems:" + fileItems);

            StringBuilder filenames = new StringBuilder();

            for (final DiskFileItem diskFileItem : fileItems) {
                if (diskFileItem.getName() == null && diskFileItem.getFieldName() != null
                        && diskFileItem.getFieldName().length() > 0) {
                    params.put(diskFileItem.getFieldName(), diskFileItem.getString());
                    continue;
                }
                if (diskFileItem.getName() == null)
                    continue;
                final File tempFile = File.createTempFile("upload" + diskFileItem.getName(), ".tmp");
                tempFiles.add(tempFile);

                diskFileItem.write(tempFile);
                request.setAttribute(diskFileItem.getName(), tempFile);
                filenames.append(diskFileItem.getName()).append(",");
            }
            params.put("Filenames", filenames.toString());
            logger.info("passing on filter");
            chain.doFilter(new Wrapper(srequest, params), response);

            for (final DiskFileItem diskFileItem : fileItems) {
                diskFileItem.delete();
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
            Log.warn(getClass().getName() + "MPartRequest, ERROR:" + e.getMessage());
            logger.error("FileUpload Failed", e);
            writeResponse((HttpServletResponse) response, HttpServletResponse.SC_EXPECTATION_FAILED);
        } catch (Throwable e) {
            logger.error(e.getMessage(), e);
            Log.warn(getClass().getName() + "MPartRequest, ERROR:" + e.getMessage());
            e.printStackTrace();
            writeResponse((HttpServletResponse) response, HttpServletResponse.SC_EXPECTATION_FAILED);
        } finally {
            for (File tempFile : tempFiles) {
                try {
                    tempFile.delete();
                } catch (Throwable t) {
                }
            }
        }
    }

}

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 va  2  s  .  c  om*/
 * @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!");
        }
    }
}

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//from  w  ww. j a v a2  s  .co  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 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:org.wso2.carbon.analytics.servlet.AnalyticsIndexProcessor.java

/**
 * Re-index the records in the given timestamp period.
 *
 * @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//www  .j av  a2s  .  co 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));
        if (operation != null && operation.trim().equalsIgnoreCase(AnalyticsAPIConstants.REINDEX_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 {
                if (!securityEnabled)
                    ServiceHolder.getAnalyticsDataService().reIndex(tenantIdParam, tableName, timeFrom, timeTo);
                else
                    ServiceHolder.getSecureAnalyticsDataService().reIndex(userName, tableName, timeFrom,
                            timeTo);
                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

/**
 * Get record count// www.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 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!");
        }
    }
}