View Javadoc
1   package org.argeo.eclipse.ui.fs;
2   
3   import java.io.IOException;
4   import java.nio.file.Files;
5   import java.nio.file.Path;
6   import java.nio.file.attribute.FileTime;
7   import java.text.DateFormat;
8   import java.text.SimpleDateFormat;
9   import java.util.Date;
10  
11  import org.argeo.eclipse.ui.EclipseUiUtils;
12  import org.eclipse.jface.viewers.ColumnLabelProvider;
13  
14  /** Expect a {@link Path} as input element */
15  public class NioFileLabelProvider extends ColumnLabelProvider {
16  	private final static FileTime EPOCH = FileTime.fromMillis(0);
17  	private static final long serialVersionUID = 2160026425187796930L;
18  	private final String propName;
19  	private DateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd HH:mm");
20  
21  	// TODO use new formatting
22  	// DateTimeFormatter formatter =
23  	// DateTimeFormatter.ofLocalizedDateTime( FormatStyle.SHORT )
24  	// .withLocale( Locale.UK )
25  	// .withZone( ZoneId.systemDefault() );
26  	public NioFileLabelProvider(String propName) {
27  		this.propName = propName;
28  	}
29  
30  	@Override
31  	public String getText(Object element) {
32  		try {
33  			Path path;
34  			if (element instanceof ParentDir) {
35  //				switch (propName) {
36  //				case FsUiConstants.PROPERTY_SIZE:
37  //					return "-";
38  //				case FsUiConstants.PROPERTY_LAST_MODIFIED:
39  //					return "-";
40  //				// return Files.getLastModifiedTime(((ParentDir) element).getPath()).toString();
41  //				case FsUiConstants.PROPERTY_TYPE:
42  //					return "Folder";
43  //				}
44  				path = ((ParentDir) element).getPath();
45  			} else
46  				path = (Path) element;
47  			switch (propName) {
48  			case FsUiConstants.PROPERTY_SIZE:
49  				if (Files.isDirectory(path))
50  					return "-";
51  				else
52  					return FsUiUtils.humanReadableByteCount(Files.size(path), false);
53  			case FsUiConstants.PROPERTY_LAST_MODIFIED:
54  				if (Files.isDirectory(path))
55  					return "-";
56  				FileTime time = Files.getLastModifiedTime(path);
57  				if (time.equals(EPOCH))
58  					return "-";
59  				else
60  					return dateFormat.format(new Date(time.toMillis()));
61  			case FsUiConstants.PROPERTY_TYPE:
62  				if (Files.isDirectory(path))
63  					return "Folder";
64  				else {
65  					String mimeType = Files.probeContentType(path);
66  					if (EclipseUiUtils.isEmpty(mimeType))
67  						return "Unknown";
68  					else
69  						return mimeType;
70  				}
71  			default:
72  				throw new IllegalArgumentException("Unsupported property " + propName);
73  			}
74  		} catch (IOException ioe) {
75  			throw new FsUiException("Cannot get property " + propName + " on " + element);
76  		}
77  	}
78  }