Java Code Examples for java.io.File

The following are top voted examples for showing how to use java.io.File. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples.

Example 1
Project: jentrata-msh   File: Zip.java View source code Vote up 16 votes
/**
 * Extracts a set of files compressed in a zip file to a directory.
 * 
 * @param fromFile the zip file.
 * @param dir the directory to which the files to be extracted. Current user
 *            directory will be chosen if it is null.
 * @throws UtilitiesException if there is any error in the extraction.
 */
public static void extract(File fromFile, File dir)
        throws UtilitiesException {
    try {
        if (dir == null) {
            dir = new File(System.getProperty("user.dir"));
        }
        else if (!dir.exists()) {
            dir.mkdirs();
        }

        if (!dir.isDirectory()) {
            throw new UtilitiesException("Invalid output directory: " + dir);
        }

        ZipFile zipFile = new ZipFile(fromFile);
        ArrayList fileEntries = new ArrayList();

        Enumeration zipEntries = zipFile.entries();
        while (zipEntries.hasMoreElements()) {
            ZipEntry zipEntry = (ZipEntry) zipEntries.nextElement();
            if (zipEntry.isDirectory()) {
                new File(dir, zipEntry.getName()).mkdirs();
            }
            else {
                fileEntries.add(zipEntry);
            }
        }

        Iterator allFiles = fileEntries.iterator();
        while (allFiles.hasNext()) {
            ZipEntry fileEntry = (ZipEntry) allFiles.next();
            File destFile = new File(dir, fileEntry.getName());
            destFile.setLastModified(fileEntry.getTime());
            destFile.getParentFile().mkdirs();
            FileOutputStream outs = new FileOutputStream(destFile);
            InputStream ins = zipFile.getInputStream(fileEntry);
            IOHandler.pipe(ins, outs);
            ins.close();
            outs.close();
        }

        zipFile.close();
    }
    catch (Exception e) {
        throw new UtilitiesException("Unable to extract zip file: "
                + fromFile, e);
    }
}
 
Example 2
Project: jentrata-msh   File: Zip.java View source code Vote up 12 votes
/**
 * Compresses a set of files contained in a directory into a zip file.
 * 
 * @param toFile the zip file.
 * @param dir the directory which contains the files to be compressed.
 * @throws UtilitiesException if there is any error in the compression.
 */
public static void compress(File toFile, File dir)
        throws UtilitiesException {
    try {
        if (dir == null || !dir.exists() || !dir.isDirectory()) {
            throw new UtilitiesException("Invalid input directory: " + dir);
        }

        FileOutputStream fos = new FileOutputStream(toFile);
        ZipOutputStream outs = new ZipOutputStream(fos);

        FileSystem fs = new FileSystem(dir);
        Iterator allFiles = fs.getFiles(true).iterator();

        while (allFiles.hasNext()) {
            File srcFile = (File) allFiles.next();
            String filepath = srcFile.getAbsolutePath();
            String dirpath = dir.getAbsolutePath();
            String entryName = filepath.substring(dirpath.length() + 1)
                    .replace('\\', '/');
            ZipEntry zipEntry = new ZipEntry(entryName);
            zipEntry.setTime(srcFile.lastModified());
            FileInputStream ins = new FileInputStream(srcFile);
            outs.putNextEntry(zipEntry);
            IOHandler.pipe(ins, outs);
            outs.closeEntry();
            ins.close();
        }

        outs.close();

    }
    catch (Exception e) {
        throw new UtilitiesException("Unable to compress zip file: "
                + toFile, e);
    }
}
 
Example 3
Project: jentrata-msh   File: EBMSReceiverSender.java View source code Vote up 10 votes
/**
 * Retrieve the payload from the message.<br>
 * 
 * The default receiver stores the payload as a files at the particular
 * place specified in the configuration.  
 */
public void onResponse() throws Exception{
	EBMSMessageData d 	= (EBMSMessageData) this.properties;
	// Get the first element with tagname is "hasMessage".
	String result		= this.getResponseElementText("hasMessage",NS_URI, 0);
	
	if (log != null){
		this.log.log("Received Message id: " + this.getMessageIdToRetreive());			
		this.log.log("Has payload ?      : " + result);
	}
					
	if (Boolean.valueOf(result).booleanValue()){
		// Retreive the actual file path.
		 			
		
		File outputFolder = new File(this.getOutputDirectory());
		if (!outputFolder.exists())
			outputFolder.mkdirs();
		
		// Get payload.
		Payload[] payloads = this.getResponsePayloads();
					
		// For each payload, we get the input stream
		// from the payload and read it to buffer.
		// then open the output file path and write the buffer.
		for (int i = 0; i < payloads.length; i++){
			String filename = "ebms."+this.getMessageIdToRetreive()+".Payload."+i;
			
			File outputFile = new File(outputFolder.getAbsolutePath()+File.separator+filename);
			// Pipe the payload to the designated file.
			NIOHandler.pipe(payloads[i].getInputStream(), new FileOutputStream(outputFile));
		}			
	}
}
 
Example 4
Project: jentrata-msh   File: FileSystem.java View source code Vote up 7 votes
/**
 * Creates a new instance of FileSystem.
 * 
 * @param root the root of this file system. If root is null, it will be set
 *            to the current user directory.
 */
public FileSystem(File root) {
    if (root == null) {
        this.root = new File(System.getProperty("user.dir"));
    }
    else {
        root = root.getAbsoluteFile();

        if (root.isDirectory() || !root.exists()) {
            this.root = root;
        }
        else {
            this.root = root.getParentFile();
        }
    }
}
 
Example 5
Project: MinecraftSecondScreenMod   File: DataStorageDriver.java View source code Vote up 7 votes
private static void writeToFile(File file, ArrayList<String> lines) {
	try {
		getSaveDir().mkdirs();
		file.createNewFile();
		file.setReadable(true);
		file.setWritable(true);
		BufferedWriter writer = new BufferedWriter(new FileWriter(file));
		for (String line : lines) {
			writer.append(line);
			writer.newLine();
		}
		writer.flush();
		writer.close();

	} catch (IOException e) {
		e.printStackTrace();
		Logger.e(TAG, "Failed writing the String Array to the file: " + file.getAbsolutePath(), e);
	}
}
 
Example 6
Project: my-ministry-assistant   File: DBBackupsListFragment.java View source code Vote up 6 votes
private void createBackup() {
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd hh-mm-ss-aaa", Locale.getDefault());
Calendar now = Calendar.getInstance();
String date = dateFormatter.format(now.getTime()).toString();
File intDB = getActivity().getApplicationContext().getDatabasePath(MinistryDatabase.DATABASE_NAME);
File extDB = FileUtils.getExternalDBFile(getActivity().getApplicationContext(), date + ".db");

try {
	if(extDB != null) {
		if(!extDB.exists())
			extDB.createNewFile();
		
		FileUtils.copyFile(intDB, extDB);
		
		reloadAdapter();
		
		Toast.makeText(getActivity(), getActivity().getApplicationContext().getString(R.string.toast_export_text), Toast.LENGTH_SHORT).show();
	}
} catch (IOException e) {
	Toast.makeText(getActivity(), getActivity().getApplicationContext().getString(R.string.toast_export_text_error), Toast.LENGTH_SHORT).show();
}
  }
 
Example 7
Project: jentrata-msh   File: FileSystem.java View source code Vote up 6 votes
/**
 * Removes the files, including the directories, under the specified 
 * directory recursively. The operation ceases when it encounters any error 
 * in removing any file.
 * 
 * @param rootDir the directory under which the files will be removed. 
 * @param isSelfRemoved true if the root directory itself should be removed.
 * @param isDeferAllowed true if the files can be removed on exit when necessary.
 * @return true if and only if all the files are removed successfully.
 */
private boolean remove(File rootDir, boolean isSelfRemoved, boolean isDeferAllowed) {
    File[] subfiles = rootDir.listFiles();
    if (subfiles != null) {
        for (int i=0; i<subfiles.length; i++) {
            if (subfiles[i].isDirectory()) {
                if (!remove(subfiles[i], true, isDeferAllowed)) {
                    if (!isDeferAllowed) {
                        return false;
                    }
                }
            }
            else {
                if (!subfiles[i].delete()) {
                    if (isDeferAllowed) {
                        subfiles[i].deleteOnExit();
                    }
                    else {
                        return false;
                    }
                }
            }
        }
    }
    if (isSelfRemoved) {
        if (!rootDir.delete()) {
            if (isDeferAllowed) {
                rootDir.deleteOnExit() ;
            }
            else {
                return false;
            }
        }
    }
    return true;
}
 
Example 8
Project: sphereMiners   File: AIManager.java View source code Vote up 6 votes
/**
 * This method creates the list of the possible AIs.
 */
private void makeAiList() {

    // create Loader
    File fileloc = new File(AI_FILELOCATION);
    File[] classes = fileloc.listFiles();

    // if there are no files, classes will be null. (See JavaManual)
    if (classes == null) {
       return;
    }

    Arrays.stream(classes).map(f -> f.getName())
                           // only add ais if they are valid (extend SphereMiner2015 class)
                          .filter(f -> f.endsWith(".class"))
                          .map(f -> f.split(".class")[0])
                          .filter(f -> isValidAi(f))
                          .forEach(f -> aiList.add(f));
}
 
Example 9
Project: jentrata-msh   File: PluginRegistry.java View source code Vote up 6 votes
/**
 * Deploys a plugin to the plugin registry.
 * 
 * @param spa the SPA file input stream.
 * @return the plugin ID of the deployed plugin.
 * @throws PluginException if unable to deploy the plugin.
 */
public String deploy(InputStream spa) throws PluginException {
    try {
        File spaFile = File.createTempFile("plugin-", "."+pluginExtension);
        FileOutputStream fos = new FileOutputStream(spaFile); 
        IOHandler.pipe(spa, fos);
        fos.close();
        
        Collection spaFiles = new ArrayList();
        spaFiles.add(spaFile);
        
        Collection spaDirs = deploySpaFiles(spaFiles);
        if (spaDirs.size() < 1) {
            throw new PluginException("Unable to deploy SPA file: "+spaFile);
        }
        
        String id = ((File)spaDirs.iterator().next()).getName();
        Collection createdPlugins = createPlugins(spaDirs);
        if (createdPlugins.size() < 1) {
            throw new PluginException("Unable to create plugin: "+id);
        }
        
        setClasspaths(createdPlugins);
        return id;
    }
    catch (Exception e) {
        throw new PluginException("Unable to deploy plugin", e);
    }
}
 
Example 10
Project: jentrata-msh   File: AttachmentDataSource.java View source code Vote up 6 votes
/** 
 * Constructs an <code>AttachmentDataSource</code> object from a
 * <code>File</code> object.
 * 
 * @param file              <code>File</code> object containing information
 *                          on the file to be loaded.
 * @param contentType       Content type of the file.
 * @param loadToMem         Load all data to memory upon creation
 * @throws IOException 
 */
public AttachmentDataSource(File file, String contentType, 
                            boolean loadToMem)
    throws IOException {

    this.contentType = contentType;
    this.encoding = null;

    if (loadToMem) {
        this.name = file.getName();
        loadData(new FileInputStream(file));
    }
    else {
        this.name = file.getCanonicalPath();
        this.data = null;
        this.offset = 0;
        this.length = file.length();
    }
}
 
Example 11
Project: jentrata-msh   File: Plugin.java View source code Vote up 6 votes
/**
 * Gets the library URLs specified in the plugin descriptor.
 * 
 * @return the library URLs specified in the plugin descriptor.
 * @throws PluginException if the libraries specified in the descriptor are invalid.
 */
private URL[] getLibraryURLs() throws PluginException {
    ArrayList<URL> urls = new ArrayList<URL>();
    for(Library library: libraries) {
        File libFile = new File(pluginFolder, library.getName());
        if (libFile.exists()) {
            try {
                if(libFile.isFile()) {
                    urls.add(libFile.toURI().toURL());
                } else if(libFile.isDirectory()) {
                    urls.add(libFile.toURI().toURL());
                    addNestedJars(libFile, urls);
                }
            }
            catch (MalformedURLException e) {
                throw new PluginException("Invalid library URL", e);
            }
        }
    }
    return (URL[]) urls.toArray(new URL[]{});
}
 
Example 12
Project: aws-toolkit-eclipse   File: AndroidSdkClasspathContainerInitializer.java View source code Vote up 6 votes
private void copySdkJarToProject(IProject project, AndroidSdkInstall sdkInstall) {
    try {
        File sdkJar = sdkInstall.getSdkJar();

        File projectRoot = project.getLocation().toFile();
        File libsDirectory = new File(projectRoot, "libs");
        if (libsDirectory.exists() == false) {
            if (!libsDirectory.mkdir()) throw new Exception("Unable to create project libs directory");
        }

        if (libsDirectory.isDirectory() == false) {
            throw new Exception("Project contains a non-directory file named 'libs' already");
        }

        File destinationFile = new File(libsDirectory, sdkJar.getName());
        if (!destinationFile.exists()) {
            FileUtils.copyFile(sdkJar, destinationFile);
            project.refreshLocal(IResource.DEPTH_ONE, null);
        }
    } catch (Exception e) {
        IStatus status = new Status(IStatus.ERROR, AndroidSDKPlugin.PLUGIN_ID, "Unable to copy AWS SDK for Android jar to project's lib directory", e);
        StatusManager.getManager().handle(status, StatusManager.SHOW | StatusManager.LOG);
    }
}
 
Example 13
Project: BLEConnect   File: UploadFile.java View source code Vote up 6 votes
public UploadFile(Context context, DropboxAPI<?> api, String dropboxPath,
        File file) {
    // We set the context this way so we don't accidentally leak activities
    mContext = context.getApplicationContext();

    mFileLen = file.length();
    mApi = api;
    mPath = dropboxPath;
    mFile = file;

    mDialog = new ProgressDialog(context);
    mDialog.setMax(100);
    mDialog.setMessage("Uploading " + file.getName());
    mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    mDialog.setProgress(0);
    mDialog.setButton("Cancel", new OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            // This will cancel the putFile operation
            mRequest.abort();
        }
    });
    mDialog.show();
}
 
Example 14
Project: dlna   File: FileManager.java View source code Vote up 6 votes
public static String mkSaveFilePath(String uri){
	File file = new File(Environment.getExternalStorageDirectory()+"/MacroDisk/"+ getFormatUri(uri));
	if(!file.exists()){
		file.mkdirs();
	}else{
		if(file.isFile()){
			file.delete();
			file.mkdirs();
		}
	}
	
	return file.getPath();
}
 
Example 15
Project: my-ministry-assistant   File: DBBackupDialogFragment.java View source code Vote up 6 votes
@Override
  public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

File extDBDir = FileUtils.getExternalDBFile(getActivity(), "");
final String[] list = extDBDir.list();
builder.setTitle(getActivity().getApplicationContext().getString(R.string.pref_restore_dialog));

builder.setItems(list, new DialogInterface.OnClickListener() {
	public void onClick(DialogInterface dialog, int which) {
		sListener.dbBackupDialogFragmentSet(list[which]);
	}
});
   
   return builder.create();
  }
 
Example 16
Project: aws-toolkit-eclipse   File: RegionUtils.java View source code Vote up 6 votes
/**
 * Caches the regions file stored in cloudfront to the destination file
 * given. Tries S3 if cloudfront is unavailable.
 *
 * If the file in s3 is older than the one on disk, does nothing.
 */
private static void cacheRegionsFile(File regionsFile) {
    Date regionsFileLastModified = new Date(0);
    if ( !regionsFile.exists() ) {
        regionsFile.getParentFile().mkdirs();
    } else {
        regionsFileLastModified = new Date(regionsFile.lastModified());
    }

    try {
        AmazonS3 s3 =
            AWSClientFactory.getAnonymousS3Client();
        ObjectMetadata objectMetadata =
            s3.getObjectMetadata("aws-vs-toolkit", "ServiceEndPoints.xml");
        if ( objectMetadata.getLastModified()
                    .after(regionsFileLastModified) ) {
            cacheRegionsFile(regionsFile, s3);
        }
    } catch ( Exception e ) {
        AwsToolkitCore.getDefault().logException(
                "Failed to cache regions file", e);
    }
}
 
Example 17
Project: my-ministry-assistant   File: Helper.java View source code Vote up 6 votes
public static boolean renameDB(Context context) {
	/** Create the file */
	File oldDB = context.getDatabasePath(MinistryDatabase.DATABASE_NAME_OLD);
	/** If the file exists we want to rename it to our new DB name :) */
	if(oldDB.exists())
		oldDB.renameTo(context.getDatabasePath(MinistryDatabase.DATABASE_NAME));
	
	return true;
}
 
Example 18
Project: jbosgi   File: ModuleIdentityRepositoryIntegration.java View source code Vote up 6 votes
public ModuleIdentityRepositoryIntegration(ServerEnvironment serverEnvironment) {
    super(Module.getCallerModuleLoader());
    File bundlesDir = serverEnvironment.getBundlesDir();
    if (bundlesDir.isDirectory() == false)
        throw MESSAGES.illegalStateArtifactBaseLocation(bundlesDir);

    modulesDir = new File(bundlesDir.getParent() + File.separator + "modules");
    if (modulesDir.isDirectory() == false)
        throw MESSAGES.illegalStateArtifactBaseLocation(modulesDir);

    bundlesPath = LayeredBundlePathFactory.resolveLayeredBundlePath(serverEnvironment);
}
 
Example 19
Project: aws-toolkit-eclipse   File: DeployUtils.java View source code Vote up 6 votes
private static void copyDirectoryWithTransformationHandler(File srcDir, File destDir, FileTransformationHandler handler) throws IOException {
    if (destDir.exists()) {
        if (destDir.isDirectory() == false) {
            throw new IOException("Destination '" + destDir + "' exists but is not a directory");
        }
    } else {
        if (destDir.mkdirs() == false) {
            throw new IOException("Destination '" + destDir + "' directory cannot be created");
        }
    }
    if (destDir.canWrite() == false) {
        throw new IOException("Destination '" + destDir + "' cannot be written to");
    }
    // recurse
    File[] files = srcDir.listFiles();
    if (files == null) {  // null if security restricted
        throw new IOException("Failed to list contents of " + srcDir);
    }
    for (int i = 0; i < files.length; i++) {
        File copiedFile = new File(destDir, files[i].getName());
        if (files[i].isDirectory()) {
            copyDirectoryWithTransformationHandler(files[i], copiedFile, handler);
        } else {
            handler.copyFromFileToFile(files[i], copiedFile);
        }
    }
}
 
Example 20
Project: webstart   File: DefaultPack200Tool.java View source code Vote up 6 votes
/**
 * [email protected]}
 */
public void repack( File source, File destination, Map<String, String> props )
    throws IOException
{
    File tempFile = new File( source.toString() + ".tmp" );

    try
    {
        pack( source, tempFile, props, false );
        unpack( tempFile, destination, props );
    }
    finally
    {
        deleteFile( tempFile );
    }
}
 
Example 21
Project: jena   File: Location.java View source code Vote up 6 votes
/**
 * Return an absolute filename where relative names are resolved from the
 * location
 */
public String absolute(String filename) {
    File f = new File(filename) ;
    // Location relative.
    if ( !f.isAbsolute() )
        filename = pathname + filename ;
    return filename ;
}
 
Example 22
Project: aws-toolkit-eclipse   File: SdkCredentialsFileContentMonitor.java View source code Vote up 6 votes
SdkCredentialsFileContentMonitor(
        File target,
        long pollingIntervalInMillis,
        FileAlterationListener listener) {

    _target = target;

    // IllegalArgumentException is expected if target.getParentFile == null
    _observer = new FileAlterationObserver(target.getParentFile(), new FileFilter() {
        public boolean accept(File file) {
            return file.equals(_target);
        }
    });

    _monitor = new FileAlterationMonitor(pollingIntervalInMillis);
    _listener = listener;

    _observer.addListener(_listener);
    _monitor.addObserver(_observer);

    // Use daemon thread to avoid thread leakage
    _monitor.setThreadFactory(new ThreadFactory() {
        public Thread newThread(Runnable runnable) {
            Thread t = new Thread(runnable);
            t.setDaemon(true);
            t.setName("aws-credentials-file-monitor-thread");
            return t;
        }
    });
}
 
Example 23
Project: jboss-dmr   File: ValueExpressionResolver.java View source code Vote up 6 votes
/**
 * Resolve a single name in the expression.  Return [email protected] null} if no resolution is possible.  The default
 * implementation (which may be delegated to) checks system properties, environment variables, and a small set of
 * special strings.
 *
 * @param name the name to resolve
 * @return the resolved value, or [email protected] null} for none
 */
protected String resolvePart(String name) {
    if ("/".equals(name)) {
        return File.separator;
    } else if (":".equals(name)) {
        return File.pathSeparator;
    }
    // First check for system property, then env variable
    String val = System.getProperty(name);
    if (val == null && name.startsWith("env."))
        val = System.getenv(name.substring(4));

    return val;
}
 
Example 24
Project: virgo.kernel   File: PropertiesArtifactMBeanTests.java View source code Vote up 6 votes
@Test
public void lifecycle() throws DeploymentException, IOException, InvalidSyntaxException, JMException {
    File artifactFile = new File("build/test.properties");
    
    FileCopyUtils.copy(new File("src/test/resources/test.properties"), artifactFile);
    
    URI artifactUri = artifactFile.toURI();
    
    this.deployer.deploy(artifactUri);
    
    assertConfigurationPresentAndCorrect("foo", "bar");
    
    mBeanServer.invoke(objectName, "stop", null, null);
    
    assertConfigurationNotPresent();
    
    mBeanServer.invoke(objectName, "start", null, null);
    
    assertConfigurationPresentAndCorrect("foo", "bar");
    
    mBeanServer.invoke(objectName, "uninstall", null, null);
    
    assertConfigurationNotPresent();
    assertMBeanNotPresent();
    assertFalse(this.deployer.isDeployed(artifactUri));
}
 
Example 25
Project: maven-autotools   File: SymlinkUtilsTest.java View source code Vote up 6 votes
private static File makeTestRoot()
throws IOException {
    File directory = File.createTempFile("symlinkutils-", "");
    directory.delete();
    directory.mkdir();
    return directory.getCanonicalFile();
}
 
Example 26
Project: android_Findex   File: FileWalker.java View source code Vote up 6 votes
public void walk(File root, String folderName, String storage) {
    File[] list = root.listFiles();
    if (list != null && !isNoMedia(list)) {
        for (File f : list) {
            if (f.isDirectory() && !f.isHidden() && !isNoMediaFolder(f, storage)) {
                walk(f, f.getName(), storage);
            } else {
                if (!f.isHidden() && !f.isDirectory()) {
                    if (!dbUtils.isFileExist(f.getAbsolutePath())) {
                        String name = f.getName();
                        map = MimeTypeMap.getSingleton();
                        String ext = MimeTypeMap.getFileExtensionFromUrl(
                                name.toLowerCase().replace(" ", "")
                        );
                        String type = map.getMimeTypeFromExtension(ext);

                        if (type == null) {
                            type = "*/*";
                        }

                        if (type.contains("video/")) {
                            type = C.TAG_VIDEO;
                        } else if (type.contains("image/")) {
                            type = C.TAG_PICTURES;
                        } else if (type.contains("audio/")) {
                            type = C.TAG_SOUNDS;
                        } else if (type.contains("application/ogg")) {
                            type = C.TAG_SOUNDS;
                        } else {
                            type = C.TAG_DOCUMENTS;
                        }

                        FileInfo fileInfo = new FileInfo();
                        fileInfo.folder = folderName;
                        fileInfo.path = f.getAbsolutePath();
                        fileInfo.name = name;
                        fileInfo.type = type;
                        fileInfo.modified = f.lastModified();
                        fileInfo.size = f.length();
                        fileInfo.storage = storage;
                        dbUtils.write(fileInfo, false);
                    }
                }
            }
        }
    }
}
 
Example 27
Project: mjprof   File: JMXConnection.java View source code Vote up 6 votes
public static void addURL(File file) throws RuntimeException {
    try {
        URL url = file.toURL();
        URLClassLoader classLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
        Class clazz = URLClassLoader.class;

        // Use reflection
        Method method = clazz.getDeclaredMethod("addURL", new Class[]{URL.class});
        method.setAccessible(true);
        method.invoke(classLoader, new Object[]{url});

    } catch (Exception e) {
        throw new RuntimeException(e);

    }
}
 
Example 28
Project: maven-autotools   File: CompileMojo.java View source code Vote up 6 votes
private File extractAutoscanScript(String scriptName)
throws IOException {
    String temporaryScriptName = "." + scriptName + "-";
    if (generatedScriptPostfix != null) {
        temporaryScriptName += generatedScriptPostfix;
    } else {
        int rnd = Math.abs(new Random().nextInt());
        temporaryScriptName += Integer.toString(rnd);
    }
    File script = new File(configureDirectory, temporaryScriptName);
    Map<String, String> variables = makeAutoscanVariables();
    Reader reader =
              new InterpolationFilterReader(
                      new InputStreamReader(
                              getClass().getResourceAsStream(scriptName),
                              "UTF-8"),
                      variables);
    try {
        Writer writer =
                      new OutputStreamWriter(
                              new FileOutputStream(script),
                              "UTF-8");
        try {
            IOUtil.copy(reader, writer);
        } finally {
            IOUtil.close(writer);
        }
    } finally {
        IOUtil.close(reader);
    }
    script.setExecutable(true);
    return script;
}
 
Example 29
Project: Pure-File-Manager   File: EnvironmentTest.java View source code Vote up 6 votes
@Override
protected void runTest() throws Throwable {
    super.runTest();
    Environment.init((Application) getContext().getApplicationContext());
    assertEquals(android.os.Environment.getRootDirectory(),
            Environment.sAndroidRootDirectory);
    assertEquals(File.listRoots()[0], Environment.sRootDirectory);
    final File primaryStorage = android.os.Environment.getExternalStorageDirectory();
    if (primaryStorage != null) {
        boolean primaryStorageFound = false;
        for (final StorageHelper.StorageVolume v : Environment.getStorageVolumes()) {
            if (v.file.equals(primaryStorage)) {
                primaryStorageFound = true;
                break;
            }
        }
        assertTrue(primaryStorageFound);
    }
}
 
Example 30
Project: AmazeFileManager   File: MainActivity.java View source code Vote up 6 votes
public File getUsbDrive() {
    File parent;
    parent = new File("/storage");

    try {
        for (File f : parent.listFiles()) {
            if (f.exists() && f.getName().toLowerCase().contains("usb") && f.canExecute()) {
                return f;
            }
        }
    } catch (Exception e) {
    }
    parent = new File("/mnt/sdcard/usbStorage");
    if (parent.exists() && parent.canExecute())
        return (parent);
    parent = new File("/mnt/sdcard/usb_storage");
    if (parent.exists() && parent.canExecute())
        return parent;

    return null;
}
 
Example 31
Project: Quartz   File: QuartzTweaker.java View source code Vote up 6 votes
@Override
public void acceptOptions(List<String> args, File gameDir, File assetsDir, String profile) {
    Path gamePath = gameDir != null ? gameDir.toPath() : Paths.get("");
    serverJar = gamePath.resolve("bin").resolve(QuartzMain.MINECRAFT_SERVER_LOCAL);
    checkState(Files.exists(serverJar), "Failed to load server JAR");

    boolean jline = true;

    if (args != null && !args.isEmpty()) {
        OptionParser parser = new OptionParser();
        parser.allowsUnrecognizedOptions();
        parser.accepts("gui");
        parser.accepts("nojline"); // TODO: Naming

        OptionSet options = parser.parse(args.toArray(new String[args.size()]));
        gui = options.has("gui");
        jline = !options.has("nojline");
    }

    QuartzLaunch.initialize(gamePath);

    // Initialize jline
    logger.debug("Initializing JLine...");
    try {
        QuartzConsole.initialize(jline);
    } catch (Throwable t) {
        logger.error("Failed to initialize fancy console", t);
        try {
            QuartzConsole.initializeFallback();
        } catch (IOException e) {
            throw new RuntimeException("Failed to initialize terminal", e);
        }
    }

    QuartzConsole.start();
}
 
Example 32
Project: youtrack-worklog-viewer   File: EncryptionUtil.java View source code Vote up 6 votes
private static char[] getSystemPassword() {
    return new StringBuilder(FIXED_PREFIX)
            .append(System.getProperty("user.name"))
            .append(File.pathSeparatorChar)
            .append(System.getProperty("user.home"))
            .append(File.pathSeparatorChar)
            .append(System.getProperty("os.name"))
            .append(File.pathSeparatorChar)
            .append(System.getProperty("os.arch"))
            .toString()
            .toCharArray();
}
 
Example 33
Project: cassandra-dev   File: DatabaseDescriptor.java View source code Vote up 6 votes
public static String getCompactionFileLocation(long expectedCompactedFileSize)
{
  long maxFreeDisk = 0;
  int maxDiskIndex = 0;
  String dataFileDirectory = null;
  for ( int i = 0 ; i < dataFileDirectories_.length ; i++ )
  {
    File f = new File(dataFileDirectories_[i]);
    if( maxFreeDisk < f.getUsableSpace())
    {
      maxFreeDisk = f.getUsableSpace();
      maxDiskIndex = i;
    }
  }
  // Load factor of 0.9 we do not want to use the entire disk that is too risky.
  maxFreeDisk = (long)(0.9 * maxFreeDisk);
  if( expectedCompactedFileSize < maxFreeDisk )
  {
    dataFileDirectory = dataFileDirectories_[maxDiskIndex];
    currentIndex_ = (maxDiskIndex + 1 )%dataFileDirectories_.length ;
  }
  else
  {
    currentIndex_ = maxDiskIndex;
  }
    return dataFileDirectory;
}
 
Example 34
Project: android-ePub-Library   File: Zip4jUtil.java View source code Vote up 6 votes
public static void setFileReadOnly(File file) throws ZipException {
	if (file == null) {
		throw new ZipException("input file is null. cannot set read only file attribute");
	}
	
	if (file.exists()) {
		file.setReadOnly();
	}
}
 
Example 35
Project: AmazeFileManager   File: Futils.java View source code Vote up 6 votes
public long[] getSpaces(String s){
    HFile hFile=new HFile(s);
    if(!hFile.isSmb() && hFile.isDirectory()){
        try {
            File file=new File(s);
            long[] ints=new long[]{file.getTotalSpace(), file.getFreeSpace(),folderSize
                    (new File(hFile.getPath()))};
            return ints;
        } catch (Exception e) {
            return new long[]{-1,-1,-1};
        }
    }
    return new long[]{-1,-1,-1};
}
 
Example 36
Project: fiji   File: MainClassForDebugging.java View source code Vote up 6 votes
public static String findClassName(String path) throws IOException {
	if (path.endsWith(".java"))
		path = path.substring(0, path.length() - 5);
	File pluginsPath =
		new File(Menus.getPlugInsPath()).getCanonicalFile();
	File file = new File(path).getCanonicalFile();
	path = file.getName();
	while ((file = file.getParentFile()) != null &&
			file.compareTo(pluginsPath) != 0)
		path = file.getName() + "." + path;
	return path;
}
 
Example 37
Project: kouchat-android   File: NetworkMessagesTest.java View source code Vote up 6 votes
/**
 * Tests sendFile().
 *
 * Expects: 14394329!SENDFILE#Christian:(1234)[80800]{37563645}a_file.txt
 *
 * @throws CommandException In case the message could not be sent.
 */
@Test
public void testSendFileMessage() throws CommandException {
    final int userCode = 1234;
    final long fileLength = 80800L;
    final String fileName = "a_file.txt";

    final File file = mock(File.class);
    when(file.getName()).thenReturn(fileName);
    when(file.length()).thenReturn(fileLength);
    final int fileHash = file.hashCode(); // Cannot be mocked it seems

    final String info = "(" + userCode + ")" +
            "[" + fileLength + "]" +
            "{" + fileHash + "}" +
            fileName;

    final User user = new User("TestUser", userCode);

    messages.sendFile(user, file);
    verify(service).sendMulticastMsg(createMessage("SENDFILE") + info);
}
 
Example 38
Project: foe   File: FileUtil.java View source code Vote up 6 votes
public static final long getFreeSpace(File dir) {
	// Use JNI to find out the free space on this partition.
	long freeSpace = -1;
	try {
		Class<? extends File> c = dir.getClass();
		Method m = c.getDeclaredMethod("getFreeSpace", new Class<?>[0]);
		if(m != null) {
			Long lFreeSpace = (Long) m.invoke(dir, new Object[0]);
			if(lFreeSpace != null) {
				freeSpace = lFreeSpace.longValue();
				System.err.println("Found free space on node's partition: on " + dir + " = " + SizeUtil.formatSize(freeSpace));
			}
		}
	} catch(NoSuchMethodException e) {
		// Ignore
		freeSpace = -1;
	} catch(Throwable t) {
		System.err.println("Trying to access 1.6 getFreeSpace(), caught " + t);
		freeSpace = -1;
	}
	return freeSpace;
}
 
Example 39
Project: schach   File: StartUpText.java View source code Vote up 6 votes
/**
 * We over-ride the post command processing to allow usDelay to do menu
 * specific processing of some commands.
 * @param inMsg
 * @param inLen
 * @param replyMsg
 * @param replyLen
 */
@Override
protected void postCommand(byte[] inMsg, int inLen, byte[] replyMsg, int replyLen)
{
    if (inMsg[1] == LCP.CLOSE || inMsg[1] == LCP.DELETE)
    {
        if (inMsg[1] == LCP.DELETE)
            try
            {
                File.defrag();
            }
            catch (IOException ioe)
            {
                File.reset();
            }
        Sound.beepSequenceUp();
        if (curMenu != null)
            curMenu.quit();
    }
    if (inMsg[1] == LCP.BOOT)
        // Reboot into firmware update mode. Only supported
        NXT.boot();
    super.postCommand(inMsg, inLen, replyMsg, replyLen);
}
 
Example 40
Project: iot-server-appliances   File: HttpServer.java View source code Vote up 5 votes
private void handleInternal(final HttpRequest request, final HttpResponse response,
							final HttpContext context) throws HttpException, IOException {

	String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
	if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) {
		throw new MethodNotSupportedException(method + " method not supported");
	}

	String target = request.getRequestLine().getUri();
	File file = new File(this.docRoot, URLDecoder.decode(target, "UTF-8"));
	if (!file.exists()) {

		response.setStatusCode(HttpStatus.SC_NOT_FOUND);
		log.severe("File " + file.getPath() + " not found");
		return;

	} else if (!file.canRead()) {

		response.setStatusCode(HttpStatus.SC_FORBIDDEN);
		log.severe("Cannot read file " + file.getPath());
		return;

	} else if (file.isDirectory()) {

		if (target.endsWith("/")) {

			boolean isExist = false;
			for (String index : DEFAULT_INDEX_FILES_LIST) {
				final File t_file = new File(this.docRoot + File.separator + target, index);
				if (t_file.exists()) {
					file = t_file;
					isExist = true;
					break;
				}
			}
			if(!isExist)return;

		} else {
			//redirect browser - doing basically what apache does
			response.setStatusCode(HttpStatus.SC_MOVED_PERMANENTLY);
			String newUrl = target + "/";
			response.setHeader("Location", newUrl);
			return;
		}

	}

	HttpCoreContext coreContext = HttpCoreContext.adapt(context);
	HttpConnection conn = coreContext.getConnection(HttpConnection.class);
	response.setStatusCode(HttpStatus.SC_OK);

	String displayAgentHome = ResourceUtil.getDisplayAgentHome();
	System.setProperty("content.types.user.table",displayAgentHome + File.separator + LauncherConstants.CONF_PATH + File.separator + "content-types.properties");
	String mimeType= URLConnection.guessContentTypeFromName(file.getName());

	NFileEntity body = new NFileEntity(file, ContentType.create(mimeType));
	response.setEntity(body);
	//log.info(conn + ": serving file " + file.getPath());
}
 
Example 41
Project: dlna   File: HttpServer.java View source code Vote up 5 votes
/**
 * Serves file from homeDir and its' subdirectories (only).
 * Uses only URI, ignores all headers and HTTP parameters.
 */
public Response serveFile( String uri, Properties header, File homeDir,
						   boolean allowDirectoryListing )
{
	Response res = null;

	// Make sure we won't die of an exception later
	if ( !homeDir.isDirectory())
		res = new Response( HTTP_INTERNALERROR, MIME_PLAINTEXT,
			"INTERNAL ERRROR: serveFile(): given homeDir is not a directory." );

	if ( res == null )
	{
		// Remove URL arguments
		uri = uri.trim().replace( File.separatorChar, '/' );
		if ( uri.indexOf( '?' ) >= 0 )
			uri = uri.substring(0, uri.indexOf( '?' ));

		// Prohibit getting out of current directory
		if ( uri.startsWith( ".." ) || uri.endsWith( ".." ) || uri.indexOf( "../" ) >= 0 )
			res = new Response( HTTP_FORBIDDEN, MIME_PLAINTEXT,
				"FORBIDDEN: Won't serve ../ for security reasons." );
	}

	File f = new File( homeDir, uri );
	if ( res == null && !f.exists())
		res = new Response( HTTP_NOTFOUND, MIME_PLAINTEXT,
			"Error 404, file not found." );

	// List the directory, if necessary
	if ( res == null && f.isDirectory())
	{
		// Browsers get confused without '/' after the
		// directory, send a redirect.
		if ( !uri.endsWith( "/" ))
		{
			uri += "/";
			res = new Response( HTTP_REDIRECT, MIME_HTML,
				"<html><body>Redirected: <a href=\"" + uri + "\">" +
				uri + "</a></body></html>");
			res.addHeader( "Location", uri );
		}

		if ( res == null )
		{
			// First try index.html and index.htm
			if ( new File( f, "index.html" ).exists())
				f = new File( homeDir, uri + "/index.html" );
			else if ( new File( f, "index.htm" ).exists())
				f = new File( homeDir, uri + "/index.htm" );
			// No index file, list the directory if it is readable
			else if ( allowDirectoryListing && f.canRead() )
			{
				String[] files = f.list();
				String msg = "<html><body><h1>Directory " + uri + "</h1><br/>";

				if ( uri.length() > 1 )
				{
					String u = uri.substring( 0, uri.length()-1 );
					int slash = u.lastIndexOf( '/' );
					if ( slash >= 0 && slash  < u.length())
						msg += "<b><a href=\"" + uri.substring(0, slash+1) + "\">..</a></b><br/>";
				}

				if (files!=null)
				{
					for ( int i=0; i<files.length; ++i )
					{
						File curFile = new File( f, files[i] );
						boolean dir = curFile.isDirectory();
						if ( dir )
						{
							msg += "<b>";
							files[i] += "/";
						}

						msg += "<a href=\"" + encodeUri( uri + files[i] ) + "\">" +
							  files[i] + "</a>";

						// Show file size
						if ( curFile.isFile())
						{
							long len = curFile.length();
							msg += " &nbsp;<font size=2>(";
							if ( len < 1024 )
								msg += len + " bytes";
							else if ( len < 1024 * 1024 )
								msg += len/1024 + "." + (len%1024/10%100) + " KB";
							else
								msg += len/(1024*1024) + "." + len%(1024*1024)/10%100 + " MB";

							msg += ")</font>";
						}
						msg += "<br/>";
						if ( dir ) msg += "</b>";
					}
				}
				msg += "</body></html>";
				res = new Response( HTTP_OK, MIME_HTML, msg );
			}
			else
			{
				res = new Response( HTTP_FORBIDDEN, MIME_PLAINTEXT,
					"FORBIDDEN: No directory listing." );
			}
		}
	}

	try
	{
		if ( res == null )
		{
			// Get MIME type from file name extension, if possible
			String mime = null;
			int dot = f.getCanonicalPath().lastIndexOf( '.' );
			if ( dot >= 0 )
				mime = (String)theMimeTypes.get( f.getCanonicalPath().substring( dot + 1 ).toLowerCase());
			if ( mime == null )
				mime = MIME_DEFAULT_BINARY;

			// Support (simple) skipping:
			long startFrom = 0;
			long endAt = -1;
			String range = header.getProperty( "range" );
			if ( range != null )
			{
				if ( range.startsWith( "bytes=" ))
				{
					range = range.substring( "bytes=".length());
					int minus = range.indexOf( '-' );
					try {
						if ( minus > 0 )
						{
							startFrom = Long.parseLong( range.substring( 0, minus ));
							endAt = Long.parseLong( range.substring( minus+1 ));
						}
					}
					catch ( NumberFormatException nfe ) {}
				}
			}

			// Change return code and add Content-Range header when skipping is requested
			long fileLen = f.length();
			if (range != null && startFrom >= 0)
			{
				if ( startFrom >= fileLen)
				{
					res = new Response( HTTP_RANGE_NOT_SATISFIABLE, MIME_PLAINTEXT, "" );
					res.addHeader( "Content-Range", "bytes 0-0/" + fileLen);
				}
				else
				{
					if ( endAt < 0 )
						endAt = fileLen-1;
					long newLen = endAt - startFrom + 1;
					if ( newLen < 0 ) newLen = 0;

					final long dataLen = newLen;
					FileInputStream fis = new FileInputStream( f ) {
						public int available() throws IOException { return (int)dataLen; }
					};
					fis.skip( startFrom );

					res = new Response( HTTP_PARTIALCONTENT, mime, fis );
					res.addHeader( "Content-Length", "" + dataLen);
					res.addHeader( "Content-Range", "bytes " + startFrom + "-" + endAt + "/" + fileLen);
				}
			}
			else
			{
				res = new Response( HTTP_OK, mime, new FileInputStream( f ));
				res.addHeader( "Content-Length", "" + fileLen);
			}
		}
	}
	catch( IOException ioe )
	{
		res = new Response( HTTP_FORBIDDEN, MIME_PLAINTEXT, "FORBIDDEN: Reading file failed." );
	}

	res.addHeader( "Accept-Ranges", "bytes"); // Announce that the file server accepts partial content requestes
	return res;
}