PageRenderTime 29ms CodeModel.GetById 12ms app.highlight 13ms RepoModel.GetById 1ms app.codeStats 0ms

/edu/uncc/parsets/util/osabstraction/AbstractOS.java

https://code.google.com/p/parsets/
Java | 224 lines | 143 code | 26 blank | 55 comment | 29 complexity | 658637b3cdd7d05fa3b7771caa7b3444 MD5 | raw file
  1package edu.uncc.parsets.util.osabstraction;
  2
  3import java.awt.FileDialog;
  4import java.awt.Frame;
  5import java.io.File;
  6import java.io.FileInputStream;
  7import java.io.FileNotFoundException;
  8import java.io.FileOutputStream;
  9import java.io.IOException;
 10import java.io.InputStream;
 11import java.nio.channels.FileChannel;
 12
 13import javax.swing.JFileChooser;
 14
 15import com.sun.jna.Platform;
 16
 17import edu.uncc.parsets.ParallelSets;
 18import edu.uncc.parsets.data.LocalDB;
 19import edu.uncc.parsets.gui.CombinedFileNameFilter;
 20import edu.uncc.parsets.util.PSLogging;
 21
 22/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\
 23 * Copyright (c) 2009, Robert Kosara, Caroline Ziemkiewicz,
 24 *                     and others (see Authors.txt for full list)
 25 * All rights reserved.
 26 * 
 27 * Redistribution and use in source and binary forms, with or without
 28 * modification, are permitted provided that the following conditions are met:
 29 * 
 30 *    * Redistributions of source code must retain the above copyright
 31 *      notice, this list of conditions and the following disclaimer.
 32 *    * Redistributions in binary form must reproduce the above copyright
 33 *      notice, this list of conditions and the following disclaimer in the
 34 *      documentation and/or other materials provided with the distribution.
 35 *    * Neither the name of UNC Charlotte nor the names of its contributors
 36 *      may be used to endorse or promote products derived from this software
 37 *      without specific prior written permission.
 38 *      
 39 * THIS SOFTWARE IS PROVIDED BY ITS AUTHORS ''AS IS'' AND ANY
 40 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 41 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 42 * DISCLAIMED. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
 43 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 44 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 45 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 46 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 47 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 48 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 49\* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
 50
 51public abstract class AbstractOS {
 52
 53	protected static boolean javaStore = false;
 54	
 55	static {
 56		javaStore = System.getProperty("parsets.javastore", "false").equalsIgnoreCase("true");
 57	}
 58
 59	
 60	private static AbstractOS currentOS;
 61
 62	protected AbstractOS() {
 63	}	
 64	
 65	/**
 66	 * Install the DB when running as a regular application.
 67	 * @param dbFile the location where to install the database
 68	 */
 69	protected void installRegular(File dbFile) {
 70		
 71	}
 72
 73	/**
 74	 * Install the DB when running from the JavaStore. The difference is that
 75	 * NIO classes can't be used, since the db is read from the jar file.
 76	 * @param dbFile the location where to install the database
 77	 */
 78	protected void installJavaStore(File dbFile) {
 79		PSLogging.logger.info("Installing new database at " + dbFile.getAbsolutePath());
 80		File parentDir = dbFile.getParentFile();
 81		if (!parentDir.exists())
 82			if (parentDir.mkdir() == false)
 83				PSLogging.logger.fatal("Could not create parent directory");
 84		
 85		PSLogging.logger.info("Source file: " + this.getClass().getResource("/"+LocalDB.LOCALDBFILENAME));
 86	    InputStream fromStream = null;
 87	    FileOutputStream toStream = null;
 88		try {
 89			fromStream = this.getClass().getResourceAsStream("/"+LocalDB.LOCALDBFILENAME);
 90			toStream = new FileOutputStream(dbFile);
 91		    byte[] buffer = new byte[4096*4];
 92		    int bytesRead;
 93
 94		    while ((bytesRead = fromStream.read(buffer)) != -1)
 95		    	toStream.write(buffer, 0, bytesRead);
 96		} catch (Exception e) {
 97			PSLogging.logger.error("Error installing DB", e);
 98		} finally {
 99			if (fromStream != null) {
100				try {
101					fromStream.close();
102				} catch (IOException e) {
103				}
104			}
105			if (toStream != null) {
106				try {
107					toStream.close();
108				} catch (IOException e) {
109				}
110			}
111		}
112	}
113	
114	public String getLocalDBPath(String dbFileName) {
115		String dbPath = getLocalDBDir()+File.separatorChar+ParallelSets.PROGRAMNAME+File.separatorChar+dbFileName;
116		File dbFile = new File(dbPath);
117		if (!dbFile.exists()) {
118			if (javaStore)
119				installJavaStore(dbFile);
120			else
121				installRegular(dbFile);
122		}
123		return dbPath;
124	}
125	
126	public abstract String getLocalDBDir();
127
128	/**
129	 * Call determineOS before calling this function.
130	 * 
131	 * @return The current OS object, or null if not supported.
132	 */
133	public static AbstractOS getCurrentOS() {
134		return currentOS;
135	}
136	
137	public static void determineOS() {
138		if (Platform.isMac())
139			currentOS = new MacOSX();
140		else if (Platform.isWindows())
141			currentOS = new Windows();
142		else if (Platform.isLinux()) // may eventually include more Unices
143			currentOS = new Linux();
144		else {
145			PSLogging.logger.fatal("OS not supported.");
146		}
147	}
148	
149	// Based on code from
150	// http://stackoverflow.com/questions/106770/standard-concise-way-to-copy-a-file-in-java
151	public static void copyFileNIO(File sourceFile, File destFile) {
152		PSLogging.logger.info("Copying "+sourceFile.getAbsolutePath()+" to "+destFile.getAbsolutePath());
153		if (!destFile.exists()) {
154			try {
155				destFile.createNewFile();
156			} catch (IOException e) {
157				PSLogging.logger.error("Could not create destination file.", e);
158			}
159		}
160
161		FileChannel source = null;
162		FileChannel destination = null;
163		try {
164			source = new FileInputStream(sourceFile).getChannel();
165			destination = new FileOutputStream(destFile).getChannel();
166			destination.transferFrom(source, 0, source.size());
167		} catch (FileNotFoundException e) {
168			PSLogging.logger.error("Source file not found.", e);
169		} catch (IOException e) {
170			PSLogging.logger.error("IO Error during copy.", e);
171		} finally {
172			if (source != null) {
173				try {
174					source.close();
175				} catch (IOException e) {
176					PSLogging.logger.error("Error closing source file.", e);
177				}
178			}
179			if (destination != null) {
180				try {
181					destination.close();
182				} catch (IOException e) {
183					PSLogging.logger.error("Error closing destination file.", e);
184				}
185			}
186		}
187	}
188
189	/**
190	 * 
191	 * @param frame the window to block
192	 * @param fileFilter The {@link CombinedFileNameFilter} to use
193	 * @param mode Either {@link FileDialog#LOAD} or {@link FileDialog#SAVE}
194	 * @return
195	 */
196	public String showDialog(Frame frame, CombinedFileNameFilter fileFilter, int mode) {
197		// TODO: start in user's home directory
198	    JFileChooser fileChooser = new JFileChooser(new File("."));
199	    if (fileFilter != null)
200	    	fileChooser.setFileFilter(fileFilter);
201	    int result = 0;
202	    if (mode == FileDialog.LOAD)
203	    	result = fileChooser.showOpenDialog(frame);
204	    else
205	    	result = fileChooser.showSaveDialog(frame);
206	    if (result == JFileChooser.APPROVE_OPTION) {
207	    	if (fileFilter.accept(fileChooser.getSelectedFile()))
208		    	return fileChooser.getSelectedFile().getAbsolutePath();
209	    	else
210	    		return fileChooser.getSelectedFile().getAbsolutePath()+fileFilter.getExtension();
211	    } else
212	    	return null;
213	}
214
215	public abstract String shortName();
216
217	/**
218	 * Shortcut, because we need to check in a few places.
219	 */
220	public boolean isMacOSX() {
221		return false;
222	}
223	
224}