org.frontcache.agent.FrontCacheAgent.java Source code

Java tutorial

Introduction

Here is the source code for org.frontcache.agent.FrontCacheAgent.java

Source

/**
 *        Copyright 2017 Eternita LLC
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
package org.frontcache.agent;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HeaderElement;
import org.apache.http.HeaderElementIterator;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.RedirectStrategy;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeaderElementIterator;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;

public class FrontCacheAgent {

    private String frontCacheURL;

    private String frontCacheURI;

    private String siteKey = "";

    private final static String IO_URI = "frontcache-io";
    private final static String INVALIDATE = "invalidate";

    private HttpClient client;

    public FrontCacheAgent(String frontcacheURL) {
        final RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(3000)
                .setCookieSpec(CookieSpecs.IGNORE_COOKIES).build();

        ConnectionKeepAliveStrategy keepAliveStrategy = new ConnectionKeepAliveStrategy() {
            @Override
            public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
                HeaderElementIterator it = new BasicHeaderElementIterator(
                        response.headerIterator(HTTP.CONN_KEEP_ALIVE));
                while (it.hasNext()) {
                    HeaderElement he = it.nextElement();
                    String param = he.getName();
                    String value = he.getValue();
                    if (value != null && param.equalsIgnoreCase("timeout")) {
                        return Long.parseLong(value) * 1000;
                    }
                }
                return 10 * 1000;
            }
        };

        client = HttpClients.custom().setDefaultRequestConfig(requestConfig)
                .setRetryHandler(new DefaultHttpRequestRetryHandler(0, false))
                .setKeepAliveStrategy(keepAliveStrategy).setRedirectStrategy(new RedirectStrategy() {
                    @Override
                    public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context)
                            throws ProtocolException {
                        return false;
                    }

                    @Override
                    public HttpUriRequest getRedirect(HttpRequest request, HttpResponse response,
                            HttpContext context) throws ProtocolException {
                        return null;
                    }
                }).build();

        this.frontCacheURL = frontcacheURL;

        if (frontcacheURL.endsWith("/"))
            this.frontCacheURI = frontcacheURL + IO_URI;
        else
            this.frontCacheURI = frontcacheURL + "/" + IO_URI;
    }

    public FrontCacheAgent(String frontcacheURL, String siteKey) {
        this(frontcacheURL);
        this.siteKey = siteKey;
    }

    /**
     * 
     * @param filter
     * @return
     */
    public String removeFromCache(String filter) {
        List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
        urlParameters.add(new BasicNameValuePair("action", INVALIDATE));
        urlParameters.add(new BasicNameValuePair("filter", filter));

        try {
            return requestFrontCache(urlParameters);
        } catch (Exception e) {
            e.printStackTrace();
            return "ERROR " + e.getMessage();
        }
    }

    /**
     * 
     * @param urlParameters
     * @return
     * @throws IOException
     */
    protected String requestFrontCache(List<NameValuePair> urlParameters) throws IOException {
        HttpPost post = new HttpPost(frontCacheURI);

        //       post.addHeader("Accept-Encoding", "gzip");

        if (null != siteKey)
            post.addHeader("X-frontcache.site-key", siteKey);

        post.setEntity(new UrlEncodedFormEntity(urlParameters));

        StringBuffer result = new StringBuffer();
        HttpResponse response = client.execute(post);
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }

        return result.toString();
    }

    public String getFrontCacheURL() {
        return frontCacheURL;
    }

    @Override
    public String toString() {
        return "FrontCacheAgent [" + frontCacheURL + "]";
    }

}