Skip to main content
summaryrefslogtreecommitdiffstats
blob: 117ca85d7bf76d81870be86ebbfab2e3f49497ec (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
/*******************************************************************************
 * Copyright (c) 2007, 2009 Oracle. All rights reserved.
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0, which accompanies this distribution
 * and is available at http://www.eclipse.org/legal/epl-v10.html.
 * 
 * Contributors:
 *     Oracle - initial API and implementation
 ******************************************************************************/
package org.eclipse.jpt.gen.internal.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.jar.JarInputStream;
import java.util.jar.Manifest;
import java.util.zip.ZipEntry;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.osgi.service.datalocation.Location;
import org.osgi.framework.Bundle;

/**
 * Collections of utility methods handling files.
 * 
 */
public class FileUtil
{
	
	private static String DELETE_FOLDER_ERR = "The directory %s could not be deleted.";
	private static String DELETE_FILE_ERR = "The file %s could not be deleted.";
	private static String FILE_READONLY_ERR = "The file %s could not be modified because write access is denied.\nPlease make sure that the file is not marked as readonly in the file system.";

	public static void deleteFolder(File folder)
		throws IOException
	{
		File[] files = folder.listFiles();
		//empty the folder first (java.io.file.delete requires it empty)
		if (files != null) {
			for (int i = 0; i < files.length; ++i) {
				File f = files[i];
				if (f.isDirectory())
					deleteFolder(f);
				else
					deletePath(f);
			}
		}
		deletePath(folder);
	}

	public static void deletePath(File f)
		throws IOException
	{
		if (!f.delete()) {
			String msgId = f.isDirectory() ?  DELETE_FOLDER_ERR :  DELETE_FILE_ERR;
			throw new IOException( String.format(msgId,f.getPath()));
		}
	}
	
	public static byte[] readFile(File src)
		throws IOException
	{
		java.io.FileInputStream fin = new java.io.FileInputStream(src);
		try {
			long fileLen = src.length();
			if (fileLen > Integer.MAX_VALUE)
				throw new IOException("file length too big to be read by FileUtil.readFile: " + fileLen);
		
			byte[] bytes = new byte[(int)fileLen];
			fin.read(bytes);
			return bytes;
		}
		finally {
			fin.close();
		}
	}

	public static void writeFile(File dest, byte[] bytes)
		throws IOException
	{
		if (dest.exists() && !dest.canWrite())
			throw new IOException( FILE_READONLY_ERR );  //throw with a clear error because otherwise FileOutputStream throws FileNotFoundException!
		java.io.FileOutputStream fout = new java.io.FileOutputStream(dest.getPath(), false/*append*/);
		try {
			fout.write(bytes);
		}
		finally {
			fout.flush();
			fout.close();
		}
	}

	/**
	 * Returns the url for a file.
	 * This basically the same as file.toUrl() but without the non-sense exception.
	 */
	public static URL getFileUrl(File file) {
		try {
			return file.toURI().toURL();
		} catch (MalformedURLException e) {
			return null; //should not happen as file.toURL() does not really throw an exception
		}
	}

	public static void setFileContent(File file, java.io.InputStream contents) throws java.io.IOException {
		Path path = new Path(file.getAbsolutePath());
		try {
			IFile iFile = ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(path);
			if (iFile == null) {
				throw new IOException("The path " + file + " does not seem to be a valid file path.");
			}
			iFile.setContents(contents, true/*force*/, true/*keepHistory*/, null/*monitor*/);
		} catch (CoreException ex) {
			throw new IOException(ex.getMessage());
		}
	}	
	
    /**
     * Extract the contents of a Jar archive to the specified destination.
     */
    public static void unjar(InputStream in, File dest) throws IOException {
        if (!dest.exists()) {
            dest.mkdirs();
        }
        if (!dest.isDirectory()) {
            throw new IOException("Destination must be a directory.");//$NON-NLS-1$
        }
        JarInputStream jin = new JarInputStream(in);
        byte[] buffer = new byte[1024];

        ZipEntry entry = jin.getNextEntry();
        while (entry != null) {
            String fileName = entry.getName();
            if (fileName.charAt(fileName.length() - 1) == '/') {
                fileName = fileName.substring(0, fileName.length() - 1);
            }
            if (fileName.charAt(0) == '/') {
                fileName = fileName.substring(1);
            }
            if (File.separatorChar != '/') {
                fileName = fileName.replace('/', File.separatorChar);
            }
            File file = new File(dest, fileName);
            if (entry.isDirectory()) {
                // make sure the directory exists
                file.mkdirs();
                jin.closeEntry();
            } else {
                // make sure the directory exists
                File parent = file.getParentFile();
                if (parent != null && !parent.exists()) {
                    parent.mkdirs();
                }

                // dump the file
                OutputStream out = new FileOutputStream(file);
                int len = 0;
                while ((len = jin.read(buffer, 0, buffer.length)) != -1) {
                    out.write(buffer, 0, len);
                }
                out.flush();
                out.close();
                jin.closeEntry();
                file.setLastModified(entry.getTime());
            }
            entry = jin.getNextEntry();
        }
        /* Explicitly write out the META-INF/MANIFEST.MF so that any headers such
         as the Class-Path are seen for the unpackaged jar
         */
        Manifest mf = jin.getManifest();
        if (mf != null) {
            File file = new File(dest, "META-INF/MANIFEST.MF");//$NON-NLS-1$
            File parent = file.getParentFile();
            if (parent.exists() == false) {
                parent.mkdirs();
            }
            OutputStream out = new FileOutputStream(file);
            mf.write(out);
            out.flush();
            out.close();
        }
        jin.close();
    }
    
	//Used to Unzip the a specific folder packed inside a plug-in bundle to the plug-in state location
	public static File extractFilesFromBundle( URL url, Bundle bundle, String path ) throws Exception {
		URL jarUrl = UrlUtil.getJarFileUrl(url);
		File jarFile = new File(jarUrl.getFile() );
		Location configLocation = Platform.getConfigurationLocation();
		String pluginId = bundle.getSymbolicName();
		File configFolder = new File( configLocation.getURL().getFile(), pluginId);
		File templDir = new File( configFolder, path );
		if( !templDir.exists() ){
			FileUtil.unjar( new FileInputStream( jarFile ), configFolder );
			//Delete un-related files and folders
			File[] files = configFolder.listFiles();
			for( File f : files ){
				if( f.isFile() )
					f.delete();
				else if(  templDir.getPath().indexOf( f.getPath() ) !=0  ){
					FileUtil.deleteFolder(f);
				}
			}
		}
		return templDir ;
	}	
}

Back to the top