Subversion Repositories bacoAlunos

Rev

Rev 1945 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
368 jmachado 1
package pt.estgp.estgweb.web;
2
 
1005 jmachado 3
import jomm.web.ftp.FileType;
4
import jomm.web.ftp.IFile;
5
import jomm.web.ftp.impl.FtpFile;
368 jmachado 6
import org.apache.commons.httpclient.util.URIUtil;
1005 jmachado 7
import org.apache.commons.net.ftp.FTP;
379 jmachado 8
import org.apache.commons.net.ftp.FTPClient;
9
import org.apache.commons.net.ftp.FTPFile;
1005 jmachado 10
import org.apache.log4j.Logger;
11
import org.dom4j.Document;
12
import org.dom4j.DocumentException;
13
import org.dom4j.Element;
14
import pt.estgp.estgweb.domain.UserSession;
15
import pt.estgp.estgweb.utils.ConfigProperties;
16
import pt.estgp.estgweb.utils.Dom4jUtil;
17
import pt.estgp.estgweb.web.exceptions.NotAuthorizedException;
368 jmachado 18
 
1005 jmachado 19
import javax.servlet.ServletException;
368 jmachado 20
import javax.servlet.http.HttpServlet;
21
import javax.servlet.http.HttpServletRequest;
22
import javax.servlet.http.HttpServletResponse;
23
import javax.servlet.jsp.JspWriter;
24
import java.io.*;
25
import java.net.*;
1005 jmachado 26
import java.util.Date;
27
import java.util.HashMap;
28
import java.util.List;
29
import java.util.Map;
368 jmachado 30
import java.util.zip.GZIPInputStream;
31
import java.util.zip.InflaterInputStream;
1005 jmachado 32
import java.util.zip.ZipInputStream;
368 jmachado 33
 
34
/**
35
 * @author Jorge Machado
36
 * @date 26/Fev/2008
37
 * @time 12:46:16
38
 * @see pt.estgp.estgweb.web
39
 */
40
public class DirWebProxy extends HttpServlet
41
{
42
 
406 jmachado 43
    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";
44
 
368 jmachado 45
    /**
851 jmachado 46
     * sss requests for both HTTP <code>GET</code> and <code>POST</code> methods.
368 jmachado 47
     *
48
     * @param request servlet request
49
     * @param response servlet response
50
     */
51
 
52
    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);
53
 
54
 
55
    protected static void processRequest(HttpServletRequest request, HttpServletResponse response)
56
            throws ServletException, 1.5.0/docs/api/java/io/IOException.html">IOException
57
    {
58
 
59
        1.5.0/docs/api/java/lang/String.html">String element = (1.5.0/docs/api/java/lang/String.html">String) request.getAttribute("element");
379 jmachado 60
        if (element.equals("node"))
368 jmachado 61
        {
379 jmachado 62
            processNode(request, response);
368 jmachado 63
        }
64
        else
65
        {
379 jmachado 66
            processLeaf(request, response);
368 jmachado 67
        }
68
    }
69
 
70
 
71
    /**
72
     * @param request
73
     * @param response
74
     * @throws ServletException
75
     * @throws IOException
76
     */
77
 
78
    protected static void processNode(HttpServletRequest request, HttpServletResponse response)
79
            throws ServletException, 1.5.0/docs/api/java/io/IOException.html">IOException
80
    {
379 jmachado 81
        styleDirectory(request, response);
368 jmachado 82
    }
83
 
84
    protected static void processLeaf(HttpServletRequest request, HttpServletResponse response)
85
            throws ServletException, 1.5.0/docs/api/java/io/IOException.html">IOException
86
    {
87
        1.5.0/docs/api/java/lang/String.html">String path = (1.5.0/docs/api/java/lang/String.html">String) request.getAttribute("path");
379 jmachado 88
        1.5.0/docs/api/java/lang/String.html">String startPath = (1.5.0/docs/api/java/lang/String.html">String) request.getAttribute("startPath");
89
        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");
368 jmachado 90
        1.5.0/docs/api/java/lang/String.html">String server = (1.5.0/docs/api/java/lang/String.html">String) request.getAttribute("server");
91
        1.5.0/docs/api/java/lang/String.html">String useOutputStream = (1.5.0/docs/api/java/lang/String.html">String) request.getAttribute("useOutputStream");
92
        1.5.0/docs/api/java/lang/String.html">String encoding = (1.5.0/docs/api/java/lang/String.html">String) request.getAttribute("encoding");
379 jmachado 93
        1.5.0/docs/api/java/lang/String.html">String proxyKey = (1.5.0/docs/api/java/lang/String.html">String) request.getAttribute("proxyKey");
368 jmachado 94
        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");
95
        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");
96
        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"));
97
        1.5.0/docs/api/java/lang/String.html">String xml = (1.5.0/docs/api/java/lang/String.html">String) request.getAttribute("xml");
98
        1.5.0/docs/api/java/lang/String.html">String label = (1.5.0/docs/api/java/lang/String.html">String) request.getAttribute("label");
99
 
100
        logger.info("server:" + server);
101
        logger.info("path:" + path);
874 jmachado 102
        logger.info("startPath:" + startPath);
379 jmachado 103
        logger.info("proxyKey:" + proxyKey);
368 jmachado 104
        logger.info("proxyHost:" + proxyHost);
105
        logger.info("proxyPort:" + proxyPort);
106
        logger.info("xml:" + xml);
107
        logger.info("style:" + style);
108
        logger.info("label:" + label);
874 jmachado 109
        logger.info("useOutputStream:" + useOutputStream);
368 jmachado 110
 
111
        if (path != null)
112
        {
113
            try
114
            {
115
                5+0%2Fdocs%2Fapi+Proxy">Proxy proxy = null;
116
                if (proxyHost != null && proxyHost.length() > 0)
117
                {
118
                    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)));
119
                }
120
 
121
 
122
 
385 jmachado 123
 
124
                if (!server.startsWith("ftp://"))
379 jmachado 125
                {
619 jmachado 126
                    if(path.equals(startPath) )
385 jmachado 127
                        path += leafUrl;
619 jmachado 128
                    1.5.0/docs/api/java/lang/String.html">String finalURL;
129
                    if(leafUrl.indexOf("?")>0)
130
                        finalURL = server + leafUrl;
131
                    else
132
                        finalURL = server + URIUtil.encodePath(path, "ISO-8859-1");
379 jmachado 133
                    1.5.0/docs/api/java/net/URL.html">URL url = new 1.5.0/docs/api/java/net/URL.html">URL(finalURL);
368 jmachado 134
 
379 jmachado 135
                    if (useOutputStream != null && useOutputStream.equals("true"))
368 jmachado 136
                    {
379 jmachado 137
                        5+0%2Fdocs%2Fapi+InputStream">InputStream stream = openStream(finalURL, proxy);
138
                        1.5.0/docs/api/java/net/URLConnection.html">URLConnection con = url.openConnection();
139
                        response.setContentType(con.getContentType());
140
                        if (xml == null || xml.equals("false"))
141
                            response.setCharacterEncoding(encoding);
142
                        response.setContentLength(con.getContentLength());
143
                        writeDirectStream(response, stream);
144
                    }
1312 jmachado 145
                    else if(server.equals("WebPages"))
146
                    {
147
                        //Internal WebPages Module
148
                        //todo load page based on language and based on path ID
149
 
150
                        //O StartPath é sempre vazio no caso dos WebPages
151
                        //portanto o Path tem o caminho completo para a pagina
152
                        //que na prática é o seu identificador
153
 
154
                        //todo usar o HTML provenietne como content
155
                        1.5.0/docs/api/java/lang/String.html">String html = "Em construcao";
156
                        generateOutputLeaf(response, request, html, style);
157
 
158
                    }
379 jmachado 159
                    else if (xml == null || xml.equals("false"))
160
                    {
161
                        5+0%2Fdocs%2Fapi+InputStream">InputStream stream = openStream(finalURL, proxy);
162
                        1.5.0/docs/api/java/lang/String.html">String content = readContent2String(stream, encoding);
163
                        generateOutputLeaf(response, request, content, style);
164
                    }
165
                    else
166
                    {
167
                        1.5.0/docs/api/java/net/URLConnection.html">URLConnection con = new 1.5.0/docs/api/java/net/URL.html">URL(finalURL).openConnection();
168
                        con.connect();
169
                        if (con.getContentLength() > 0)
170
                        {
368 jmachado 171
//                      Document dom = Dom4jUtil.parse(stream);
379 jmachado 172
                            generateOutputLeafXml(response, request, finalURL, proxy, style);
173
                        }
368 jmachado 174
                    }
175
                }
379 jmachado 176
                else
177
                {
178
                    5+0%2Fdocs%2Fapi+Document">Document directoryDocument = (5+0%2Fdocs%2Fapi+Document">Document) request.getAttribute("directoryDocument");
380 jmachado 179
                    if(leafUrl != null && leafUrl.length() > 0)
180
                    {
181
                        1.5.0/docs/api/java/lang/String.html">String endPath = "";
182
                        if(startPath != null)
183
                        {
184
                            endPath = path.substring(startPath.length());
185
                        }
1069 jmachado 186
                        if(leafUrl.endsWith("/") && endPath.startsWith("/"))
187
                        {
188
                            path = startPath + leafUrl.substring(0,leafUrl.length()-1) + endPath;
189
                        }
190
                        else
191
                            path = startPath + leafUrl + endPath;
380 jmachado 192
                    }
1005 jmachado 193
                    if(!extendDiretoryDocument(request, response, path, proxyKey, server, startPath + leafUrl, directoryDocument))
194
                        return;
390 jmachado 195
 
379 jmachado 196
                    styleDirectory(request, response);
197
                }
368 jmachado 198
            }
697 jmachado 199
            catch (NotAuthorizedException e)
200
            {
201
                UserSession userSession = UserSessionProxy.loadUserSessionFromRequest(request);
202
                1.5.0/docs/api/java/lang/String.html">String username = userSession != null ? userSession.getUsername() : "UNKNOWN";
874 jmachado 203
                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);
697 jmachado 204
                response.sendError(401);
205
            }
368 jmachado 206
            catch (1.5.0/docs/api/java/io/FileNotFoundException.html">FileNotFoundException e)
207
            {
706 jmachado 208
 
209
                logger.warn("url not found for server:" + server + " and path:" + path + " " + "REMOTE USER" + request.getRemoteUser() + " " + request.getRequestURL());
368 jmachado 210
                response.sendError(404);
211
            }
212
            catch (1.5.0/docs/api/java/lang/Exception.html">Exception e)
213
            {
884 jmachado 214
                logger.error(e, e);
368 jmachado 215
                throw new 1.5.0/docs/api/java/io/IOException.html">IOException(e.toString());
216
            }
217
        }
218
        else
219
        {
220
            logger.warn("url not found for server:" + server + " and path:" + path);
221
            response.sendError(404);
222
        }
379 jmachado 223
    }
368 jmachado 224
 
379 jmachado 225
 
226
    public static 1.5.0/docs/api/java/lang/String.html">String FTP_FILE_PREFIX = "FTP_";
227
 
228
    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)
229
    {
380 jmachado 230
        element.addAttribute(name, value);
368 jmachado 231
    }
232
 
233
 
1085 jmachado 234
    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)
379 jmachado 235
            throws ServletException, 1.5.0/docs/api/java/io/IOException.html">IOException
368 jmachado 236
    {
406 jmachado 237
 
379 jmachado 238
        try
368 jmachado 239
        {
1085 jmachado 240
            UserSession userSession = UserSessionProxy.loadUserSessionFromRequest(request);
241
            FTPFileProxy.UserCredentialsForFtp u = FTPFileProxy.getUserCredentialsForFtp(server, userSession);
242
 
243
            1.5.0/docs/api/java/lang/String.html">String username = u.username;
244
            1.5.0/docs/api/java/lang/String.html">String password = u.password;
245
 
246
            if(username == null || password == null) //NAO PODE LIGAR
1069 jmachado 247
            {
1085 jmachado 248
                response.sendError(401);
249
                return false;
1069 jmachado 250
            }
1085 jmachado 251
 
379 jmachado 252
 
253
            if (path != null)
254
            {
1085 jmachado 255
                FtpServer ftpServer = FtpServer.getServer(serverUrl, username, password);
256
                FTPClient client = FTPFileProxy.getFtpClient(ftpServer, userSession, server, serverUrl);
1005 jmachado 257
                if(client == null)
258
                {
259
                    return false;
260
                }
1085 jmachado 261
 
406 jmachado 262
 
379 jmachado 263
                5+0%2Fdocs%2Fapi+Element">Element actualNode = (5+0%2Fdocs%2Fapi+Element">Element) request.getAttribute("actualNode");
264
 
265
                if(startPath.equals("/"))
266
                    startPath = "";
406 jmachado 267
                request.setAttribute(FTP_ACTUAL_PATH_KEY,startPath);
379 jmachado 268
                if (path.equals(startPath))
269
                {
697 jmachado 270
                    if(!client.changeWorkingDirectory(path))
271
                    {
272
                        throw new NotAuthorizedException();
273
                    }
379 jmachado 274
                    FTPFile[] files = client.listFiles();
1085 jmachado 275
                    List<IFile> iFiles = FtpFile.init(files, serverUrl, path);
379 jmachado 276
                    //root
277
                    for (IFile iFile : iFiles)
278
                    {
380 jmachado 279
                        5+0%2Fdocs%2Fapi+Element">Element iFileElem = actualNode.addElement("leaf");
1067 jmachado 280
                        addAttribute(iFileElem, "node", "false");
379 jmachado 281
                        addAttribute(iFileElem, "id", FTP_FILE_PREFIX + "0_" + iFile.getName());
380 jmachado 282
                        addAttribute(iFileElem, "idPrefixSize","" +  (FTP_FILE_PREFIX + "0_").length());
283
 
379 jmachado 284
                        addAttribute(iFileElem, "label", iFile.getName());
285
                        addAttribute(iFileElem, "visualization", "filesystem");
286
                        addAttribute(iFileElem, "size", "" + iFile.getSize());
287
                        addAttribute(iFileElem, "lastModification", "" + iFile.getLastUpdate().toString());
288
                        if (iFile.getType() == FileType.DIRECTORY)
289
                        {
290
                            addAttribute(iFileElem, "ftpDirectory", "true");
291
                        }
292
                        else
293
                        {
392 jmachado 294
                            addAttribute(iFileElem, "extension", iFile.getExtension());
379 jmachado 295
                            addAttribute(iFileElem, "ftpDirectory", "false");
296
                            addAttribute(iFileElem, "absolute", "true");
297
                            addAttribute(iFileElem, "url", iFile.getCompleteUrl());
298
                        }
299
                    }
300
                }
301
                else
302
                {
303
 
304
                    1.5.0/docs/api/java/lang/String.html">String pathAux = path.substring(startPath.length());
380 jmachado 305
                    1.5.0/docs/api/java/lang/String.html">String[] pathFragments;
1069 jmachado 306
                    if(pathAux.startsWith("/"))
380 jmachado 307
                        pathFragments = pathAux.substring(1).split("/");
308
                    else
309
                        pathFragments = pathAux.split("/");
379 jmachado 310
 
380 jmachado 311
 
700 jmachado 312
                     if(!client.changeWorkingDirectory(startPath))
313
                    {
314
                        throw new NotAuthorizedException();
315
                    }
379 jmachado 316
                    FTPFile[] files = client.listFiles();
1085 jmachado 317
                    List<IFile> iFiles = FtpFile.init(files, serverUrl, path);
379 jmachado 318
                    5+0%2Fdocs%2Fapi+Element">Element goDeepElement = null;
380 jmachado 319
                    1.5.0/docs/api/java/lang/String.html">String actualId = null;
379 jmachado 320
                    for (IFile iFile : iFiles)
321
                    {
1067 jmachado 322
                        5+0%2Fdocs%2Fapi+Element">Element iFileElem = actualNode.addElement("leaf");
323
                        addAttribute(iFileElem, "node", "true");
379 jmachado 324
                        addAttribute(iFileElem, "id", FTP_FILE_PREFIX + "0_" + iFile.getName());
380 jmachado 325
                        addAttribute(iFileElem, "idPrefixSize","" +  (FTP_FILE_PREFIX + "0_").length());
326
 
379 jmachado 327
                        addAttribute(iFileElem, "label", iFile.getName());
328
                        addAttribute(iFileElem, "visualization", "filesystem");
329
                        addAttribute(iFileElem, "size", "" + iFile.getSize());
330
                        addAttribute(iFileElem, "lastModification", "" + iFile.getLastUpdate().toString());
331
                        if (iFile.getType() == FileType.DIRECTORY)
332
                        {
333
                            addAttribute(iFileElem, "ftpDirectory", "true");
334
                        }
335
                        else
336
                        {
392 jmachado 337
                            addAttribute(iFileElem, "extension", iFile.getExtension());
379 jmachado 338
                            addAttribute(iFileElem, "ftpDirectory", "false");
339
                            addAttribute(iFileElem, "absolute", "true");
340
                            addAttribute(iFileElem, "url", iFile.getCompleteUrl());
341
                        }
342
 
343
                        if (iFile.getName().equals(pathFragments[0]))
380 jmachado 344
                        {
345
                            actualId = FTP_FILE_PREFIX + "0_" + iFile.getName();
379 jmachado 346
                            goDeepElement = iFileElem;
380 jmachado 347
                        }
379 jmachado 348
                    }
349
 
350
 
351
 
380 jmachado 352
                    1.5.0/docs/api/java/lang/String.html">String startPathAux = startPath;
353
 
379 jmachado 354
                    for (int i = 0; i < pathFragments.length; i++)
355
                    {
356
                        5+0%2Fdocs%2Fapi+Element">Element nextGoDeepElement = null;
357
                        1.5.0/docs/api/java/lang/String.html">String d = pathFragments[i];
380 jmachado 358
                        startPathAux = startPathAux + "/" + d;
706 jmachado 359
                        if(!client.changeWorkingDirectory(startPathAux))
700 jmachado 360
                        {
361
                            throw new NotAuthorizedException();
362
                        }
363
 
379 jmachado 364
                        files = client.listFiles();
1085 jmachado 365
                        iFiles = FtpFile.init(files, serverUrl, path);
380 jmachado 366
 
379 jmachado 367
                        for (IFile iFile : iFiles)
368
                        {
369
                            5+0%2Fdocs%2Fapi+Element">Element iFileElem;
370
 
371
                            if(i == pathFragments.length - 1)
1067 jmachado 372
                            {
380 jmachado 373
                                iFileElem = goDeepElement.addElement("leaf");
1067 jmachado 374
                                addAttribute(iFileElem, "node","false");
375
                            }
379 jmachado 376
                            else
1067 jmachado 377
                            {
378
                                iFileElem = goDeepElement.addElement("leaf");
379
                                addAttribute(iFileElem, "node","true");
380
                            }
379 jmachado 381
 
382
                            addAttribute(iFileElem, "id", FTP_FILE_PREFIX + (i+1) + "_" + iFile.getName());
380 jmachado 383
                            addAttribute(iFileElem, "idPrefixSize","" +  (FTP_FILE_PREFIX + (i+1) + "_").length());
379 jmachado 384
                            addAttribute(iFileElem, "label", iFile.getName());
385
                            addAttribute(iFileElem, "visualization", "filesystem");
386
                            addAttribute(iFileElem, "size", "" + iFile.getSize());
387
                            addAttribute(iFileElem, "lastModification", "" + iFile.getLastUpdate().toString());
388
                            if (iFile.getType() == FileType.DIRECTORY)
389
                            {
390
                                addAttribute(iFileElem, "ftpDirectory", "true");
391
                            }
392
                            else
393
                            {
380 jmachado 394
                                addAttribute(iFileElem, "extension", iFile.getExtension());
379 jmachado 395
                                addAttribute(iFileElem, "ftpDirectory", "false");
396
                                addAttribute(iFileElem, "absolute", "true");
397
                                addAttribute(iFileElem, "url", iFile.getCompleteUrl());
398
                            }
399
 
400
                            if (i < pathFragments.length - 1 && iFile.getName().equals(pathFragments[i + 1]))
380 jmachado 401
                            {
379 jmachado 402
                                nextGoDeepElement = iFileElem;
380 jmachado 403
                                actualId = FTP_FILE_PREFIX + (i+1) + "_" + iFile.getName();
404
                            }
379 jmachado 405
                        }
406
                        goDeepElement = nextGoDeepElement;
407
                    }
380 jmachado 408
                    request.setAttribute("ACTUAL_REMOTE_CHILD",actualId);
379 jmachado 409
                }
410
                client.quit();
411
                client.disconnect();
412
            }
413
            else
414
            {
1085 jmachado 415
                throw new 1.5.0/docs/api/java/io/FileNotFoundException.html">FileNotFoundException("url not found for server:" + serverUrl + " and path:" + path);
379 jmachado 416
            }
417
        }
418
        catch (1.5.0/docs/api/java/lang/Throwable.html">Throwable e)
419
        {
698 jmachado 420
            if(e instanceof NotAuthorizedException)
421
                throw (NotAuthorizedException)e;
379 jmachado 422
            logger.error(e, e);
423
        }
1005 jmachado 424
        return true;
379 jmachado 425
    }
426
 
427
 
428
    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
429
    {
430
        if (style)
431
        {
432
            Map<String, Object> parameters = new HashMap<String, Object>();
368 jmachado 433
//            OutputFormat outputFormat = new OutputFormat();
434
//            outputFormat.setSuppressDeclaration(true);
435
//            outputFormat.setEncoding("UTF-8");
436
//            StringWriter writer = new StringWriter();
437
//            Dom4jUtil.write(dom,writer, outputFormat);
438
//            org.w3c.dom.Document d = new org.dom4j.io.DOMWriter().write(dom);
439
//            parameters.put("body",dom.selectSingleNode("/"));
379 jmachado 440
            parameters.put("includeXML", finalURL);
441
            styleDirectory(request, response, parameters, null);
368 jmachado 442
        }
443
        else
444
        {
379 jmachado 445
            5+0%2Fdocs%2Fapi+InputStream">InputStream stream = openStream(finalURL, proxy);
368 jmachado 446
            5+0%2Fdocs%2Fapi+Document">Document dom = Dom4jUtil.parse(stream);
379 jmachado 447
            Dom4jUtil.write(dom, response.getWriter());
368 jmachado 448
        }
449
    }
450
 
379 jmachado 451
    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
368 jmachado 452
    {
379 jmachado 453
        if (style)
368 jmachado 454
        {
455
//            Map<String,Object> parameters = new HashMap<String,Object>();
456
//            parameters.put("body",content);
379 jmachado 457
            styleDirectory(request, response, new HashMap<String, Object>(), content);
368 jmachado 458
        }
459
        else
460
        {
461
            response.getWriter().write(content);
462
        }
463
    }
464
 
465
    private static void styleDirectory(HttpServletRequest request, HttpServletResponse response) throws 1.5.0/docs/api/java/io/IOException.html">IOException
466
    {
379 jmachado 467
        styleDirectory(request, response, new HashMap<String, Object>(), null);
368 jmachado 468
    }
469
 
380 jmachado 470
//    private static String normalizeXmlId(String id)
471
//    {
472
//        StringBuilder strBuilder = new StringBuilder();
473
//        strBuilder.append('_');
474
//        for(int i = 0; i < id.length();i++)
475
//        {
476
//            char c = id.charAt(i);
477
//            if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'))
478
//            {
479
//                strBuilder.append(c);
480
//            }
481
//            else
482
//            {
483
//                strBuilder.append('.');
484
//            }
485
//        }
486
//        return strBuilder.toString();
487
//    }
488
 
379 jmachado 489
    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
368 jmachado 490
    {
491
        1.5.0/docs/api/java/lang/String.html">String stylesheet = (1.5.0/docs/api/java/lang/String.html">String) request.getAttribute("stylesheet");
492
        5+0%2Fdocs%2Fapi+Document">Document directoryDocument = (5+0%2Fdocs%2Fapi+Document">Document) request.getAttribute("directoryDocument");
493
        1.5.0/docs/api/java/lang/String.html">String actualNodeId = (1.5.0/docs/api/java/lang/String.html">String) request.getAttribute("actualNodeId");
379 jmachado 494
        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");
368 jmachado 495
        UserSession userSession = UserSessionProxy.loadUserSessionFromRequest(request);
884 jmachado 496
        1.5.0/docs/api/java/lang/System.html">System.out.println("Using stylesheet = " + stylesheet);
368 jmachado 497
 
379 jmachado 498
        parameters.put("contextPath", request.getContextPath());
1312 jmachado 499
        1.5.0/docs/api/java/lang/String.html">String language = UserSessionProxy.loadUserSessionLanguageFromRequest(request);
500
        if(language != null)
501
            parameters.put("language", language);
502
 
668 jmachado 503
        1.5.0/docs/api/java/lang/String.html">String username = "descolnhecido";
504
        1.5.0/docs/api/java/lang/String.html">String roles = "";
505
        1.5.0/docs/api/java/lang/String.html">String name = username;
506
 
507
        if (userSession != null && userSession.getUsername() != null)
508
            username = userSession.getUsername();
509
        if (userSession != null && userSession.getName() != null)
510
            name = userSession.getName();
511
        if (userSession != null && userSession.getUser() != null)
512
            roles = userSession.getUser().getRoles();
513
 
514
        parameters.put("username", username);
515
        parameters.put("name", name);
516
        parameters.put("roles", roles);
517
 
379 jmachado 518
        parameters.put("ACTUAL", actualNodeId);
519
        parameters.put("ACTUAL_REMOTE_CHILD", actualRemoteNodeId);
368 jmachado 520
 
521
        try
522
        {
379 jmachado 523
            1.5.0/docs/api/java/lang/String.html">String html = Dom4jUtil.styleDocument(directoryDocument, stylesheet, parameters);
524
            if (bodyContent != null)
525
                html = html.replace("@@BODY_CONTENT@@", bodyContent);
368 jmachado 526
            response.getWriter().write(html);
527
        }
528
        catch (1.5.0/docs/api/java/lang/Exception.html">Exception e)
529
        {
379 jmachado 530
            logger.error(e, e);
368 jmachado 531
            response.sendError(500);
532
        }
533
    }
534
 
535
    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
536
    {
537
        byte[] buf = new byte[1024];
538
        int readedBytes;
539
        1.5.0/docs/api/java/io/StringWriter.html">StringWriter writer = new 1.5.0/docs/api/java/io/StringWriter.html">StringWriter();
540
        while ((readedBytes = stream.read(buf)) > 0)
541
        {
542
            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);
543
            writer.write(s);
544
        }
545
        return writer.toString();
546
    }
547
 
548
    private static void writeDirectStream(HttpServletResponse response, 5+0%2Fdocs%2Fapi+InputStream">InputStream stream) throws 1.5.0/docs/api/java/io/IOException.html">IOException
549
    {
550
        byte[] buf = new byte[1024];
551
        int readedBytes;
552
        5+0%2Fdocs%2Fapi+OutputStream">OutputStream os = response.getOutputStream();
553
        while ((readedBytes = stream.read(buf)) > 0)
554
        {
555
            os.write(buf, 0, readedBytes);
556
        }
557
        os.close();
558
    }
559
 
560
    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
561
    {
562
        5+0%2Fdocs%2Fapi+InputStream">InputStream in = null;
563
        1.5.0/docs/api/java/net/URL.html">URL url = new 1.5.0/docs/api/java/net/URL.html">URL(requestURL);
564
 
565
        1.5.0/docs/api/java/net/HttpURLConnection.html">HttpURLConnection con = null;
566
        int responseCode = 0;
567
        do
568
        {
569
            if (proxy != null)
570
                con = (1.5.0/docs/api/java/net/HttpURLConnection.html">HttpURLConnection) url.openConnection(proxy);
571
            else
572
                con = (1.5.0/docs/api/java/net/HttpURLConnection.html">HttpURLConnection) url.openConnection();
573
            con.setRequestProperty("User-Agent", "ESTG-Baco/1.0");
574
            con.setRequestProperty("Accept-Encoding", "compress, gzip, identify");
575
            try
576
            {
577
                responseCode = con.getResponseCode();
578
                logger.debug("responseCode=" + responseCode);
579
            }
580
            catch (1.5.0/docs/api/java/io/FileNotFoundException.html">FileNotFoundException e)
581
            {
582
                // assume it's a 503 response
583
                logger.info(requestURL, e);
584
                responseCode = 1.5.0/docs/api/java/net/HttpURLConnection.html">HttpURLConnection.HTTP_UNAVAILABLE;
585
            }
586
 
587
            if (responseCode == 1.5.0/docs/api/java/net/HttpURLConnection.html">HttpURLConnection.HTTP_UNAVAILABLE)
588
            {
589
                long retrySeconds = con.getHeaderFieldInt("Retry-After", -1);
590
                if (retrySeconds == -1)
591
                {
592
                    long now = (new 5+0%2Fdocs%2Fapi+Date">Date()).getTime();
593
                    long retryDate = con.getHeaderFieldDate("Retry-After", now);
594
                    retrySeconds = retryDate - now;
595
                }
596
                if (retrySeconds == 0)
597
                { // Apparently, it's a bad URL
598
                    throw new 1.5.0/docs/api/java/io/FileNotFoundException.html">FileNotFoundException("Bad URL?");
599
                }
600
                logger.error("Server response: Retry-After=" + retrySeconds);
601
                if (retrySeconds > 0)
602
                {
603
                    try
604
                    {
605
                        1.5.0/docs/api/java/lang/Thread.html">Thread.sleep(retrySeconds * 1000);
606
                    }
607
                    catch (1.5.0/docs/api/java/lang/InterruptedException.html">InterruptedException ex)
608
                    {
609
                        ex.printStackTrace();
610
                    }
611
                }
612
            }
613
        }
614
        while (responseCode == 1.5.0/docs/api/java/net/HttpURLConnection.html">HttpURLConnection.HTTP_UNAVAILABLE);
615
        1.5.0/docs/api/java/lang/String.html">String contentEncoding = con.getHeaderField("Content-Encoding");
616
        logger.debug("contentEncoding=" + contentEncoding);
617
        if ("compress".equals(contentEncoding))
618
        {
619
            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());
620
            zis.getNextEntry();
621
            in = zis;
622
        }
623
        else if ("gzip".equals(contentEncoding))
624
        {
625
            in = new 1.5.0/docs/api/java/util/zip/GZIPInputStream.html">GZIPInputStream(con.getInputStream());
626
        }
627
        else if ("deflate".equals(contentEncoding))
628
        {
629
            in = new 1.5.0/docs/api/java/util/zip/InflaterInputStream.html">InflaterInputStream(con.getInputStream());
630
        }
631
        else
632
        {
633
            in = con.getInputStream();
634
        }
635
        return in;
636
    }
637
 
638
    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
639
    {
640
        1.5.0/docs/api/java/lang/String.html">String serverUrl = ConfigProperties.getProperty("server." + server);
641
        1.5.0/docs/api/java/lang/String.html">String serverEncoding = ConfigProperties.getProperty(server + ".encoding");
642
        1.5.0/docs/api/java/lang/String.html">String confStartPath = ConfigProperties.getProperty("server." + server + ".start.path");
643
        if (confStartPath != null)
644
            path = confStartPath + path;
645
 
646
 
647
        try
648
        {
649
            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"));
650
            1.5.0/docs/api/java/net/URLConnection.html">URLConnection con = url.openConnection();
651
            5+0%2Fdocs%2Fapi+InputStream">InputStream stream = con.getInputStream();
652
 
653
            byte[] buf = new byte[1024];
654
            int readedBytes;
655
 
656
            while ((readedBytes = stream.read(buf)) > 0)
657
            {
658
                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);
659
                out.print(str);
660
            }
661
        }
662
        catch (1.5.0/docs/api/java/io/FileNotFoundException.html">FileNotFoundException e)
663
        {
664
            throw new 1.5.0/docs/api/java/io/FileNotFoundException.html">FileNotFoundException("url not found for server:" + server + " and path:" + path);
665
        }
666
        catch (1.5.0/docs/api/java/lang/Exception.html">Exception e)
667
        {
668
            throw new 1.5.0/docs/api/java/io/IOException.html">IOException(e.toString());
669
        }
670
 
671
    }
672
 
673
 
674
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
675
    /**
676
     * Handles the HTTP <code>GET</code> method.
677
     *
678
     * @param request  servlet request
679
     * @param response servlet response
680
     */
681
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
682
            throws ServletException, 1.5.0/docs/api/java/io/IOException.html">IOException
683
    {
684
        processRequest(request, response);
685
    }
686
 
687
    /**
688
     * Handles the HTTP <code>POST</code> method.
689
     *
690
     * @param request  servlet request
691
     * @param response servlet response
692
     */
693
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
694
            throws ServletException, 1.5.0/docs/api/java/io/IOException.html">IOException
695
    {
696
        processRequest(request, response);
697
    }
698
 
699
    /**
700
     * Returns a short description of the servlet.
701
     */
702
    public 1.5.0/docs/api/java/lang/String.html">String getServletInfo()
703
    {
704
        return "Proxy Servlet to forward to HTTP or FTP Proxy";
705
    }
406 jmachado 706
 
707
    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
708
    {
709
        FtpServer server = FtpServer.getServer("ftp://www.global.estgp.pt","jmachado","linux5631");
710
        FTPClient client = server.getClient();
1005 jmachado 711
        if(client == null)
712
        {
713
            logger.warn("###################");
714
            logger.warn("################### > CANT CONNECT FTP");
715
 
716
        }
717
 
406 jmachado 718
        client.setFileType(FTP.BINARY_FILE_TYPE);
719
        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");
720
        client.changeWorkingDirectory("/Engenharia.Informatica.9119/AnoLectivo.2008-2009/Semestre1/Engenharia.Do.Software");
721
        client.makeDirectory("ttt");
722
        1.5.0/docs/api/java/lang/System.html">System.out.println(client.storeFile("resources.properties",teste));
723
        client.quit();
724
        client.disconnect();
725
    }
368 jmachado 726
    // </editor-fold>
727
}