package pt.estgp.estgweb.web;
import jomm.web.ftp.FileType;
import jomm.web.ftp.IFile;
import jomm.web.ftp.impl.FtpFile;
import org.apache.commons.httpclient.util.URIUtil;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import pt.estgp.estgweb.domain.UserSession;
import pt.estgp.estgweb.utils.ConfigProperties;
import pt.estgp.estgweb.utils.Dom4jUtil;
import pt.estgp.estgweb.web.exceptions.NotAuthorizedException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspWriter;
import java.io.*;
import java.net.*;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.GZIPInputStream;
import java.util.zip.InflaterInputStream;
import java.util.zip.ZipInputStream;
/**
* @author Jorge Machado
* @date 26/Fev/2008
* @time 12:46:16
* @see pt.estgp.estgweb.web
*/
public class DirWebProxy
extends HttpServlet
{
public static final 1.5.0/docs/api/java/lang/String.html">String FTP_ACTUAL_PATH_KEY =
"pt.estgp.estgweb.web.DirWebProxy.FTP_ACTUAL_PATH_KEY";
/**
* sss requests for both HTTP <code>GET</code> and <code>POST</code> methods.
*
* @param request servlet request
* @param response servlet response
*/
private static final 1.5.0/docs/api/java/util/logging/Logger.html">Logger logger =
1.5.0/docs/api/java/util/logging/Logger.html">Logger.
getLogger(DirWebProxy.
class);
protected static void processRequest
(HttpServletRequest request, HttpServletResponse response
)
throws ServletException,
1.5.0/docs/api/java/io/IOException.html">IOException
{
1.5.0/docs/api/java/lang/String.html">String element =
(1.5.0/docs/api/java/lang/String.html">String) request.
getAttribute("element");
if (element.
equals("node"))
{
processNode
(request, response
);
}
else
{
processLeaf
(request, response
);
}
}
/**
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
protected static void processNode
(HttpServletRequest request, HttpServletResponse response
)
throws ServletException,
1.5.0/docs/api/java/io/IOException.html">IOException
{
styleDirectory
(request, response
);
}
protected static void processLeaf
(HttpServletRequest request, HttpServletResponse response
)
throws ServletException,
1.5.0/docs/api/java/io/IOException.html">IOException
{
1.5.0/docs/api/java/lang/String.html">String path =
(1.5.0/docs/api/java/lang/String.html">String) request.
getAttribute("path");
1.5.0/docs/api/java/lang/String.html">String startPath =
(1.5.0/docs/api/java/lang/String.html">String) request.
getAttribute("startPath");
1.5.0/docs/api/java/lang/String.html">String leafUrl =
(1.5.0/docs/api/java/lang/String.html">String) request.
getAttribute("leaf.url");
1.5.0/docs/api/java/lang/String.html">String server =
(1.5.0/docs/api/java/lang/String.html">String) request.
getAttribute("server");
1.5.0/docs/api/java/lang/String.html">String useOutputStream =
(1.5.0/docs/api/java/lang/String.html">String) request.
getAttribute("useOutputStream");
1.5.0/docs/api/java/lang/String.html">String encoding =
(1.5.0/docs/api/java/lang/String.html">String) request.
getAttribute("encoding");
1.5.0/docs/api/java/lang/String.html">String proxyKey =
(1.5.0/docs/api/java/lang/String.html">String) request.
getAttribute("proxyKey");
1.5.0/docs/api/java/lang/String.html">String proxyHost =
(1.5.0/docs/api/java/lang/String.html">String) request.
getAttribute("proxy.host");
1.5.0/docs/api/java/lang/String.html">String proxyPort =
(1.5.0/docs/api/java/lang/String.html">String) request.
getAttribute("proxy.port");
boolean style =
1.5.0/docs/api/java/lang/Boolean.html">Boolean.
parseBoolean((1.5.0/docs/api/java/lang/String.html">String) request.
getAttribute("style"));
1.5.0/docs/api/java/lang/String.html">String xml =
(1.5.0/docs/api/java/lang/String.html">String) request.
getAttribute("xml");
1.5.0/docs/api/java/lang/String.html">String label =
(1.5.0/docs/api/java/lang/String.html">String) request.
getAttribute("label");
logger.
info("server:" + server
);
logger.
info("path:" + path
);
logger.
info("startPath:" + startPath
);
logger.
info("proxyKey:" + proxyKey
);
logger.
info("proxyHost:" + proxyHost
);
logger.
info("proxyPort:" + proxyPort
);
logger.
info("xml:" + xml
);
logger.
info("style:" + style
);
logger.
info("label:" + label
);
logger.
info("useOutputStream:" + useOutputStream
);
if (path
!=
null)
{
try
{
5+0%2Fdocs%2Fapi+Proxy">Proxy proxy =
null;
if (proxyHost
!=
null && proxyHost.
length() > 0
)
{
proxy =
new 5+0%2Fdocs%2Fapi+Proxy">Proxy(5+0%2Fdocs%2Fapi+Proxy">Proxy.
1.5.0/docs/api/java/lang/reflect/Type.html">Type.
HTTP,
new 1.5.0/docs/api/java/net/InetSocketAddress.html">InetSocketAddress(proxyHost,
1.5.0/docs/api/java/lang/Integer.html">Integer.
parseInt(proxyPort
)));
}
if (!server.
startsWith("ftp://"))
{
if(path.
equals(startPath
) )
path += leafUrl
;
1.5.0/docs/api/java/lang/String.html">String finalURL
;
if(leafUrl.
indexOf("?")>0
)
finalURL = server + leafUrl
;
else
finalURL = server + URIUtil.
encodePath(path,
"ISO-8859-1");
1.5.0/docs/api/java/net/URL.html">URL url =
new 1.5.0/docs/api/java/net/URL.html">URL(finalURL
);
if (useOutputStream
!=
null && useOutputStream.
equals("true"))
{
5+0%2Fdocs%2Fapi+InputStream">InputStream stream = openStream
(finalURL, proxy
);
1.5.0/docs/api/java/net/URLConnection.html">URLConnection con = url.
openConnection();
response.
setContentType(con.
getContentType());
if (xml ==
null || xml.
equals("false"))
response.
setCharacterEncoding(encoding
);
response.
setContentLength(con.
getContentLength());
writeDirectStream
(response, stream
);
}
else if(server.
equals("WebPages"))
{
//Internal WebPages Module
//todo load page based on language and based on path ID
//O StartPath é sempre vazio no caso dos WebPages
//portanto o Path tem o caminho completo para a pagina
//que na prática é o seu identificador
//todo usar o HTML provenietne como content
1.5.0/docs/api/java/lang/String.html">String html =
"Em construcao";
generateOutputLeaf
(response, request, html, style
);
}
else if (xml ==
null || xml.
equals("false"))
{
5+0%2Fdocs%2Fapi+InputStream">InputStream stream = openStream
(finalURL, proxy
);
1.5.0/docs/api/java/lang/String.html">String content = readContent2String
(stream, encoding
);
generateOutputLeaf
(response, request, content, style
);
}
else
{
1.5.0/docs/api/java/net/URLConnection.html">URLConnection con =
new 1.5.0/docs/api/java/net/URL.html">URL(finalURL
).
openConnection();
con.
connect();
if (con.
getContentLength() > 0)
{
// Document dom = Dom4jUtil.parse(stream);
generateOutputLeafXml
(response, request, finalURL, proxy, style
);
}
}
}
else
{
5+0%2Fdocs%2Fapi+Document">Document directoryDocument =
(5+0%2Fdocs%2Fapi+Document">Document) request.
getAttribute("directoryDocument");
if(leafUrl
!=
null && leafUrl.
length() > 0
)
{
1.5.0/docs/api/java/lang/String.html">String endPath =
"";
if(startPath
!=
null)
{
endPath = path.
substring(startPath.
length());
}
if(leafUrl.
endsWith("/") && endPath.
startsWith("/"))
{
path = startPath + leafUrl.
substring(0,leafUrl.
length()-1
) + endPath
;
}
else
path = startPath + leafUrl + endPath
;
}
if(!extendDiretoryDocument
(request, response, path, proxyKey, server, startPath + leafUrl, directoryDocument
))
return;
styleDirectory
(request, response
);
}
}
catch (NotAuthorizedException e
)
{
UserSession userSession = UserSessionProxy.
loadUserSessionFromRequest(request
);
1.5.0/docs/api/java/lang/String.html">String username = userSession
!=
null ? userSession.
getUsername() :
"UNKNOWN";
logger.
warn(username +
":" + request.
getRemoteAddr() +
" cant access this area server:" + server +
" and path:" + path +
" " + request.
getRemoteUser() +
" " + request.
getRequestURL() +
" spath " + request.
getServletPath() +
" queryString " + request.
getQueryString() ,e
);
response.
sendError(401
);
}
catch (1.5.0/docs/api/java/io/FileNotFoundException.html">FileNotFoundException e
)
{
logger.
warn("url not found for server:" + server +
" and path:" + path +
" " +
"REMOTE USER" + request.
getRemoteUser() +
" " + request.
getRequestURL());
response.
sendError(404
);
}
catch (1.5.0/docs/api/java/lang/Exception.html">Exception e
)
{
logger.
error(e, e
);
throw new 1.5.0/docs/api/java/io/IOException.html">IOException(e.
toString());
}
}
else
{
logger.
warn("url not found for server:" + server +
" and path:" + path
);
response.
sendError(404
);
}
}
public static 1.5.0/docs/api/java/lang/String.html">String FTP_FILE_PREFIX =
"FTP_";
public static void addAttribute
(5+0%2Fdocs%2Fapi+Element">Element element,
1.5.0/docs/api/java/lang/String.html">String name,
1.5.0/docs/api/java/lang/String.html">String value
)
{
element.
addAttribute(name, value
);
}
protected static boolean extendDiretoryDocument
(HttpServletRequest request,HttpServletResponse response,
1.5.0/docs/api/java/lang/String.html">String path,
1.5.0/docs/api/java/lang/String.html">String server,
1.5.0/docs/api/java/lang/String.html">String serverUrl,
1.5.0/docs/api/java/lang/String.html">String startPath,
5+0%2Fdocs%2Fapi+Document">Document directoryDocument
)
throws ServletException,
1.5.0/docs/api/java/io/IOException.html">IOException
{
try
{
UserSession userSession = UserSessionProxy.
loadUserSessionFromRequest(request
);
FTPFileProxy.
UserCredentialsForFtp u = FTPFileProxy.
getUserCredentialsForFtp(server, userSession
);
1.5.0/docs/api/java/lang/String.html">String username = u.
username;
1.5.0/docs/api/java/lang/String.html">String password = u.
password;
if(username ==
null || password ==
null) //NAO PODE LIGAR
{
response.
sendError(401
);
return false;
}
if (path
!=
null)
{
FtpServer ftpServer = FtpServer.
getServer(serverUrl, username, password
);
FTPClient client = FTPFileProxy.
getFtpClient(ftpServer, userSession, server, serverUrl
);
if(client ==
null)
{
return false;
}
5+0%2Fdocs%2Fapi+Element">Element actualNode =
(5+0%2Fdocs%2Fapi+Element">Element) request.
getAttribute("actualNode");
if(startPath.
equals("/"))
startPath =
"";
request.
setAttribute(FTP_ACTUAL_PATH_KEY,startPath
);
if (path.
equals(startPath
))
{
if(!client.
changeWorkingDirectory(path
))
{
throw new NotAuthorizedException
();
}
FTPFile
[] files = client.
listFiles();
List
<IFile
> iFiles = FtpFile.
init(files, serverUrl, path
);
//root
for (IFile iFile : iFiles
)
{
5+0%2Fdocs%2Fapi+Element">Element iFileElem = actualNode.
addElement("leaf");
addAttribute
(iFileElem,
"node",
"false");
addAttribute
(iFileElem,
"id", FTP_FILE_PREFIX +
"0_" + iFile.
getName());
addAttribute
(iFileElem,
"idPrefixSize",
"" +
(FTP_FILE_PREFIX +
"0_").
length());
addAttribute
(iFileElem,
"label", iFile.
getName());
addAttribute
(iFileElem,
"visualization",
"filesystem");
addAttribute
(iFileElem,
"size",
"" + iFile.
getSize());
addAttribute
(iFileElem,
"lastModification",
"" + iFile.
getLastUpdate().
toString());
if (iFile.
getType() == FileType.
DIRECTORY)
{
addAttribute
(iFileElem,
"ftpDirectory",
"true");
}
else
{
addAttribute
(iFileElem,
"extension", iFile.
getExtension());
addAttribute
(iFileElem,
"ftpDirectory",
"false");
addAttribute
(iFileElem,
"absolute",
"true");
addAttribute
(iFileElem,
"url", iFile.
getCompleteUrl());
}
}
}
else
{
1.5.0/docs/api/java/lang/String.html">String pathAux = path.
substring(startPath.
length());
1.5.0/docs/api/java/lang/String.html">String[] pathFragments
;
if(pathAux.
startsWith("/"))
pathFragments = pathAux.
substring(1).
split("/");
else
pathFragments = pathAux.
split("/");
if(!client.
changeWorkingDirectory(startPath
))
{
throw new NotAuthorizedException
();
}
FTPFile
[] files = client.
listFiles();
List
<IFile
> iFiles = FtpFile.
init(files, serverUrl, path
);
5+0%2Fdocs%2Fapi+Element">Element goDeepElement =
null;
1.5.0/docs/api/java/lang/String.html">String actualId =
null;
for (IFile iFile : iFiles
)
{
5+0%2Fdocs%2Fapi+Element">Element iFileElem = actualNode.
addElement("leaf");
addAttribute
(iFileElem,
"node",
"true");
addAttribute
(iFileElem,
"id", FTP_FILE_PREFIX +
"0_" + iFile.
getName());
addAttribute
(iFileElem,
"idPrefixSize",
"" +
(FTP_FILE_PREFIX +
"0_").
length());
addAttribute
(iFileElem,
"label", iFile.
getName());
addAttribute
(iFileElem,
"visualization",
"filesystem");
addAttribute
(iFileElem,
"size",
"" + iFile.
getSize());
addAttribute
(iFileElem,
"lastModification",
"" + iFile.
getLastUpdate().
toString());
if (iFile.
getType() == FileType.
DIRECTORY)
{
addAttribute
(iFileElem,
"ftpDirectory",
"true");
}
else
{
addAttribute
(iFileElem,
"extension", iFile.
getExtension());
addAttribute
(iFileElem,
"ftpDirectory",
"false");
addAttribute
(iFileElem,
"absolute",
"true");
addAttribute
(iFileElem,
"url", iFile.
getCompleteUrl());
}
if (iFile.
getName().
equals(pathFragments
[0]))
{
actualId = FTP_FILE_PREFIX +
"0_" + iFile.
getName();
goDeepElement = iFileElem
;
}
}
1.5.0/docs/api/java/lang/String.html">String startPathAux = startPath
;
for (int i =
0; i
< pathFragments.
length; i++
)
{
5+0%2Fdocs%2Fapi+Element">Element nextGoDeepElement =
null;
1.5.0/docs/api/java/lang/String.html">String d = pathFragments
[i
];
startPathAux = startPathAux +
"/" + d
;
if(!client.
changeWorkingDirectory(startPathAux
))
{
throw new NotAuthorizedException
();
}
files = client.
listFiles();
iFiles = FtpFile.
init(files, serverUrl, path
);
for (IFile iFile : iFiles
)
{
5+0%2Fdocs%2Fapi+Element">Element iFileElem
;
if(i == pathFragments.
length -
1)
{
iFileElem = goDeepElement.
addElement("leaf");
addAttribute
(iFileElem,
"node",
"false");
}
else
{
iFileElem = goDeepElement.
addElement("leaf");
addAttribute
(iFileElem,
"node",
"true");
}
addAttribute
(iFileElem,
"id", FTP_FILE_PREFIX +
(i+
1) +
"_" + iFile.
getName());
addAttribute
(iFileElem,
"idPrefixSize",
"" +
(FTP_FILE_PREFIX +
(i+
1) +
"_").
length());
addAttribute
(iFileElem,
"label", iFile.
getName());
addAttribute
(iFileElem,
"visualization",
"filesystem");
addAttribute
(iFileElem,
"size",
"" + iFile.
getSize());
addAttribute
(iFileElem,
"lastModification",
"" + iFile.
getLastUpdate().
toString());
if (iFile.
getType() == FileType.
DIRECTORY)
{
addAttribute
(iFileElem,
"ftpDirectory",
"true");
}
else
{
addAttribute
(iFileElem,
"extension", iFile.
getExtension());
addAttribute
(iFileElem,
"ftpDirectory",
"false");
addAttribute
(iFileElem,
"absolute",
"true");
addAttribute
(iFileElem,
"url", iFile.
getCompleteUrl());
}
if (i
< pathFragments.
length - 1
&& iFile.
getName().
equals(pathFragments
[i + 1
]))
{
nextGoDeepElement = iFileElem
;
actualId = FTP_FILE_PREFIX +
(i+
1) +
"_" + iFile.
getName();
}
}
goDeepElement = nextGoDeepElement
;
}
request.
setAttribute("ACTUAL_REMOTE_CHILD",actualId
);
}
client.
quit();
client.
disconnect();
}
else
{
throw new 1.5.0/docs/api/java/io/FileNotFoundException.html">FileNotFoundException("url not found for server:" + serverUrl +
" and path:" + path
);
}
}
catch (1.5.0/docs/api/java/lang/Throwable.html">Throwable e
)
{
if(e
instanceof NotAuthorizedException
)
throw (NotAuthorizedException
)e
;
logger.
error(e, e
);
}
return true;
}
private static void generateOutputLeafXml
(HttpServletResponse response, HttpServletRequest request,
1.5.0/docs/api/java/lang/String.html">String finalURL,
5+0%2Fdocs%2Fapi+Proxy">Proxy proxy,
boolean style
) throws 1.5.0/docs/api/java/io/IOException.html">IOException, DocumentException
{
if (style
)
{
Map
<String, Object
> parameters =
new HashMap
<String, Object
>();
// OutputFormat outputFormat = new OutputFormat();
// outputFormat.setSuppressDeclaration(true);
// outputFormat.setEncoding("UTF-8");
// StringWriter writer = new StringWriter();
// Dom4jUtil.write(dom,writer, outputFormat);
// org.w3c.dom.Document d = new org.dom4j.io.DOMWriter().write(dom);
// parameters.put("body",dom.selectSingleNode("/"));
parameters.
put("includeXML", finalURL
);
styleDirectory
(request, response, parameters,
null);
}
else
{
5+0%2Fdocs%2Fapi+InputStream">InputStream stream = openStream
(finalURL, proxy
);
5+0%2Fdocs%2Fapi+Document">Document dom = Dom4jUtil.
parse(stream
);
Dom4jUtil.
write(dom, response.
getWriter());
}
}
private static void generateOutputLeaf
(HttpServletResponse response, HttpServletRequest request,
1.5.0/docs/api/java/lang/String.html">String content,
boolean style
) throws 1.5.0/docs/api/java/io/IOException.html">IOException
{
if (style
)
{
// Map<String,Object> parameters = new HashMap<String,Object>();
// parameters.put("body",content);
styleDirectory
(request, response,
new HashMap
<String, Object
>(), content
);
}
else
{
response.
getWriter().
write(content
);
}
}
private static void styleDirectory
(HttpServletRequest request, HttpServletResponse response
) throws 1.5.0/docs/api/java/io/IOException.html">IOException
{
styleDirectory
(request, response,
new HashMap
<String, Object
>(),
null);
}
// private static String normalizeXmlId(String id)
// {
// StringBuilder strBuilder = new StringBuilder();
// strBuilder.append('_');
// for(int i = 0; i < id.length();i++)
// {
// char c = id.charAt(i);
// if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'))
// {
// strBuilder.append(c);
// }
// else
// {
// strBuilder.append('.');
// }
// }
// return strBuilder.toString();
// }
private static void styleDirectory
(HttpServletRequest request, HttpServletResponse response, Map
<String, Object
> parameters,
1.5.0/docs/api/java/lang/String.html">String bodyContent
) throws 1.5.0/docs/api/java/io/IOException.html">IOException
{
1.5.0/docs/api/java/lang/String.html">String stylesheet =
(1.5.0/docs/api/java/lang/String.html">String) request.
getAttribute("stylesheet");
5+0%2Fdocs%2Fapi+Document">Document directoryDocument =
(5+0%2Fdocs%2Fapi+Document">Document) request.
getAttribute("directoryDocument");
1.5.0/docs/api/java/lang/String.html">String actualNodeId =
(1.5.0/docs/api/java/lang/String.html">String) request.
getAttribute("actualNodeId");
1.5.0/docs/api/java/lang/String.html">String actualRemoteNodeId =
(1.5.0/docs/api/java/lang/String.html">String) request.
getAttribute("ACTUAL_REMOTE_CHILD");
UserSession userSession = UserSessionProxy.
loadUserSessionFromRequest(request
);
1.5.0/docs/api/java/lang/System.html">System.
out.
println("Using stylesheet = " + stylesheet
);
parameters.
put("contextPath", request.
getContextPath());
1.5.0/docs/api/java/lang/String.html">String language = UserSessionProxy.
loadUserSessionLanguageFromRequest(request
);
if(language
!=
null)
parameters.
put("language", language
);
1.5.0/docs/api/java/lang/String.html">String username =
"descolnhecido";
1.5.0/docs/api/java/lang/String.html">String roles =
"";
1.5.0/docs/api/java/lang/String.html">String name = username
;
if (userSession
!=
null && userSession.
getUsername() !=
null)
username = userSession.
getUsername();
if (userSession
!=
null && userSession.
getName() !=
null)
name = userSession.
getName();
if (userSession
!=
null && userSession.
getUser() !=
null)
roles = userSession.
getUser().
getRoles();
parameters.
put("username", username
);
parameters.
put("name", name
);
parameters.
put("roles", roles
);
parameters.
put("ACTUAL", actualNodeId
);
parameters.
put("ACTUAL_REMOTE_CHILD", actualRemoteNodeId
);
try
{
1.5.0/docs/api/java/lang/String.html">String html = Dom4jUtil.
styleDocument(directoryDocument, stylesheet, parameters
);
if (bodyContent
!=
null)
html = html.
replace("@@BODY_CONTENT@@", bodyContent
);
response.
getWriter().
write(html
);
}
catch (1.5.0/docs/api/java/lang/Exception.html">Exception e
)
{
logger.
error(e, e
);
response.
sendError(500
);
}
}
private static 1.5.0/docs/api/java/lang/String.html">String readContent2String
(5+0%2Fdocs%2Fapi+InputStream">InputStream stream,
1.5.0/docs/api/java/lang/String.html">String encoding
) throws 1.5.0/docs/api/java/io/IOException.html">IOException
{
byte[] buf =
new byte[1024
];
int readedBytes
;
1.5.0/docs/api/java/io/StringWriter.html">StringWriter writer =
new 1.5.0/docs/api/java/io/StringWriter.html">StringWriter();
while ((readedBytes = stream.
read(buf
)) > 0
)
{
1.5.0/docs/api/java/lang/String.html">String s =
new 1.5.0/docs/api/java/lang/String.html">String(buf, 0, readedBytes, encoding
);
writer.
write(s
);
}
return writer.
toString();
}
private static void writeDirectStream
(HttpServletResponse response,
5+0%2Fdocs%2Fapi+InputStream">InputStream stream
) throws 1.5.0/docs/api/java/io/IOException.html">IOException
{
byte[] buf =
new byte[1024
];
int readedBytes
;
5+0%2Fdocs%2Fapi+OutputStream">OutputStream os = response.
getOutputStream();
while ((readedBytes = stream.
read(buf
)) > 0
)
{
os.
write(buf, 0, readedBytes
);
}
os.
close();
}
private static 5+0%2Fdocs%2Fapi+InputStream">InputStream openStream
(1.5.0/docs/api/java/lang/String.html">String requestURL,
5+0%2Fdocs%2Fapi+Proxy">Proxy proxy
) throws 1.5.0/docs/api/java/io/IOException.html">IOException
{
5+0%2Fdocs%2Fapi+InputStream">InputStream in =
null;
1.5.0/docs/api/java/net/URL.html">URL url =
new 1.5.0/docs/api/java/net/URL.html">URL(requestURL
);
1.5.0/docs/api/java/net/HttpURLConnection.html">HttpURLConnection con =
null;
int responseCode =
0;
do
{
if (proxy
!=
null)
con =
(1.5.0/docs/api/java/net/HttpURLConnection.html">HttpURLConnection) url.
openConnection(proxy
);
else
con =
(1.5.0/docs/api/java/net/HttpURLConnection.html">HttpURLConnection) url.
openConnection();
con.
setRequestProperty("User-Agent",
"ESTG-Baco/1.0");
con.
setRequestProperty("Accept-Encoding",
"compress, gzip, identify");
try
{
responseCode = con.
getResponseCode();
logger.
debug("responseCode=" + responseCode
);
}
catch (1.5.0/docs/api/java/io/FileNotFoundException.html">FileNotFoundException e
)
{
// assume it's a 503 response
logger.
info(requestURL, e
);
responseCode =
1.5.0/docs/api/java/net/HttpURLConnection.html">HttpURLConnection.
HTTP_UNAVAILABLE;
}
if (responseCode ==
1.5.0/docs/api/java/net/HttpURLConnection.html">HttpURLConnection.
HTTP_UNAVAILABLE)
{
long retrySeconds = con.
getHeaderFieldInt("Retry-After", -1
);
if (retrySeconds == -1
)
{
long now =
(new 5+0%2Fdocs%2Fapi+Date">Date()).
getTime();
long retryDate = con.
getHeaderFieldDate("Retry-After", now
);
retrySeconds = retryDate - now
;
}
if (retrySeconds ==
0)
{ // Apparently, it's a bad URL
throw new 1.5.0/docs/api/java/io/FileNotFoundException.html">FileNotFoundException("Bad URL?");
}
logger.
error("Server response: Retry-After=" + retrySeconds
);
if (retrySeconds
> 0
)
{
try
{
1.5.0/docs/api/java/lang/Thread.html">Thread.
sleep(retrySeconds
* 1000
);
}
catch (1.5.0/docs/api/java/lang/InterruptedException.html">InterruptedException ex
)
{
ex.
printStackTrace();
}
}
}
}
while (responseCode ==
1.5.0/docs/api/java/net/HttpURLConnection.html">HttpURLConnection.
HTTP_UNAVAILABLE);
1.5.0/docs/api/java/lang/String.html">String contentEncoding = con.
getHeaderField("Content-Encoding");
logger.
debug("contentEncoding=" + contentEncoding
);
if ("compress".
equals(contentEncoding
))
{
1.5.0/docs/api/java/util/zip/ZipInputStream.html">ZipInputStream zis =
new 1.5.0/docs/api/java/util/zip/ZipInputStream.html">ZipInputStream(con.
getInputStream());
zis.
getNextEntry();
in = zis
;
}
else if ("gzip".
equals(contentEncoding
))
{
in =
new 1.5.0/docs/api/java/util/zip/GZIPInputStream.html">GZIPInputStream(con.
getInputStream());
}
else if ("deflate".
equals(contentEncoding
))
{
in =
new 1.5.0/docs/api/java/util/zip/InflaterInputStream.html">InflaterInputStream(con.
getInputStream());
}
else
{
in = con.
getInputStream();
}
return in
;
}
public static void processHttpRequestService
(JspWriter out,
1.5.0/docs/api/java/lang/String.html">String server,
1.5.0/docs/api/java/lang/String.html">String path
) throws 1.5.0/docs/api/java/io/IOException.html">IOException, ServletException
{
1.5.0/docs/api/java/lang/String.html">String serverUrl = ConfigProperties.
getProperty("server." + server
);
1.5.0/docs/api/java/lang/String.html">String serverEncoding = ConfigProperties.
getProperty(server +
".encoding");
1.5.0/docs/api/java/lang/String.html">String confStartPath = ConfigProperties.
getProperty("server." + server +
".start.path");
if (confStartPath
!=
null)
path = confStartPath + path
;
try
{
1.5.0/docs/api/java/net/URL.html">URL url =
new 1.5.0/docs/api/java/net/URL.html">URL(serverUrl + URIUtil.
encodePath(path,
"ISO-8859-1"));
1.5.0/docs/api/java/net/URLConnection.html">URLConnection con = url.
openConnection();
5+0%2Fdocs%2Fapi+InputStream">InputStream stream = con.
getInputStream();
byte[] buf =
new byte[1024
];
int readedBytes
;
while ((readedBytes = stream.
read(buf
)) > 0
)
{
1.5.0/docs/api/java/lang/String.html">String str =
new 1.5.0/docs/api/java/lang/String.html">String(buf, 0, readedBytes, serverEncoding
);
out.
print(str
);
}
}
catch (1.5.0/docs/api/java/io/FileNotFoundException.html">FileNotFoundException e
)
{
throw new 1.5.0/docs/api/java/io/FileNotFoundException.html">FileNotFoundException("url not found for server:" + server +
" and path:" + path
);
}
catch (1.5.0/docs/api/java/lang/Exception.html">Exception e
)
{
throw new 1.5.0/docs/api/java/io/IOException.html">IOException(e.
toString());
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
*/
protected void doGet
(HttpServletRequest request, HttpServletResponse response
)
throws ServletException,
1.5.0/docs/api/java/io/IOException.html">IOException
{
processRequest
(request, response
);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
*/
protected void doPost
(HttpServletRequest request, HttpServletResponse response
)
throws ServletException,
1.5.0/docs/api/java/io/IOException.html">IOException
{
processRequest
(request, response
);
}
/**
* Returns a short description of the servlet.
*/
public 1.5.0/docs/api/java/lang/String.html">String getServletInfo
()
{
return "Proxy Servlet to forward to HTTP or FTP Proxy";
}
public static void main
(1.5.0/docs/api/java/lang/String.html">String[]args
) throws 1.5.0/docs/api/java/io/IOException.html">IOException
{
FtpServer server = FtpServer.
getServer("ftp://www.global.estgp.pt",
"jmachado",
"linux5631");
FTPClient client = server.
getClient();
if(client ==
null)
{
logger.
warn("###################");
logger.
warn("################### > CANT CONNECT FTP");
}
client.
setFileType(FTP.
BINARY_FILE_TYPE);
1.5.0/docs/api/java/io/FileInputStream.html">FileInputStream teste =
new 1.5.0/docs/api/java/io/FileInputStream.html">FileInputStream("D:\\resources.properties");
client.
changeWorkingDirectory("/Engenharia.Informatica.9119/AnoLectivo.2008-2009/Semestre1/Engenharia.Do.Software");
client.
makeDirectory("ttt");
1.5.0/docs/api/java/lang/System.html">System.
out.
println(client.
storeFile("resources.properties",teste
));
client.
quit();
client.
disconnect();
}
// </editor-fold>
}