001 /* 002 * Copyright 2002-2004 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not 005 * use this file except in compliance with the License. You may obtain a copy of 006 * the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 012 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 013 * License for the specific language governing permissions and limitations under 014 * the License. 015 */ 016 package org.springframework.richclient.filechooser; 017 018 import java.io.File; 019 import java.io.IOException; 020 021 import org.springframework.rules.closure.Closure; 022 import org.springframework.rules.constraint.Constraint; 023 import org.springframework.core.io.Resource; 024 import org.springframework.rules.factory.Constraints; 025 026 /** 027 * @author Keith Donald 028 */ 029 public class FileChecks { 030 private static FileExists exists = new FileExists(); 031 032 private static FileIsFile file = new FileIsFile(); 033 034 private static FileIsReadable readable = new FileIsReadable(); 035 036 private static FileConverter fileConverter = new FileConverter(); 037 038 private FileChecks() { 039 040 } 041 042 public static Constraint readableFileCheck() { 043 Constraints c = Constraints.instance(); 044 Constraint checks = c.all(new Constraint[] { exists, file, readable }); 045 return c.testResultOf(fileConverter, checks); 046 } 047 048 public static class FileExists implements Constraint { 049 public boolean test(Object argument) { 050 File f = (File)argument; 051 return f != null && f.exists(); 052 } 053 } 054 055 public static class FileIsFile implements Constraint { 056 public boolean test(Object argument) { 057 File f = (File)argument; 058 return f != null && !f.isDirectory(); 059 } 060 } 061 062 public static class FileIsReadable implements Constraint { 063 public boolean test(Object argument) { 064 File f = (File)argument; 065 return f != null && f.canRead(); 066 } 067 } 068 069 public static class FileConverter implements Closure { 070 public Object call(Object argument) { 071 File f; 072 if (argument == null) { 073 return null; 074 } 075 if (argument instanceof File) { 076 return argument; 077 } 078 if (argument instanceof String) { 079 f = new File((String)argument); 080 } 081 else if (argument instanceof Resource) { 082 try { 083 f = ((Resource)argument).getFile(); 084 } 085 catch (IOException e) { 086 return null; 087 } 088 } 089 else { 090 f = (File)argument; 091 } 092 return f; 093 } 094 } 095 096 }