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:com.vmware.identity.proxyservice.LogonProcessorImpl.java

@Override
public void authenticationSuccess(Message arg0, Locale locale, String tenant, HttpServletRequest request,
        HttpServletResponse response) {/*from ww w  .  ja v a 2s. c om*/

    try {
        Validate.notNull(arg0, "arg0");
        Validate.notNull(response, "response obj for service provider");
        Validate.notNull(request, "request obj for service provider");
        Validate.notEmpty(tenant, "tenant");

        SAMLResponseSenderFactory responseSenderFactory = new SAMLAuthnResponseSenderFactory();

        IdmAccessor idmAccessor = new DefaultIdmAccessorFactory().getIdmAccessor();
        idmAccessor.setTenant(tenant);

        if (arg0.isIdpInitiated()) {
            log.debug("IDP-Initiated: Begin processing authentication response.");
            Validate.notNull(locale, "locale");

            PrincipalId principal = validateExternalUser(idmAccessor, arg0);
            if (principal == null) {
                authenticationError(arg0, locale, tenant, request, response);
                return;
            }

            Session currentSession = Shared.getSession(sessionManager, request, tenant);
            if (currentSession == null) {
                currentSession = this.sessionManager.createSession(principal, AuthnMethod.ASSERTION,
                        arg0.getSessionIndex(), arg0.getSource());

                String tenantSessionCookieName = Shared.getTenantSessionCookieName(tenant);
                log.trace("Setting cookie " + tenantSessionCookieName + " value " + currentSession.getId());

                Shared.addSessionCookie(tenantSessionCookieName, currentSession.getId(), response);
            }

            String rpID = chooseSignInRPSite(idmAccessor, request, response, locale);

            if (null == rpID) {
                //skip for this request. There will be a new request with RP selected.
                log.debug("No Relying party was selected yet. Skip sending the SAML response!");
            } else {
                SAMLResponseSender responseSender = responseSenderFactory.buildResponseSender(tenant, response,
                        locale, null, //for IDP initiated, no relay state in post Response to SP
                        null, //no request
                        currentSession.getAuthnMethod(), currentSession.getId(),
                        currentSession.getPrincipalId(), messageSource, sessionManager);

                Document token = responseSender.generateTokenForResponse(rpID);

                responseSender.sendResponseToRP(rpID, token);
            }

            log.info("IDP-Initiated: End processing authentication response. Session was created.");
        } else {

            log.debug("SP-Initiated: Begin processing authentication response.");
            Validate.notNull(requestState, "requestState");
            locale = requestState.getLocale();
            Validate.notNull(locale, "locale");

            tenant = requestState.getIdmAccessor().getTenant();

            PrincipalId principal = validateExternalUser(idmAccessor, arg0);
            if (principal == null) {
                authenticationError(arg0, locale, tenant, request, response);
                return;
            }

            //send response to initiating relying party
            requestState.addResponseHeaders(response); // set response headers
            requestState.setPrincipalId(principal);
            requestState.setAuthnMethod(AuthnMethod.ASSERTION);
            requestState.createSession(arg0.getSessionIndex(), arg0.getSource());

            String tenantSessionCookieName = Shared.getTenantSessionCookieName(tenant);
            log.trace("Setting cookie " + tenantSessionCookieName + " value " + requestState.getSessionId());

            Shared.addSessionCookie(tenantSessionCookieName, requestState.getSessionId(), response);

            SAMLResponseSender responseSender = responseSenderFactory.buildResponseSender(tenant, response,
                    locale, null, //for IDP initiated, no relay state in post Response to SP
                    requestState, AuthnMethod.ASSERTION, requestState.getSessionId(), principal, messageSource,
                    sessionManager);

            String rpID = requestState.getAuthnRequest().getIssuer().getValue();

            Validate.notEmpty(rpID, "No Relying party ID in SAML authentication request!");
            Document token = responseSender.generateTokenForResponse(rpID);
            responseSender.sendResponseToRP(rpID, token);

            log.info("SP-Initiated: End processing  Authentication response. Session was created.");
        }
    } catch (InvalidTokenException f) {
        log.error("Caught InvalidTokenException in validating external token {}", f.toString());
        com.vmware.identity.websso.client.ValidationResult extResponseVr = new com.vmware.identity.websso.client.ValidationResult(
                HttpServletResponse.SC_NOT_ACCEPTABLE, OasisNames.RESPONDER,
                "Unable to validate token issued by external IDP");
        arg0.setValidationResult(extResponseVr);
        authenticationError(arg0, locale, tenant, request, response);

    } catch (SamlServiceException e) {
        log.error("Caught Saml Service Exception in creating WebSSO session or issuring token. ", e.toString());
        if (!arg0.isIdpInitiated() && requestState != null) {
            requestState.setValidationResult(new ValidationResult(OasisNames.RESPONDER, e.getMessage()));
        }
        authenticationError(arg0, locale, tenant, request, response); // server
    } catch (IOException g) {
        log.error("Caught IOException in sending out response or redirecting to relying party {}",
                g.toString());
        internalError(g, locale, tenant, request, response);
    }
}

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

/**
 * Stream the records in a given record group.
 *
 * @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 av  a 2  s.  c o  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.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 get request!");
        }
    }
}

From source file:org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver.java

/**
 * Handle the case where no {@linkplain org.springframework.http.converter.HttpMessageConverter message converters}
 * were found that were acceptable for the client (expressed via the {@code Accept} header.
 * <p>The default implementation sends an HTTP 406 error and returns an empty {@code ModelAndView}.
 * Alternatively, a fallback view could be chosen, or the HttpMediaTypeNotAcceptableException
 * could be rethrown as-is./*from  w ww  .ja  va  2s .  c o  m*/
 * @param ex the HttpMediaTypeNotAcceptableException to be handled
 * @param request current HTTP request
 * @param response current HTTP response
 * @param handler the executed handler
 * @return an empty ModelAndView indicating the exception was handled
 * @throws IOException potentially thrown from response.sendError()
 */
protected ModelAndView handleHttpMediaTypeNotAcceptable(HttpMediaTypeNotAcceptableException ex,
        HttpServletRequest request, HttpServletResponse response, @Nullable Object handler) throws IOException {

    response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE);
    return new ModelAndView();
}

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

/**
 * Responsible for uploading the runs.//from   w  w w . ja v  a 2 s  . co  m
 * @param request
 * @param response
 * @return String
 * @throws java.io.IOException
 * @throws javax.servlet.ServletException
 * @throws java.lang.ClassNotFoundException
 */
public String uploadRuns(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException, ClassNotFoundException {
    // 3. Upload the run
    HashSet<String> duplicateSet = new HashSet<String>();
    HashSet<String> replaceSet = new HashSet<String>();
    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 ("replace".equals(fieldName)) {
                replaceSet.add(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);
        }
        int runIdx = fileName.lastIndexOf(".");
        String runName = host + '.' + fileName.substring(0, runIdx);
        File runTmp = unjarTmp(uploadFile);
        //Check if archived recently
        if (checkIfArchived(runName) && !(replaceSet.contains(fileName.substring(0, runIdx)))) {
            //Now check if timestamps are same
            //Get the timestamp of run being uploaded at this point
            //ts is timestamp of run being uploaded
            String ts = getRunIdTimestamp(runName, Config.TMP_DIR);
            l1: while (true) {
                //reposTs is timestamp of run being compared in the
                //repository
                String reposTs = getRunIdTimestamp(runName, Config.OUT_DIR);
                if (reposTs.equals(ts)) {
                    duplicateSet.add(fileName.substring(0, runIdx));
                } else {
                    runName = getNextRunId(runName);
                    if (checkIfArchived(runName))
                        continue l1;
                    File newRunNameFile = new File(Config.OUT_DIR, runName);
                    if (newRunNameFile.exists()) {
                        recursiveDelete(newRunNameFile);
                    }
                    if (recursiveCopy(runTmp, newRunNameFile)) {
                        newRunNameFile.setLastModified(runTmp.lastModified());
                        uploadTags(runName);
                        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;
            }
        } else {
            //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();
            }
            File newRunFile = new File(Config.OUT_DIR, runId);
            if (newRunFile.exists()) {
                recursiveDelete(newRunFile);
            }
            if (recursiveCopy(runTmp, newRunFile)) {
                newRunFile.setLastModified(runTmp.lastModified());
                uploadFile.delete();
                uploadTags(runId);
                recursiveDelete(runTmp);
            } else {
                logger.warning("Origin upload requested. Copy error!");
                response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE);
                break;
            }
        }
        response.setStatus(HttpServletResponse.SC_CREATED);
        //break;
    }
    request.setAttribute("duplicates", duplicateSet);
    return "/duplicates.jsp";
}

From source file:org.infoglue.cms.applications.contenttool.actions.UpdateContentVersionAttributeAction.java

/**
 * This command updates a certain attribute in a content version.
 * Lately we added a timeout on the wait for other threads to finish to avoid locks.
 *//*from   www .  j  av  a2 s  .  c  o m*/
public String doSaveAndReturnValue() {
    /*
    try
    {
       Random rand = new Random();
        int randomNum = rand.nextInt((10 - 1) + 1) + 1;
       System.out.println("Sleep...");
       Thread.sleep(randomNum*1000);
    } 
    catch (Exception e)
    {
    }
    */

    int index = 0;
    while (active && index < 100) {
        logger.info("Waiting for previous thread..");
        try {
            Thread.sleep(50);
        } catch (Exception e) {
        }
        index++;
    }

    synchronized (active) {
        active = new Boolean(true);
    }

    try {
        logger.info("Updating content version attribute through ajax....");
        logger.info("contentId:" + contentId);
        logger.info("languageId:" + languageId);
        logger.info("attributeName:" + attributeName);

        super.initialize(this.contentVersionId, this.contentId, this.languageId);

        this.contentVersionVO = this.getContentVersionVO();
        if (this.contentVersionVO == null) {
            ContentVO contentVO = ContentController.getContentController().getContentVOWithId(contentId);
            ContentTypeDefinitionVO contentTypeDefinitionVO = ContentTypeDefinitionController.getController()
                    .getContentTypeDefinitionVOWithId(contentVO.getContentTypeDefinitionId());

            StringBuffer sb = new StringBuffer();
            sb.append(
                    "<?xml version=\"1.0\" encoding=\"UTF-8\"?><article xmlns=\"x-schema:ArticleSchema.xml\"><attributes>");
            List contentTypeAttributes = ContentTypeDefinitionController.getController()
                    .getContentTypeAttributes(contentTypeDefinitionVO, true);
            Iterator contentTypeAttributesIterator = contentTypeAttributes.iterator();
            while (contentTypeAttributesIterator.hasNext()) {
                ContentTypeAttribute contentTypeAttribute = (ContentTypeAttribute) contentTypeAttributesIterator
                        .next();
                String initialValue = contentTypeAttribute.getContentTypeAttribute("initialData")
                        .getContentTypeAttributeParameterValue().getValue("label");
                if (initialValue == null || initialValue.trim().equals(""))
                    initialValue = "State " + contentTypeAttribute.getName();
                sb.append("<" + contentTypeAttribute.getName() + "><![CDATA[" + initialValue + "]]></"
                        + contentTypeAttribute.getName() + ">");
            }
            sb.append("</attributes></article>");

            ContentVersionVO contentVersionVO = new ContentVersionVO();
            contentVersionVO.setVersionComment("Autocreated");
            contentVersionVO.setVersionModifier(this.getInfoGluePrincipal().getName());
            contentVersionVO.setVersionValue(sb.toString());
            this.contentVersionVO = ContentVersionController.getContentVersionController().create(contentId,
                    languageId, contentVersionVO, null);
        } else if (!this.contentVersionVO.getStateId().equals(ContentVersionVO.WORKING_STATE)) {
            ContentVersionVO latestContentVersionVO = ContentVersionController.getContentVersionController()
                    .getLatestContentVersionVO(this.contentVersionVO.getContentId(),
                            this.contentVersionVO.getLanguageId());
            if (latestContentVersionVO.getId().intValue() > this.contentVersionVO.getId().intValue()
                    && latestContentVersionVO.getStateId().equals(ContentVersionVO.WORKING_STATE)) {
                logger.warn("The version is actually not in published state any more: "
                        + latestContentVersionVO.getContentId());
                this.contentVersionVO = latestContentVersionVO;
                this.contentVersionId = latestContentVersionVO.getId();
            } else {
                ContentVersionVO contentVersion = ContentStateController.changeState(
                        this.contentVersionVO.getContentVersionId(), ContentVersionVO.WORKING_STATE,
                        "Edit on sight", false, null, this.getInfoGluePrincipal(),
                        this.contentVersionVO.getContentId(), new ArrayList());
                logger.info("Changed state on: " + latestContentVersionVO.getContentId());
                this.contentVersionId = contentVersion.getContentVersionId();
                this.contentVersionVO = contentVersion;
            }
        }

        String attributeValue = getRequest().getParameter(this.attributeName);
        logger.info("*************************************************");
        logger.info("** SAVING **");
        logger.info("*************************************************");
        logger.info("attributeValue real:" + attributeValue);

        /*
        for(int i=0; i<attributeValue.length(); i++)
           logger.info("c:" + (int)attributeValue.charAt(i) + "-" + Integer.toHexString((int)attributeValue.charAt(i)));
        */

        if (attributeValue != null) {
            boolean enableCustomCharactersParsing = CmsPropertyHandler.getEnableCustomCharactersParsing();
            logger.info("enableCustomCharactersParsing: " + enableCustomCharactersParsing);
            if (enableCustomCharactersParsing) {
                boolean isUTF8 = false;
                boolean hasUnicodeChars = false;
                if (attributeValue.indexOf((char) 65533) > -1)
                    isUTF8 = true;

                for (int i = 0; i < attributeValue.length(); i++) {
                    int c = (int) attributeValue.charAt(i);
                    //logger.error("c2:" + c + "-" + Integer.toHexString(c));
                    if (c > 255 && c < 65533)
                        hasUnicodeChars = true;
                }

                logger.debug("isUTF8:" + isUTF8);
                logger.debug("hasUnicodeChars:" + hasUnicodeChars);

                if (!isUTF8 && !hasUnicodeChars) {
                    String fromEncoding = CmsPropertyHandler.getUploadFromEncoding();
                    if (fromEncoding == null)
                        fromEncoding = "iso-8859-1";

                    String toEncoding = CmsPropertyHandler.getUploadToEncoding();
                    if (toEncoding == null)
                        toEncoding = "utf-8";

                    String[] controlChars = CmsPropertyHandler.getCustomCharactersForConversionParsed();
                    if (logger.isInfoEnabled()) {
                        logger.info("controlChars: " + Arrays.toString(controlChars));
                    }

                    boolean convert = true;
                    for (String charToTest : controlChars) {
                        if (logger.isInfoEnabled()) {
                            logger.info("Index for " + charToTest + ":" + attributeValue.indexOf(charToTest));
                        }
                        if (attributeValue.indexOf(charToTest) > -1) {
                            convert = false;
                            break;
                        }
                    }

                    if (convert) {
                        attributeValue = new String(attributeValue.getBytes(fromEncoding), toEncoding);
                    }

                }
            }

            logger.info("\n\nattributeValue original:" + attributeValue);
            attributeValue = parseInlineAssetReferences(attributeValue);
            logger.info("attributeValue transformed:" + attributeValue + "\n\n");

            setAttributeValue(this.contentVersionVO, this.attributeName, attributeValue);
            ceb.throwIfNotEmpty();

            this.contentVersionVO.setVersionModifier(this.getInfoGluePrincipal().getName());
            ContentVersionController.getContentVersionController().update(this.contentId, this.languageId,
                    this.contentVersionVO, this.getInfoGluePrincipal());
            logger.info("*************************************************");

            attributeValue = PageEditorHelper.parseAttributeForInlineEditing(attributeValue, true,
                    getDeliverContext(), contentId, languageId);
        }

        this.getResponse().setContentType("text/plain; charset=utf-8");
        this.getResponse().setCharacterEncoding("utf-8");
        //this.getResponse().setContentType("text/plain");
        this.getResponse().getWriter().println(attributeValue);
    } catch (ConstraintException ce) {
        logger.info("Error saving attribute - not allowed by validation: " + ce.getMessage());
        this.getResponse().setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
        try {
            final String errorCode = ce.getErrorCode();
            String localizedErrorMessage;
            if (errorCode.length() > 5) {
                localizedErrorMessage = StringEscapeUtils.unescapeXml(errorCode);
            } else {
                localizedErrorMessage = getLocalizedErrorMessage(getLocale(), errorCode);
                String requiredErrorCode = "300";
                if (requiredErrorCode.equals(errorCode)) {
                    try {
                        String fieldName = ce.getFieldName();
                        fieldName = fieldName.substring(fieldName.lastIndexOf(".") + 1);
                        ContentVO contentVO = ContentController.getContentController()
                                .getContentVOWithId(this.contentId);
                        String fieldDisplayName = ContentTypeDefinitionController.getController()
                                .getContentTypeDefinitionAttributeDisplayName(
                                        contentVO.getContentTypeDefinitionId(), fieldName,
                                        getLocale().getLanguage());
                        if (fieldDisplayName == null) {
                            logger.info("Did not find a display name for attribute. " + fieldName);
                        } else {
                            localizedErrorMessage += " (" + fieldDisplayName + ")";
                        }
                    } catch (Exception ex) {
                        logger.warn(
                                "Failed to get the display name for required field validation error. ContentId: "
                                        + contentId + ". FieldName: " + ce.getFieldName() + ". Message: "
                                        + ex.getMessage());
                        logger.info(
                                "Failed to get the display name for required field validation error. ContentId: "
                                        + contentId + ". FieldName: " + ce.getFieldName(),
                                ex);
                    }
                }
            }
            this.getResponse().setCharacterEncoding("utf-8");
            this.getResponse().getWriter().println(localizedErrorMessage);
        } catch (IOException ex) {
            logger.error("Error when reporting constraint exception for content attribute update. Message: "
                    + ex.getMessage());
        }
        return NONE;
    } catch (Throwable t) {
        logger.error("Error saving attribute: " + t.getMessage(), t);
        this.getResponse().setStatus(this.getResponse().SC_INTERNAL_SERVER_ERROR);
        return ERROR;
    } finally {
        synchronized (active) {
            active = new Boolean(false);
        }
    }

    return NONE;
}

From source file:de.zib.gndms.kit.monitor.GroovyMoniServlet.java

private static ServletRuntimeException notAcceptable(String s) {
    return new ServletRuntimeException(HttpServletResponse.SC_NOT_ACCEPTABLE, s, false);
}

From source file:org.infoscoop.gadgets.servlet.HttpRequestHandler.java

/** Format a response as JSON, including additional JSON inserted by chained content fetchers. */
protected Object transformBody(HttpApiRequest request, HttpResponse results) throws GadgetException {
    String body = results.getResponseAsString();
    /*//  w ww  .  j a va 2s  . c  o m
    if ("feed".equalsIgnoreCase(request.format)) {
      return processFeed(request, body);
    } else
    */
    if ("json".equalsIgnoreCase(request.format)) {
        try {
            body = body.trim();
            if (body.length() > 0 && body.charAt(0) == '[') {
                return new JSONArray(body);
            } else {
                return new JSONObject(body);
            }
        } catch (JSONException e) {
            // TODO: include data block with invalid JSON
            throw new ProtocolException(HttpServletResponse.SC_NOT_ACCEPTABLE, "Response not valid JSON", e);
        }
    }

    return body;
}

From source file:org.dataconservancy.ui.api.ProjectController.java

@ExceptionHandler(BizPolicyException.class)
public void handleException(BizPolicyException e, HttpServletRequest req, HttpServletResponse resp) {
    log.debug("Handling exception [" + e.getClass() + "] [" + e.getMessage() + "]");

    if (e.getType() == Type.AUTHENTICATION_ERROR) {
        resp.setStatus(HttpStatus.SC_UNAUTHORIZED);
    } else if (e.getType() == BizPolicyException.Type.AUTHORIZATION_ERROR) {
        resp.setStatus(HttpStatus.SC_UNAUTHORIZED);
    } else if (e.getType() == BizPolicyException.Type.VALIDATION_ERROR) {
        resp.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
    } else {/*w ww  .ja  v a2  s .c om*/
        resp.setStatus(HttpStatus.SC_BAD_REQUEST);
    }

    // TODO have to set Authentication header?

    try {
        resp.getWriter().print(e.getMessage());
        resp.getWriter().flush();
        resp.getWriter().close();
    } catch (Exception ee) {
        log.debug("Handling exception", e);
    }
}

From source file:com.google.nigori.server.NigoriServlet.java

/**
 * Handle initial request from client and dispatch to appropriate handler or return error message.
 *//*from w  w  w .j  ava 2s. co m*/
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    try {
        addCorsHeaders(resp);
        // Subset of path managed by this servlet; e.g. if URI is "/nigori/get" and servlet path
        // is "/nigori, then we want to retrieve "get" as the request type
        int startIndex = req.getServletPath().length() + 1;
        String requestURI = req.getRequestURI();
        if (requestURI.length() <= startIndex) {
            ServletException s = new ServletException(HttpServletResponse.SC_BAD_REQUEST,
                    "No request type specified.\n" + supportedTypes + "\n");
            log.fine(s.toString());
            s.writeHttpResponse(resp);
            return;
        }
        String requestType = requestURI.substring(startIndex);
        String requestMimetype = req.getContentType();
        RequestHandlerType handlerType = new RequestHandlerType(requestMimetype, requestType);

        RequestHandler handler = handlers.get(handlerType);
        if (handler == null) {
            throw new ServletException(HttpServletResponse.SC_NOT_ACCEPTABLE,
                    "Unsupported request pair: " + handlerType + "\n" + supportedTypes + "\n");
        }
        try {
            handler.handle(req, resp);
        } catch (NotFoundException e) {
            ServletException s = new ServletException(HttpServletResponse.SC_NOT_FOUND,
                    e.getLocalizedMessage());
            log.fine(s.toString());
            s.writeHttpResponse(resp);
        } catch (UnauthorisedException e) {
            ServletException s = new ServletException(HttpServletResponse.SC_UNAUTHORIZED,
                    "Authorisation failed: " + e.getLocalizedMessage());
            log.warning(s.toString());
            s.writeHttpResponse(resp);
        } catch (IOException ioe) {
            throw new ServletException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Internal error sending data to client");
        } catch (MessageLibrary.JsonConversionException jce) {
            throw new ServletException(HttpServletResponse.SC_BAD_REQUEST,
                    "JSON format error: " + jce.getMessage());
        } catch (RuntimeException re) {
            log.severe(re.toString());
            throw new ServletException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, re.toString());
        }

    } catch (ServletException e) {
        log.severe(e.toString());
        e.writeHttpResponse(resp);
    }
}

From source file:org.jitsi.videobridge.rest.HandlerImpl.java

/**
 * Modifies a <tt>Conference</tt> with ID <tt>target</tt> in (the
 * associated) <tt>Videobridge</tt>.
 *
 * @param target the ID of the <tt>Conference</tt> to modify in (the
 * associated) <tt>Videobridge</tt>
 * @param baseRequest the original unwrapped {@link Request} object
 * @param request the request either as the {@code Request} object or a
 * wrapper of that request/*from   www  .j  a  v a 2 s. c  o  m*/
 * @param response the response either as the {@code Response} object or a
 * wrapper of that response
 * @throws IOException
 * @throws ServletException
 */
private void doPatchConferenceJSON(String target, Request baseRequest, HttpServletRequest request,
        HttpServletResponse response) throws IOException, ServletException {
    Videobridge videobridge = getVideobridge();

    if (videobridge == null) {
        response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
    } else {
        Conference conference = videobridge.getConference(target, null);

        if (conference == null) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        } else if (RESTUtil.isJSONContentType(request.getContentType())) {
            Object requestJSONObject = null;
            int status = 0;

            try {
                requestJSONObject = new JSONParser().parse(request.getReader());
                if ((requestJSONObject == null) || !(requestJSONObject instanceof JSONObject)) {
                    status = HttpServletResponse.SC_BAD_REQUEST;
                }
            } catch (ParseException pe) {
                status = HttpServletResponse.SC_BAD_REQUEST;
            }
            if (status == 0) {
                ColibriConferenceIQ requestConferenceIQ = JSONDeserializer
                        .deserializeConference((JSONObject) requestJSONObject);

                if ((requestConferenceIQ == null) || ((requestConferenceIQ.getID() != null)
                        && !requestConferenceIQ.getID().equals(conference.getID()))) {
                    status = HttpServletResponse.SC_BAD_REQUEST;
                } else {
                    ColibriConferenceIQ responseConferenceIQ = null;

                    try {
                        IQ responseIQ = videobridge.handleColibriConferenceIQ(requestConferenceIQ,
                                Videobridge.OPTION_ALLOW_NO_FOCUS);

                        if (responseIQ instanceof ColibriConferenceIQ) {
                            responseConferenceIQ = (ColibriConferenceIQ) responseIQ;
                        } else {
                            status = getHttpStatusCodeForResultIq(responseIQ);
                        }
                    } catch (Exception e) {
                        status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
                    }
                    if (status == 0 && responseConferenceIQ != null) {
                        JSONObject responseJSONObject = JSONSerializer
                                .serializeConference(responseConferenceIQ);

                        if (responseJSONObject == null)
                            responseJSONObject = new JSONObject();

                        response.setStatus(HttpServletResponse.SC_OK);
                        responseJSONObject.writeJSONString(response.getWriter());
                    }
                }
            }
            if (status != 0)
                response.setStatus(status);
        } else {
            response.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
        }
    }
}