Example usage for io.netty.handler.codec.http HttpHeaderNames EXPIRES

List of usage examples for io.netty.handler.codec.http HttpHeaderNames EXPIRES

Introduction

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

Prototype

AsciiString EXPIRES

To view the source code for io.netty.handler.codec.http HttpHeaderNames EXPIRES.

Click Source Link

Document

"expires"

Usage

From source file:com.bunjlabs.fuga.network.netty.NettyHttpServerHandler.java

License:Apache License

private void writeResponse(ChannelHandlerContext ctx, Request request, Response response) {
    HttpResponse httpresponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
            HttpResponseStatus.valueOf(response.status()));

    httpresponse.headers().set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
    httpresponse.headers().set(HttpHeaderNames.CONTENT_TYPE, response.contentType());

    // Disable cache by default
    httpresponse.headers().set(HttpHeaderNames.CACHE_CONTROL, "no-cache, no-store, must-revalidate, max-age=0");
    httpresponse.headers().set(HttpHeaderNames.PRAGMA, "no-cache");
    httpresponse.headers().set(HttpHeaderNames.EXPIRES, "0");

    response.headers().entrySet().stream().forEach((e) -> httpresponse.headers().set(e.getKey(), e.getValue()));

    httpresponse.headers().set(HttpHeaderNames.SERVER, "Fuga Netty Web Server/" + serverVersion);

    // Set cookies
    httpresponse.headers().set(HttpHeaderNames.SET_COOKIE,
            ServerCookieEncoder.STRICT.encode(NettyCookieConverter.convertListToNetty(response.cookies())));

    if (response.length() >= 0) {
        httpresponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.length());
    }/*from w ww  .ja  v a2 s .co  m*/

    if (HttpUtil.isKeepAlive(httprequest)) {
        httpresponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    } else {
        httpresponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
    }

    ctx.write(httpresponse);

    if (response.stream() != null) {
        ctx.write(new HttpChunkedInput(new ChunkedStream(response.stream())));
    }

    LastHttpContent fs = new DefaultLastHttpContent();
    ChannelFuture sendContentFuture = ctx.writeAndFlush(fs);
    if (!HttpUtil.isKeepAlive(httprequest)) {
        sendContentFuture.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:com.cmz.http.file.HttpStaticFileServerHandler.java

License:Apache License

/**
 * Sets the Date and Cache headers for the HTTP Response
 *
 * @param response// ww w. java 2s .  c o m
 *            HTTP response
 * @param fileToCache
 *            file to extract content type
 */
private static void setDateAndCacheHeaders(HttpResponse response, File fileToCache) {
    SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
    dateFormatter.setTimeZone(TimeZone.getTimeZone(HTTP_DATE_GMT_TIMEZONE));

    // Date header
    Calendar time = new GregorianCalendar();
    response.headers().set(HttpHeaderNames.DATE, dateFormatter.format(time.getTime()));

    // Add cache headers
    time.add(Calendar.SECOND, HTTP_CACHE_SECONDS);
    response.headers().set(HttpHeaderNames.EXPIRES, dateFormatter.format(time.getTime()));
    response.headers().set(HttpHeaderNames.CACHE_CONTROL, "private, max-age=" + HTTP_CACHE_SECONDS);
    response.headers().set(HttpHeaderNames.LAST_MODIFIED,
            dateFormatter.format(new Date(fileToCache.lastModified())));
}

From source file:com.ociweb.pronghorn.adapter.netty.impl.HttpStaticFileServerHandler.java

License:Apache License

/**
 * Sets the Date and Cache headers for the HTTP Response
 *
 * @param response/*from   w w  w .ja v a  2 s . c  om*/
 *            HTTP response
 * @param fileToCache
 *            file to extract content type
 */
private static void setDateAndCacheHeaders(HttpResponse response, long lastModified) {
    SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
    dateFormatter.setTimeZone(TimeZone.getTimeZone(HTTP_DATE_GMT_TIMEZONE));

    // Date header
    Calendar time = new GregorianCalendar();
    response.headers().set(HttpHeaderNames.DATE, dateFormatter.format(time.getTime()));

    // Add cache headers
    time.add(Calendar.SECOND, HTTP_CACHE_SECONDS);
    response.headers().set(HttpHeaderNames.EXPIRES, dateFormatter.format(time.getTime()));
    response.headers().set(HttpHeaderNames.CACHE_CONTROL, "private, max-age=" + HTTP_CACHE_SECONDS);
    response.headers().set(HttpHeaderNames.LAST_MODIFIED, dateFormatter.format(new Date(lastModified)));
}

From source file:dpfmanager.shell.modules.server.get.HttpGetHandler.java

License:Open Source License

private void setDateAndCacheHeaders(HttpResponse response, File fileToCache) {
    SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
    dateFormatter.setTimeZone(TimeZone.getTimeZone(HTTP_DATE_GMT_TIMEZONE));

    // Date header
    Calendar time = new GregorianCalendar();
    response.headers().set(HttpHeaderNames.DATE, dateFormatter.format(time.getTime()));

    // Add cache headers
    time.add(Calendar.SECOND, HTTP_CACHE_SECONDS);
    response.headers().set(HttpHeaderNames.EXPIRES, dateFormatter.format(time.getTime()));
    response.headers().set(HttpHeaderNames.CACHE_CONTROL, "private, max-age=" + HTTP_CACHE_SECONDS);
    response.headers().set(HttpHeaderNames.LAST_MODIFIED,
            dateFormatter.format(new Date(fileToCache.lastModified())));
}

From source file:eu.operando.operandoapp.service.ProxyService.java

License:Open Source License

private HttpFiltersSource getFiltersSource() {
    return new HttpFiltersSourceAdapter() {
        @Override//from  ww w.  ja v a  2 s  . c  o m
        public HttpFilters filterRequest(HttpRequest originalRequest) {
            return new HttpFiltersAdapter(originalRequest) {
                @Override
                public HttpObject serverToProxyResponse(HttpObject httpObject) {
                    //check for proxy running
                    if (MainUtil.isProxyPaused(mainContext))
                        return httpObject;

                    if (httpObject instanceof HttpMessage) {
                        HttpMessage response = (HttpMessage) httpObject;
                        response.headers().set(HttpHeaderNames.CACHE_CONTROL,
                                "no-cache, no-store, must-revalidate");
                        response.headers().set(HttpHeaderNames.PRAGMA, "no-cache");
                        response.headers().set(HttpHeaderNames.EXPIRES, "0");
                    }
                    try {
                        Method content = httpObject.getClass().getMethod("content");
                        if (content != null) {
                            ByteBuf buf = (ByteBuf) content.invoke(httpObject);
                            boolean flag = false;
                            List<ResponseFilter> responseFilters = db.getAllResponseFilters();
                            if (responseFilters.size() > 0) {
                                String contentStr = buf.toString(Charset.forName("UTF-8")); //Charset.forName(Charset.forName("UTF-8")
                                for (ResponseFilter responseFilter : responseFilters) {
                                    String toReplace = responseFilter.getContent();
                                    if (StringUtils.containsIgnoreCase(contentStr, toReplace)) {
                                        contentStr = contentStr.replaceAll("(?i)" + toReplace,
                                                StringUtils.leftPad("", toReplace.length(), '#'));
                                        flag = true;
                                    }
                                }
                                if (flag) {
                                    buf.clear().writeBytes(contentStr.getBytes(Charset.forName("UTF-8")));
                                }
                            }
                        }
                    } catch (IndexOutOfBoundsException ex) {
                        ex.printStackTrace();
                        Log.e("Exception", ex.getMessage());
                    } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) {
                        //ignore
                    }
                    return httpObject;
                }

                @Override
                public HttpResponse clientToProxyRequest(HttpObject httpObject) {
                    //check for proxy running
                    if (MainUtil.isProxyPaused(mainContext)) {
                        return null;
                    }

                    //check for trusted access point
                    String ssid = ((WifiManager) getSystemService(Context.WIFI_SERVICE)).getConnectionInfo()
                            .getSSID();
                    String bssid = ((WifiManager) getSystemService(Context.WIFI_SERVICE)).getConnectionInfo()
                            .getBSSID();
                    boolean trusted = false;
                    TrustedAccessPoint curr_tap = new TrustedAccessPoint(ssid, bssid);
                    for (TrustedAccessPoint tap : db.getAllTrustedAccessPoints()) {
                        if (curr_tap.isEqual(tap)) {
                            trusted = true;
                        }
                    }
                    if (!trusted) {
                        return getUntrustedGatewayResponse();
                    }

                    //check for blocked url

                    //check for exfiltration
                    requestFilterUtil = new RequestFilterUtil(getApplicationContext());
                    locationInfo = requestFilterUtil.getLocationInfo();
                    contactsInfo = requestFilterUtil.getContactsInfo();
                    IMEI = requestFilterUtil.getIMEI();
                    phoneNumber = requestFilterUtil.getPhoneNumber();
                    subscriberID = requestFilterUtil.getSubscriberID();
                    carrierName = requestFilterUtil.getCarrierName();
                    androidID = requestFilterUtil.getAndroidID();
                    macAdresses = requestFilterUtil.getMacAddresses();

                    if (httpObject instanceof HttpMessage) {
                        HttpMessage request = (HttpMessage) httpObject;
                        if (request.headers().contains(CustomHeaderField)) {
                            applicationInfo = request.headers().get(CustomHeaderField);
                            request.headers().remove(CustomHeaderField);
                        }
                        if (request.headers().contains(HttpHeaderNames.ACCEPT_ENCODING)) {
                            request.headers().remove(HttpHeaderNames.ACCEPT_ENCODING);
                        }
                        if (!ProxyUtils.isCONNECT(request)
                                && request.headers().contains(HttpHeaderNames.HOST)) {
                            String hostName = ((HttpRequest) request).uri(); //request.headers().get(HttpHeaderNames.HOST).toLowerCase();
                            if (db.isDomainBlocked(hostName))
                                return getBlockedHostResponse(hostName);
                        }
                    }

                    String requestURI;
                    Set<RequestFilterUtil.FilterType> exfiltrated = new HashSet<>();

                    if (httpObject instanceof HttpRequest) {
                        HttpRequest request = (HttpRequest) httpObject;
                        requestURI = request.uri();
                        try {
                            requestURI = URLDecoder.decode(requestURI, "UTF-8");
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                        if (locationInfo.length > 0) {
                            //tolerate location miscalculation
                            float latitude = Float.parseFloat(locationInfo[0]);
                            float longitude = Float.parseFloat(locationInfo[1]);
                            Matcher m = Pattern.compile("\\d+\\.\\d+").matcher(requestURI);
                            List<String> floats_in_uri = new ArrayList();
                            while (m.find()) {
                                floats_in_uri.add(m.group());
                            }
                            for (String s : floats_in_uri) {
                                if (Math.abs(Float.parseFloat(s) - latitude) < 0.5
                                        || Math.abs(Float.parseFloat(s) - longitude) < 0.1) {
                                    exfiltrated.add(RequestFilterUtil.FilterType.LOCATION);
                                }
                            }
                        }
                        if (StringUtils.containsAny(requestURI, contactsInfo)) {
                            exfiltrated.add(RequestFilterUtil.FilterType.CONTACTS);
                        }
                        if (StringUtils.containsAny(requestURI, macAdresses)) {
                            exfiltrated.add(RequestFilterUtil.FilterType.MACADRESSES);
                        }
                        if (requestURI.contains(IMEI) && !IMEI.equals("")) {
                            exfiltrated.add(RequestFilterUtil.FilterType.IMEI);
                        }
                        if (requestURI.contains(phoneNumber) && !phoneNumber.equals("")) {
                            exfiltrated.add(RequestFilterUtil.FilterType.PHONENUMBER);
                        }
                        if (requestURI.contains(subscriberID) && !subscriberID.equals("")) {
                            exfiltrated.add(RequestFilterUtil.FilterType.IMSI);
                        }
                        if (requestURI.contains(carrierName) && !carrierName.equals("")) {
                            exfiltrated.add(RequestFilterUtil.FilterType.CARRIERNAME);
                        }
                        if (requestURI.contains(androidID) && !androidID.equals("")) {
                            exfiltrated.add(RequestFilterUtil.FilterType.ANDROIDID);
                        }
                    }
                    try {
                        Method content = httpObject.getClass().getMethod("content");
                        if (content != null) {
                            ByteBuf buf = (ByteBuf) content.invoke(httpObject);
                            String contentStr = buf.toString(Charset.forName("UTF-8"));
                            if (locationInfo.length > 0) {
                                //tolerate location miscalculation
                                float latitude = Float.parseFloat(locationInfo[0]);
                                float longitude = Float.parseFloat(locationInfo[1]);
                                Matcher m = Pattern.compile("\\d+\\.\\d+").matcher(contentStr);
                                List<String> floats_in_uri = new ArrayList();
                                while (m.find()) {
                                    floats_in_uri.add(m.group());
                                }
                                for (String s : floats_in_uri) {
                                    if (Math.abs(Float.parseFloat(s) - latitude) < 0.5
                                            || Math.abs(Float.parseFloat(s) - longitude) < 0.1) {
                                        exfiltrated.add(RequestFilterUtil.FilterType.LOCATION);
                                    }
                                }
                            }
                            if (StringUtils.containsAny(contentStr, contactsInfo)) {
                                exfiltrated.add(RequestFilterUtil.FilterType.CONTACTS);
                            }
                            if (StringUtils.containsAny(contentStr, macAdresses)) {
                                exfiltrated.add(RequestFilterUtil.FilterType.MACADRESSES);
                            }
                            if (contentStr.contains(IMEI) && !IMEI.equals("")) {
                                exfiltrated.add(RequestFilterUtil.FilterType.IMEI);
                            }
                            if (contentStr.contains(phoneNumber) && !phoneNumber.equals("")) {
                                exfiltrated.add(RequestFilterUtil.FilterType.PHONENUMBER);
                            }
                            if (contentStr.contains(subscriberID) && !subscriberID.equals("")) {
                                exfiltrated.add(RequestFilterUtil.FilterType.IMSI);
                            }
                            if (contentStr.contains(carrierName) && !carrierName.equals("")) {
                                exfiltrated.add(RequestFilterUtil.FilterType.CARRIERNAME);
                            }
                            if (contentStr.contains(androidID) && !androidID.equals("")) {
                                exfiltrated.add(RequestFilterUtil.FilterType.ANDROIDID);
                            }
                        }
                    } catch (IndexOutOfBoundsException ex) {
                        ex.printStackTrace();
                        Log.e("Exception", ex.getMessage());
                    } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) {
                        //ignore
                    }

                    //check exfiltrated list
                    if (!exfiltrated.isEmpty()) {
                        //retrieve all blocked and allowed domains
                        List<BlockedDomain> blocked = db.getAllBlockedDomains();
                        List<AllowedDomain> allowed = db.getAllAllowedDomains();
                        //get application name from app info
                        String appName = applicationInfo.replaceAll("\\(.+?\\)", "");
                        //check blocked domains
                        //if domain is stored as blocked, return a forbidden response
                        for (BlockedDomain b_dmn : blocked) {
                            if (b_dmn.info.equals(appName)) {
                                return getForbiddenRequestResponse(applicationInfo, exfiltrated);
                            }
                        }
                        //if domain is stored as allowed, return null for actual response
                        for (AllowedDomain a_dmn : allowed) {
                            if (a_dmn.info.equals(appName)) {
                                return null;
                            }
                        }
                        //get exfiltrated info to string array
                        String[] exfiltrated_array = new String[exfiltrated.size()];
                        int i = 0;
                        for (RequestFilterUtil.FilterType filter_type : exfiltrated) {
                            exfiltrated_array[i] = filter_type.name();
                            i++;
                        }
                        //retrieve all pending notifications
                        List<PendingNotification> pending = db.getAllPendingNotifications();
                        for (PendingNotification pending_notification : pending) {
                            //if pending notification includes specific app name and app permissions return response that a pending notification exists
                            if (pending_notification.app_info.equals(applicationInfo)) {
                                return getPendingResponse();
                            }
                        }
                        //if none pending notification exists, display a new notification
                        int notificationId = mainContext.getNotificationId();
                        mainContext.getNotificationUtil().displayExfiltratedNotification(getBaseContext(),
                                applicationInfo, exfiltrated, notificationId);
                        mainContext.setNotificationId(notificationId + 3);
                        //and update statistics
                        db.updateStatistics(exfiltrated);
                        return getAwaitingResponse();
                    }
                    return null;
                }
            };
        }
    };
}

From source file:eu.operando.proxy.service.ProxyService.java

License:Open Source License

private HttpFiltersSource getFiltersSource() {

    return new HttpFiltersSourceAdapter() {

        //                @Override
        //                public int getMaximumRequestBufferSizeInBytes() {
        //                    // TODO Auto-generated method stub
        //                    return 10 * 1024 * 1024;
        ////from  ww w.  java 2s .c  o m
        //                }
        //
        //                @Override
        //                public int getMaximumResponseBufferSizeInBytes() {
        //                    // TODO Auto-generated method stub
        //                    return 10 * 1024 * 1024;
        //                }

        @Override
        public HttpFilters filterRequest(HttpRequest originalRequest) {

            return new HttpFiltersAdapter(originalRequest) {

                @Override
                public HttpObject serverToProxyResponse(HttpObject httpObject) {

                    if (MainUtil.isProxyPaused(mainContext))
                        return httpObject;

                    if (httpObject instanceof HttpMessage) {
                        HttpMessage response = (HttpMessage) httpObject;
                        response.headers().set(HttpHeaderNames.CACHE_CONTROL,
                                "no-cache, no-store, must-revalidate");
                        response.headers().set(HttpHeaderNames.PRAGMA, "no-cache");
                        response.headers().set(HttpHeaderNames.EXPIRES, "0");
                    }
                    try {
                        Method content = httpObject.getClass().getMethod("content");
                        if (content != null) {
                            ByteBuf buf = (ByteBuf) content.invoke(httpObject);
                            boolean flag = false;
                            List<ResponseFilter> responseFilters = db.getAllResponseFilters();
                            if (responseFilters.size() > 0) {

                                String contentStr = buf.toString(Charset.forName("UTF-8")); //Charset.forName(Charset.forName("UTF-8")
                                for (ResponseFilter responseFilter : responseFilters) {

                                    String toReplace = responseFilter.getContent();

                                    if (StringUtils.containsIgnoreCase(contentStr, toReplace)) {
                                        contentStr = contentStr.replaceAll("(?i)" + toReplace,
                                                StringUtils.leftPad("", toReplace.length(), '#'));
                                        flag = true;
                                    }

                                }
                                if (flag) {
                                    buf.clear().writeBytes(contentStr.getBytes(Charset.forName("UTF-8")));
                                }
                            }

                        }
                    } catch (IndexOutOfBoundsException ex) {
                        ex.printStackTrace();
                        Log.e("Exception", ex.getMessage());
                    } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) {
                        //ignore
                    }
                    return httpObject;
                }

                @Override
                public HttpResponse clientToProxyRequest(HttpObject httpObject) {

                    if (MainUtil.isProxyPaused(mainContext))
                        return null;

                    String requestURI;
                    Set<RequestFilterUtil.FilterType> exfiltrated = new HashSet<>();
                    String[] locationInfo = requestFilterUtil.getLocationInfo();
                    String[] contactsInfo = requestFilterUtil.getContactsInfo();
                    String[] phoneInfo = requestFilterUtil.getPhoneInfo();

                    if (httpObject instanceof HttpMessage) {
                        HttpMessage request = (HttpMessage) httpObject;
                        if (request.headers().contains(CustomHeaderField)) {
                            applicationInfoStr = request.headers().get(CustomHeaderField);
                            request.headers().remove(CustomHeaderField);
                        }

                        if (request.headers().contains(HttpHeaderNames.ACCEPT_ENCODING)) {
                            request.headers().remove(HttpHeaderNames.ACCEPT_ENCODING);
                        }

                        /*
                        Sanitize Hosts
                        */
                        if (!ProxyUtils.isCONNECT(request)
                                && request.headers().contains(HttpHeaderNames.HOST)) {
                            String hostName = request.headers().get(HttpHeaderNames.HOST).toLowerCase();
                            if (db.isDomainBlocked(hostName))
                                return getBlockedHostResponse(hostName);
                        }

                    }

                    if (httpObject instanceof HttpRequest) {

                        HttpRequest request = (HttpRequest) httpObject;
                        requestURI = request.uri();

                        try {
                            requestURI = URLDecoder.decode(requestURI, "UTF-8");
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }

                        /*
                        Request URI checks
                         */
                        if (StringUtils.containsAny(requestURI, locationInfo)) {
                            exfiltrated.add(RequestFilterUtil.FilterType.LOCATION);
                        }

                        if (StringUtils.containsAny(requestURI, contactsInfo)) {
                            exfiltrated.add(RequestFilterUtil.FilterType.CONTACTS);
                        }

                        if (StringUtils.containsAny(requestURI, phoneInfo)) {
                            exfiltrated.add(RequestFilterUtil.FilterType.PHONEINFO);
                        }

                        if (!exfiltrated.isEmpty()) {
                            mainContext.getNotificationUtil().displayExfiltratedNotification(applicationInfoStr,
                                    exfiltrated);
                            return getForbiddenRequestResponse(applicationInfoStr, exfiltrated);
                        }

                    }

                    try {
                        Method content = httpObject.getClass().getMethod("content");
                        if (content != null) {
                            ByteBuf buf = (ByteBuf) content.invoke(httpObject);

                            String contentStr = buf.toString(Charset.forName("UTF-8"));

                            if (StringUtils.containsAny(contentStr, locationInfo)) {
                                exfiltrated.add(RequestFilterUtil.FilterType.LOCATION);
                            }

                            if (StringUtils.containsAny(contentStr, contactsInfo)) {
                                exfiltrated.add(RequestFilterUtil.FilterType.CONTACTS);
                            }

                            if (StringUtils.containsAny(contentStr, phoneInfo)) {
                                exfiltrated.add(RequestFilterUtil.FilterType.PHONEINFO);
                            }

                            if (!exfiltrated.isEmpty()) {
                                mainContext.getNotificationUtil()
                                        .displayExfiltratedNotification(applicationInfoStr, exfiltrated);
                                return getForbiddenRequestResponse(applicationInfoStr, exfiltrated);
                            }

                        }
                    } catch (IndexOutOfBoundsException ex) {
                        ex.printStackTrace();
                        Log.e("Exception", ex.getMessage());
                    } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) {
                        //ignore
                    }

                    return null;
                }

            };
        }
    };
}

From source file:fr.kissy.zergling_push.infrastructure.HttpStaticFileServerHandler.java

License:Apache License

/**
* Sets the Date and Cache headers for the HTTP Response
*
* @param response//from   www  .j  a  v  a2  s . c om
*            HTTP response
* @param fileToCache
*            file to extract content type
*/
private static void setDateAndCacheHeaders(HttpResponse response, File fileToCache) {
    SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
    dateFormatter.setTimeZone(TimeZone.getTimeZone(HTTP_DATE_GMT_TIMEZONE));

    // Date header
    Calendar time = new GregorianCalendar();
    response.headers().set(HttpHeaderNames.DATE, dateFormatter.format(time.getTime()));

    // Add cache headers
    response.headers().set(HttpHeaderNames.EXPIRES, dateFormatter.format(time.getTime()));
    response.headers().set(HttpHeaderNames.CACHE_CONTROL, "no-store");
    response.headers().set(HttpHeaderNames.LAST_MODIFIED,
            dateFormatter.format(new Date(fileToCache.lastModified())));
}

From source file:io.crate.protocols.http.HttpBlobHandler.java

License:Apache License

private void setDefaultGetHeaders(HttpResponse response) {
    response.headers().set(HttpHeaderNames.ACCEPT_RANGES, "bytes");
    response.headers().set(HttpHeaderNames.EXPIRES, EXPIRES_VALUE);
    response.headers().set(HttpHeaderNames.CACHE_CONTROL, CACHE_CONTROL_VALUE);
}

From source file:org.glowroot.ui.CommonHandler.java

License:Apache License

private CommonResponse handleStaticResource(String path, CommonRequest request) throws IOException {
    URL url = getSecureUrlForPath(RESOURCE_BASE + path);
    if (url == null) {
        // log at debug only since this is typically just exploit bot spam
        logger.debug("unexpected path: {}", path);
        return new CommonResponse(NOT_FOUND);
    }/*from   ww w  .  java 2s . c o  m*/
    Date expires = getExpiresForPath(path);
    if (request.getHeader(HttpHeaderNames.IF_MODIFIED_SINCE) != null && expires == null) {
        // all static resources without explicit expires are versioned and can be safely
        // cached forever
        return new CommonResponse(NOT_MODIFIED);
    }
    int extensionStartIndex = path.lastIndexOf('.');
    checkState(extensionStartIndex != -1, "found path under %s with no extension: %s", RESOURCE_BASE, path);
    String extension = path.substring(extensionStartIndex + 1);
    MediaType mediaType = mediaTypes.get(extension);
    checkNotNull(mediaType, "found extension under %s with no media type: %s", RESOURCE_BASE, extension);
    CommonResponse response = new CommonResponse(OK, mediaType, url);
    if (expires != null) {
        response.setHeader(HttpHeaderNames.EXPIRES, expires);
    } else {
        response.setHeader(HttpHeaderNames.LAST_MODIFIED, new Date(0));
        response.setHeader(HttpHeaderNames.EXPIRES, new Date(clock.currentTimeMillis() + TEN_YEARS));
    }
    return response;
}

From source file:org.pidome.server.system.network.http.Http2ClientHandler.java

@Override
public void writeResponse(ChannelHandlerContext ctx, HttpResponseStatus status, byte[] buf, String fileType,
        String streamId, boolean cache) {

    String plainIp = HttpRequestHandler.getPlainIp(ctx.channel().localAddress());

    ByteBuf content = ctx.alloc().buffer(buf.length);
    content.writeBytes(buf);/*from   ww  w.ja  v a  2 s.  c  o m*/
    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, content);
    HttpUtil.setContentLength(response, response.content().readableBytes());
    streamId(response, streamId);

    response.headers().set(HttpHeaderNames.CONTENT_TYPE, fileType);

    response.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpRequestHandler.getContentTypeHeader(fileType));
    response.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN,
            "https://" + plainIp + ((port != 80) ? ":" + port : ""));
    response.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
    response.headers().set(HttpHeaderNames.SERVER, "PiDome integrated 0.2 HTTP2");

    if (cache == true) {
        DateTime dt = new DateTime();
        HttpHeaderDateFormat dateFormat = HttpHeaderDateFormat.get();
        response.headers().set(HttpHeaderNames.CACHE_CONTROL, "public, max-age=3153600");
        response.headers().set(HttpHeaderNames.EXPIRES, dateFormat.format(dt.plusMonths(12).toDate()));
    } else {
        response.headers().set(HttpHeaderNames.CACHE_CONTROL, "no-cache, must-revalidate");
        response.headers().set(HttpHeaderNames.EXPIRES, "Sat, 26 Jul 1997 05:00:00 GMT");
    }

    ctx.writeAndFlush(response);
}