Skip to content

Instantly share code, notes, and snippets.

@ajnfde
Created April 27, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ajnfde/dca5b39e7e5286df3aef to your computer and use it in GitHub Desktop.
Save ajnfde/dca5b39e7e5286df3aef to your computer and use it in GitHub Desktop.
package com.capgemini.adc.infra.remote.server;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.capgemini.adc.infra.exception.InfrastructureTechnicalException;
import com.capgemini.adc.infra.log.LogFactory;
/**ExternCallServlet 1.1
* Routage des appels FWK1 vers FWK3.
* Lors du premier appel du FWK 3 on ouvre une session (matérialisé par le FWK session cookie).
* Ce cookie est stocké en tant que attribut dans la session du FWK1 et réutilisé pour les appels suivants.
*
* @author Thomas Kasten
*/
@SuppressWarnings("serial")
public class ExternCallServlet extends HttpServlet {
// static file upload parameters
final static String crlf = "\r\n";
final static String twoHyphens = "--";
final static String boundary = "*****";
/* On vient d'une action FWK 1 (ajax) ou du <c:import/> de la page pontv2.jsp.
*
* parametres
* requestPath : l'url externe à appeler
* uploadFileName : nom d'un éventuel fichier à uploader
* paramètres métier divers
*/
@Override
public void service(HttpServletRequest req, HttpServletResponse res)
throws javax.servlet.ServletException {
URL url;
HttpURLConnection conn;
InputStream in;
OutputStream out;
byte[] chunk = new byte[2048];
String fw3sessionCookie; // cookie identifiant la session distante avec le FWK 3
String uploadFilePath = null;
int bytesRead;
int maxFollowRedirect = 3; // number of max. allowed 302 answers from server
int serverResponseCode = -1;
try {
String requestPath = req.getAttribute("requestPath") != null ? String.valueOf(req.getAttribute("requestPath")) : req.getParameter("requestPath");
url = new URL (buildUrlWithParameters(req, getInitParameter("externcall.url"), requestPath)); // ajout paramètres GET
LogFactory.logDebug("Extern call to " + url,"");
do { // retry if servers answers 302-redirected
LogFactory.logDebug("Calling : " + url.toString());
conn = (HttpURLConnection) url.openConnection();
HttpURLConnection.setFollowRedirects(false);
conn.setUseCaches(false);
// utilisation du cookie de session fw3 pour se raccrocher à une session existante
fw3sessionCookie = (String)req.getSession().getAttribute("FW3_session");
if (fw3sessionCookie != null) {
LogFactory.logDebug("Using knwon FW3 session cookie : " + fw3sessionCookie);
conn.setRequestProperty("Cookie", "JSESSIONID=" + fw3sessionCookie + ";");
}
else{
LogFactory.logDebug("NO FW3 session cookie available");
}
conn.setDoOutput(true);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Cache-Control", "no-cache");
if(serverResponseCode != HttpServletResponse.SC_FOUND && "POST".equals(req.getParameter("requestMethod"))){ // ajout paramètres POST
conn.setRequestMethod("POST");
prepareExternPost(req, conn);
uploadFilePath = req.getParameter("uploadFile");
// fileupload
if(uploadFilePath != null){
writeFileDataIntoRequest(req, conn, uploadFilePath);
}
}
else {
conn.setRequestMethod("GET");
}
serverResponseCode = conn.getResponseCode();
if (serverResponseCode == HttpServletResponse.SC_FOUND /* 302 */)
url = new URL(conn.getHeaderField("Location"));
LogFactory.logDebug("Fw3 response code: " + conn.getResponseCode());
// obtention et stockage d'un cookie de session fw3 pour réutilisation ultérieure
fw3sessionCookie = getServerCookie(conn, "JSESSIONID");
if(fw3sessionCookie != null){
req.getSession().setAttribute("FW3_session",fw3sessionCookie );
LogFactory.logDebug("Obtained new FW3 session cookie : " + fw3sessionCookie);
} else
LogFactory.logDebug("Fw3 response without session cookie");
} while(maxFollowRedirect-- > 0 && serverResponseCode == HttpServletResponse.SC_FOUND /* 302 */);
in = conn.getInputStream();
res.setContentType(conn.getContentType());
out = res.getOutputStream();
while( (bytesRead = in.read(chunk)) > 0 ){
out.write(chunk, 0, bytesRead);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
private void writeFileDataIntoRequest(HttpServletRequest req, HttpURLConnection conn,
String uploadFilePath) throws IOException, FileNotFoundException,
InfrastructureTechnicalException {
DataOutputStream uploadData;
InputStream inFile = new FileInputStream(uploadFilePath);
byte[] buf = new byte[2048];
int nbBytesRead;
String filename;
filename = req.getParameter("file");
conn.setDoInput(true);
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
uploadData = new DataOutputStream(conn.getOutputStream());
uploadData.writeBytes(twoHyphens + boundary + crlf);
uploadData.writeBytes("Content-Disposition: form-data; name=\"" + "file" + "\";filename=\"" + filename + "\"" + crlf);
uploadData.writeBytes(crlf);
while ((nbBytesRead = inFile.read(buf)) > -1) {
uploadData.write(buf, 0, nbBytesRead);
}
inFile.close();
uploadData.writeBytes(crlf);
uploadData.writeBytes(twoHyphens + boundary + twoHyphens + crlf);
LogFactory.logDebug("File uploaded: " + filename + ". (" +uploadFilePath+")");
}
protected String buildUrlWithParameters(HttpServletRequest req, String extAppUrl, String urlPath) throws Exception {
boolean isFirst = true;
StringBuffer buf = new StringBuffer();
buf.append(extAppUrl);
//Ajout du "/" si manquant.
if(!urlPath.startsWith("/")) {
buf.append("/");
}
buf.append(urlPath);
if(!"POST".equals(req.getParameter("requestMethod"))){ // ajout des paramètres GET
for(String key : req.getParameterMap().keySet()){
if("requestPath".equals(key) || "requestMethod".equals(key))
continue;
if(isFirst){
isFirst = false;
buf.append("?");
}
else
buf.append("&");
buf.append(key.toString());
buf.append("=");
buf.append(URLEncoder.encode(req.getParameter(key), "UTF-8"));
}
}
return buf.toString();
}
/**
* Ajout des paramètres au corps de la requête HTTP.
* @param req
* @param conn
* @throws IOException
*/
protected void prepareExternPost(HttpServletRequest req, HttpURLConnection conn)
throws IOException {
Map<String, String[]> parameterMap = req.getParameterMap();
if (!parameterMap.isEmpty()) {
StringBuilder paramsBuilder = new StringBuilder();
for(String key : req.getParameterMap().keySet()) {
paramsBuilder.append(key);
paramsBuilder.append("=");
paramsBuilder.append(req.getParameter(key));
paramsBuilder.append("&");
}
String urlParameters = paramsBuilder.toString();
if (urlParameters.endsWith("&")) {
urlParameters = urlParameters.substring(0,
urlParameters.length() - 1);
}
;
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
}
}
public String getServerCookie(HttpURLConnection conn, String cookieName)
throws InfrastructureTechnicalException {
String[] fields = null;
String[] cookie;
for (int i = 0;; i++) {
String headerName = conn.getHeaderFieldKey(i); // sends request
String headerValue = conn.getHeaderField(i);
// Launcher.println(headerName + ": " + headerValue);
if (headerName == null && headerValue == null) {
// No more headers
break;
}
if ("Set-Cookie".equalsIgnoreCase(headerName)) {
// Parse cookie
fields = headerValue.split(";\\s*");
cookie = fields[0].split("=");
try {
LogFactory.logDebug(cookie[0] + "=" + cookie[1]);
} catch (ArrayIndexOutOfBoundsException x) {
LogFactory.logDebug(cookie[0] + "=" + cookie[1]);
}
if(cookieName.equals(cookie[0]))
return cookie[1];
}
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment