Source Code Cross Referenced for FtpFile.java in  » Portal » Open-Portal » com » sun » portal » netfile » servlet » java2 » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » Portal » Open Portal » com.sun.portal.netfile.servlet.java2 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001:        /**
002:         * $Id: FtpFile.java,v 1.37 2006/08/04 06:44:13 aj157941 Exp $
003:         * Copyright 2002 Sun Microsystems, Inc. All
004:         * rights reserved. Use of this product is subject
005:         * to license terms. Federal Acquisitions:
006:         * Commercial Software -- Government Users
007:         * Subject to Standard License Terms and
008:         * Conditions.
009:         *
010:         * Sun, Sun Microsystems, the Sun logo, and Sun ONE
011:         * are trademarks or registered trademarks of Sun Microsystems,
012:         * Inc. in the United States and other countries.
013:         */package com.sun.portal.netfile.servlet.java2;
014:
015:        import java.util.*;
016:        import com.sun.portal.log.common.PortalLogger;
017:        import java.util.logging.*;
018:        import java.io.*;
019:        import java.text.SimpleDateFormat;
020:
021:        import com.sun.portal.netfile.shared.*;
022:
023:        class FtpFile {
024:
025:            private NetFileResource nfRes = null;
026:            private static Logger logger = PortalLogger
027:                    .getLogger(FtpFile.class);
028:            protected String szEncoding;
029:            protected FullFtpClient ffc = null;
030:            //Keeps track of number of directories scanned during a search
031:            protected int intDirsTraversed = 0;
032:            protected ArrayList alSearchResults = new ArrayList();
033:            Locale clocale;
034:
035:            FtpFile(String szMachineEncoding, Locale cloc) {
036:                this .szEncoding = szMachineEncoding;
037:                this .clocale = cloc;
038:            }
039:
040:            String[] searchFTPDir(String usernam, String passwrd,
041:                    String machnam, String VMSnam, String pattern,
042:                    boolean ignoreCase, boolean searchSubfolders,
043:                    String dir_nam, int maxsrchdir,
044:                    NetFileResource nfrUsrResBundle) throws NetFileException {
045:
046:                this .nfRes = nfrUsrResBundle;
047:                this .ffc = initialiseFtpClient(usernam, passwrd, machnam,
048:                        VMSnam, dir_nam);
049:
050:                search(usernam, passwrd, machnam, VMSnam, pattern, ignoreCase,
051:                        searchSubfolders, dir_nam, maxsrchdir, nfrUsrResBundle);
052:
053:                if (intDirsTraversed > maxsrchdir) {
054:                    /*
055:                     * When maximum search directories has been exceeded, send the msg
056:                     * to the client along with the search results found till that point.
057:                     */
058:                    String[] searchResults = new String[alSearchResults.size() + 1];
059:                    searchResults[0] = "ERROR:"
060:                            + nfrUsrResBundle.getString("maxSearch");
061:                    for (int j = 1; j < searchResults.length; j++) {
062:                        searchResults[j] = (String) alSearchResults.get(j - 1);
063:                    }
064:                    return searchResults;
065:                }
066:
067:                if (alSearchResults.size() == 0) {
068:                    return new String[] { "        " };
069:                } else {
070:                    String[] sa_results = new String[alSearchResults.size()];
071:                    for (int j = 0; j < sa_results.length; ++j) {
072:                        sa_results[j] = (String) alSearchResults.get(j);
073:                    }
074:                    return sa_results;
075:                }
076:            }
077:
078:            void search(String usernam, String passwrd, String machnam,
079:                    String VMSnam, String pattern, boolean ignoreCase,
080:                    boolean searchSubfolders, String dir_nam, int maxsrchdir,
081:                    NetFileResource nfrUsrResBundle) throws NetFileException {
082:                try {
083:                    ++intDirsTraversed;
084:                    writeDebug("Directory number being searched = "
085:                            + intDirsTraversed, null);
086:
087:                    if (intDirsTraversed > maxsrchdir)
088:                        return;
089:
090:                    String[] sa_file_listing = getFTPDir(usernam, passwrd,
091:                            machnam, VMSnam, dir_nam, nfrUsrResBundle, false);
092:
093:                    if ((sa_file_listing == null)
094:                            || (sa_file_listing.length < 2))
095:                        return;
096:
097:                    String pwdString = ffc.pwd();
098:                    int firstIndex = pwdString.indexOf('\"');
099:                    int secondIndex = pwdString.lastIndexOf('\"');
100:                    String pwd = pwdString.substring(firstIndex + 1,
101:                            secondIndex);
102:
103:                    // file listing array contains file attributes is in this format -
104:                    // <file-type-indicator>, <file-name>, <file-size>, <file-modified-time>
105:                    // eg. sa_file_listing[0] = "-"
106:                    //sa_file_listing[] = "abc.xyz"
107:                    //sa_file_listing[] = "32"
108:                    //sa_file_listing[] = "Feb 27 06, 05:28 AM"
109:                    //since we are concerned only with the file name, we will always pick
110:                    // the (4*i + 2) th element of the array
111:                    for (int i = 1; i < sa_file_listing.length; i += 4) {
112:                        String fileName = sa_file_listing[i];
113:
114:                        if (fileName != null) {
115:                            fileName = fileName.trim();
116:                            if (!("".equals(fileName) || ".".equals(fileName) || ".."
117:                                    .equals(fileName))) {
118:                                //                        String filePath = dir_nam + "/" + fileName;
119:                                String filePath = pwd + "/" + fileName;
120:
121:                                if (ignoreCase) {
122:                                    fileName = fileName.toLowerCase();
123:                                    pattern = pattern.toLowerCase();
124:                                }
125:
126:                                boolean matchesPattern = false;
127:                                StringTokenizer stPattern = new StringTokenizer(
128:                                        pattern, ".");
129:                                StringTokenizer stfileName = new StringTokenizer(
130:                                        fileName, ".");
131:                                if (stfileName.countTokens() >= stPattern
132:                                        .countTokens()) {
133:                                    while (stPattern.hasMoreTokens()) {
134:                                        String fileNameString = stfileName
135:                                                .nextToken();
136:                                        String patternString = stPattern
137:                                                .nextToken();
138:                                        if (patternString.startsWith("*")) {
139:                                            int indexOfWildcard = patternString
140:                                                    .indexOf("*");
141:                                            patternString = patternString
142:                                                    .substring(indexOfWildcard + 1);
143:                                            if (!stPattern.hasMoreTokens())
144:                                                matchesPattern = fileNameString
145:                                                        .endsWith(patternString);
146:                                            else if ((patternString.trim()
147:                                                    .length() == 0)
148:                                                    || fileNameString
149:                                                            .endsWith(patternString))
150:                                                matchesPattern = true;
151:                                            else
152:                                                matchesPattern = false;
153:                                        } else if (patternString.endsWith("*")) {
154:                                            int indexOfWildcard = patternString
155:                                                    .indexOf("*");
156:                                            patternString = patternString
157:                                                    .substring(0,
158:                                                            indexOfWildcard);
159:                                            if (!stPattern.hasMoreTokens())
160:                                                matchesPattern = fileNameString
161:                                                        .startsWith(patternString);
162:                                            else if ((patternString.trim()
163:                                                    .length() == 0)
164:                                                    || fileNameString
165:                                                            .startsWith(patternString))
166:                                                matchesPattern = true;
167:                                            else
168:                                                matchesPattern = false;
169:                                        } else {
170:                                            if (fileNameString
171:                                                    .equals(patternString))
172:                                                matchesPattern = true;
173:                                            else
174:                                                matchesPattern = false;
175:                                        }
176:
177:                                        if (!matchesPattern)
178:                                            break;
179:                                    }
180:                                }
181:
182:                                if (matchesPattern) {
183:                                    writeDebug("Adding " + filePath
184:                                            + " to search results", null);
185:                                    //                            alSearchResults.add("/" + VMSnam + filePath);
186:                                    alSearchResults.add(filePath);
187:                                }
188:
189:                                //                        if((new File(filePath)).isDirectory())
190:                                if (searchSubfolders) {
191:
192:                                    try {
193:                                        // since there is no command for checking if 'filePath'
194:                                        // is a directory, just putting a small hack here.
195:                                        //the 'cd' command will throw an IOException if it's
196:                                        //done on a file istead of a directory.
197:                                        ffc.cd(filePath);
198:                                        try {
199:                                            writeDebug("Changing to directory "
200:                                                    + filePath + " to search",
201:                                                    null);
202:                                            search(usernam, passwrd, machnam,
203:                                                    VMSnam, pattern,
204:                                                    ignoreCase,
205:                                                    searchSubfolders, filePath,
206:                                                    maxsrchdir, nfrUsrResBundle);
207:
208:                                        } catch (NetFileException nfe) {
209:                                            if (intDirsTraversed > maxsrchdir)
210:                                                throw nfe;
211:                                        } catch (Exception e) {
212:                                            writeErrorDebug(
213:                                                    "("
214:                                                            + nfrUsrResBundle
215:                                                                    .getString("error13")
216:                                                            + ")", e);
217:                                            writeErrorDebug(
218:                                                    "Exception in searching directory "
219:                                                            + filePath + " in "
220:                                                            + VMSnam, e);
221:                                        }
222:                                    } catch (IOException e) {
223:                                        /* ignore */
224:                                    } finally {
225:                                        ffc.cd(pwd);
226:                                    }
227:                                }
228:                            }
229:                        }
230:                    }
231:                } catch (NetFileException nfe) {
232:                    if (intDirsTraversed > maxsrchdir)
233:                        throw nfe;
234:                } catch (Exception e) {
235:                    writeErrorDebug("Exception in searching " + VMSnam
236:                            + dir_nam + "/", e);
237:                    throw new NetFileException(
238:                            NetFileException.NETFILE_GENERROR_CODE,
239:                            nfrUsrResBundle.getString("ff.1", new Object[] {
240:                                    VMSnam, dir_nam }));
241:                }
242:            }
243:
244:            InputStream getInputFTPStream(String usernam, String passwrd,
245:                    String machnam, String VMSnam, String mainfilenam,
246:                    String dir_nam, NetFileResource nfrUsrResBundle)
247:                    throws NetFileException {
248:
249:                Exception e = null;
250:                InputStream ftpin = null;
251:
252:                this .nfRes = nfrUsrResBundle;
253:
254:                try {
255:                    ffc = initialiseFtpClient(usernam, passwrd, machnam,
256:                            VMSnam, dir_nam);
257:                    ftpin = ffc.get(mainfilenam);
258:
259:                } catch (Exception ex) {
260:                    e = ex;
261:                    //TBD: Get string from resource bundle.
262:                    //performFinalProcessing(e,getString("ff.2"),ffc);
263:                    performFinalProcessing(e,
264:                            "Exceptione obtaining the FTP file", ffc);
265:                }
266:
267:                return ftpin;
268:            }
269:
270:            OutputStream getOutputFTPStream(String usernam, String passwrd,
271:                    String machnam, String VMSnam, String remotefil_arg,
272:                    String dir_nam, NetFileResource nfrUsrResBundle)
273:                    throws NetFileException {
274:
275:                return this .getOutputFTPStream(usernam, passwrd, machnam,
276:                        VMSnam, remotefil_arg, dir_nam, nfrUsrResBundle, false);
277:            }
278:
279:            OutputStream getOutputFTPStream(String usernam, String passwrd,
280:                    String machnam, String VMSnam, String remotefil_arg,
281:                    String dir_nam, NetFileResource nfrUsrResBundle,
282:                    boolean append) throws NetFileException {
283:
284:                Exception e = null;
285:                OutputStream ftpout = null;
286:
287:                this .nfRes = nfrUsrResBundle;
288:
289:                try {
290:                    ffc = initialiseFtpClient(usernam, passwrd, machnam,
291:                            VMSnam, dir_nam);
292:                    if (append) {
293:                        ftpout = ffc.append(remotefil_arg);
294:                    } else {
295:                        ftpout = ffc.put(remotefil_arg);
296:                    }
297:
298:                } catch (Exception ex) {
299:                    e = ex;
300:                    performFinalProcessing(e, "Could upload file", ffc);
301:                }
302:
303:                return ftpout;
304:            }
305:
306:            void closeFtpFile() {
307:                try {
308:                    if (this .ffc != null) {
309:                        this .ffc.quit();
310:                    }
311:                    ffc = null;
312:                } catch (IOException ioe) {
313:                    ffc = null;
314:                }
315:            }
316:
317:            String getFTPFile(String usernam, String passwrd, String machnam,
318:                    String VMSnam, String mainfilenam, String dir_nam,
319:                    String tmpdir, NetFileResource nfrUsrResBundle,
320:                    String usersession) throws NetFileException {
321:
322:                String mknodfilename = "";
323:                String txtouting = "";
324:                Exception e = null;
325:                FullFtpClient nfFtpClient = null;
326:                InputStream instream = null;
327:                BufferedOutputStream bos = null;
328:                ByteArrayOutputStream buftxt = new ByteArrayOutputStream();
329:                byte[] buffer = new byte[8 * 1024];
330:                this .nfRes = nfrUsrResBundle;
331:
332:                try {
333:                    int c;
334:                    Long random = new Long(System.currentTimeMillis());
335:                    mknodfilename = tmpdir + "/" + random.toString()
336:                            + usernam.toUpperCase() + mainfilenam;
337:                    File newfil = new File(mknodfilename);
338:                    if (newfil.exists()) {
339:                        newfil.delete();
340:                    }
341:                    bos = new BufferedOutputStream(new FileOutputStream(newfil));
342:                    nfFtpClient = initialiseFtpClient(usernam, passwrd,
343:                            machnam, VMSnam, dir_nam);
344:                    instream = nfFtpClient.get(mainfilenam);
345:
346:                    while ((c = instream.read(buffer)) > -1) {
347:                        bos.write(buffer, 0, c);
348:                        buftxt.write(buffer, 0, c);
349:                    }
350:                    instream.close();
351:                    bos.flush();
352:                    bos.close();
353:
354:                    txtouting = buftxt.toString();
355:                    if ((txtouting.startsWith("ERROR:")
356:                            || txtouting.indexOf(nfrUsrResBundle
357:                                    .getString("permissiondenied")) >= 0 || txtouting
358:                            .indexOf(nfrUsrResBundle.getString("nosuchfile")) >= 0)) {
359:                        return "ERROR:" + nfrUsrResBundle.getString("error6");
360:                    }
361:                } catch (Exception ex) {
362:                    e = ex;
363:                    performFinalProcessing(e,
364:                            nfrUsrResBundle.getString("ff.4"), nfFtpClient);
365:
366:                } finally {
367:                    try {
368:                        if (instream != null)
369:                            instream.close();
370:                        if (bos != null)
371:                            bos.close();
372:                        if (buftxt != null)
373:                            buftxt.close();
374:                    } catch (IOException ioe) {
375:                    }
376:                }
377:
378:                return mknodfilename;
379:            }
380:
381:            /**
382:             * Delete file
383:             */
384:            String delFTPFile(String username, String password, String machine,
385:                    String share, String szDelFileName, String directory,
386:                    NetFileResource nfrUsrResBundle) throws NetFileException {
387:
388:                FullFtpClient fullFtpClient = null;
389:                Exception e = null;
390:
391:                this .nfRes = nfrUsrResBundle;
392:
393:                try {
394:                    fullFtpClient = initialiseFtpClient(username, password,
395:                            machine, share, directory);
396:                    fullFtpClient.delete(szDelFileName);
397:                    fullFtpClient.closeServer();
398:                } catch (Exception ex) {
399:                    e = ex;
400:                    //performFinalProcessing(e, "Could not delete the file " + szDelFileName, fullFtpClient);
401:                    performFinalProcessing(e, nfrUsrResBundle.getString("ff.5",
402:                            new Object[] { szDelFileName }), fullFtpClient);
403:                }
404:
405:                return nfrUsrResBundle.getString("FileDeleted");
406:            }
407:
408:            /**
409:             * Delete folder
410:             */
411:            String delFTPFolder(String username, String password,
412:                    String machine, String share, String directory,
413:                    NetFileResource nfrUsrResBundle) throws NetFileException {
414:
415:                FullFtpClient fullFtpClient = null;
416:                Exception e = null;
417:
418:                this .nfRes = nfrUsrResBundle;
419:                try {
420:                    fullFtpClient = initialiseFtpClient(username, password,
421:                            machine, share, directory);
422:                    fullFtpClient.cdup();
423:                    String tmp = directory
424:                            .substring(directory.lastIndexOf("/") + 1);
425:                    fullFtpClient.rmdir(tmp);
426:                    fullFtpClient.closeServer();
427:                } catch (Exception ex) {
428:                    e = ex;
429:                    performFinalProcessing(e, nfrUsrResBundle.getString("ff.5",
430:                            new Object[] { directory }), fullFtpClient);
431:                }
432:                return "FolderDeleted";
433:            }
434:
435:            public String[] getFTPDir(String username, String password,
436:                    String machname, String VMSname, String dirS,
437:                    NetFileResource nfrUsrResBundle) throws NetFileException {
438:                return getFTPDir(username, password, machname, VMSname, dirS,
439:                        nfrUsrResBundle, true);
440:            }
441:
442:            private String[] getFTPDir(String username, String password,
443:                    String machname, String VMSname, String dirS,
444:                    NetFileResource nfrUsrResBundle, boolean closeConn)
445:                    throws NetFileException {
446:
447:                FullFtpClient full_ftp_client = null;
448:                Exception e = null;
449:                String[] file_listing = new String[] {};
450:                this .nfRes = nfrUsrResBundle;
451:
452:                try {
453:                    if (this .ffc == null) {
454:                        full_ftp_client = initialiseFtpClient(username,
455:                                password, machname, VMSname, dirS);
456:                    } else {
457:                        full_ftp_client = this .ffc;
458:                        //                full_ftp_client.cd(VMSname + dirS);
459:                    }
460:                    java.util.List names_list = getNamesList(full_ftp_client);
461:                    file_listing = (String[]) (new ArrayList(names_list))
462:                            .toArray(new String[] {});
463:                    java.util.List full_listing = getList(full_ftp_client,
464:                            false);
465:                    String[][] listing = processListings(names_list,
466:                            full_listing);
467:                    int number_of_files = names_list.size();
468:                    file_listing = new String[number_of_files * 4];
469:                    int j = 0;
470:
471:                    for (int i = 0; i < number_of_files; ++i) {
472:
473:                        if (listing[i][1].equals("..")
474:                                || listing[i][1].startsWith(".")) {
475:                            continue;
476:                        } else {
477:                            file_listing[j++] = listing[i][0];
478:                            file_listing[j++] = listing[i][1];
479:                            file_listing[j++] = listing[i][3];
480:                            file_listing[j++] = listing[i][2];
481:                        }
482:                    }
483:
484:                } catch (Exception ex) {
485:                    e = ex;
486:                } finally {
487:                    if (closeConn) {
488:                        try {
489:                            full_ftp_client.quit();
490:                        } catch (Exception ge) {
491:                        }
492:                    }
493:                }
494:                //performFinalProcessing(e,"Could not obtain FTP listing",full_ftp_client);
495:                performFinalProcessing(e, nfrUsrResBundle.getString("ff.6"),
496:                        full_ftp_client);
497:                return file_listing;
498:            }
499:
500:            private java.util.List getNamesList(FullFtpClient full_ftp_client)
501:                    throws Exception {
502:                return getList(full_ftp_client, true);
503:            }
504:
505:            private java.util.List getList(FullFtpClient full_ftp_client,
506:                    boolean names_only) throws Exception {
507:                if (full_ftp_client == null) {
508:                    throw new IllegalArgumentException("null full ftp client");
509:                }
510:                sun.net.TelnetInputStream list = null;
511:                ArrayList v_list = new ArrayList();
512:                if (names_only) {
513:                    list = full_ftp_client.nlist();
514:                } else {
515:                    list = full_ftp_client.list(true);
516:                }
517:
518:                java.io.InputStreamReader ipsr_list = new java.io.InputStreamReader(
519:                        list, this .szEncoding);
520:                java.io.BufferedReader br_list = new java.io.BufferedReader(
521:                        ipsr_list);
522:                String s_input_line = null;
523:                while (true) {
524:                    s_input_line = br_list.readLine();
525:                    if (s_input_line == null)
526:                        break;
527:                    v_list.add(s_input_line);
528:                }
529:                br_list.close();
530:                ipsr_list.close();
531:                list.close();
532:                s_input_line = null;
533:                br_list = null;
534:                ipsr_list = null;
535:                list = null;
536:                return v_list;
537:            }
538:
539:            private String[][] processListings(java.util.List v_file_names,
540:                    java.util.List v_full_listing) throws Exception {
541:
542:                int listing_size = v_full_listing.size();
543:                if (listing_size <= 0)
544:                    return new String[][] {};
545:
546:                String last_entry = (String) (v_full_listing
547:                        .get(listing_size - 1));
548:
549:                boolean is_windows = !(last_entry.startsWith("-")
550:                        || last_entry.startsWith("d")
551:                        || last_entry.startsWith("l")
552:                        || last_entry.startsWith("d")
553:                        || last_entry.startsWith("b")
554:                        || last_entry.startsWith("c")
555:                        || last_entry.startsWith("p")
556:                        || last_entry.startsWith("s") || last_entry
557:                        .startsWith("D"));
558:
559:                String[][] listing = null;
560:                if (is_windows)
561:                    listing = processMSDirectoryListingType(v_file_names,
562:                            v_full_listing);
563:                else
564:                    listing = processUnixDirectoryListingType(v_file_names,
565:                            v_full_listing);
566:
567:                return listing;
568:            }
569:
570:            private void mergeListing(java.util.List fileListing,
571:                    java.util.List fullListing) {
572:                /*
573:                 *  NetFile assumes that both file listing and full file listing are same.
574:                 *  But in cases when they are unequal ( say when the FTP server returns
575:                 *  different listings for file names and full file listing) then it throws
576:                 *  exception to the user without giving him the listings.
577:                 *
578:                 *  This method handles the cases when the fileListing and full listing
579:                 *  Lists are of different sizes.
580:                 *
581:                 *  Assumption: fileListing and fullListing have the files arranged in
582:                 *              the same order except with few special files that are listed
583:                 *              only in the fullListing and not in fileListing.
584:                 */
585:                int fileIndex, listingIndex;
586:                String fileName, fullListingRow;
587:                for (fileIndex = 0, listingIndex = 0; fileIndex < fileListing
588:                        .size(); fileIndex++, listingIndex++) {
589:                    fileName = (String) fileListing.get(fileIndex);
590:                    fullListingRow = (String) fullListing.get(listingIndex);
591:                    if (fullListingRow.indexOf(fileName) != -1) {
592:                        continue;
593:                    } else {
594:                        do {
595:                            fullListing.remove(listingIndex);
596:                            fullListingRow = (String) fullListing
597:                                    .get(listingIndex);
598:                        } while (fullListingRow.indexOf(fileName) == -1);
599:                        fileIndex--;
600:                        listingIndex--;
601:                    }
602:                }
603:            }
604:
605:            private String getModifiedDateFormat(String modifiedTime) {
606:                Date d;
607:                if (modifiedTime.indexOf('-') != -1) {
608:                    SimpleDateFormat format = new SimpleDateFormat(nfRes
609:                            .getString("ff.DateFormat1"), clocale);
610:                    format.setCalendar(new GregorianCalendar(TimeZone
611:                            .getDefault()));
612:                    try {
613:                        d = format.parse(modifiedTime);
614:                    } catch (Exception e) {
615:                        //                logger.log(Level.SEVERE, "Exception: ", e);
616:                        logger.log(Level.SEVERE, "PSSRNF_CSPNSJ2037");
617:                        return null;
618:                    }
619:                } else {
620:                    GregorianCalendar calendar = new GregorianCalendar(TimeZone
621:                            .getDefault());
622:                    String strArray[] = new String[3];
623:                    StringTokenizer stok = new StringTokenizer(modifiedTime,
624:                            " ");
625:                    int tokenCount = stok.countTokens();
626:                    for (int i = 0; i < tokenCount; i++) {
627:                        strArray[i] = stok.nextToken();
628:                    }
629:                    calendar.set(Calendar.MONTH, getMonthCode(strArray[0]));
630:                    calendar.set(Calendar.DATE, Integer.parseInt(strArray[1]));
631:                    String dateStr = strArray[2];
632:                    if (dateStr.indexOf(":") != -1) {
633:                        int colonIndex = dateStr.indexOf(":");
634:                        String hourStr = dateStr.substring(0, colonIndex);
635:                        String minuteStr = dateStr.substring(colonIndex + 1)
636:                                .trim();
637:                        calendar.set(Calendar.HOUR_OF_DAY, Integer
638:                                .parseInt(hourStr));
639:                        calendar.set(Calendar.MINUTE, Integer
640:                                .parseInt(minuteStr));
641:                    } else {
642:                        calendar.set(Calendar.YEAR, Integer.parseInt(dateStr
643:                                .trim()));
644:                    }
645:                    d = calendar.getTime();
646:                }
647:
648:                SimpleDateFormat sdf = new SimpleDateFormat(nfRes
649:                        .getString("ff.DateFormat2"), clocale);
650:                sdf.setCalendar(new GregorianCalendar(TimeZone.getDefault()));
651:                return sdf.format(d);
652:            }
653:
654:            public int getMonthCode(String month) {
655:                int monthCode = -1;
656:                if (month.equalsIgnoreCase("jan")) {
657:                    monthCode = Calendar.JANUARY;
658:                } else if (month.equalsIgnoreCase("feb")) {
659:                    monthCode = Calendar.FEBRUARY;
660:                } else if (month.equalsIgnoreCase("mar")) {
661:                    monthCode = Calendar.MARCH;
662:                } else if (month.equalsIgnoreCase("apr")) {
663:                    monthCode = Calendar.APRIL;
664:                } else if (month.equalsIgnoreCase("may")) {
665:                    monthCode = Calendar.MAY;
666:                } else if (month.equalsIgnoreCase("jun")) {
667:                    monthCode = Calendar.JUNE;
668:                } else if (month.equalsIgnoreCase("jul")) {
669:                    monthCode = Calendar.JULY;
670:                } else if (month.equalsIgnoreCase("aug")) {
671:                    monthCode = Calendar.AUGUST;
672:                } else if (month.equalsIgnoreCase("sep")) {
673:                    monthCode = Calendar.SEPTEMBER;
674:                } else if (month.equalsIgnoreCase("oct")) {
675:                    monthCode = Calendar.OCTOBER;
676:                } else if (month.equalsIgnoreCase("nov")) {
677:                    monthCode = Calendar.NOVEMBER;
678:                } else if (month.equalsIgnoreCase("dec")) {
679:                    monthCode = Calendar.DECEMBER;
680:                }
681:                return monthCode;
682:            }
683:
684:            private String[][] processUnixDirectoryListingType(
685:                    java.util.List v_file_names, java.util.List v_full_listing)
686:                    throws Exception {
687:                if (v_file_names.size() != v_full_listing.size())
688:                    mergeListing(v_file_names, v_full_listing);
689:
690:                int number_of_files = v_file_names.size();
691:                int full_listing_length = v_full_listing.size();
692:
693:                String[][] listing = new String[number_of_files][4];
694:                String file_name = null;
695:                String full_listing_row = null;
696:
697:                for (int i = number_of_files - 1, j = full_listing_length - 1; i >= 0; --i, --j) {
698:                    listing[i][1] = file_name = (String) (v_file_names.get(i));
699:                    full_listing_row = (String) (v_full_listing.get(j));
700:                    /*
701:                     *Following lines mimick the legacy logic of previous getFTPDir()
702:                     *However they are patently wrong. Consider the case of links for
703:                     *example.
704:                     */
705:                    if (full_listing_row.charAt(0) == 'd')
706:                        listing[i][0] = "d";
707:                    else
708:                        listing[i][0] = full_listing_row.charAt(0) + "";
709:                    int k = -1;
710:                    if (listing[i][0].equals("t"))
711:                        continue;//Netware hosts adds total 0 along with filelist
712:                    //so skipping "total 0" from file listing
713:                    if (listing[i][0].equals("l")) {
714:                        k = full_listing_row.indexOf((file_name + " ->")) - 1;
715:                        /*
716:                         *In case of links, we are getting the
717:                         *<from> -> <to>
718:                         *to show up. Hence we are getting the full name
719:                         *from output of "ls -la"
720:                         */
721:                        listing[i][1] = file_name = full_listing_row.substring(
722:                                k, full_listing_row.length());
723:                    } else
724:                        k = full_listing_row.lastIndexOf(file_name) - 1;
725:                    for (; k >= 0; --k)
726:                        if ((full_listing_row.charAt(k) != ' '))
727:                            break;
728:                    int end_of_date = k + 1;
729:                    //Start of time/year
730:                    for (; k >= 0; --k)
731:                        if (full_listing_row.charAt(k) == ' ')
732:                            break;
733:                    //End of day
734:                    for (; k >= 0; --k)
735:                        if ((full_listing_row.charAt(k) != ' '))
736:                            break;
737:                    //Start of day
738:                    for (; k >= 0; --k)
739:                        if (full_listing_row.charAt(k) == ' ')
740:                            break;
741:                    //End of month
742:                    for (; k >= 0; --k)
743:                        if ((full_listing_row.charAt(k) != ' '))
744:                            break;
745:                    //Start of month
746:                    for (; k >= 0; --k)
747:                        if (full_listing_row.charAt(k) == ' ')
748:                            break;
749:                    listing[i][2] = getModifiedDateFormat(full_listing_row
750:                            .substring(k + 1, end_of_date));
751:                    //End of length
752:                    for (; k >= 0; --k)
753:                        if ((full_listing_row.charAt(k) != ' '))
754:                            break;
755:                    int end_of_length = k + 1;
756:                    //Start of length
757:                    for (; k >= 0; --k)
758:                        if (full_listing_row.charAt(k) == ' ')
759:                            break;
760:                    listing[i][3] = full_listing_row.substring(k + 1,
761:                            end_of_length);
762:                }
763:
764:                return listing;
765:            }
766:
767:            private String[][] processMSDirectoryListingType(
768:                    java.util.List v_file_names, java.util.List v_full_listing)
769:                    throws Exception {
770:                int number_of_files = v_file_names.size();
771:                String[][] listing = new String[number_of_files][4];
772:                String full_listing_row = null;
773:
774:                for (int i = number_of_files - 1; i >= 0; --i) {
775:                    listing[i][1] = (String) (v_file_names.get(i));
776:                    full_listing_row = (String) (v_full_listing.get(i));
777:                    if (full_listing_row.indexOf("<DIR>") > 0) {
778:                        listing[i][3] = "0";
779:                        listing[i][0] = "d";
780:                    } else
781:                        listing[i][0] = "-";
782:                    int j = 0;
783:                    for (; j < full_listing_row.length(); ++j)
784:                        if (full_listing_row.charAt(j) == ' ')
785:                            break;
786:                    for (; j < full_listing_row.length(); ++j)
787:                        if ((full_listing_row.charAt(j) != ' '))
788:                            break;
789:
790:                    for (; j < full_listing_row.length(); ++j)
791:                        if (full_listing_row.charAt(j) == ' ')
792:                            break;
793:                    listing[i][2] = getModifiedDateFormat(full_listing_row
794:                            .substring(0, j));
795:                    if (listing[i][3] == null) {
796:                        int start_of_length = -1;
797:                        for (; j < full_listing_row.length(); ++j)
798:                            if ((full_listing_row.charAt(j) != ' '))
799:                                break;
800:                        start_of_length = j;
801:
802:                        for (; j < full_listing_row.length(); ++j)
803:                            if (full_listing_row.charAt(j) == ' ')
804:                                break;
805:
806:                        listing[i][3] = full_listing_row.substring(
807:                                start_of_length, j);
808:                    }
809:                }
810:                return listing;
811:            }
812:
813:            /*    private String getCommonFormat(String date){
814:             StringTokenizer tokenizer = new StringTokenizer(date, "-");
815:             List list = new ArrayList();
816:             while(tokenizer.hasMoreTokens()){
817:             list.add(tokenizer.nextToken());
818:             }
819:
820:             StringBuffer newFormat = new StringBuffer();
821:             String day, month, year;
822:
823:             if(list.size() != 3){
824:             return null;
825:             }
826:
827:             month = getMonthCode((String)list.get(0));
828:             day = (String)list.get(1);
829:             year = getYear((String)list.get(2));
830:
831:             newFormat.append(month);
832:             newFormat.append(" ");
833:             newFormat.append(day);
834:             newFormat.append(" ");
835:             newFormat.append(year);
836:             newFormat.append(" ");
837:
838:             }*/
839:
840:            void rename(String username, String password, String machine,
841:                    String share, String directory, String szOldName,
842:                    String szNewName, NetFileResource nfrUsrResBundle)
843:                    throws NetFileException {
844:
845:                FullFtpClient fullFtpClient = null;
846:                Exception e = null;
847:                this .nfRes = nfrUsrResBundle;
848:
849:                try {
850:                    fullFtpClient = initialiseFtpClient(username, password,
851:                            machine, share, directory);
852:                    fullFtpClient.rename(szOldName, szNewName);
853:                } catch (Exception ex) {
854:                    e = ex;
855:                    if (ex instanceof  FileNotFoundException)
856:                        throw new NetFileException(
857:                                NetFileException.NETFILE_GENERROR_CODE, nfRes
858:                                        .getString("ff.7",
859:                                                new Object[] { szNewName }));
860:                    // File with name {0} might exist or you do not have permissions.
861:                    else
862:                        performFinalProcessing(e, "Could not rename file "
863:                                + szOldName, fullFtpClient);
864:                } finally {
865:                    try {
866:                        if (fullFtpClient != null) {
867:                            fullFtpClient.closeServer();
868:                        }
869:                    } catch (Exception e1) {
870:                    }
871:                }
872:
873:            }
874:
875:            private void performFinalProcessing(Exception ex,
876:                    String szDebugMsg, FullFtpClient ffc)
877:                    throws NetFileException {
878:
879:                if (ex != null) {
880:                    try {
881:                        if (ffc != null) {
882:                            ffc.closeServer();
883:                        }
884:                    } catch (Exception e) {
885:                    }
886:
887:                    writeDebug(szDebugMsg, ex);
888:
889:                    if (ex instanceof  FileNotFoundException) {
890:                        throw new NetFileException(
891:                                NetFileException.NETFILE_GENERROR_CODE, nfRes
892:                                        .getString("ff.8"));
893:                        //"File does not exist or you do not have permissions.");
894:                    } else if (ex instanceof  NetFileException) {
895:                        throw (NetFileException) ex;
896:                    } else {
897:                        throw new NetFileException(
898:                                NetFileException.NETFILE_GENERROR_CODE, nfRes
899:                                        .getString("ff.9"));
900:                        //"Operation could not be performed for unknown reason(s). Please try again.");
901:                    }
902:                }
903:            }
904:
905:            protected FullFtpClient initialiseFtpClient(String username,
906:                    String password, String machine, String share,
907:                    String directory) throws NetFileException {
908:
909:                FullFtpClient ffc = null;
910:
911:                try {
912:                    ffc = new FullFtpClient(machine, this .szEncoding);
913:                    ffc.setMachineToAccess(machine);
914:
915:                } catch (Exception ioe) {
916:                    writeDebug("Failed to Bind on Port 21 to host: " + machine,
917:                            ioe);
918:                    throw new NetFileException(
919:                            NetFileException.NETFILE_GENERROR_CODE, nfRes
920:                                    .getString("ff.10",
921:                                            new Object[] { machine }));
922:                    //"Unable to connect to the host " + machine);
923:                }
924:
925:                try {
926:                    ffc.login(username, password);
927:
928:                } catch (Exception e) {
929:                    writeDebug("Login error to " + machine, e);
930:                    throw new NetFileException(
931:                            NetFileException.NETFILE_GENERROR_CODE, nfRes
932:                                    .getString("ff.11",
933:                                            new Object[] { machine }));
934:                    //"Login failed to " + machine);
935:                }
936:
937:                try {
938:                    ffc.cd(share + directory);
939:
940:                } catch (FileNotFoundException fnfe) {
941:                    writeDebug("Cannot change to directory " + share
942:                            + directory, fnfe);
943:                    throw new NetFileException(
944:                            NetFileException.NETFILE_GENERROR_CODE, nfRes
945:                                    .getString("ff.12", new Object[] { share,
946:                                            directory }));
947:                    //"Could not change to directory " + share + directory + ". Directory might not exist or access is denied.");
948:                } catch (Exception ioe) {
949:                    writeDebug("Cannot change to directory " + share
950:                            + directory, ioe);
951:                    throw new NetFileException(
952:                            NetFileException.NETFILE_GENERROR_CODE, nfRes
953:                                    .getString("ff.13", new Object[] { share,
954:                                            directory }));
955:                    //"Could not change to directory " + share + directory);
956:                }
957:
958:                try {
959:                    ffc.binary();
960:
961:                } catch (Exception ioe) {
962:                    writeDebug("Cannot change mode to binary", ioe);
963:                    throw new NetFileException(
964:                            NetFileException.NETFILE_GENERROR_CODE, nfRes
965:                                    .getString("ff.14"));
966:                    //"Could not change to binary mode to execute FTP commands");
967:                }
968:                return ffc;
969:            }
970:
971:            protected void writeDebug(String szMsg, Exception e) {
972:                if (e != null) {
973:                    //            logger.log(Level.INFO, szMsg, e);
974:                    logger.log(Level.INFO, "PSSRNF_CSPNSJ2038");
975:                } else {
976:                    //            logger.info(szMsg);
977:                    logger.info("PSSRNF_CSPNSJ2039");
978:                }
979:            }
980:
981:            protected void writeErrorDebug(String szError, Exception e) {
982:                if (e != null)
983:                    //            logger.log(Level.SEVERE, szError, e);
984:                    logger.log(Level.SEVERE, "PSSRNF_CSPNSJ2040");
985:                else
986:                    //            logger.severe(szError);
987:                    logger.severe("PSSRNF_CSPNSJ2041");
988:            }
989:
990:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.