001 /* 002 * ftp4j - A pure Java FTP client library 003 * 004 * Copyright (C) 2008-2009 Carlo Pelliccia (www.sauronsoftware.it) 005 * 006 * This program is free software: you can redistribute it and/or modify 007 * it under the terms of the GNU Lesser General Public License version 008 * 2.1, as published by the Free Software Foundation. 009 * 010 * This program is distributed in the hope that it will be useful, 011 * but WITHOUT ANY WARRANTY; without even the implied warranty of 012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 013 * GNU General Public License for more details. 014 * 015 * You should have received a copy of the GNU Lesser General Public 016 * License version 2.1 along with this program. 017 * If not, see <http://www.gnu.org/licenses/>. 018 */ 019 package it.sauronsoftware.ftp4j.listparsers; 020 021 import java.text.DateFormat; 022 import java.text.ParseException; 023 import java.text.SimpleDateFormat; 024 import java.util.Date; 025 import java.util.regex.Matcher; 026 import java.util.regex.Pattern; 027 028 import it.sauronsoftware.ftp4j.FTPFile; 029 import it.sauronsoftware.ftp4j.FTPListParseException; 030 import it.sauronsoftware.ftp4j.FTPListParser; 031 032 /** 033 * This parser can handle the MSDOS-style LIST responses. 034 * 035 * @author Carlo Pelliccia 036 */ 037 public class DOSListParser implements FTPListParser { 038 039 private static final Pattern PATTERN = Pattern 040 .compile("^(\\d{2})-(\\d{2})-(\\d{2})\\s+(\\d{2}):(\\d{2})(AM|PM)\\s+" 041 + "(<DIR>|\\d+)\\s+([^\\\\/*?\"<>|]+)$"); 042 043 private static final DateFormat DATE_FORMAT = new SimpleDateFormat( 044 "MM/dd/yy hh:mm a"); 045 046 public FTPFile[] parse(String[] lines) throws FTPListParseException { 047 int size = lines.length; 048 FTPFile[] ret = new FTPFile[size]; 049 for (int i = 0; i < size; i++) { 050 Matcher m = PATTERN.matcher(lines[i]); 051 if (m.matches()) { 052 String month = m.group(1); 053 String day = m.group(2); 054 String year = m.group(3); 055 String hour = m.group(4); 056 String minute = m.group(5); 057 String ampm = m.group(6); 058 String dirOrSize = m.group(7); 059 String name = m.group(8); 060 ret[i] = new FTPFile(); 061 ret[i].setName(name); 062 if (dirOrSize.equalsIgnoreCase("<DIR>")) { 063 ret[i].setType(FTPFile.TYPE_DIRECTORY); 064 ret[i].setSize(0); 065 } else { 066 long fileSize; 067 try { 068 fileSize = Long.parseLong(dirOrSize); 069 } catch (Throwable t) { 070 throw new FTPListParseException(); 071 } 072 ret[i].setType(FTPFile.TYPE_FILE); 073 ret[i].setSize(fileSize); 074 } 075 String mdString = month + "/" + day + "/" + year + " " + hour 076 + ":" + minute + " " + ampm; 077 Date md; 078 try { 079 md = DATE_FORMAT.parse(mdString); 080 } catch (ParseException e) { 081 throw new FTPListParseException(); 082 } 083 ret[i].setModifiedDate(md); 084 } else { 085 throw new FTPListParseException(); 086 } 087 } 088 return ret; 089 } 090 091 }