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:org.dataconservancy.ui.api.ProjectController.java

/**
 * Handles updating a project matching the given id Note: Dates should be in
 * the format dd mm yyyy// w w  w  . j av a  2 s  .  c  om
 * 
 * @param idpart
 * @throws ProjectServiceException
 * @throws InvalidXmlException
 * @throws BizPolicyException
 * @throws IOException
 */
@RequestMapping(value = "/{idpart}", method = { RequestMethod.PUT })
public void handleUpdateProjectRequest(@PathVariable String idpart,
        @RequestHeader(value = "Accept", required = false) String mimeType, @RequestBody byte[] content,
        HttpServletRequest req, HttpServletResponse resp)
        throws BizInternalException, InvalidXmlException, BizPolicyException, IOException {

    // TODO Why doesn't spring do this?
    if (req.getContentType().contains("application/x-www-form-urlencoded")) {
        content = URLDecoder.decode(new String(content, "UTF-8"), "UTF-8").getBytes("UTF-8");
    }

    Person user = getAuthenticatedUser();
    if (user == null) {
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;
    } else {
        Project newProject = objectBuilder.buildProject(new ByteArrayInputStream(content));
        String id = util.buildRequestUrl(req);

        Project originalProject = projectService.get(id);

        if (originalProject != null) {

            if (newProject.getId().equalsIgnoreCase(id)) {
                if (authorizationService.canUpdateProject(user, newProject)) {
                    projectBizService.updateProject(newProject, user);

                    resp.setCharacterEncoding("UTF-8");
                    resp.setContentType("text/xml");

                    newProject = projectService.get(id);
                    Bop bop = new Bop();
                    bop.addProject(newProject);
                    objectBuilder.buildBusinessObjectPackage(bop, resp.getOutputStream());
                } else {
                    resp.sendError(HttpServletResponse.SC_FORBIDDEN);
                    return;
                }
            } else {
                try {
                    resp.sendError(HttpServletResponse.SC_BAD_REQUEST,
                            "ID doesn't match ID of supplied project");
                } catch (Exception ee) {
                    log.debug("Handling exception", ee);
                }
            }

        } else {
            try {
                resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Could not find project with id: " + idpart);
            } catch (Exception ee) {
                log.debug("Handling exception", ee);
            }
        }
    }
}

From source file:io.wcm.caconfig.editor.impl.ConfigPersistServlet.java

private void sendForbiddenWithMessage(SlingHttpServletResponse response, String message) throws IOException {
    response.setContentType("text/plain;charset=" + CharEncoding.UTF_8);
    response.getWriter().write(message);
    response.setStatus(HttpServletResponse.SC_FORBIDDEN);
}

From source file:com.janrain.backplane2.server.Token.java

private void checkAllowedSources(Collection<TokenSource> tokenFoundIn) throws TokenException {
    if (tokenFoundIn == null || tokenFoundIn.size() > 1) {
        throw new TokenException("exactly one token source allowed, found in: " + tokenFoundIn,
                HttpServletResponse.SC_FORBIDDEN);
    }/*from ww  w  .  j  a  v  a 2  s.c om*/

    for (TokenSource tokenSource : tokenFoundIn) {
        if (!getType().getTokenAllowedSources().contains(tokenSource)) {
            throw new TokenException("token source not allowed: " + tokenSource,
                    HttpServletResponse.SC_FORBIDDEN);
        }
    }
}

From source file:com.janrain.backplane2.server.Backplane2Controller.java

/**
 * Retrieve messages from the server./*  ww  w. j a va2s .  com*/
 *
 * @param access_token required
 * @param block        optional
 * @param callback     optional
 * @param since        optional
 * @return json object
 * @throws SimpleDBException
 * @throws BackplaneServerException
 */

@RequestMapping(value = "/messages", method = { RequestMethod.GET })
public @ResponseBody Map<String, Object> messages(final HttpServletRequest request,
        HttpServletResponse response,
        @RequestParam(value = OAUTH2_ACCESS_TOKEN_PARAM_NAME, required = false) final String access_token,
        @RequestParam(value = "block", defaultValue = "0", required = false) String block,
        @RequestParam(required = false) String callback,
        @RequestParam(value = "since", required = false) String since,
        @RequestHeader(value = "Referer", required = false) String referer,
        @RequestHeader(value = "Authorization", required = false) final String authorizationHeader)
        throws SimpleDBException, BackplaneServerException {

    ServletUtil.checkSecure(request);

    TimerContext context = null;
    // only time the event if it is not blocking
    if ("0".equals(block)) {
        context = v2GetsTimer.time();
    }

    try {
        MessageRequest messageRequest = new MessageRequest(callback, since, block);

        Token token = Token.fromRequest(daoFactory, request, access_token, authorizationHeader);
        if (token.getType().isRefresh()) {
            return returnMessage(OAuth2.OAUTH2_TOKEN_INVALID_REQUEST, "Invalid token type: " + token.getType(),
                    HttpServletResponse.SC_FORBIDDEN, response);
        }

        MessagesResponse bpResponse = new MessagesResponse(messageRequest.getSince());
        boolean exit = false;
        do {
            daoFactory.getBackplaneMessageDAO().retrieveMessagesPerScope(bpResponse, token);
            if (!bpResponse.hasMessages() && new Date().before(messageRequest.getReturnBefore())) {
                try {
                    Thread.sleep(MESSAGES_POLL_SLEEP_MILLIS);
                } catch (InterruptedException e) {
                    //ignore
                }
            } else {
                exit = true;
            }
        } while (!exit);

        Map<String, Object> result = bpResponse.asResponseFields(request.getServerName(),
                token.getType().isPrivileged());
        aniLogPollMessages(request, referer, bpResponse.getMessages());
        return result;

    } catch (TokenException te) {
        return handleTokenException(te, response);
    } catch (BackplaneServerException bse) {
        throw bse;
    } catch (InvalidRequestException ire) {
        throw ire;
    } catch (Exception e) {
        throw new BackplaneServerException("Error processing messages request: " + e.getMessage(), e);
    } finally {
        if (context != null) {
            context.stop();
        }
    }
}

From source file:com.googlecode.fascinator.portal.services.impl.PortalSecurityManagerImpl.java

/**
 * Wrapper method for other SSO methods provided by the security manager. If
 * desired, the security manager can take care of the integration using the
 * default usage pattern, rather then calling them individually.
 * /*  w ww . jav a 2s .  c o  m*/
 * @param session : The session of the current request
 * @param formData : FormData object for the current request
 * @return boolean : True if SSO has redirected, in which case no response
 *         should be sent by Dispatch, otherwise False.
 */
@Override
public boolean runSsoIntegration(JsonSessionState session, FormData formData) {
    this.formData = formData;

    // Used in integrating with thrid party systems. They can send us a
    // user, we will log them in via a SSO round-trip, then send them back
    // to the external system
    String returnUrl = request.getParameter("returnUrl");
    if (returnUrl != null) {
        log.info("External redirect requested: '{}'", returnUrl);
        session.set("ssoReturnUrl", returnUrl);
    }

    // The URL parameters can contain a trust token
    String utoken = request.getParameter("token");
    String stoken = (String) session.get("validToken");
    String token = null;
    // Or an 'old' token still in the session
    if (stoken != null) {
        token = stoken;
    }
    // But give the URL priority
    if (utoken != null) {
        token = utoken;
    }
    if (token != null) {
        // Valid token
        if (testTrustToken(session, token)) {
            // Dispatch can continue
            return false;
        }

        // Invalid token
        // Given that trust tokens are designed for system integration
        // we are going to fail with a non-branded error message
        try {
            response.sendError(HttpServletResponse.SC_FORBIDDEN, "Invalid or expired security token!");
        } catch (IOException ex) {
            log.error("Error sending 403 response to client!");
        }
        // We don't want Dispatch to send a response
        return true;
    }

    // Single Sign-On integration
    try {
        // Instantiate with access to the session
        String ssoId = ssoInit(session);
        if (ssoId != null) {
            // We are logging in, so send them to the SSO portal
            String ssoUrl = ssoGetRemoteLogonURL(session, ssoId);
            if (ssoUrl != null) {
                log.info("Redirect to external URL: '{}'", ssoUrl);
                response.sendRedirect(ssoUrl);
                return true;
            }
        } else {
            // Otherwise, check if we have user's details
            boolean valid = ssoCheckUserDetails(session);
            // If we validly logged in an SSO user, check for an
            // external redirect to third party systems
            if (valid) {
                returnUrl = (String) session.get("ssoReturnUrl");
                if (returnUrl != null) {
                    log.info("Redirect to external URL: '{}'", returnUrl);
                    session.remove("ssoReturnUrl");
                    response.sendRedirect(returnUrl);
                    return true;
                }
            }
        }
    } catch (Exception ex) {
        log.error("SSO Error!", ex);
    }

    return false;
}

From source file:com.alfaariss.oa.profile.saml2.profile.sso.SingleLogout.java

private void processSAMLRequest(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws OAException {
    SAMLMessageContext<SignableSAMLObject, SignableSAMLObject, SAMLObject> context = null;
    String sBinding = null;//from   ww  w. j a  v  a2 s .com
    try {
        //Decode message
        AbstractDecodingFactory decFactory = AbstractDecodingFactory.resolveInstance(servletRequest,
                servletResponse, _bindingProperties);
        if (decFactory == null) {
            _logger.debug("Decoding factory not created: Invalid request");
            throw new MessageDecodingException("Could not determine binding");
        }

        SAMLMessageDecoder decoder = decFactory.getDecoder();
        sBinding = decoder.getBindingURI();

        _logger.debug("Binding URI: " + sBinding);

        context = decFactory.getContext();
        context.setLocalEntityId(_sEntityID);
        context.setLocalEntityMetadata(_entityDescriptor);

        //Decode request
        try {
            decoder.decode(context);
        } catch (SecurityException e) {
            _logger.debug("Could not decode inbound message due to security exception", e);
            throw new SAML2SecurityException(RequestorEvent.REQUEST_INVALID);
        }

        //verify saml message in request
        SignableSAMLObject requestMessage = context.getInboundSAMLMessage();

        if (_logger.isDebugEnabled()) {
            if (requestMessage != null)
                logXML(requestMessage);
        }

        if (requestMessage instanceof LogoutRequest) {
            //DD <LogoutRequest> signing is forced by code for HTTP POST or Redirect binding [saml-profiles-2.0-os r1223].
            boolean bMandatorySinging = sBinding.equals(SAMLConstants.SAML2_POST_BINDING_URI)
                    || sBinding.equals(SAMLConstants.SAML2_REDIRECT_BINDING_URI);

            HTTPInTransport inTransport = (HTTPInTransport) context.getInboundMessageTransport();
            String sigParam = inTransport.getParameterValue("Signature");
            boolean bSigned = !DatatypeHelper.isEmpty(sigParam) || requestMessage.isSigned();
            if (bMandatorySinging && !bSigned) {
                _logger.debug("LogoutRequest MUST be signed if the HTTP POST or Redirect binding is used");
                throw new SAML2SecurityException(RequestorEvent.REQUEST_INVALID);
            }

            //synchronous bindings: The requester MUST authenticate itself 
            //to the identity provider, either by signing the 
            //<LogoutRequest> or using any other binding-supported 
            //mechanism.
            //DD <LogoutRequest> signing is not forced by code for synchronous bindings, but should be enabled by configuration in a production environment

            LogoutRequest lr = (LogoutRequest) requestMessage;
            String sReason = lr.getReason();

            processLogoutRequest(servletRequest, servletResponse, context, sBinding, sReason);
        } else {
            _logger.debug("Unsupported SAML message in request");
            throw new MessageDecodingException("Unsupported SAML message");
        }
    } catch (StatusException e) //SAML processing error
    {
        _eventLogger.info(new RequestorEventLogItem(null, null, null, e.getEvent(), null,
                servletRequest.getRemoteAddr(), e.getRequestorID(), this, e.getMessage()));

        sendResponse(context, servletRequest, servletResponse, sBinding);
    } catch (MessageDecodingException e) //Binding processing error  
    {
        _logger.debug("Decoding error", e);
        _eventLogger.info(new RequestorEventLogItem(null, null, null, RequestorEvent.REQUEST_INVALID, null,
                servletRequest.getRemoteAddr(), null, this, null));
        if (sBinding != null && sBinding.equals(SAMLConstants.SAML2_SOAP11_BINDING_URI)) {
            SOAP11Utils.sendSOAPFault(context, RequestorEvent.REQUEST_INVALID);
        } else {
            try {
                if (!servletResponse.isCommitted())
                    servletResponse.sendError(HttpServletResponse.SC_BAD_REQUEST);
            } catch (IOException e1) {
                _logger.warn("Could not send response", e1);
            }
        }
    } catch (SAML2SecurityException e)
    //The message does not meet the required security constraints
    {
        _logger.debug("Security error", e);
        _eventLogger.info(new RequestorEventLogItem(null, null, null, e.getEvent(), null,
                servletRequest.getRemoteAddr(), null, this, "Security Fault"));

        //DD Security error -> Return a "403 Forbidden" response
        try {
            if (!servletResponse.isCommitted())
                servletResponse.sendError(HttpServletResponse.SC_FORBIDDEN);
        } catch (IOException e1) {
            _logger.warn("Could not send response", e1);
        }
    } catch (OAException e) //Internal error
    {
        throw e;
    } catch (Exception e) {
        _logger.fatal("Could not process SAML request message", e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    }
}

From source file:net.riezebos.thoth.servlets.ThothServlet.java

protected void handleForbidden(HttpServletRequest request, HttpServletResponse response) throws IOException {
    if (isLoggedIn(request))
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
    else {/*w  w  w  .j a va2  s  . c  o  m*/
        String queryString = request.getQueryString();
        String originalRequest = request.getRequestURI() + (queryString == null ? "" : "?" + queryString);

        HttpSession session = request.getSession(true);
        session.setAttribute(REDIRECT_AFTER_LOGIN, originalRequest);

        String loginRedirect = getRootRedirect(request);
        loginRedirect += "?cmd=" + LoginCommand.TYPE_CODE;
        response.sendRedirect(loginRedirect);
    }
}

From source file:io.warp10.continuum.egress.EgressFetchHandler.java

@Override
public void handle(String target, Request baseRequest, HttpServletRequest req, HttpServletResponse resp)
        throws IOException, ServletException {
    boolean fromArchive = false;
    boolean splitFetch = false;
    boolean writeTimestamp = false;

    if (Constants.API_ENDPOINT_FETCH.equals(target)) {
        baseRequest.setHandled(true);// w w w  .  java 2  s  .c o  m
        fromArchive = false;
    } else if (Constants.API_ENDPOINT_AFETCH.equals(target)) {
        baseRequest.setHandled(true);
        fromArchive = true;
    } else if (Constants.API_ENDPOINT_SFETCH.equals(target)) {
        baseRequest.setHandled(true);
        splitFetch = true;
    } else if (Constants.API_ENDPOINT_CHECK.equals(target)) {
        baseRequest.setHandled(true);
        resp.setStatus(HttpServletResponse.SC_OK);
        return;
    } else {
        return;
    }

    try {
        // Labels for Sensision
        Map<String, String> labels = new HashMap<String, String>();

        labels.put(SensisionConstants.SENSISION_LABEL_TYPE, target);

        //
        // Add CORS header
        //

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

        String start = null;
        String stop = null;

        long now = Long.MIN_VALUE;
        long timespan = 0L;

        String nowParam = null;
        String timespanParam = null;
        String dedupParam = null;
        String showErrorsParam = null;

        if (splitFetch) {
            nowParam = req.getHeader(Constants.getHeader(Configuration.HTTP_HEADER_NOW_HEADERX));
            timespanParam = req.getHeader(Constants.getHeader(Configuration.HTTP_HEADER_TIMESPAN_HEADERX));
            showErrorsParam = req.getHeader(Constants.getHeader(Configuration.HTTP_HEADER_SHOW_ERRORS_HEADERX));
        } else {
            start = req.getParameter(Constants.HTTP_PARAM_START);
            stop = req.getParameter(Constants.HTTP_PARAM_STOP);

            nowParam = req.getParameter(Constants.HTTP_PARAM_NOW);
            timespanParam = req.getParameter(Constants.HTTP_PARAM_TIMESPAN);
            dedupParam = req.getParameter(Constants.HTTP_PARAM_DEDUP);
            showErrorsParam = req.getParameter(Constants.HTTP_PARAM_SHOW_ERRORS);
        }

        String maxDecoderLenParam = req.getParameter(Constants.HTTP_PARAM_MAXSIZE);
        int maxDecoderLen = null != maxDecoderLenParam ? Integer.parseInt(maxDecoderLenParam)
                : Constants.DEFAULT_PACKED_MAXSIZE;

        String suffix = req.getParameter(Constants.HTTP_PARAM_SUFFIX);
        if (null == suffix) {
            suffix = Constants.DEFAULT_PACKED_CLASS_SUFFIX;
        }

        boolean unpack = null != req.getParameter(Constants.HTTP_PARAM_UNPACK);

        long chunksize = Long.MAX_VALUE;

        if (null != req.getParameter(Constants.HTTP_PARAM_CHUNKSIZE)) {
            chunksize = Long.parseLong(req.getParameter(Constants.HTTP_PARAM_CHUNKSIZE));
        }

        if (chunksize <= 0) {
            throw new IOException("Invalid chunksize.");
        }

        boolean showErrors = null != showErrorsParam;
        boolean dedup = null != dedupParam && "true".equals(dedupParam);

        if (null != start && null != stop) {
            long tsstart = fmt.parseDateTime(start).getMillis() * Constants.TIME_UNITS_PER_MS;
            long tsstop = fmt.parseDateTime(stop).getMillis() * Constants.TIME_UNITS_PER_MS;

            if (tsstart < tsstop) {
                now = tsstop;
                timespan = tsstop - tsstart;
            } else {
                now = tsstart;
                timespan = tsstart - tsstop;
            }
        } else if (null != nowParam && null != timespanParam) {
            if ("now".equals(nowParam)) {
                now = TimeSource.getTime();
            } else {
                try {
                    now = Long.parseLong(nowParam);
                } catch (Exception e) {
                    now = fmt.parseDateTime(nowParam).getMillis() * Constants.TIME_UNITS_PER_MS;
                }
            }

            timespan = Long.parseLong(timespanParam);
        }

        if (Long.MIN_VALUE == now) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "Missing now/timespan or start/stop parameters.");
            return;
        }

        String selector = splitFetch ? null : req.getParameter(Constants.HTTP_PARAM_SELECTOR);

        //
        // Extract token from header
        //

        String token = req.getHeader(Constants.getHeader(Configuration.HTTP_HEADER_TOKENX));

        // If token was not found in header, extract it from the 'token' parameter
        if (null == token && !splitFetch) {
            token = req.getParameter(Constants.HTTP_PARAM_TOKEN);
        }

        String fetchSig = req.getHeader(Constants.getHeader(Configuration.HTTP_HEADER_FETCH_SIGNATURE));

        //
        // Check token signature if it was provided
        //

        boolean signed = false;

        if (splitFetch) {
            // Force showErrors
            showErrors = true;
            signed = true;
        }

        if (null != fetchSig) {
            if (null != fetchPSK) {
                String[] subelts = fetchSig.split(":");
                if (2 != subelts.length) {
                    throw new IOException("Invalid fetch signature.");
                }
                long nowts = System.currentTimeMillis();
                long sigts = new BigInteger(subelts[0], 16).longValue();
                long sighash = new BigInteger(subelts[1], 16).longValue();

                if (nowts - sigts > 10000L) {
                    throw new IOException("Fetch signature has expired.");
                }

                // Recompute hash of ts:token

                String tstoken = Long.toString(sigts) + ":" + token;

                long checkedhash = SipHashInline.hash24(fetchPSK, tstoken.getBytes(Charsets.ISO_8859_1));

                if (checkedhash != sighash) {
                    throw new IOException("Corrupted fetch signature");
                }

                signed = true;
            } else {
                throw new IOException("Fetch PreSharedKey is not set.");
            }
        }

        ReadToken rtoken = null;

        String format = splitFetch ? "wrapper" : req.getParameter(Constants.HTTP_PARAM_FORMAT);

        if (!splitFetch) {
            try {
                rtoken = Tokens.extractReadToken(token);

                if (rtoken.getHooksSize() > 0) {
                    throw new IOException("Tokens with hooks cannot be used for fetching data.");
                }
            } catch (WarpScriptException ee) {
                throw new IOException(ee);
            }

            if (null == rtoken) {
                resp.sendError(HttpServletResponse.SC_FORBIDDEN, "Missing token.");
                return;
            }
        }

        boolean showAttr = "true".equals(req.getParameter(Constants.HTTP_PARAM_SHOWATTR));

        boolean sortMeta = "true".equals(req.getParameter(Constants.HTTP_PARAM_SORTMETA));

        //
        // 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
        //
        //

        Set<Metadata> metadatas = new HashSet<Metadata>();
        List<Iterator<Metadata>> iterators = new ArrayList<Iterator<Metadata>>();

        if (!splitFetch) {

            if (null == selector) {
                throw new IOException("Missing '" + Constants.HTTP_PARAM_SELECTOR + "' parameter.");
            }

            String[] selectors = selector.split("\\s+");

            for (String sel : selectors) {
                Matcher m = SELECTOR_RE.matcher(sel);

                if (!m.matches()) {
                    resp.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) {
                    throw new IOException(pe);
                }

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

                labelsSelectors.remove(Constants.PRODUCER_LABEL);
                labelsSelectors.remove(Constants.OWNER_LABEL);
                labelsSelectors.remove(Constants.APPLICATION_LABEL);

                labelsSelectors.putAll(Tokens.labelSelectorsFromReadToken(rtoken));

                List<Metadata> metas = null;

                List<String> clsSels = new ArrayList<String>();
                List<Map<String, String>> lblsSels = new ArrayList<Map<String, String>>();

                clsSels.add(classSelector);
                lblsSels.add(labelsSelectors);

                try {
                    metas = directoryClient.find(clsSels, lblsSels);
                    metadatas.addAll(metas);
                } catch (Exception e) {
                    //
                    // If metadatas is not empty, create an iterator for it, then clear it
                    //
                    if (!metadatas.isEmpty()) {
                        iterators.add(metadatas.iterator());
                        metadatas.clear();
                    }
                    iterators.add(directoryClient.iterator(clsSels, lblsSels));
                }
            }
        } else {
            //
            // Add an iterator which reads splits from the request body
            //

            boolean gzipped = false;

            if (null != req.getHeader("Content-Type")
                    && "application/gzip".equals(req.getHeader("Content-Type"))) {
                gzipped = true;
            }

            BufferedReader br = null;

            if (gzipped) {
                GZIPInputStream is = new GZIPInputStream(req.getInputStream());
                br = new BufferedReader(new InputStreamReader(is));
            } else {
                br = req.getReader();
            }

            final BufferedReader fbr = br;

            MetadataIterator iterator = new MetadataIterator() {

                private List<Metadata> metadatas = new ArrayList<Metadata>();

                private boolean done = false;

                private String lasttoken = "";

                @Override
                public void close() throws Exception {
                    fbr.close();
                }

                @Override
                public Metadata next() {
                    if (!metadatas.isEmpty()) {
                        Metadata meta = metadatas.get(metadatas.size() - 1);
                        metadatas.remove(metadatas.size() - 1);
                        return meta;
                    } else {
                        if (hasNext()) {
                            return next();
                        } else {
                            throw new NoSuchElementException();
                        }
                    }
                }

                @Override
                public boolean hasNext() {
                    if (!metadatas.isEmpty()) {
                        return true;
                    }

                    if (done) {
                        return false;
                    }

                    String line = null;

                    try {
                        line = fbr.readLine();
                    } catch (IOException ioe) {
                        throw new RuntimeException(ioe);
                    }

                    if (null == line) {
                        done = true;
                        return false;
                    }

                    //
                    // Decode/Unwrap/Deserialize the split
                    //

                    byte[] data = OrderPreservingBase64.decode(line.getBytes(Charsets.US_ASCII));
                    if (null != fetchAES) {
                        data = CryptoUtils.unwrap(fetchAES, data);
                    }

                    if (null == data) {
                        throw new RuntimeException("Invalid wrapped content.");
                    }

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

                    GTSSplit split = new GTSSplit();

                    try {
                        deserializer.deserialize(split, data);
                    } catch (TException te) {
                        throw new RuntimeException(te);
                    }

                    //
                    // Check the expiry
                    //

                    long instant = System.currentTimeMillis();

                    if (instant - split.getTimestamp() > maxSplitAge || instant > split.getExpiry()) {
                        throw new RuntimeException("Split has expired.");
                    }

                    this.metadatas.addAll(split.getMetadatas());

                    // We assume there was at least one metadata instance in the split!!!
                    return true;
                }
            };

            iterators.add(iterator);
        }

        List<Metadata> metas = new ArrayList<Metadata>();
        metas.addAll(metadatas);

        if (!metas.isEmpty()) {
            iterators.add(metas.iterator());
        }

        //
        // Loop over the iterators, storing the read metadata to a temporary file encrypted on disk
        // Data is encrypted using a onetime pad
        //

        final byte[] onetimepad = new byte[(int) Math.min(65537, System.currentTimeMillis() % 100000)];
        new Random().nextBytes(onetimepad);

        final File cache = File.createTempFile(
                Long.toHexString(System.currentTimeMillis()) + "-" + Long.toHexString(System.nanoTime()),
                ".dircache");
        cache.deleteOnExit();

        FileWriter writer = new FileWriter(cache);

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

        int padidx = 0;

        for (Iterator<Metadata> itermeta : iterators) {
            try {
                while (itermeta.hasNext()) {
                    Metadata metadata = itermeta.next();

                    try {
                        byte[] bytes = serializer.serialize(metadata);
                        // Apply onetimepad
                        for (int i = 0; i < bytes.length; i++) {
                            bytes[i] = (byte) (bytes[i] ^ onetimepad[padidx++]);
                            if (padidx >= onetimepad.length) {
                                padidx = 0;
                            }
                        }
                        OrderPreservingBase64.encodeToWriter(bytes, writer);
                        writer.write('\n');
                    } catch (TException te) {
                    }
                }

                if (!itermeta.hasNext() && (itermeta instanceof MetadataIterator)) {
                    try {
                        ((MetadataIterator) itermeta).close();
                    } catch (Exception e) {
                    }
                }
            } catch (Throwable t) {
                throw t;
            } finally {
                if (itermeta instanceof MetadataIterator) {
                    try {
                        ((MetadataIterator) itermeta).close();
                    } catch (Exception e) {
                    }
                }
            }
        }

        writer.close();

        //
        // Create an iterator based on the cache
        //

        MetadataIterator cacheiterator = new MetadataIterator() {

            BufferedReader reader = new BufferedReader(new FileReader(cache));

            private Metadata current = null;
            private boolean done = false;

            private TDeserializer deserializer = new TDeserializer(new TCompactProtocol.Factory());

            int padidx = 0;

            @Override
            public boolean hasNext() {
                if (done) {
                    return false;
                }

                if (null != current) {
                    return true;
                }

                try {
                    String line = reader.readLine();
                    if (null == line) {
                        done = true;
                        return false;
                    }
                    byte[] raw = OrderPreservingBase64.decode(line.getBytes(Charsets.US_ASCII));
                    // Apply one time pad
                    for (int i = 0; i < raw.length; i++) {
                        raw[i] = (byte) (raw[i] ^ onetimepad[padidx++]);
                        if (padidx >= onetimepad.length) {
                            padidx = 0;
                        }
                    }
                    Metadata metadata = new Metadata();
                    try {
                        deserializer.deserialize(metadata, raw);
                        this.current = metadata;
                        return true;
                    } catch (TException te) {
                        LOG.error("", te);
                    }
                } catch (IOException ioe) {
                    LOG.error("", ioe);
                }

                return false;
            }

            @Override
            public Metadata next() {
                if (null != this.current) {
                    Metadata metadata = this.current;
                    this.current = null;
                    return metadata;
                } else {
                    throw new NoSuchElementException();
                }
            }

            @Override
            public void close() throws Exception {
                this.reader.close();
                cache.delete();
            }
        };

        iterators.clear();
        iterators.add(cacheiterator);

        metas = new ArrayList<Metadata>();

        PrintWriter pw = resp.getWriter();

        AtomicReference<Metadata> lastMeta = new AtomicReference<Metadata>(null);
        AtomicLong lastCount = new AtomicLong(0L);

        long fetchtimespan = timespan;

        for (Iterator<Metadata> itermeta : iterators) {
            while (itermeta.hasNext()) {
                metas.add(itermeta.next());

                //
                // Access the data store every 'FETCH_BATCHSIZE' GTS or at the end of each iterator
                //

                if (metas.size() > FETCH_BATCHSIZE || !itermeta.hasNext()) {
                    try (GTSDecoderIterator iterrsc = storeClient.fetch(rtoken, metas, now, fetchtimespan,
                            fromArchive, writeTimestamp)) {
                        GTSDecoderIterator iter = iterrsc;

                        if (unpack) {
                            iter = new UnpackingGTSDecoderIterator(iter, suffix);
                            timespan = Long.MIN_VALUE + 1;
                        }

                        if ("text".equals(format)) {
                            textDump(pw, iter, now, timespan, false, dedup, signed, showAttr, lastMeta,
                                    lastCount, sortMeta);
                        } else if ("fulltext".equals(format)) {
                            textDump(pw, iter, now, timespan, true, dedup, signed, showAttr, lastMeta,
                                    lastCount, sortMeta);
                        } else if ("raw".equals(format)) {
                            rawDump(pw, iter, dedup, signed, timespan, lastMeta, lastCount, sortMeta);
                        } else if ("wrapper".equals(format)) {
                            wrapperDump(pw, iter, dedup, signed, fetchPSK, timespan, lastMeta, lastCount);
                        } else if ("json".equals(format)) {
                            jsonDump(pw, iter, now, timespan, dedup, signed, lastMeta, lastCount);
                        } else if ("tsv".equals(format)) {
                            tsvDump(pw, iter, now, timespan, false, dedup, signed, lastMeta, lastCount,
                                    sortMeta);
                        } else if ("fulltsv".equals(format)) {
                            tsvDump(pw, iter, now, timespan, true, dedup, signed, lastMeta, lastCount,
                                    sortMeta);
                        } else if ("pack".equals(format)) {
                            packedDump(pw, iter, now, timespan, dedup, signed, lastMeta, lastCount,
                                    maxDecoderLen, suffix, chunksize, sortMeta);
                        } else if ("null".equals(format)) {
                            nullDump(iter);
                        } else {
                            textDump(pw, iter, now, timespan, false, dedup, signed, showAttr, lastMeta,
                                    lastCount, sortMeta);
                        }
                    } catch (Throwable t) {
                        LOG.error("", t);
                        Sensision.update(SensisionConstants.CLASS_WARP_FETCH_ERRORS, Sensision.EMPTY_LABELS, 1);
                        if (showErrors) {
                            pw.println();
                            StringWriter sw = new StringWriter();
                            PrintWriter pw2 = new PrintWriter(sw);
                            t.printStackTrace(pw2);
                            pw2.close();
                            sw.flush();
                            String error = URLEncoder.encode(sw.toString(), "UTF-8");
                            pw.println(Constants.EGRESS_FETCH_ERROR_PREFIX + error);
                        }
                        throw new IOException(t);
                    } finally {
                        if (!itermeta.hasNext() && (itermeta instanceof MetadataIterator)) {
                            try {
                                ((MetadataIterator) itermeta).close();
                            } catch (Exception e) {
                            }
                        }
                    }

                    //
                    // Reset 'metas'
                    //

                    metas.clear();
                }
            }

            if (!itermeta.hasNext() && (itermeta instanceof MetadataIterator)) {
                try {
                    ((MetadataIterator) itermeta).close();
                } catch (Exception e) {
                }
            }
        }

        Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_FETCH_REQUESTS, labels, 1);
    } catch (Exception e) {
        if (!resp.isCommitted()) {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
            return;
        }
    }
}

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

/**
 * /*from w  ww  . j  a  va  2s .com*/
 * @param externalIdentifier the external UUID of an annotation.
 * @return the xml-element representing the list of permissions, i.e. pairs (principalId, accessMode),
 * built upon the table "annotations_principals_accesses".
 * @throws IOException if sending an error fails.
 */
@GET
@Produces(MediaType.TEXT_XML)
@Path("{annotationid: " + BackendConstants.regExpIdentifier + "}/permissions")
@Transactional(readOnly = true)
public JAXBElement<PermissionList> getAnnotationPermissions(
        @PathParam("annotationid") String externalIdentifier) throws IOException {
    Map params = new HashMap();
    try {
        PermissionList result = (PermissionList) (new RequestWrappers(this)).wrapRequestResource(params,
                new GetPermissionList(), Resource.ANNOTATION, Access.READ, externalIdentifier);
        if (result != null) {
            return (new ObjectFactory()).createPermissionList(result);
        } else {
            return (new ObjectFactory()).createPermissionList(new PermissionList());
        }
    } catch (NotInDataBaseException e1) {
        httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND, e1.getMessage());
        return (new ObjectFactory()).createPermissionList(new PermissionList());
    } catch (ForbiddenException e2) {
        httpServletResponse.sendError(HttpServletResponse.SC_FORBIDDEN, e2.getMessage());
        return (new ObjectFactory()).createPermissionList(new PermissionList());
    }
}