Example usage for io.netty.handler.codec.http HttpResponseStatus FORBIDDEN

List of usage examples for io.netty.handler.codec.http HttpResponseStatus FORBIDDEN

Introduction

In this page you can find the example usage for io.netty.handler.codec.http HttpResponseStatus FORBIDDEN.

Prototype

HttpResponseStatus FORBIDDEN

To view the source code for io.netty.handler.codec.http HttpResponseStatus FORBIDDEN.

Click Source Link

Document

403 Forbidden

Usage

From source file:co.cask.cdap.internal.app.runtime.adapter.AdapterServiceTest.java

License:Apache License

@Test
public void checkForbiddenOperations() throws Exception {
    String adapterName = "myAdp";
    DummyBatchTemplate.Config config = new DummyBatchTemplate.Config("some", "0 0 1 1 *");
    AdapterConfig adapterConfig = new AdapterConfig("desc", DummyBatchTemplate.NAME, GSON.toJsonTree(config));

    // Create an adapter to deploy template application.
    adapterService.createAdapter(NAMESPACE, adapterName, adapterConfig);
    AdapterDefinition adapterSpec = adapterService.getAdapter(NAMESPACE, adapterName);
    Assert.assertNotNull(adapterSpec);/*from   w w  w .ja  va2 s.  c o  m*/

    // We should not be able to delete the application since we have created an adapter.
    Assert.assertFalse(adapterService.canDeleteApp(Id.Application.from(NAMESPACE, DummyBatchTemplate.NAME)));

    // Remove adapter but this does not delete the template app automatically.
    adapterService.removeAdapter(NAMESPACE, adapterName);

    // We should be able to delete the application since no adapters exist.
    Assert.assertTrue(adapterService.canDeleteApp(Id.Application.from(NAMESPACE, DummyBatchTemplate.NAME)));

    // This request should fail since the application is a template application.
    HttpResponse response = doPost(
            String.format("%s/namespaces/%s/apps/%s/workflows/%s/start", Constants.Gateway.API_VERSION_3,
                    TEST_NAMESPACE1, adapterConfig.getTemplate(), DummyBatchTemplate.AdapterWorkflow.NAME));
    Assert.assertEquals(HttpResponseStatus.FORBIDDEN.code(), response.getStatusLine().getStatusCode());

    // the deletion of the only adapter using the application should have deleted the app and an attempt to delete the
    // application should reutrn not found
    response = doDelete(String.format("%s/namespaces/%s/apps/%s", Constants.Gateway.API_VERSION_3,
            TEST_NAMESPACE1, adapterConfig.getTemplate()));
    Assert.assertEquals(HttpResponseStatus.NOT_FOUND.code(), response.getStatusLine().getStatusCode());

    String workerAdapter = "workAdapter";
    DummyWorkerTemplate.Config config1 = new DummyWorkerTemplate.Config(2);
    AdapterConfig adapterConfig1 = new AdapterConfig("desc1", DummyWorkerTemplate.NAME,
            GSON.toJsonTree(config1));
    adapterService.createAdapter(NAMESPACE, workerAdapter, adapterConfig1);
    adapterSpec = adapterService.getAdapter(NAMESPACE, workerAdapter);
    Assert.assertNotNull(adapterSpec);

    // This request should fail since the application is a template application.
    response = doPost(String.format("%s/namespaces/%s/apps/%s/workers/%s/stop", Constants.Gateway.API_VERSION_3,
            TEST_NAMESPACE1, adapterConfig1.getTemplate(), DummyWorkerTemplate.TWorker.NAME));
    Assert.assertEquals(HttpResponseStatus.FORBIDDEN.code(), response.getStatusLine().getStatusCode());
    adapterService.removeAdapter(NAMESPACE, workerAdapter);
}

From source file:com.bloom.zerofs.rest.NettyResponseChannel.java

License:Open Source License

/**
 * Converts a {@link ResponseStatus} into a {@link HttpResponseStatus}.
 * @param responseStatus {@link ResponseStatus} that needs to be mapped to a {@link HttpResponseStatus}.
 * @return the {@link HttpResponseStatus} that maps to the {@link ResponseStatus}.
 *///from ww  w  . j  a v a2  s . c o  m
private HttpResponseStatus getHttpResponseStatus(ResponseStatus responseStatus) {
    HttpResponseStatus status;
    switch (responseStatus) {
    case Ok:
        status = HttpResponseStatus.OK;
        break;
    case Created:
        status = HttpResponseStatus.CREATED;
        break;
    case Accepted:
        status = HttpResponseStatus.ACCEPTED;
        break;
    case NotModified:
        status = HttpResponseStatus.NOT_MODIFIED;
        break;
    case BadRequest:
        nettyMetrics.badRequestCount.inc();
        status = HttpResponseStatus.BAD_REQUEST;
        break;
    case Unauthorized:
        nettyMetrics.unauthorizedCount.inc();
        status = HttpResponseStatus.UNAUTHORIZED;
        break;
    case NotFound:
        nettyMetrics.notFoundCount.inc();
        status = HttpResponseStatus.NOT_FOUND;
        break;
    case Gone:
        nettyMetrics.goneCount.inc();
        status = HttpResponseStatus.GONE;
        break;
    case Forbidden:
        nettyMetrics.forbiddenCount.inc();
        status = HttpResponseStatus.FORBIDDEN;
        break;
    case ProxyAuthenticationRequired:
        nettyMetrics.proxyAuthRequiredCount.inc();
        status = HttpResponseStatus.PROXY_AUTHENTICATION_REQUIRED;
        break;
    case InternalServerError:
        nettyMetrics.internalServerErrorCount.inc();
        status = HttpResponseStatus.INTERNAL_SERVER_ERROR;
        break;
    default:
        nettyMetrics.unknownResponseStatusCount.inc();
        status = HttpResponseStatus.INTERNAL_SERVER_ERROR;
        break;
    }
    return status;
}

From source file:com.chenyang.proxy.http.HttpSchemaHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext uaChannelCtx, final Object msg) throws Exception {

    if (msg instanceof HttpRequest) {
        HttpRequest httpRequest = (HttpRequest) msg;

        String originalHost = HostNamePortUtil.getHostName(httpRequest);
        int originalPort = HostNamePortUtil.getPort(httpRequest);
        HttpRemote apnProxyRemote = new HttpRemote(originalHost, originalPort);

        if (!HostAuthenticationUtil.isValidAddress(apnProxyRemote.getInetSocketAddress())) {
            HttpErrorUtil.writeAndFlush(uaChannelCtx.channel(), HttpResponseStatus.FORBIDDEN);
            return;
        }/*  w  w  w .  ja  va 2 s .c  o  m*/

        Channel uaChannel = uaChannelCtx.channel();

        HttpConnectionAttribute apnProxyConnectionAttribute = HttpConnectionAttribute.build(
                uaChannel.remoteAddress().toString(), httpRequest.getMethod().name(), httpRequest.getUri(),
                httpRequest.getProtocolVersion().text(),
                httpRequest.headers().get(HttpHeaders.Names.USER_AGENT), apnProxyRemote);

        uaChannelCtx.attr(HttpConnectionAttribute.ATTRIBUTE_KEY).set(apnProxyConnectionAttribute);
        uaChannel.attr(HttpConnectionAttribute.ATTRIBUTE_KEY).set(apnProxyConnectionAttribute);

        if (httpRequest.getMethod().equals(HttpMethod.CONNECT)) {
            if (uaChannelCtx.pipeline().get(HttpUserAgentForwardHandler.HANDLER_NAME) != null) {
                uaChannelCtx.pipeline().remove(HttpUserAgentForwardHandler.HANDLER_NAME);
            }
            if (uaChannelCtx.pipeline().get(HttpUserAgentTunnelHandler.HANDLER_NAME) == null) {
                uaChannelCtx.pipeline().addLast(HttpUserAgentTunnelHandler.HANDLER_NAME,
                        new HttpUserAgentTunnelHandler());
            }
        } else {
            if (uaChannelCtx.pipeline().get(HttpUserAgentForwardHandler.HANDLER_NAME) == null) {
                uaChannelCtx.pipeline().addLast(HttpUserAgentForwardHandler.HANDLER_NAME,
                        new HttpUserAgentForwardHandler());
            }
        }
    }

    uaChannelCtx.fireChannelRead(msg);
}

From source file:com.chiorichan.http.HttpHandler.java

License:Mozilla Public License

/**
 * Handles the HTTP request. Each HTTP subsystem will be explicitly activated until a resolve is determined.
 *
 * @throws IOException/* ww w  . j  a  v  a 2 s.c o  m*/
 *              Universal exception for all Input/Output errors
 * @throws HttpError
 *              for HTTP Errors
 * @throws PermissionException
 *              for permission problems, like access denied
 * @throws MultipleException
 *              for multiple Scripting Factory Evaluation Exceptions
 * @throws ScriptingException
 *              for Scripting Factory Evaluation Exception
 * @throws SessionException
 *              for problems initializing a new or used session
 */
private void handleHttp() throws Exception // IOException, HttpError, SiteException, PermissionException, MultipleException, ScriptingException, SessionException
{
    log.log(Level.INFO, request.methodString() + " " + request.getFullUrl());

    Session sess = request.startSession();

    log.log(Level.FINE, "Session {id=%s,timeout=%s,new=%s}", sess.getSessId(), sess.getTimeout(), sess.isNew());

    if (response.getStage() == HttpResponseStage.CLOSED)
        throw new IOException("Connection reset by peer"); // This is not the only place 'Connection reset by peer' is thrown

    RequestEvent requestEvent = new RequestEvent(request);

    try {
        EventBus.instance().callEventWithException(requestEvent);
    } catch (EventException ex) {
        throw new IOException(
                "Exception encountered during request event call, most likely the fault of a plugin.", ex);
    }

    response.setStatus(requestEvent.getStatus());

    if (requestEvent.isCancelled()) {
        int status = requestEvent.getStatus();
        String reason = requestEvent.getReason();

        if (status == 200) {
            status = 502;
            reason = "Navigation Cancelled by Plugin Event";
        }

        NetworkManager.getLogger().warning("Navigation was cancelled by a Plugin Event");

        throw new HttpError(status, reason);
    }

    if (response.isCommitted())
        return;

    // Throws IOException and HttpError
    fi = new WebInterpreter(request);
    response.annotations.putAll(fi.getAnnotations());

    currentSite = request.getLocation();
    sess.setSite(currentSite);

    if (request.getSubdomain().length() > 0
            && !currentSite.getSubdomain(request.getSubdomain()).isMaped(request.getDomain())) {
        if ("www".equalsIgnoreCase(request.getSubdomain())
                || AppConfig.get().getBoolean("sites.redirectMissingSubDomains")) {
            log.log(Level.SEVERE, "Redirecting non-existent subdomain '%s' to root domain '%s'",
                    request.getSubdomain(), request.getFullUrl(""));
            response.sendRedirect(request.getFullUrl(""));
        } else {
            log.log(Level.SEVERE, "The requested subdomain '%s' is non-existent.", request.getSubdomain(),
                    request.getFullDomain(""));
            response.sendError(HttpResponseStatus.NOT_FOUND, "Subdomain not found");
        }
        return;
    }

    File docRoot = currentSite.getSubdomain(request.getSubdomain()).directory();

    Validate.notNull(docRoot);

    if (sess.isLoginPresent())
        log.log(Level.FINE, "Account {id=%s,displayName=%s}", sess.getId(), sess.getDisplayName());

    /*
     * Start: SSL enforcer
     *
     * Acts on the value of annotation 'SSL'.
     * REQUIRED means a forbidden error will be thrown is it can not be accomplished
     *
     * Options include:
     * Preferred: If SSL is available, we preferred to be switched to it
     * PostOnly: SSL is REQUIRED is this is a POST request
     * GetOnly: SSL is REQUIRED if this is a GET request
     * Required: SSL is REQUIRED, no exceptions!
     * Deny: SSL is DENIED, no exceptions!
     * Ignore: We don't care one way or other, do nothing! DEFAULT
     */
    SslLevel sslLevel = SslLevel.parse(fi.get("ssl"));
    boolean required = false;

    switch (sslLevel) {
    case Preferred:
        if (NetworkManager.isHttpsRunning())
            required = true;
        break;
    case PostOnly:
        if (request.method() == HttpMethod.POST)
            required = true;
        break;
    case GetOnly:
        if (request.method() == HttpMethod.GET)
            required = true;
        break;
    case Required:
        required = true;
        break;
    case Deny:
        if (ssl) {
            if (!response.switchToUnsecure())
                response.sendError(HttpCode.HTTP_FORBIDDEN, "This page requires an unsecure connection.");
            return;
        }
        break;
    case Ignore:
        break;
    }

    if (required && !ssl) {
        if (!response.switchToSecure())
            response.sendError(HttpCode.HTTP_FORBIDDEN, "This page requires a secure connection.");
        return;
    }
    /*
     * End: SSL enforcer
     */

    if (fi.getStatus() != HttpResponseStatus.OK)
        throw new HttpError(fi.getStatus());

    /*
     * Start: Apache Configuration Section
     *
     * Loads a Apache configuration and .htaccess files into a common handler, then parsed for directives like access restrictions and basic auth
     * TODO Load server-wide Apache Configuration then merge with Site Configuration
     */
    ApacheHandler htaccess = new ApacheHandler();
    response.setApacheParser(htaccess);

    try {
        boolean result = htaccess.handleDirectives(currentSite.getApacheConfig(), this);

        if (htaccess.overrideNone() || htaccess.overrideListNone()) // Ignore .htaccess files
        {
            if (fi.hasFile())
                if (!htaccess.handleDirectives(new ApacheConfiguration(fi.getFile().getParentFile()), this))
                    result = false;

            if (!htaccess.handleDirectives(new ApacheConfiguration(docRoot), this))
                result = false;
        }

        if (!result) {
            if (!response.isCommitted())
                response.sendError(500,
                        "Your request was blocked by an internal configuration directive, exact details are unknown.");
            return;
        }
    } catch (ApacheDirectiveException e) {
        log.log(Level.SEVERE, "Caught Apache directive exception: " + e.getMessage());

        // TODO Throw 500 unless told not to
    }
    /*
     * End: Apache Configuration Section
     */

    if (!fi.hasFile() && !fi.hasHTML())
        response.setStatus(HttpResponseStatus.NO_CONTENT);

    sess.setGlobal("__FILE__", fi.getFile());

    request.putRewriteParams(fi.getRewriteParams());
    response.setContentType(fi.getContentType());
    response.setEncoding(fi.getEncoding());

    request.getServer().put(ServerVars.DOCUMENT_ROOT, docRoot);

    request.setGlobal("_SERVER", request.getServer());
    request.setGlobal("_POST", request.getPostMap());
    request.setGlobal("_GET", request.getGetMap());
    request.setGlobal("_REWRITE", request.getRewriteMap());
    request.setGlobal("_FILES", request.getUploadedFiles());

    // TODO Implement NONCE requirement for login page
    NonceLevel level = NonceLevel.parse(fi.get("nonce"));
    boolean nonceProvided = sess.nonce() == null ? false
            : request.getRequestMap().get(sess.nonce().key()) != null;
    boolean processNonce = false;

    switch (level) {
    case Required:
        processNonce = true;
        break;
    case GetOnly:
        processNonce = request.method() == HttpMethod.GET || nonceProvided;
        break;
    case PostOnly:
        processNonce = request.method() == HttpMethod.POST || nonceProvided;
        break;
    case Flexible:
        processNonce = nonceProvided;
        break;
    case Disabled:
    default:
        // Do Nothing
    }

    Map<String, String> nonceMap = Maps.newHashMap();

    if (processNonce) {
        if (!nonceProvided) {
            log.log(Level.SEVERE,
                    "The request has failed NONCE validation, because the nonce key was not present!");
            response.sendError(HttpResponseStatus.FORBIDDEN, "Your request has failed NONCE validation!");
            return;
        }

        Nonce nonce = sess.nonce();

        if (level == NonceLevel.Required)
            // Required NonceLevels are of the highest protected state
            sess.destroyNonce();

        try {
            if (!(request.getRequestMap().get(nonce.key()) instanceof String))
                throw new NonceException("Nonce token is not a string");
            nonce.validateWithException((String) request.getRequestMap().get(nonce.key()));
        } catch (NonceException e) {
            log.log(Level.SEVERE,
                    "The request has failed NONCE validation, because " + e.getMessage().toLowerCase() + "!");
            response.sendError(HttpResponseStatus.FORBIDDEN, "Your request has failed NONCE validation!");
            sess.destroyNonce();
            return;
        } finally {
            log.log(Level.INFO, "The request has passed the NONCE validation!");
            request.nonceProcessed(true);
            nonceMap = nonce.mapValues();
        }
    }

    if (request.validateLogins())
        return;

    if (level != NonceLevel.Disabled)
        request.setGlobal("_NONCE", nonceMap);

    try {
        if (request.getUploadedFiles().size() > 0)
            log.log(Level.INFO,
                    "Uploads {"
                            + StringFunc.limitLength(
                                    Joiner.on(",").skipNulls().join(request.getUploadedFiles().values()), 255)
                            + "}");

        if (request.getGetMap().size() > 0)
            log.log(Level.INFO, "Params GET {" + StringFunc.limitLength(
                    Joiner.on(",").withKeyValueSeparator("=").useForNull("null").join(request.getGetMap()), 255)
                    + "}");

        if (request.getPostMap().size() > 0)
            log.log(Level.INFO, "Params POST {" + StringFunc.limitLength(
                    Joiner.on(",").withKeyValueSeparator("=").useForNull("null").join(request.getPostMap()),
                    255) + "}");

        if (request.getRewriteMap().size() > 0)
            log.log(Level.INFO, "Params REWRITE {" + StringFunc.limitLength(
                    Joiner.on(",").withKeyValueSeparator("=").useForNull("null").join(request.getRewriteMap()),
                    255) + "}");

        if (fi.getAnnotations().size() > 0)
            log.log(Level.INFO, "Params ANNOTATIONS {" + StringFunc.limitLength(
                    Joiner.on(",").withKeyValueSeparator("=").useForNull("null").join(fi.getAnnotations()), 255)
                    + "}");
    } catch (Throwable t) {
        t.printStackTrace();
    }

    if (AppConfig.get().getBoolean("advanced.security.requestMapEnabled", true))
        request.setGlobal("_REQUEST", request.getRequestMap());

    ByteBuf rendered = Unpooled.buffer();

    ScriptingFactory factory = request.getEvalFactory();
    factory.setEncoding(fi.getEncoding());

    NetworkSecurity.isForbidden(htaccess, currentSite, fi);

    String req = fi.get("reqperm");

    if (req == null)
        req = "-1";

    sess.requirePermission(req, currentSite.getId());

    // Enhancement: Allow HTML to be ran under different shells. Default is embedded.
    if (fi.hasHTML()) {
        ScriptingResult result = factory.eval(
                ScriptingContext.fromSource(fi.getHTML(), "<embedded>").request(request).site(currentSite));

        if (result.hasExceptions())
            // TODO Print notices to output like PHP does
            for (ScriptingException e : result.getExceptions()) {
                ExceptionReport.throwExceptions(e);
                log.exceptions(e);
                if (e.reportingLevel().isEnabled())
                    rendered.writeBytes(e.getMessage().getBytes());
            }

        if (result.isSuccessful()) {
            rendered.writeBytes(result.content());
            if (result.getObject() != null && !(result.getObject() instanceof NullObject))
                try {
                    rendered.writeBytes(ObjectFunc.castToStringWithException(result.getObject()).getBytes());
                } catch (Exception e) {
                    log.log(Level.SEVERE, "Exception Excountered: %s", e.getMessage());
                    if (Versioning.isDevelopment())
                        log.log(Level.SEVERE, e.getStackTrace()[0].toString());
                }
        }

        log.log(Level.INFO, "EvalHtml {timing=%sms,success=%s}", Timings.mark(this), result.isSuccessful());
    }

    if (fi.hasFile()) {
        if (fi.isDirectoryRequest()) {
            processDirectoryListing();
            return;
        }

        ScriptingResult result = factory.eval(ScriptingContext.fromFile(fi).request(request).site(currentSite));

        if (result.hasExceptions())
            // TODO Print notices to output like PHP does
            for (ScriptingException e : result.getExceptions()) {
                ExceptionReport.throwExceptions(e);
                log.exceptions(e);
                if (e.reportingLevel().isEnabled() && e.getMessage() != null)
                    rendered.writeBytes(e.getMessage().getBytes());
            }

        if (result.isSuccessful()) {
            rendered.writeBytes(result.content());
            if (result.getObject() != null && !(result.getObject() instanceof NullObject))
                try {
                    rendered.writeBytes(ObjectFunc.castToStringWithException(result.getObject()).getBytes());
                } catch (Exception e) {
                    rendered.writeBytes(result.getObject().toString().getBytes());
                    log.log(Level.SEVERE, "Exception encountered while writing returned object to output. %s",
                            e.getMessage());
                    if (Versioning.isDevelopment())
                        log.log(Level.SEVERE, e.getStackTrace()[0].toString());
                }
        }

        log.log(Level.INFO, "EvalFile {file=%s,timing=%sms,success=%s}", fi.getFilePath(), Timings.mark(this),
                result.isSuccessful());
    }

    // if the connection was in a MultiPart mode, wait for the mode to change then return gracefully.
    if (response.stage == HttpResponseStage.MULTIPART) {
        while (response.stage == HttpResponseStage.MULTIPART)
            // I wonder if there is a better way to handle multipart responses.
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new HttpError(500, "Internal Server Error encountered during multipart execution.");
            }

        return;
    }
    // If the connection was closed from page redirect, return gracefully.
    else if (response.stage == HttpResponseStage.CLOSED || response.stage == HttpResponseStage.WRITTEN)
        return;

    // Allows scripts to directly override interpreter values. For example: Themes, Views, Titles
    for (Entry<String, String> kv : response.annotations.entrySet())
        fi.put(kv.getKey(), kv.getValue());

    RenderEvent renderEvent = new RenderEvent(this, rendered, fi.getEncoding(), fi.getAnnotations());

    try {
        EventBus.instance().callEventWithException(renderEvent);
        if (renderEvent.getSource() != null)
            rendered = renderEvent.getSource();
    } catch (EventException ex) {
        throw new ScriptingException(ReportingLevel.E_ERROR,
                "Caught EventException while trying to fire the RenderEvent", ex.getCause());
    }

    log.log(Level.INFO, "Written {bytes=%s,total_timing=%sms}", rendered.readableBytes(), Timings.finish(this));

    try {
        response.write(rendered);
    } catch (IllegalReferenceCountException e) {
        log.log(Level.SEVERE, "Exception encountered while writting script object to output, %s",
                e.getMessage());
    }
}

From source file:com.earasoft.framework.http.WebSocketServerHandler.java

License:Apache License

private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest request) {
    // Handle a bad request.
    if (!request.getDecoderResult().isSuccess()) {
        sendHttpResponse(ctx, request, new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.BAD_REQUEST));
        return;//from  w  ww. j  a  v  a  2s .c o m
    }

    if (RouterHits.checkIfMappingExit(request)) {
        //Do Router Mapping First
        RouterHits.execute(ctx, request);
        return;
    }

    if ("/websocket".equals(request.getUri())) {
        // Handshake
        WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
                getWebSocketLocation(request), null, true);
        handshaker = wsFactory.newHandshaker(request);
        if (handshaker == null) {
            WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
        } else {
            handshaker.handshake(ctx.channel(), request);
            channels.add(ctx.channel());
        }
        return;
    }

    final String uri = request.getUri();
    //System.out.println("uri: " + uri);
    final String path = sanitizeUri("www", uri);
    //System.out.println("path: " + path);
    if (path == null) {
        sendHttpResponse(ctx, request, new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.FORBIDDEN));

        return;
    }

    File file = new File(path);
    if (file.isHidden() || !file.exists()) {
        sendHttpResponse(ctx, request, new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.NOT_FOUND));
        return;
    }

    if (file.isDirectory()) {
        if (uri.endsWith("/")) {

            File checkIndexFile = new File(file.getAbsolutePath() + File.separator + "index.html");

            System.out.println(checkIndexFile.exists());
            if (checkIndexFile.exists()) {
                file = checkIndexFile;
            } else {
                sendListing(ctx, file);
                return;
            }
        } else {
            sendRedirect(ctx, uri + '/');

        }
    }

    if (!file.isFile()) {
        sendHttpResponse(ctx, request, new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.FORBIDDEN));
        return;
    }

    // Cache Validation
    String ifModifiedSince = request.headers().get(IF_MODIFIED_SINCE);
    if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) {
        SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
        Date ifModifiedSinceDate = null;
        try {
            ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // Only compare up to the second because the datetime format we send to the client
        // does not have milliseconds
        long ifModifiedSinceDateSeconds = ifModifiedSinceDate.getTime() / 1000;
        long fileLastModifiedSeconds = file.lastModified() / 1000;
        if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) {
            sendNotModified(ctx);
            return;
        }
    }

    RandomAccessFile raf;
    try {
        raf = new RandomAccessFile(file, "r");
    } catch (FileNotFoundException ignore) {
        sendHttpResponse(ctx, request, new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.NOT_FOUND));
        return;
    }
    long fileLength = 0;
    try {
        fileLength = raf.length();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    HttpHeaders.setContentLength(response, fileLength);
    setContentTypeHeader(response, file);
    setDateAndCacheHeaders(response, file);
    if (HttpHeaders.isKeepAlive(request)) {
        response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }

    // Write the initial line and the header.
    ctx.write(response);

    // Write the content.
    ChannelFuture sendFileFuture = null;
    ChannelFuture lastContentFuture;
    if (ctx.pipeline().get(SslHandler.class) == null) {
        sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength),
                ctx.newProgressivePromise());
        // Write the end marker.
        lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
    } else {
        try {
            sendFileFuture = ctx.writeAndFlush(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)),
                    ctx.newProgressivePromise());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // HttpChunkedInput will write the end marker (LastHttpContent) for us.
        lastContentFuture = sendFileFuture;
    }

    sendFileFuture.addListener(new ChannelProgressiveFutureListener() {
        @Override
        public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) {
            if (total < 0) { // total unknown
                System.err.println(future.channel() + " Transfer progress: " + progress);
            } else {
                System.err.println(future.channel() + " Transfer progress: " + progress + " / " + total);
            }
        }

        @Override
        public void operationComplete(ChannelProgressiveFuture future) {
            System.err.println(future.channel() + " Transfer complete.");
        }
    });

    // Decide whether to close the connection or not.
    if (!HttpHeaders.isKeepAlive(request)) {
        // Close the connection when the whole content is written out.
        lastContentFuture.addListener(ChannelFutureListener.CLOSE);
    }

    //        // Send the demo page and favicon.ico
    //        if ("/".equals(req.getUri()) && req.getMethod() == GET) {
    //            ByteBuf content = WebSocketServerIndexPage.getContent(getWebSocketLocation(req));
    //            FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK, content);
    //
    //            res.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8");
    //            HttpHeaders.setContentLength(res, content.readableBytes());
    //
    //            sendHttpResponse(ctx, req, res);
    //            return;
    //        }
    //        
    //        if ("/favicon.ico".equals(req.getUri())) {
    //            FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND);
    //            sendHttpResponse(ctx, req, res);
    //            return;
    //        }

    sendHttpResponse(ctx, request, new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.FORBIDDEN));
    return;

}

From source file:com.ejisto.modules.vertx.handler.SecurityEnforcer.java

License:Open Source License

@Override
public void handle(HttpServerRequest request) {

    final MultiMap headers = request.headers();
    Optional<String> xRequestedWith = Optional.ofNullable(headers.get(X_REQUESTED_WITH))
            .filter("XMLHttpRequest"::equals);

    if (xRequestedWith.isPresent()) {
        if (!isDevModeActive()) {
            request.response().write(SECURITY_TOKEN);
        }/*from w  ww  .  java2  s  . c om*/
        Optional<String> header = Optional.ofNullable(headers.get(XSRF_TOKEN_HEADER)).filter(token::equals);
        if (!header.isPresent()) {
            Boilerplate.writeError(request, HttpResponseStatus.FORBIDDEN.code(),
                    HttpResponseStatus.FORBIDDEN.reasonPhrase());
            return;
        }
    }

    if ("/index.html".equals(request.path())) {
        Cookie cookie = new DefaultCookie(XSRF_TOKEN, token);
        cookie.setPath("/");
        request.response().headers().set(HttpHeaders.SET_COOKIE, ServerCookieEncoder.encode(cookie));
    }
    super.handle(request);
}

From source file:com.github.smallcreep.bmp.client.tests.TestProxyBMPClient.java

License:Apache License

@Test
public void testOverridesResponseAsString() throws Throwable {
    getBmpLittleProxy().setFilterResponse(
            "contents.setTextContents('<html><body>Response successfully intercepted</body></html>'); "
                    + "var HttpResponseStatusClass = Java.type('io.netty.handler.codec.http.HttpResponseStatus'); "
                    + "var st = HttpResponseStatusClass.FORBIDDEN;response.setStatus(st);");
    Unirest.setProxy(new HttpHost(getBmpLittleProxy().getAddress(), getBmpLittleProxy().getPort()));
    HttpResponse<String> response = Unirest.get(URL_PROTOCOL + URL_FOR_TEST).asString();
    assertEquals("<html><body>Response successfully intercepted</body></html>", response.getBody());
    assertEquals(HttpResponseStatus.FORBIDDEN.code(), response.getStatus());
}

From source file:com.github.smallcreep.bmp.client.tests.TestProxyBMPClient.java

License:Apache License

@Test
public void testOverridesResponseAsResponseFilter() throws Throwable {
    Headers headersExpected = new Headers();
    List<String> accessControlAllowCredentialsList = new ArrayList<>();
    accessControlAllowCredentialsList.add("test");
    accessControlAllowCredentialsList.add("test2");
    headersExpected.put(ACCESS_CONTROL_ALLOW_CREDENTIALS, accessControlAllowCredentialsList);
    List<String> accessControlMaxAgeList = new ArrayList<>();
    accessControlMaxAgeList.add("test3");
    headersExpected.put(ACCESS_CONTROL_MAX_AGE, accessControlMaxAgeList);
    io.netty.handler.codec.http.HttpResponse responseOverrides = new DefaultFullHttpResponse(
            HttpVersion.HTTP_1_1, HttpResponseStatus.FORBIDDEN);
    for (String headers : headersExpected.keySet()) {
        for (String headersValue : headersExpected.get(headers)) {
            responseOverrides.headers().add(headers, headersValue);
        }/*  w w w .j av  a  2s.com*/
    }
    HttpMessageContents contents = new HttpMessageContents(
            new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.FORBIDDEN));
    contents.setTextContents("<html><body>Response successfully intercepted</body></html>");
    BMPResponseFilter bmpResponseFilter = new BMPResponseFilter(responseOverrides, contents, null);
    getBmpLittleProxy().setFilterResponse(bmpResponseFilter);
    Unirest.setProxy(new HttpHost(getBmpLittleProxy().getAddress(), getBmpLittleProxy().getPort()));
    HttpResponse<String> response = Unirest.get(URL_PROTOCOL + URL_FOR_TEST).asString();
    assertOverrideResponseEquals(accessControlAllowCredentialsList, accessControlMaxAgeList, response);
}

From source file:com.github.smallcreep.bmp.client.tests.TestProxyBMPClient.java

License:Apache License

@Test
public void testOverridesResponseAsResponseFilterAndListUrl() throws Throwable {
    Headers headersExpected = new Headers();
    List<String> accessControlAllowCredentialsList = new ArrayList<>();
    accessControlAllowCredentialsList.add("test");
    accessControlAllowCredentialsList.add("test2");
    headersExpected.put(ACCESS_CONTROL_ALLOW_CREDENTIALS, accessControlAllowCredentialsList);
    List<String> accessControlMaxAgeList = new ArrayList<>();
    accessControlMaxAgeList.add("test3");
    headersExpected.put(ACCESS_CONTROL_MAX_AGE, accessControlMaxAgeList);
    io.netty.handler.codec.http.HttpResponse responseOverrides = new DefaultFullHttpResponse(
            HttpVersion.HTTP_1_1, HttpResponseStatus.FORBIDDEN);
    for (String headers : headersExpected.keySet()) {
        for (String headersValue : headersExpected.get(headers)) {
            responseOverrides.headers().add(headers, headersValue);
        }//  w  ww.ja va2  s  .c o  m
    }
    HttpMessageContents contents = new HttpMessageContents(
            new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.FORBIDDEN));
    contents.setTextContents("<html><body>Response successfully intercepted</body></html>");
    List<FilterUrls> filterUrls = new ArrayList<>();
    filterUrls.add(new FilterUrls("(.*)index\\.html(.*)"));
    filterUrls.add(new FilterUrls("^http:\\/\\/search\\.maven\\.org\\/$", HttpMethod.GET));
    filterUrls.add(new FilterUrls("(.*)test\\.html(.*)", HttpMethod.POST));
    BMPResponseFilter bmpResponseFilter = new BMPResponseFilter(responseOverrides, contents, null, filterUrls);
    getBmpLittleProxy().setFilterResponse(bmpResponseFilter);
    Unirest.setProxy(new HttpHost(getBmpLittleProxy().getAddress(), getBmpLittleProxy().getPort()));

    HttpResponse<String> response = Unirest.get(URL_PROTOCOL + URL_FOR_TEST).asString();
    assertOverrideResponseEquals(accessControlAllowCredentialsList, accessControlMaxAgeList, response);
    response = Unirest.post(URL_PROTOCOL + URL_FOR_TEST).asString();
    assertOverrideResponseNotEquals(accessControlAllowCredentialsList, accessControlMaxAgeList, response);

    response = Unirest.get("http://search.maven.org/index.html").asString();
    assertOverrideResponseEquals(accessControlAllowCredentialsList, accessControlMaxAgeList, response);
    response = Unirest.post("http://search.maven.org/index.html").asString();
    assertOverrideResponseEquals(accessControlAllowCredentialsList, accessControlMaxAgeList, response);

    response = Unirest.get("http://search.maven.org/test.html").asString();
    assertOverrideResponseNotEquals(accessControlAllowCredentialsList, accessControlMaxAgeList, response);
    response = Unirest.post("http://search.maven.org/test.html").asString();
    assertOverrideResponseEquals(accessControlAllowCredentialsList, accessControlMaxAgeList, response);

    response = Unirest.get("http://search.maven.org/abracadabra.alibaba").asString();
    assertOverrideResponseNotEquals(accessControlAllowCredentialsList, accessControlMaxAgeList, response);
    response = Unirest.post("http://search.maven.org/abracadabra.alibaba").asString();
    assertOverrideResponseNotEquals(accessControlAllowCredentialsList, accessControlMaxAgeList, response);
}

From source file:com.github.smallcreep.bmp.client.tests.TestProxyBMPClient.java

License:Apache License

@Test
public void testOverridesResponseAsResponseFilterAndType() throws Throwable {
    Headers headersExpected = new Headers();
    List<String> accessControlAllowCredentialsList = new ArrayList<>();
    accessControlAllowCredentialsList.add("test");
    accessControlAllowCredentialsList.add("test2");
    headersExpected.put(ACCESS_CONTROL_ALLOW_CREDENTIALS, accessControlAllowCredentialsList);
    List<String> accessControlMaxAgeList = new ArrayList<>();
    accessControlMaxAgeList.add("test3");
    headersExpected.put(ACCESS_CONTROL_MAX_AGE, accessControlMaxAgeList);
    io.netty.handler.codec.http.HttpResponse responseOverrides = new DefaultFullHttpResponse(
            HttpVersion.HTTP_1_1, HttpResponseStatus.FORBIDDEN);
    for (String headers : headersExpected.keySet()) {
        for (String headersValue : headersExpected.get(headers)) {
            responseOverrides.headers().add(headers, headersValue);
        }// w ww.j  a va2  s  . co m
    }
    HttpMessageContents contents = new HttpMessageContents(
            new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.FORBIDDEN));
    contents.setTextContents("<html><body>Response successfully intercepted</body></html>");
    List<FilterUrls> filterUrls = new ArrayList<>();
    DefaultHttpHeaders httpHeaders = new DefaultHttpHeaders();
    httpHeaders.add(HttpHeaders.Names.CONTENT_TYPE, "text/css");
    filterUrls.add(new FilterUrls("^http:\\/\\/search\\.maven\\.org\\/(.*)$", HttpMethod.GET, httpHeaders));

    BMPResponseFilter bmpResponseFilter = new BMPResponseFilter(responseOverrides, contents, null, filterUrls);
    getBmpLittleProxy().setFilterResponse(bmpResponseFilter);
    Unirest.setProxy(new HttpHost(getBmpLittleProxy().getAddress(), getBmpLittleProxy().getPort()));

    HttpResponse<String> response = Unirest.get("http://search.maven.org/ajaxsolr/css/central.css").asString();
    assertOverrideResponseEquals(accessControlAllowCredentialsList, accessControlMaxAgeList, response);

    response = Unirest.get("http://search.maven.org/test.html").asString();
    assertOverrideResponseNotEquals(accessControlAllowCredentialsList, accessControlMaxAgeList, response);

    response = Unirest.get("http://search.maven.org/").asString();
    assertOverrideResponseNotEquals(accessControlAllowCredentialsList, accessControlMaxAgeList, response);
}