rsanchez
2014-09-29 4be65eae04c0ed497bf404d43f9a11a4993a239d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
package net.curisit.securis;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import net.curisit.securis.beans.RequestBean;
import net.curisit.securis.utils.JsonUtils;
import net.curisit.securis.utils.Params;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
 * Manage all server connections
 * 
 * @author roberto <roberto.sanchez@curisit.net>
 */
public class ConnectionManager {
   private static final Logger LOG = LogManager.getLogger(ConnectionManager.class);
   private static ConnectionManager singleton;
   private final String serverUrl;
   private final CloseableHttpClient httpClient;
   
   private ConnectionManager() throws SeCurisException {
       String aux = Params.get(Params.KEYS.LICENSE_SERVER_URL, "https://securis.curistec.com/api");
       if (aux.endsWith("/")) {
           serverUrl = aux.substring(0, aux.length()-2);
       } else {
           serverUrl = aux;
       }
       httpClient = createHttpClient();
   }
   
   private CloseableHttpClient createHttpClient() throws SeCurisException {
          SSLContextBuilder builder = new SSLContextBuilder();
           SSLConnectionSocketFactory sslsf = null; 
           try {
               builder.loadTrustMaterial((KeyStore)null, new TrustStrategy() {
                   @Override
                   public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                       return true;
                   }
               });
               sslsf = new SSLConnectionSocketFactory(builder.build());
           } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e1) {
               LOG.error(e1);
               throw new SeCurisException("Error creating SSL socket factory");
           }
           return HttpClientBuilder.create().setSSLSocketFactory(sslsf).build();
   }
   public synchronized static ConnectionManager getInstance() throws SeCurisException {
       if (singleton == null) {
           singleton = new ConnectionManager();
       }
       return singleton;
   }
   public <T> T executePost(String command, Class<T> returnType, RequestBean req) throws SeCurisException {
        HttpPost postRequest = new HttpPost(String.format("%s/%s", serverUrl, command));
        postRequest.addHeader("accept", "application/json");
        postRequest.addHeader("content-type", "application/json");
        try {
            postRequest.setEntity(new StringEntity(JsonUtils.toJSON(req)));
        } catch (UnsupportedEncodingException | SeCurisException e1) {
            throw new SeCurisException("Error preparing POST command", e1);
        }
        HttpResponse response;
        try {
            response = httpClient.execute(postRequest);
            if (response.getStatusLine().getStatusCode() != 200) {
                throw new SeCurisException("Error executing command " + command + ", status: " + response.getStatusLine().getStatusCode());
            }
            String jsonLic = IOUtils.toString(response.getEntity().getContent());
            LOG.info("License read OK: {}", jsonLic);
            T responseBean = JsonUtils.json2object(jsonLic, returnType);
            LOG.info("Response bean read OK: {}", responseBean);
            LOG.info("JSON to write in file: {}", JsonUtils.toJSON(responseBean));
            
            return responseBean;
        } catch (IOException e) {
            LOG.error("Error acessing SeCuris server", e);
            throw new SeCurisException("Error accessing SeCuris server");
        }
     }
    public <T> T executeGet(String command, Class<T> returnType) throws SeCurisException {
        HttpGet getRequest = new HttpGet(String.format("%s/%s", serverUrl, command));
        getRequest.addHeader("accept", "application/json");
        HttpResponse response;
        try {
            response = httpClient.execute(getRequest);
            if (response.getStatusLine().getStatusCode() != 200) {
                throw new SeCurisException("Error executing command " + command + ", status: " + response.getStatusLine().getStatusCode());
            }
            String jsonLic = IOUtils.toString(response.getEntity().getContent());
            LOG.info("License read OK: {}", jsonLic);
            T responseBean = JsonUtils.json2object(jsonLic, returnType);
            LOG.info("Response bean read OK: {}", responseBean);
            LOG.info("JSON to write in file: {}", JsonUtils.toJSON(responseBean));
            
            return responseBean;
        } catch (IOException e) {
            LOG.error("Error acessing SeCuris server", e);
            throw new SeCurisException("Error accessing SeCuris server");
        }
    }
     
   public static class Command {
        public static final String TEST = "ping";
        public static final String CREATE_LIC = "request";
        public static final String RENEW_LIC = "renew";
   }
}