Example usage for javax.servlet.http HttpServletResponse SC_FORBIDDEN

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

Introduction

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

Prototype

int SC_FORBIDDEN

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

Click Source Link

Document

Status code (403) indicating the server understood the request but refused to fulfill it.

Usage

From source file:io.warp10.standalone.StandaloneDeleteHandler.java

@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    if (target.equals(Constants.API_ENDPOINT_DELETE)) {
        baseRequest.setHandled(true);/*from w  w  w .j  a v  a  2s.c o m*/
    } else {
        return;
    }

    //
    // CORS header
    //

    response.setHeader("Access-Control-Allow-Origin", "*");

    long nano = System.nanoTime();

    //
    // Extract DatalogRequest if specified
    //

    String datalogHeader = request.getHeader(Constants.getHeader(Configuration.HTTP_HEADER_DATALOG));

    DatalogRequest dr = null;

    boolean forwarded = false;

    if (null != datalogHeader) {
        byte[] bytes = OrderPreservingBase64.decode(datalogHeader.getBytes(Charsets.US_ASCII));

        if (null != datalogPSK) {
            bytes = CryptoUtils.unwrap(datalogPSK, bytes);
        }

        if (null == bytes) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Invalid Datalog header.");
            return;
        }

        TDeserializer deser = new TDeserializer(new TCompactProtocol.Factory());

        try {
            dr = new DatalogRequest();
            deser.deserialize(dr, bytes);
        } catch (TException te) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, te.getMessage());
            return;
        }

        Map<String, String> labels = new HashMap<String, String>();
        labels.put(SensisionConstants.SENSISION_LABEL_ID, new String(
                OrderPreservingBase64.decode(dr.getId().getBytes(Charsets.US_ASCII)), Charsets.UTF_8));
        labels.put(SensisionConstants.SENSISION_LABEL_TYPE, dr.getType());
        Sensision.update(SensisionConstants.CLASS_WARP_DATALOG_REQUESTS_RECEIVED, labels, 1);

        //
        // Check that the request query string matches the QS in the datalog request
        //

        if (!request.getQueryString().equals(dr.getDeleteQueryString())) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Invalid DatalogRequest.");
            return;
        }

        forwarded = true;
    }

    //
    // TODO(hbs): Extract producer/owner from token
    //

    String token = null != dr ? dr.getToken()
            : request.getHeader(Constants.getHeader(Configuration.HTTP_HEADER_TOKENX));

    if (null == token) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Missing token.");
        return;
    }

    WriteToken writeToken;

    try {
        writeToken = Tokens.extractWriteToken(token);
    } catch (WarpScriptException ee) {
        ee.printStackTrace();
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ee.getMessage());
        return;
    }

    String application = writeToken.getAppName();
    String producer = Tokens.getUUID(writeToken.getProducerId());
    String owner = Tokens.getUUID(writeToken.getOwnerId());

    //
    // For delete operations, producer and owner MUST be equal
    //

    if (!producer.equals(owner)) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Invalid write token for deletion.");
        return;
    }

    Map<String, String> sensisionLabels = new HashMap<String, String>();
    sensisionLabels.put(SensisionConstants.SENSISION_LABEL_PRODUCER, producer);

    long count = 0;
    long gts = 0;

    Throwable t = null;
    StringBuilder metas = new StringBuilder();

    //
    // Extract start/end
    //

    String startstr = request.getParameter(Constants.HTTP_PARAM_START);
    String endstr = request.getParameter(Constants.HTTP_PARAM_END);

    //
    // Extract selector
    //

    String selector = request.getParameter(Constants.HTTP_PARAM_SELECTOR);

    String minage = request.getParameter(Constants.HTTP_PARAM_MINAGE);

    if (null != minage) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Standalone version does not support the '" + Constants.HTTP_PARAM_MINAGE
                        + "' parameter in delete requests.");
        return;
    }

    boolean dryrun = null != request.getParameter(Constants.HTTP_PARAM_DRYRUN);

    File loggingFile = null;
    PrintWriter loggingWriter = null;

    //
    // Open the logging file if logging is enabled
    //

    if (null != loggingDir) {
        long nanos = null != dr ? dr.getTimestamp() : TimeSource.getNanoTime();
        StringBuilder sb = new StringBuilder();
        sb.append(Long.toHexString(nanos));
        sb.insert(0, "0000000000000000", 0, 16 - sb.length());
        sb.append("-");
        if (null != dr) {
            sb.append(dr.getId());
        } else {
            sb.append(datalogId);
        }

        sb.append("-");
        sb.append(dtf.print(nanos / 1000000L));
        sb.append(Long.toString(1000000L + (nanos % 1000000L)).substring(1));
        sb.append("Z");

        if (null == dr) {
            dr = new DatalogRequest();
            dr.setTimestamp(nanos);
            dr.setType(Constants.DATALOG_DELETE);
            dr.setId(datalogId);
            dr.setToken(token);
            dr.setDeleteQueryString(request.getQueryString());
        }

        if (null != dr && (!forwarded || (forwarded && this.logforwarded))) {
            //
            // Serialize the request
            //

            TSerializer ser = new TSerializer(new TCompactProtocol.Factory());

            byte[] encoded;

            try {
                encoded = ser.serialize(dr);
            } catch (TException te) {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, te.getMessage());
                return;
            }

            if (null != this.datalogPSK) {
                encoded = CryptoUtils.wrap(this.datalogPSK, encoded);
            }

            encoded = OrderPreservingBase64.encode(encoded);

            loggingFile = new File(loggingDir, sb.toString());
            loggingWriter = new PrintWriter(new FileWriterWithEncoding(loggingFile, Charsets.UTF_8));

            //
            // Write request
            //

            loggingWriter.println(new String(encoded, Charsets.US_ASCII));
        }
    }

    boolean validated = false;

    try {
        if (null == producer || null == owner) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN, "Invalid token.");
            return;
        }

        //
        // Build extra labels
        //

        Map<String, String> extraLabels = new HashMap<String, String>();
        //
        // Only set owner and potentially app, producer may vary
        //      
        extraLabels.put(Constants.OWNER_LABEL, owner);
        // FIXME(hbs): remove me
        if (null != application) {
            extraLabels.put(Constants.APPLICATION_LABEL, application);
            sensisionLabels.put(SensisionConstants.SENSISION_LABEL_APPLICATION, application);
        }

        boolean hasRange = false;

        long start = Long.MIN_VALUE;
        long end = Long.MAX_VALUE;

        if (null != startstr) {
            if (null == endstr) {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "Both " + Constants.HTTP_PARAM_START + " and " + Constants.HTTP_PARAM_END
                                + " should be defined.");
                return;
            }
            if (startstr.contains("T")) {
                start = fmt.parseDateTime(startstr).getMillis() * Constants.TIME_UNITS_PER_MS;
            } else {
                start = Long.valueOf(startstr);
            }
        }

        if (null != endstr) {
            if (null == startstr) {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "Both " + Constants.HTTP_PARAM_START + " and " + Constants.HTTP_PARAM_END
                                + " should be defined.");
                return;
            }
            if (endstr.contains("T")) {
                end = fmt.parseDateTime(endstr).getMillis() * Constants.TIME_UNITS_PER_MS;
            } else {
                end = Long.valueOf(endstr);
            }
        }

        if (Long.MIN_VALUE == start && Long.MAX_VALUE == end
                && null == request.getParameter(Constants.HTTP_PARAM_DELETEALL)) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Parameter "
                    + Constants.HTTP_PARAM_DELETEALL + " should be set when deleting a full range.");
            return;
        }

        if (Long.MIN_VALUE != start || Long.MAX_VALUE != end) {
            hasRange = true;
        }

        if (start > end) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Invalid time range specification.");
            return;
        }

        //
        // Extract the class and labels selectors
        // The class selector and label selectors are supposed to have
        // values which use percent encoding, i.e. explicit percent encoding which
        // might have been re-encoded using percent encoding when passed as parameter
        //
        //

        Matcher m = EgressFetchHandler.SELECTOR_RE.matcher(selector);

        if (!m.matches()) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }

        String classSelector = URLDecoder.decode(m.group(1), "UTF-8");
        String labelsSelection = m.group(2);

        Map<String, String> labelsSelectors;

        try {
            labelsSelectors = GTSHelper.parseLabelsSelectors(labelsSelection);
        } catch (ParseException pe) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, pe.getMessage());
            return;
        }

        validated = true;

        //
        // Force 'producer'/'owner'/'app' from token
        //

        labelsSelectors.putAll(extraLabels);

        List<Metadata> metadatas = null;

        List<String> clsSels = new ArrayList<String>();
        List<Map<String, String>> lblsSels = new ArrayList<Map<String, String>>();
        clsSels.add(classSelector);
        lblsSels.add(labelsSelectors);

        metadatas = directoryClient.find(clsSels, lblsSels);

        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType("text/plain");

        PrintWriter pw = response.getWriter();
        StringBuilder sb = new StringBuilder();

        for (Metadata metadata : metadatas) {
            //
            // Remove from DB
            //

            if (!hasRange) {
                if (!dryrun) {
                    this.directoryClient.unregister(metadata);
                }
            }

            //
            // Remove data
            //

            long localCount = 0;

            if (!dryrun) {
                localCount = this.storeClient.delete(writeToken, metadata, start, end);
            }

            count += localCount;

            sb.setLength(0);
            GTSHelper.metadataToString(sb, metadata.getName(), metadata.getLabels());

            if (metadata.getAttributesSize() > 0) {
                GTSHelper.labelsToString(sb, metadata.getAttributes());
            } else {
                sb.append("{}");
            }

            pw.write(sb.toString());
            pw.write("\r\n");
            metas.append(sb);
            metas.append("\n");
            gts++;

            // Log detailed metrics for this GTS owner and app
            Map<String, String> labels = new HashMap<>();
            labels.put(SensisionConstants.SENSISION_LABEL_OWNER,
                    metadata.getLabels().get(Constants.OWNER_LABEL));
            labels.put(SensisionConstants.SENSISION_LABEL_APPLICATION,
                    metadata.getLabels().get(Constants.APPLICATION_LABEL));
            Sensision.update(
                    SensisionConstants.SENSISION_CLASS_CONTINUUM_STANDALONE_DELETE_DATAPOINTS_PEROWNERAPP,
                    labels, localCount);
        }
    } catch (Exception e) {
        t = e;
        throw e;
    } finally {
        if (null != loggingWriter) {
            Map<String, String> labels = new HashMap<String, String>();
            labels.put(SensisionConstants.SENSISION_LABEL_ID, new String(
                    OrderPreservingBase64.decode(dr.getId().getBytes(Charsets.US_ASCII)), Charsets.UTF_8));
            labels.put(SensisionConstants.SENSISION_LABEL_TYPE, dr.getType());
            Sensision.update(SensisionConstants.CLASS_WARP_DATALOG_REQUESTS_LOGGED, labels, 1);

            loggingWriter.close();
            if (validated) {
                loggingFile.renameTo(new File(loggingFile.getAbsolutePath() + DatalogForwarder.DATALOG_SUFFIX));
            } else {
                loggingFile.delete();
            }
        }

        Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_STANDALONE_DELETE_REQUESTS,
                sensisionLabels, 1);
        Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_STANDALONE_DELETE_GTS, sensisionLabels,
                gts);
        Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_STANDALONE_DELETE_DATAPOINTS,
                sensisionLabels, count);
        Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_STANDALONE_DELETE_TIME_US,
                sensisionLabels, (System.nanoTime() - nano) / 1000);

        LoggingEvent event = LogUtil.setLoggingEventAttribute(null, LogUtil.DELETION_TOKEN, token);
        event = LogUtil.setLoggingEventAttribute(event, LogUtil.DELETION_SELECTOR, selector);
        event = LogUtil.setLoggingEventAttribute(event, LogUtil.DELETION_START, startstr);
        event = LogUtil.setLoggingEventAttribute(event, LogUtil.DELETION_END, endstr);
        event = LogUtil.setLoggingEventAttribute(event, LogUtil.DELETION_METADATA, metas.toString());
        event = LogUtil.setLoggingEventAttribute(event, LogUtil.DELETION_COUNT, Long.toString(count));
        event = LogUtil.setLoggingEventAttribute(event, LogUtil.DELETION_GTS, Long.toString(gts));

        LogUtil.addHttpHeaders(event, request);

        if (null != t) {
            LogUtil.setLoggingEventStackTrace(null, LogUtil.STACK_TRACE, t);
        }

        LOG.info(LogUtil.serializeLoggingEvent(this.keyStore, event));
    }

    response.setStatus(HttpServletResponse.SC_OK);
}

From source file:com.haulmont.cuba.restapi.DataServiceController.java

@RequestMapping(value = "/api/commit", method = RequestMethod.POST)
public void commit(@RequestParam(value = "s") String sessionId,
        @RequestHeader(value = "Content-Type") MimeType contentType, @RequestBody String requestContent,
        HttpServletRequest request, HttpServletResponse response)
        throws IOException, InvocationTargetException, NoSuchMethodException, IllegalAccessException {

    if (!connect(sessionId, response))
        return;/*from w w  w .  ja  v a2  s .  c  o  m*/

    try {
        Converter converter = conversionFactory.getConverter(contentType);

        CommitRequest commitRequest = converter.parseCommitRequest(requestContent);

        Collection commitInstances = commitRequest.getCommitInstances();
        Set<String> newInstanceIds = commitRequest.getNewInstanceIds();

        assignUuidToNewInstances(commitInstances, newInstanceIds);

        for (Object commitInstance : commitInstances) {
            if (commitInstance instanceof BaseGenericIdEntity && !isNewInstance(newInstanceIds, commitInstance)
                    && !PersistenceHelper.isDetached(commitInstance)) {
                PersistenceHelper.makePatch((BaseGenericIdEntity) commitInstance);
            }
        }

        //send error if the user don't have permissions to commit at least one of the entities
        if (!commitPermitted(commitInstances, newInstanceIds)) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            return;
        }

        Collection removeInstances = commitRequest.getRemoveInstances();
        //send error if the user don't have permissions to remove at least one of the entities
        if (!removePermitted(removeInstances)) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            return;
        }

        CommitContext commitContext = new CommitContext();
        commitContext.setCommitInstances(commitInstances);
        commitContext.setRemoveInstances(removeInstances);
        commitContext.setSoftDeletion(commitRequest.isSoftDeletion());

        List<EntityLoadInfo> newInstances = new ArrayList<>(newInstanceIds.size());
        for (String str : newInstanceIds) {
            newInstances.add(entityLoadInfoBuilder.parse(str));
        }

        for (Entity entity : commitContext.getCommitInstances()) {
            MetaClass metaClass = metadata.getSession().getClassNN(entity.getClass());
            for (MetaProperty property : metaClass.getProperties()) {
                if (property.getRange().isClass() && !metadata.getTools().isEmbedded(property)
                        && !property.getRange().getCardinality().isMany() && !property.isReadOnly()
                        && PersistenceHelper.isLoaded(entity, property.getName())) {

                    Entity refEntity = entity.getValue(property.getName());
                    if (refEntity == null || refEntity.getId() == null)
                        continue;

                    if (entityLoadInfoBuilder.contains(newInstances, refEntity)) {
                        // reference to a new entity
                        Entity e = getEntityById(commitContext.getCommitInstances(), refEntity.getId());
                        ((AbstractInstance) entity).setValue(property.getName(), e, false);
                    } else if (BaseGenericIdEntity.class
                            .isAssignableFrom(refEntity.getMetaClass().getJavaClass())) {
                        // reference to an existing entity
                        Object refEntityId = refEntity.getId();
                        refEntity = metadata.create(refEntity.getMetaClass());
                        ((BaseGenericIdEntity) refEntity).setId(refEntityId);
                        PersistenceHelper.makeDetached((BaseGenericIdEntity) refEntity);
                        ((AbstractInstance) entity).setValue(property.getName(), refEntity, false);
                    }
                }
            }
        }

        Set<Entity> result = dataService.commit(commitContext);

        String converted = converter.process(result);
        writeResponse(response, converted, converter.getMimeType());
    } catch (RowLevelSecurityException e) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN,
                "The operation with entity " + e.getEntity() + " is denied");
    } catch (Throwable e) {
        sendError(request, response, e);
    } finally {
        authentication.end();
    }
}

From source file:eu.dasish.annotation.backend.rest.AnnotationResource.java

/**
 * The request can be sent by principals with "developer" or "admin" account.
 * @param n # of threads.//from   ww w  .j  ava2 s.  c  o m
 * @return a message reporting test success.
 * @throws IOException if sending an error fails.
 * @throws NotInDataBaseException if getting annotation fails.
 */
@GET
@Produces(MediaType.TEXT_PLAIN)
@Path("stressTest")
@Transactional(readOnly = true)
public String getAnnotationsMultithread(@QueryParam("n") int n) throws IOException, NotInDataBaseException {
    Number remotePrincipalID = this.getPrincipalID();
    if (remotePrincipalID == null) {
        return "You are not logged in";
    }
    String typeOfAccount = dbDispatcher.getTypeOfPrincipalAccount(remotePrincipalID);
    if (typeOfAccount.equals(admin) || typeOfAccount.equals(DebugResource.developer)) {

        System.out.print("Preparing the data: getting the list of all annotations, picking up " + n
                + " of them randomly, and initializing threads");
        final List<Number> annotationIDs = dbDispatcher.getFilteredAnnotationIDs(null, null, null, null,
                remotePrincipalID, "read", null, null, null);
        final int size = annotationIDs.size();
        List<GetThread> threads = new ArrayList<GetThread>(n);
        Random rand = new Random();
        for (int i = 0; i < n; i++) {
            int r = rand.nextInt(size);
            String annotationExternalId = dbDispatcher
                    .getResourceExternalIdentifier(annotationIDs.get(r), Resource.ANNOTATION).toString();
            GetThread thread = new GetThread(this, annotationExternalId);
            threads.add(thread);
        }

        System.out.print(
                "Running on getAnnotation(id) (no serialized output is shown to save time) on randomly selected annotation ids.");
        for (int i = 0; i < n; i++) {
            threads.get(i).run();
        }

        return "Stress-tested annotationrResource's getAnnotation(xxx): ok";
    } else {
        httpServletResponse.sendError(HttpServletResponse.SC_FORBIDDEN);
        return "You cannot enjoy this priviledged service because youe are neither admin nor developer. Ask the admin for more priviledges";
    }
}

From source file:eu.dasish.annotation.backend.rest.CachedRepresentationResource.java

/**
 * //from ww  w  . ja v a2  s  .  c o  m
 * @param cachedInfo a {@link CachedRepresentationInfo} object representing the new metadata.
 * @return a message about how many rows in "cached_representation" table have been updated: "1" if updated, "0" otherwise.
 * @throws IOException if sending an error fails.
 */
@PUT
@Consumes(MediaType.TEXT_XML)
@Produces(MediaType.APPLICATION_XML)
@Path("metadata")
public String updateCachedMetadata(CachedRepresentationInfo cachedInfo) throws IOException {
    Map params = new HashMap();
    params.put("info", cachedInfo);
    try {
        Integer result = (Integer) (new RequestWrappers(this)).wrapRequestResource(params,
                new UpdateCachedMetadata(), Resource.CACHED_REPRESENTATION, Access.ALL, cachedInfo.getId());
        if (result != null) {
            return result + "rows are updated";
        } else {
            return "Nothing is updated. ";
        }
    } catch (NotInDataBaseException e1) {
        httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND, e1.getMessage());
        return e1.getMessage();
    } catch (ForbiddenException e2) {
        httpServletResponse.sendError(HttpServletResponse.SC_FORBIDDEN, e2.getMessage());
        return e2.getMessage();
    }
}

From source file:org.jetbrains.webdemo.sessions.MyHttpSession.java

private void sendRenameFileResult() {
    try {// ww w  .j a  v  a2s .c  om
        String publicId = request.getParameter("publicId");
        String newName = request.getParameter("newName");
        newName = newName.endsWith(".kt") ? newName : newName + ".kt";
        MySqlConnector.getInstance().renameFile(sessionInfo.getUserInfo(), publicId, newName);
        writeResponse("ok", HttpServletResponse.SC_OK);
    } catch (NullPointerException e) {
        writeResponse("Can't get parameters", HttpServletResponse.SC_BAD_REQUEST);
    } catch (DatabaseOperationException e) {
        writeResponse(e.getMessage(), HttpServletResponse.SC_FORBIDDEN);
    }
}

From source file:eu.dasish.annotation.backend.rest.NotebookResource.java

/**
 * /*from  w  ww  .  jav  a2s  .  c  om*/
 * @param externalIdentifier the external UUID identifier of a notebook.
 * @param notebookInfo the fresh {@link NotebookInfo} object.
 * @return a {@link ResponseBody} element containing the just updated {@link Notebook} element
 * and the list of actions (which are not yet specified for the notebooks).
 * @throws IOException if sending an error fails.
 */
@PUT
@Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.APPLICATION_XML)
@Path("{notebookid: " + BackendConstants.regExpIdentifier + "}")
public JAXBElement<ResponseBody> updateNotebookInfo(@PathParam("notebookid") String externalIdentifier,
        NotebookInfo notebookInfo) throws IOException {
    Number remotePrincipalID = this.getPrincipalID();
    if (remotePrincipalID == null) {
        return new ObjectFactory().createResponseBody(new ResponseBody());
    }
    String path = this.getRelativeServiceURI();
    String notebookURI = notebookInfo.getHref();
    if (!(path + "/notebooks/" + externalIdentifier).equals(notebookURI)) {
        httpServletResponse.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return new ObjectFactory().createResponseBody(new ResponseBody());
    }
    ;
    try {
        final Number notebookID = dbDispatcher
                .getResourceInternalIdentifier(UUID.fromString(externalIdentifier), Resource.NOTEBOOK);
        try {
            if (remotePrincipalID.equals(dbDispatcher.getNotebookOwner(notebookID))
                    || dbDispatcher.getTypeOfPrincipalAccount(remotePrincipalID).equals(admin)) {
                boolean success = dbDispatcher.updateNotebookMetadata(notebookID, notebookInfo);
                if (success) {
                    return new ObjectFactory()
                            .createResponseBody(dbDispatcher.makeNotebookResponseEnvelope(notebookID));
                } else {
                    httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    return new ObjectFactory().createResponseBody(new ResponseBody());
                }
            } else {
                loggerServer.debug(
                        " Ownership changing is the part of the full update of the notebook metadadata.");
                httpServletResponse.sendError(HttpServletResponse.SC_FORBIDDEN);
                return new ObjectFactory().createResponseBody(new ResponseBody());
            }
        } catch (NotInDataBaseException e1) {
            loggerServer.debug(e1.toString());
            httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e1.toString());
            return new ObjectFactory().createResponseBody(new ResponseBody());
        }
    } catch (NotInDataBaseException e) {
        loggerServer.debug(e.toString());
        httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND, e.toString());
        return new ObjectFactory().createResponseBody(new ResponseBody());
    }
}

From source file:com.sonicle.webtop.core.app.servlet.ResourceRequest.java

private LookupResult lookupDomainImage(HttpServletRequest request, URL targetUrl, String domainId) {
    String targetPath = targetUrl.getPath();
    URL fileUrl = null;/*  w w w  .jav  a2s  .  co  m*/

    try {
        WebTopApp wta = WebTopApp.get(request);
        String remainingPath = StringUtils.substringAfter(targetPath, "images/");
        if (StringUtils.isBlank(remainingPath))
            throw new NotFoundException();
        String imagesPath = wta.getImagesPath(domainId);
        File file = new File(imagesPath + remainingPath);
        if (!file.exists())
            throw new NotFoundException();
        fileUrl = file.toURI().toURL();

        Resource resFile = getFile(wta, fileUrl);
        return new StaticFile(fileUrl.toString(), getMimeType(targetPath), ClientCaching.NO, resFile);

    } catch (ForbiddenException ex) {
        return new Error(HttpServletResponse.SC_FORBIDDEN, "Forbidden");
    } catch (MalformedURLException | NotFoundException ex) {
        return new Error(HttpServletResponse.SC_NOT_FOUND, "Not Found");
    } catch (InternalServerException ex) {
        return new Error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error");
    } catch (ServletException ex) {
        return new Error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getMessage());
    }
}

From source file:net.java.jaspicoil.SimpleBasicServerAuthModule.java

private AuthStatus sendErrorAndFail(HttpServletRequest request, HttpServletResponse response, String message) {
    response.setHeader(AUTHENTICATE_HEADER, createAuthenticateValue(getRealm(request)));
    response.setStatus(HttpServletResponse.SC_FORBIDDEN);
    LOG.fine(message);/*from  www  . jav a  2  s  . c  om*/
    return AuthStatus.FAILURE;
}

From source file:com.netbase.insightapi.clientlib.InsightAPIQuery.java

/**
 * Returns true if the query is complete. An InsightAPIQuery is not complete
 * unless it's finished, and it did not return a rate limit exceeded
 * complaint. This is distinct from "succeeded", which requires that
 * statusCode == SC_OK (200)./*from   ww  w .  j  a  v a  2  s .  co  m*/
 */
public boolean isComplete() {
    return (statusCode != -1 && (statusCode != HttpServletResponse.SC_FORBIDDEN
            || !responseContent.toLowerCase().contains("rate limit")));
}

From source file:com.vmware.identity.samlservice.AuthnRequestState.java

public void parseRequestForTenant(String tenant, AuthenticationFilter<AuthnRequestState> authenticator)
        throws IllegalStateException {
    log.debug("parseRequestForTenant, tenant " + tenant);

    Validate.notNull(this.idmAccessor);
    Validate.notNull(this.request);

    if (!(authenticator instanceof AuthnRequestStateRsaAmAuthenticationFilter
            || (authenticator instanceof AuthnRequestStateCookieWrapper
                    && ((AuthnRequestStateCookieWrapper) authenticator)
                            .getAuthenticator() instanceof AuthnRequestStateRsaAmAuthenticationFilter))) {
        // check for replays and resent request
        if (this.requestCache.shouldDenyRequest(this.samlRequest)) {
            log.info("Replay attack detected - DENYING authentication request");
            this.validationResult = new ValidationResult(HttpServletResponse.SC_FORBIDDEN, "Forbidden",
                    "Replay");
            throw new IllegalStateException("Forbidden");
        } else {/*w w  w  .j  a v a 2  s . c  o m*/
            this.setIsExistingRequest(this.requestCache.isExistingRequest(this.samlRequest));
            this.requestCache.storeRequest(this.samlRequest);
        }
    }

    // relying party unknown at this point, specify null
    SamlService service = this.createSamlServiceForTenant(tenant, null);

    try {
        this.idmAccessor.setTenant(tenant);
        authenticator.preAuthenticate(this);
    } catch (SamlServiceException e) {
        log.error("Caught Saml Service Exception from preAuthenticate ", e);
        if (this.validationResult == null) {
            this.validationResult = new ValidationResult(HttpServletResponse.SC_FORBIDDEN, "Forbidden", null);
        }
        throw new IllegalStateException(e);
    }

    // decode request
    try {
        this.authnRequest = service.decodeSamlAuthnRequest(this.request);
    } catch (MessageDecodingException e) {
        // fail the validation with specific error code and rethrow
        this.validationResult = new ValidationResult(HttpServletResponse.SC_BAD_REQUEST, "BadRequest", null);
        log.error("Unable to decode message ", e);
        throw new IllegalStateException(e);
    } catch (SecurityException e) {
        // fail the validation with specific error code and rethrow
        this.validationResult = new ValidationResult(HttpServletResponse.SC_BAD_REQUEST, "BadRequest", null);
        log.error("Unable to validate the authentication request ", e);
        throw new IllegalStateException(e);
    }
    // if signature was specified along with signing algorithm, verify
    // signature
    Issuer issuer = this.authnRequest.getIssuer();
    if (issuer == null || issuer.getValue() == null
            || this.idmAccessor.getRelyingPartyByUrl(issuer.getValue()) == null) {
        service = null;
    } else {
        this.setIssuerValue(issuer.getValue());
        service = this.createSamlServiceForTenant(tenant, this.getIssuerValue());
    }
    if (service == null) {
        // return 400 to the caller and throw
        log.error("Could not recognize issuer.");
        this.validationResult = new ValidationResult(HttpServletResponse.SC_BAD_REQUEST, "BadRequest",
                "Issuer");
        throw new IllegalStateException("Issuer not recognized");
    }
    if (this.sigAlg != null && this.signature != null) {
        try {
            service.verifySignature(this.signedMessage, this.signature);
        } catch (IllegalStateException e) {
            // fail the validation with specific error code and rethrow
            log.error("Could not validate the signature against message.", e);
            this.validationResult = new ValidationResult(OasisNames.RESPONDER, OasisNames.REQUEST_DENIED);
            throw new IllegalStateException(e);
        }
    }

    this.setSamlAuthFactory(new DefaultSamlAuthorityFactory(SignatureAlgorithm.RSA_SHA256,
            authenticator.getPrincipalAttributeExtractorFactory(Shared.IDM_HOSTNAME),
            authenticator.getConfigExtractorFactory(Shared.IDM_HOSTNAME))); // TODO
                                                                                                                                                                                                                                             // use
                                                                                                                                                                                                                                             // actual
                                                                                                                                                                                                                                             // tenant
                                                                                                                                                                                                                                             // settings

    this.validationResult = this.validator.validate(this);

    if (this.validationResult.isValid()) {
        // mark as parsed and retrieve cookie
        this.processingState = ProcessingState.PARSED;
    }
}