Example usage for java.io File getUsableSpace

List of usage examples for java.io File getUsableSpace

Introduction

In this page you can find the example usage for java.io File getUsableSpace.

Prototype

public long getUsableSpace() 

Source Link

Document

Returns the number of bytes available to this virtual machine on the partition named by this abstract pathname.

Usage

From source file:org.opencastproject.workingfilerepository.impl.WorkingFileRepositoryImpl.java

/**
 * {@inheritDoc}//w  ww  .j  a  v a 2s  .  c  o  m
 * 
 * @see org.opencastproject.workingfilerepository.api.WorkingFileRepository#getUsableSpace()
 */
public Option<Long> getUsableSpace() {
    File f = new File(rootDirectory);
    return Option.some(f.getUsableSpace());
}

From source file:san.FileSystemImpl.java

/**
* getUsableSapce()/*from   w  w  w .ja  va2  s . c o  m*/
* @param dirPath - directory path
* @param path - path
* @throws - SanException
* @returns - Returns the number of bytes available to this VM
*            in the partition named by this abstract path name
*/
public long getUsableSpace(String dirPath, String path) throws SanException {

    if (RegexStrUtil.isNull(dirPath) || RegexStrUtil.isNull(path)) {
        throw new SanException("getFreeSpace(), dirPath or path is null");
    }

    File dir = getDir(dirPath, path);
    if (dir == null) {
        throw new SanException("getFreeSapce() " + path + dirPath);
    }

    try {
        if (dir.exists()) {
            long usableSpace = dir.getUsableSpace();
            logger.info("usableSpace = " + usableSpace);
            return dir.getUsableSpace();
        } else {
            return 0;
        }
    } catch (Exception e) {
        throw new SanException("error in dir.getUsableSpace()" + e.getMessage(), e);
    }
}

From source file:com.wcs.newsletter.controller.ConfigController.java

public void installDefaultContents() {
    try {/*from w  ww  .j  a va 2 s.c om*/

        long id = CounterLocalServiceUtil.increment();
        ThemeDisplay themeDisplay = LiferayUtil.getThemeDisplay();
        DLFolder folder = DLFolderLocalServiceUtil.createDLFolder(id);
        folder.setName("Webstar-Newsletter");
        folder.setParentFolderId(0);
        folder.setDescription("Folder for default Webstar-Newsletter contents");
        folder.setGroupId(themeDisplay.getScopeGroupId());
        folder.setCompanyId(themeDisplay.getCompanyId());
        folder.setUserId(themeDisplay.getRealUserId());
        folder.setParentFolderId(DLFolderConstants.DEFAULT_PARENT_FOLDER_ID);
        long defaultRepoId = DLFolderConstants.getDataRepositoryId(themeDisplay.getScopeGroupId(),
                DLFolderConstants.DEFAULT_PARENT_FOLDER_ID);
        folder.setRepositoryId(defaultRepoId);
        Date allDate = new Date();
        folder.setCreateDate(allDate);
        folder.setModifiedDate(allDate);
        folder.setLastPostDate(allDate);
        folder = DLFolderLocalServiceUtil.addDLFolder(folder);
        ServiceContext serviceContext = new ServiceContext();
        serviceContext.setScopeGroupId(folder.getGroupId());
        serviceContext.setAddGuestPermissions(true);
        serviceContext.setGuestPermissions(new String[] { ActionKeys.ACCESS });

        long syncId = CounterLocalServiceUtil.increment();
        DLSync foldersSync = DLSyncLocalServiceUtil.createDLSync(syncId);
        foldersSync.setFileId(folder.getFolderId());
        foldersSync.setParentFolderId(folder.getParentFolderId());
        foldersSync.setCompanyId(folder.getCompanyId());
        foldersSync.setFileUuid(folder.getUuid());
        foldersSync.setRepositoryId(folder.getRepositoryId());
        foldersSync.setName(folder.getName());
        foldersSync.setEvent("add");
        foldersSync.setType("folder");
        foldersSync.setVersion("-1");
        foldersSync.setCreateDate(allDate);
        foldersSync.setModifiedDate(allDate);
        DLSyncLocalServiceUtil.updateDLSync(foldersSync);

        /* Confirm tempalte 1*/
        long fileId = CounterLocalServiceUtil.increment();
        InputStream inputStream = getClass().getClassLoader()
                .getResourceAsStream("install/HU_Confirm_Email.html");
        String filename = "Confirm_Template_HU.html";
        File confTemp1 = File.createTempFile("temp", ".tmp");
        FileOutputStream out = new FileOutputStream(confTemp1);
        IOUtils.copy(inputStream, out);

        DLFileEntry templateFile = DLFileEntryServiceUtil.addFileEntry(folder.getGroupId(),
                folder.getRepositoryId(), folder.getFolderId(), confTemp1.getName(), "text/html", filename,
                filename, "", folder.getDefaultFileEntryTypeId(), null, confTemp1, null,
                confTemp1.getUsableSpace(), serviceContext);
        DLFileEntryLocalServiceUtil.updateFileEntry(folder.getUserId(), templateFile.getFileEntryId(), filename,
                "text/html", filename, filename, "", true, templateFile.getFileEntryTypeId(), null, confTemp1,
                null, confTemp1.getUsableSpace(), serviceContext);
        confTemp1.deleteOnExit();

        /* Confirm tempalte 2*/
        fileId = CounterLocalServiceUtil.increment();
        inputStream = getClass().getClassLoader().getResourceAsStream("install/EN_Confirm_Email.html");
        filename = "Confirm_Template_EN.html";
        File confTemp2 = File.createTempFile("temp2", ".tmp");
        out = new FileOutputStream(confTemp2);
        IOUtils.copy(inputStream, out);

        templateFile = DLFileEntryServiceUtil.addFileEntry(folder.getGroupId(), folder.getRepositoryId(),
                folder.getFolderId(), confTemp2.getName(), "text/html", filename, filename, "",
                folder.getDefaultFileEntryTypeId(), null, confTemp2, null, confTemp2.getUsableSpace(),
                serviceContext);
        DLFileEntryLocalServiceUtil.updateFileEntry(folder.getUserId(), templateFile.getFileEntryId(), filename,
                "text/html", filename, filename, "", true, templateFile.getFileEntryTypeId(), null, confTemp2,
                null, confTemp2.getUsableSpace(), serviceContext);
        confTemp2.deleteOnExit();

        /*Set default confirm template to EN version */

        List<NewsletterConfig> configs = NewsletterConfigLocalServiceUtil.findByConfigKey("emailTemplate");
        NewsletterConfig defaultTemplate;
        if (configs.isEmpty()) {
            defaultTemplate = new NewsletterConfigImpl();
            defaultTemplate.setConfigKey("emailTemplate");
            defaultTemplate.setConfigValue(String.valueOf(templateFile.getFileEntryId()));
            NewsletterConfigLocalServiceUtil.addNewsletterConfig(defaultTemplate);
        } else {
            defaultTemplate = configs.get(0);
            defaultTemplate.setConfigValue(String.valueOf(templateFile.getFileEntryId()));
            NewsletterConfigLocalServiceUtil.updateNewsletterConfig(defaultTemplate);
        }

        /* Newsletter tempalte 1*/
        fileId = CounterLocalServiceUtil.increment();
        inputStream = getClass().getClassLoader().getResourceAsStream("install/HU_newsletterTemplate.html");
        filename = "Newsletter_Template_HU.html";
        File newsletterTemp1 = File.createTempFile("temp3", ".tmp");
        out = new FileOutputStream(newsletterTemp1);
        IOUtils.copy(inputStream, out);

        templateFile = DLFileEntryServiceUtil.addFileEntry(folder.getGroupId(), folder.getRepositoryId(),
                folder.getFolderId(), newsletterTemp1.getName(), "text/html", filename, filename, "",
                folder.getDefaultFileEntryTypeId(), null, newsletterTemp1, null,
                newsletterTemp1.getUsableSpace(), serviceContext);
        DLFileEntryLocalServiceUtil.updateFileEntry(folder.getUserId(), templateFile.getFileEntryId(), filename,
                "text/html", filename, filename, "", true, templateFile.getFileEntryTypeId(), null,
                newsletterTemp1, null, newsletterTemp1.getUsableSpace(), serviceContext);
        newsletterTemp1.deleteOnExit();

        /* Newsletter tempalte 2*/
        fileId = CounterLocalServiceUtil.increment();
        inputStream = getClass().getClassLoader().getResourceAsStream("install/EN_newsletterTemplate.html");
        filename = "Newsletter_Template_EN.html";
        File newsletterTemp2 = File.createTempFile("temp4", ".tmp");
        out = new FileOutputStream(newsletterTemp2);
        IOUtils.copy(inputStream, out);

        templateFile = DLFileEntryServiceUtil.addFileEntry(folder.getGroupId(), folder.getRepositoryId(),
                folder.getFolderId(), newsletterTemp2.getName(), "text/html", filename, filename, "",
                folder.getDefaultFileEntryTypeId(), null, newsletterTemp2, null,
                newsletterTemp2.getUsableSpace(), serviceContext);
        DLFileEntryLocalServiceUtil.updateFileEntry(folder.getUserId(), templateFile.getFileEntryId(), filename,
                "text/html", filename, filename, "", true, templateFile.getFileEntryTypeId(), null,
                newsletterTemp2, null, newsletterTemp2.getUsableSpace(), serviceContext);
        newsletterTemp2.deleteOnExit();

        NewsletterConfig defaultsInstalledConfig = new NewsletterConfigImpl();
        defaultsInstalledConfig.setConfigKey("defaultsInstalled");
        defaultsInstalledConfig.setConfigValue("1");
        NewsletterConfigLocalServiceUtil.addNewsletterConfig(defaultsInstalledConfig);

        Category actualCategory = null;
        Locale[] localesForDefaultCategories = LiferayUtil.getAvailableLocales();
        for (Locale local : localesForDefaultCategories) {
            actualCategory = new CategoryImpl();
            actualCategory.setLocale(local.toString());
            actualCategory.setName("Default_" + local);
            CategoryLocalServiceUtil.addCategory(actualCategory);
        }

    } catch (IOException ex) {
        Logger.getLogger(ConfigController.class.getName()).log(Level.SEVERE, null, ex);
    } catch (PortalException ex) {
        Logger.getLogger(ConfigController.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SystemException ex) {
        Logger.getLogger(ConfigController.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.dcm4chee.dashboard.ui.filesystem.FileSystemPanel.java

@Override
public void onBeforeRender() {
    super.onBeforeRender();

    try {//from   ww w  . ja v a2 s.c  o m
        DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode(new FileSystemModel());
        for (String groupname : DashboardDelegator
                .getInstance(
                        (((BaseWicketApplication) getApplication()).getInitParameter("DashboardServiceName")))
                .listAllFileSystemGroups()) {
            FileSystemModel group = new FileSystemModel();

            int index = groupname.indexOf("group=");
            if (index < 0)
                continue;
            group.setDirectoryPath(groupname.substring(index + 6));
            group.setDescription(groupname + ",AET=" + DashboardDelegator.getInstance(
                    (((BaseWicketApplication) getApplication()).getInitParameter("DashboardServiceName")))
                    .getDefaultRetrieveAETitle(groupname));
            group.setGroup(true);
            DefaultMutableTreeNode groupNode;
            rootNode.add(groupNode = new DefaultMutableTreeNode(group));

            File[] fileSystems = null;
            try {
                fileSystems = DashboardDelegator.getInstance(
                        (((BaseWicketApplication) getApplication()).getInitParameter("DashboardServiceName")))
                        .listFileSystemsOfGroup(groupname);
            } catch (MBeanException mbe) {
            }

            if (!((fileSystems == null) || (fileSystems.length == 0))) {
                long minBytesFree = DashboardDelegator.getInstance(
                        (((BaseWicketApplication) getApplication()).getInitParameter("DashboardServiceName")))
                        .getMinimumFreeDiskSpaceOfGroup(groupname);

                for (File file : fileSystems) {
                    FileSystemModel fsm = new FileSystemModel();
                    fsm.setDirectoryPath(file.getName());
                    fsm.setDescription(
                            file.getName().startsWith("tar:") ? file.getName() : file.getAbsolutePath());
                    fsm.setOverallDiskSpace(file.getTotalSpace() / FileSystemModel.MEGA);
                    fsm.setUsedDiskSpace(
                            Math.max((file.getTotalSpace() - file.getUsableSpace()) / FileSystemModel.MEGA, 0));
                    fsm.setFreeDiskSpace(Math.max(file.getUsableSpace() / FileSystemModel.MEGA, 0));
                    fsm.setMinimumFreeDiskSpace(
                            fsm.getOverallDiskSpaceLong() == 0 ? 0 : minBytesFree / FileSystemModel.MEGA);
                    fsm.setUsableDiskSpace(
                            Math.max((file.getUsableSpace() - minBytesFree) / FileSystemModel.MEGA, 0));
                    fsm.setRemainingTime(Math.max((file.getUsableSpace() - minBytesFree) / DashboardDelegator
                            .getInstance((((BaseWicketApplication) getApplication())
                                    .getInitParameter("DashboardServiceName")))
                            .getExpectedDataVolumePerDay(groupname), 0));

                    group.setOverallDiskSpace(group.getOverallDiskSpaceLong() + fsm.getOverallDiskSpaceLong());
                    group.setUsedDiskSpace(group.getUsedDiskSpaceLong() + fsm.getUsedDiskSpaceLong());
                    group.setFreeDiskSpace(group.getFreeDiskSpaceLong() + fsm.getFreeDiskSpaceLong());
                    group.setMinimumFreeDiskSpace(
                            group.getMinimumFreeDiskSpaceLong() + fsm.getMinimumFreeDiskSpaceLong());
                    group.setUsableDiskSpace(group.getUsableDiskSpaceLong() + fsm.getUsableDiskSpaceLong());
                    group.setRemainingTime(group.getRemainingTime() + fsm.getRemainingTime());
                    groupNode.add(new DefaultMutableTreeNode(fsm));
                }
            }
        }

        String[] otherFileSystems = DashboardDelegator
                .getInstance(
                        (((BaseWicketApplication) getApplication()).getInitParameter("DashboardServiceName")))
                .listOtherFileSystems();
        if (otherFileSystems != null && otherFileSystems.length > 0) {

            FileSystemModel group = new FileSystemModel();
            group.setDirectoryPath(
                    new ResourceModel("dashboard.filesystem.group.other").wrapOnAssignment(this).getObject());
            group.setGroup(true);
            group.setRemainingTime(-1);
            DefaultMutableTreeNode groupNode;
            rootNode.add(groupNode = new DefaultMutableTreeNode(group));

            for (String otherFileSystem : otherFileSystems) {
                File file = new File(otherFileSystem);
                FileSystemModel fsm = new FileSystemModel();
                fsm.setDirectoryPath(file.getAbsolutePath());
                fsm.setDescription(file.getName().startsWith("tar:") ? file.getName() : file.getAbsolutePath());
                fsm.setOverallDiskSpace(file.getTotalSpace() / FileSystemModel.MEGA);
                fsm.setUsedDiskSpace(
                        Math.max((file.getTotalSpace() - file.getUsableSpace()) / FileSystemModel.MEGA, 0));
                fsm.setFreeDiskSpace(Math.max(file.getUsableSpace() / FileSystemModel.MEGA, 0));
                fsm.setMinimumFreeDiskSpace(fsm.getOverallDiskSpaceLong() / FileSystemModel.MEGA);
                fsm.setUsableDiskSpace(Math.max(file.getUsableSpace() / FileSystemModel.MEGA, 0));
                fsm.setRemainingTime(-1);

                group.setOverallDiskSpace(group.getOverallDiskSpaceLong() + fsm.getOverallDiskSpaceLong());
                group.setUsedDiskSpace(group.getUsedDiskSpaceLong() + fsm.getUsedDiskSpaceLong());
                group.setFreeDiskSpace(group.getFreeDiskSpaceLong() + fsm.getFreeDiskSpaceLong());
                group.setMinimumFreeDiskSpace(
                        group.getMinimumFreeDiskSpaceLong() + fsm.getMinimumFreeDiskSpaceLong());
                group.setUsableDiskSpace(group.getUsableDiskSpaceLong() + fsm.getUsableDiskSpaceLong());
                group.setVisible(false);
                groupNode.add(new DefaultMutableTreeNode(fsm));
            }
        }

        FileSystemTreeTable fileSystemTreeTable = new FileSystemTreeTable("filesystem-tree-table",
                new DefaultTreeModel(rootNode),
                new IColumn[] {
                        new PropertyTreeColumn(new ColumnLocation(Alignment.LEFT, 25, Unit.PERCENT),
                                new ResourceModel("dashboard.filesystem.table.column.name")
                                        .wrapOnAssignment(this).getObject(),
                                "userObject.directoryPath"),
                        new ImageRenderableColumn(new ColumnLocation(Alignment.MIDDLE, 30, Unit.PROPORTIONAL),
                                new ResourceModel("dashboard.filesystem.table.column.image")
                                        .wrapOnAssignment(this).getObject(),
                                "userObject.directoryPath"),
                        new PropertyRenderableColumn(new ColumnLocation(Alignment.RIGHT, 7, Unit.PERCENT),
                                new ResourceModel("dashboard.filesystem.table.column.overall")
                                        .wrapOnAssignment(this).getObject(),
                                "userObject.overallDiskSpaceString"),
                        new PropertyRenderableColumn(new ColumnLocation(Alignment.RIGHT, 7, Unit.PERCENT),
                                new ResourceModel("dashboard.filesystem.table.column.used")
                                        .wrapOnAssignment(this).getObject(),
                                "userObject.usedDiskSpaceString"),
                        new PropertyRenderableColumn(new ColumnLocation(Alignment.RIGHT, 7, Unit.PERCENT),
                                new ResourceModel("dashboard.filesystem.table.column.free")
                                        .wrapOnAssignment(this).getObject(),
                                "userObject.freeDiskSpaceString"),
                        new PropertyRenderableColumn(new ColumnLocation(Alignment.RIGHT, 7, Unit.PERCENT),
                                new ResourceModel("dashboard.filesystem.table.column.minimumfree")
                                        .wrapOnAssignment(this).getObject(),
                                "userObject.minimumFreeDiskSpaceString"),
                        new PropertyRenderableColumn(new ColumnLocation(Alignment.RIGHT, 7, Unit.PERCENT),
                                new ResourceModel("dashboard.filesystem.table.column.usable")
                                        .wrapOnAssignment(this).getObject(),
                                "userObject.usableDiskSpaceString"),
                        new PropertyRenderableColumn(new ColumnLocation(Alignment.RIGHT, 10, Unit.PERCENT),
                                new ResourceModel("dashboard.filesystem.table.column.remainingtime")
                                        .wrapOnAssignment(this).getObject(),
                                "userObject.remainingTimeString") });
        fileSystemTreeTable.getTreeState().setAllowSelectMultiple(true);
        fileSystemTreeTable.getTreeState().collapseAll();
        fileSystemTreeTable.setRootLess(true);
        addOrReplace(fileSystemTreeTable);
    } catch (Exception e) {
        log.error(this.getClass().toString() + ": " + "onBeforeRender: " + e.getMessage());
        log.debug("Exception: ", e);
        throw new WicketRuntimeException(e.getLocalizedMessage(), e);
    }
}

From source file:org.lockss.util.PlatformUtil.java

public DF getJavaDF(String path) {
    File f = null;
    try {//ww w .j a  va 2s .c om
        f = new File(path).getCanonicalFile();
    } catch (IOException e) {
        f = new File(path).getAbsoluteFile();
    }
    // mirror the df behaviour of returning null if path doesn't exist
    if (!f.exists()) {
        return null;
    }
    DF df = new DF();
    df.path = path;
    df.size = f.getTotalSpace() / 1024;
    df.avail = f.getUsableSpace() / 1024;
    df.used = df.size - (f.getFreeSpace() / 1024);
    df.percent = Math.ceil((df.size - df.avail) * 100.00 / df.size);
    df.percentString = String.valueOf(Math.round(df.percent)) + "%";
    df.percent /= 100.00;
    df.fs = null;
    df.mnt = longestRootFile(f);
    if (log.isDebug2())
        log.debug2(df.toString());
    return df;
}

From source file:org.rhq.core.util.updater.Deployer.java

/**
 * Returns an estimated amount of disk space the deployment will need if it gets installed.
 * @return information on the estimated disk usage
 * @throws Exception if cannot determine the estimated disk usage
 *//*w w w  . ja v a  2 s .c  o m*/
public DeploymentDiskUsage estimateDiskUsage() throws Exception {
    final DeploymentDiskUsage diskUsage = new DeploymentDiskUsage();

    File partition = this.deploymentData.getDestinationDir();
    long usableSpace = partition.getUsableSpace();
    while (usableSpace == 0L && partition != null) {
        partition = partition.getParentFile();
        if (partition != null) {
            usableSpace = partition.getUsableSpace();
        }
    }

    diskUsage.setMaxDiskUsable(usableSpace);

    Set<File> zipFiles = this.deploymentData.getZipFiles();
    for (File zipFile : zipFiles) {
        ZipUtil.walkZipFile(zipFile, new ZipEntryVisitor() {
            public boolean visit(ZipEntry entry, ZipInputStream stream) throws Exception {
                if (!entry.isDirectory()) {
                    final long size = entry.getSize();
                    diskUsage.increaseDiskUsage(size > 0 ? size : 0);
                    diskUsage.incrementFileCount();
                }
                return true;
            }
        });
    }

    Map<File, File> rawFiles = this.deploymentData.getRawFiles();
    for (File rawFile : rawFiles.keySet()) {
        diskUsage.increaseDiskUsage(rawFile.length());
        diskUsage.incrementFileCount();
    }

    return diskUsage;
}

From source file:com.boundlessgeo.geoserver.api.controllers.ImportController.java

/**
 * API endpoint to get space available info when uploading files
 * /* w  w w . j  a v  a  2  s  .  c  o  m*/
 * TODO: If a dedicated file/resource API controller gets created, migrate this method to there
 * TODO: If/when workspace-specific upload limitations are implemented, update this to be 
 *       workspace-specific
 * @return A JSON object containing information about the space available in the workspace
 * @throws IOException 
 */
@RequestMapping(value = "/{wsName:.+}", method = RequestMethod.GET)
public @ResponseBody JSONObj info(@PathVariable String wsName) throws IOException {
    JSONObj obj = new JSONObj();
    Catalog catalog = geoServer.getCatalog();
    WorkspaceInfo ws = findWorkspace(wsName, catalog);

    if (ws != null) {
        obj.put("workspace", ws.getName());
    }
    //Temp dir
    File tmpDir = new File(System.getProperty("java.io.tmpdir"));

    //Global REST upload dir
    String externalRoot = null;
    if (externalRoot == null) {
        externalRoot = RESTUtils.extractMapItem(
                RESTUtils.loadMapfromWorkSpace(ws == null ? null : ws.getName(), catalog), RESTUtils.ROOT_KEY);
    }
    if (externalRoot == null) {
        externalRoot = RESTUtils.extractMapItem(RESTUtils.loadMapFromGlobal(), RESTUtils.ROOT_KEY);
    }
    if (externalRoot == null) {
        externalRoot = Paths.toFile(catalog.getResourceLoader().getBaseDirectory(),
                Paths.path("data", ws == null ? null : ws.getName())).getAbsolutePath();
    }

    File destDir = new File(externalRoot);

    long freeSpace = 0;

    if (tmpDir.exists()) {
        freeSpace = tmpDir.getUsableSpace();
        obj.put("tmpDir", tmpDir.getPath());
        obj.put("tmpSpace", freeSpace);
    }
    if (destDir.exists()) {
        freeSpace = destDir.getUsableSpace();
        obj.put("uploadDir", destDir.getPath());
        obj.put("uploadSpace", freeSpace);

        obj.put("spaceUsed", FileUtils.sizeOfDirectory(destDir));
    }
    //In case the destDir is on a different filesystem than the tmpDir, take the min of both
    if (tmpDir.exists() && destDir.exists()) {
        freeSpace = Math.min(tmpDir.getUsableSpace(), destDir.getUsableSpace());
    }
    obj.put("spaceAvailable", freeSpace);

    return obj;
}

From source file:com.jp.miaulavirtual.DisplayMessageActivity.java

public int downloadFile(String request) {
    URL url2;/*from   www. jav a2s.c om*/
    URLConnection conn;
    int lastSlash;
    Long fileSize = null;
    BufferedInputStream inStream;
    BufferedOutputStream outStream;
    FileOutputStream fileStream;
    String cookies = cookieFormat(scookie); // format cookie for URL setRequestProperty
    final int BUFFER_SIZE = 23 * 1024;
    int id = 1;

    File file = null;

    Log.d("Document", "2 respueesta");
    try {
        // Just resources
        lastSlash = url.toString().lastIndexOf('/');

        // Directory creation
        String root = Environment.getExternalStorageDirectory().toString();
        Boolean isSDPresent = android.os.Environment.getExternalStorageState()
                .equals(android.os.Environment.MEDIA_MOUNTED);
        // check if is there external storage
        if (!isSDPresent) {
            task_status = false;
            id = 9;
        } else {
            String folder;
            if (comunidades) {
                folder = onData.get(2)[1];
            } else {
                folder = onData.get(1)[1];
            }
            folder = folder.replaceAll(
                    "\\d{4}-\\d{4}\\s|\\d{4}-\\d{2}\\s|Documentos\\sde\\s?|Gr\\..+?\\s|\\(.+?\\)", "");
            folder = folder.toString().trim();
            Log.d("Folder", folder);
            File myDir = new File(root + "/Android/data/com.jp.miaulavirtual/files/" + folder);
            myDir.mkdirs();

            // Document creation
            String name = url.toString().substring(lastSlash + 1);
            file = new File(myDir, name);
            Log.d("Document", name);
            fileSize = (long) file.length();

            // Check if we have already downloaded the whole file
            if (file.exists()) {
                dialog.setProgress(100); // full progress if file already donwloaded
            } else {
                // Start the connection with COOKIES (we already verified that the cookies aren't expired and we can use them)
                url2 = new URL(request);
                conn = url2.openConnection();
                conn.setUseCaches(false);
                conn.setRequestProperty("Cookie", cookies);
                conn.setConnectTimeout(10 * 1000);
                conn.setReadTimeout(20 * 1000);
                fileSize = (long) conn.getContentLength();

                // Check if we have necesary space
                if (fileSize >= myDir.getUsableSpace()) {
                    task_status = false;
                    id = 2;
                } else {

                    // Start downloading
                    inStream = new BufferedInputStream(conn.getInputStream());
                    fileStream = new FileOutputStream(file);
                    outStream = new BufferedOutputStream(fileStream, BUFFER_SIZE);
                    byte[] data = new byte[BUFFER_SIZE];
                    int bytesRead = 0;
                    int setMax = (conn.getContentLength() / 1024);
                    dialog.setMax(setMax);

                    while (task_status && (bytesRead = inStream.read(data, 0, data.length)) >= 0) {
                        outStream.write(data, 0, bytesRead);
                        // update progress bar
                        dialog.incrementProgressBy((int) (bytesRead / 1024));
                    }

                    // Close stream
                    outStream.close();
                    fileStream.close();
                    inStream.close();

                    // Delete file if Cancel button
                    if (!task_status) {
                        file.delete();
                        if (myDir.listFiles().length <= 0)
                            myDir.delete();
                        id = 0;
                    }
                }
            }
            Log.d("Status", String.valueOf(task_status));
            // Open file
            if (task_status) {
                Log.d("Type", "Hola2");
                dialog.dismiss();
                Intent intent = new Intent();
                intent.setAction(android.content.Intent.ACTION_VIEW);

                MimeTypeMap mime = MimeTypeMap.getSingleton();
                // Get extension file
                String file_s = file.toString();
                String extension = "";

                int i = file_s.lastIndexOf('.');
                int p = Math.max(file_s.lastIndexOf('/'), file_s.lastIndexOf('\\'));

                if (i > p) {
                    extension = file_s.substring(i + 1);
                }

                // Get extension reference
                String doc_type = mime.getMimeTypeFromExtension(extension);

                Log.d("Type", extension);

                intent.setDataAndType(Uri.fromFile(file), doc_type);
                startActivity(intent);
            }
        }
    } catch (MalformedURLException e) // Invalid URL
    {
        task_status = false;
        if (file.exists()) {
            file.delete();
        }
        id = 3;
    } catch (FileNotFoundException e) // FIle not found
    {
        task_status = false;
        if (file.exists()) {
            file.delete();
        }
        id = 4;
    } catch (SocketTimeoutException e) // time out
    {
        Log.d("Timeout", "Timeout");
        task_status = false;
        if (file.exists()) {
            file.delete();
        }
        id = 7;
    } catch (Exception e) // General error
    {
        task_status = false;
        if (file.exists()) {
            file.delete();
        }
        id = 8;
    }
    Log.d("Type", String.valueOf(id));
    Log.d("StartOk3", "Como he llegado hasta aqu?");
    // notify completion
    Log.d("ID", String.valueOf(id));
    return id;

}

From source file:de.sourcestream.movieDB.MainActivity.java

/**
 * First configure the Universal Image Downloader,
 * then we set the main layout to be activity_main.xml
 * and we add the slide menu items.//ww  w .  j  a v  a2 s . co m
 *
 * @param savedInstanceState If non-null, this activity is being re-constructed from a previous saved state as given here.
 */
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    mTitle = mDrawerTitle = getTitle();

    // load slide menu items
    navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
    ViewGroup header = (ViewGroup) getLayoutInflater().inflate(R.layout.drawer_header, null, false);
    ImageView drawerBackButton = (ImageView) header.findViewById(R.id.drawerBackButton);
    drawerBackButton.setOnClickListener(onDrawerBackButton);
    mDrawerList.addHeaderView(header);
    mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
    // setting the nav drawer list adapter
    mDrawerList.setAdapter(new ArrayAdapter<>(this, R.layout.drawer_list_item, R.id.title, navMenuTitles));

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    if (toolbar != null) {
        setSupportActionBar(toolbar);
        toolbar.bringToFront();
    }

    mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
            mDrawerLayout, /* DrawerLayout object */
            toolbar, R.string.app_name, // nav drawer open - description for accessibility
            R.string.app_name // nav drawer close - description for accessibility
    ) {
        public void onDrawerClosed(View drawerView) {
            super.onDrawerClosed(drawerView);
            // calling onPrepareOptionsMenu() to show search view
            invalidateOptionsMenu();
            syncState();
        }

        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
            // calling onPrepareOptionsMenu() to hide search view
            invalidateOptionsMenu();
            syncState();
        }

        // updates the title, toolbar transparency and search view
        public void onDrawerSlide(View drawerView, float slideOffset) {
            super.onDrawerSlide(drawerView, slideOffset);
            if (slideOffset > .55 && !isDrawerOpen) {
                // opening drawer
                // mDrawerTitle is app title
                getSupportActionBar().setTitle(mDrawerTitle);
                invalidateOptionsMenu();
                isDrawerOpen = true;
            } else if (slideOffset < .45 && isDrawerOpen) {
                // closing drawer
                // mTitle is title of the current view, can be movies, tv shows or movie title
                getSupportActionBar().setTitle(mTitle);
                invalidateOptionsMenu();
                isDrawerOpen = false;
            }
        }

    };
    mDrawerLayout.setDrawerListener(mDrawerToggle);

    // Get the action bar title to set padding
    TextView titleTextView = null;

    try {
        Field f = toolbar.getClass().getDeclaredField("mTitleTextView");
        f.setAccessible(true);
        titleTextView = (TextView) f.get(toolbar);
    } catch (NoSuchFieldException e) {

    } catch (IllegalAccessException e) {

    }
    if (titleTextView != null) {
        float scale = getResources().getDisplayMetrics().density;
        titleTextView.setPadding((int) scale * 15, 0, 0, 0);
    }

    phone = getResources().getBoolean(R.bool.portrait_only);

    searchDB = new SearchDB(getApplicationContext());

    if (savedInstanceState == null) {
        // Check orientation and lock to portrait if we are on phone
        if (phone) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }

        // on first time display view for first nav item
        displayView(1);

        // Use hockey module to check for updates
        checkForUpdates();

        // Universal Loader options and configuration.
        DisplayImageOptions options = new DisplayImageOptions.Builder()
                // Bitmaps in RGB_565 consume 2 times less memory than in ARGB_8888.
                .bitmapConfig(Bitmap.Config.RGB_565).imageScaleType(ImageScaleType.EXACTLY).cacheInMemory(false)
                .showImageOnLoading(R.drawable.placeholder_default)
                .showImageForEmptyUri(R.drawable.placeholder_default)
                .showImageOnFail(R.drawable.placeholder_default).cacheOnDisk(true).build();
        Context context = this;
        File cacheDir = StorageUtils.getCacheDirectory(context);
        // Create global configuration and initialize ImageLoader with this config
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this)
                .diskCache(new UnlimitedDiscCache(cacheDir)) // default
                .defaultDisplayImageOptions(options).build();
        ImageLoader.getInstance().init(config);

        // Check cache size
        long size = 0;
        File[] filesCache = cacheDir.listFiles();
        for (File file : filesCache) {
            size += file.length();
        }
        if (cacheDir.getUsableSpace() < MinFreeSpace || size > CacheSize) {
            ImageLoader.getInstance().getDiskCache().clear();
            searchDB.cleanSuggestionRecords();
        }

    } else {
        oldPos = savedInstanceState.getInt("oldPos");
        currentMovViewPagerPos = savedInstanceState.getInt("currentMovViewPagerPos");
        currentTVViewPagerPos = savedInstanceState.getInt("currentTVViewPagerPos");
        restoreMovieDetailsState = savedInstanceState.getBoolean("restoreMovieDetailsState");
        restoreMovieDetailsAdapterState = savedInstanceState.getBoolean("restoreMovieDetailsAdapterState");
        movieDetailsBundle = savedInstanceState.getParcelableArrayList("movieDetailsBundle");
        castDetailsBundle = savedInstanceState.getParcelableArrayList("castDetailsBundle");
        tvDetailsBundle = savedInstanceState.getParcelableArrayList("tvDetailsBundle");
        currOrientation = savedInstanceState.getInt("currOrientation");
        lastVisitedSimMovie = savedInstanceState.getInt("lastVisitedSimMovie");
        lastVisitedSimTV = savedInstanceState.getInt("lastVisitedSimTV");
        lastVisitedMovieInCredits = savedInstanceState.getInt("lastVisitedMovieInCredits");
        saveInMovieDetailsSimFragment = savedInstanceState.getBoolean("saveInMovieDetailsSimFragment");

        FragmentManager fm = getFragmentManager();
        // prevent the following bug: go to gallery preview -> swap orientation ->
        // go to movies list -> swap orientation -> action bar bugged
        // so if we are not on gallery preview we show toolbar
        if (fm.getBackStackEntryCount() == 0
                || !fm.getBackStackEntryAt(fm.getBackStackEntryCount() - 1).getName().equals("galleryList")) {
            new Handler().post(new Runnable() {
                @Override
                public void run() {
                    if (getSupportActionBar() != null && !getSupportActionBar().isShowing())
                        getSupportActionBar().show();
                }
            });
        }
    }

    // Get reference for the imageLoader
    imageLoader = ImageLoader.getInstance();

    // Options used for the backdrop image in movie and tv details and gallery
    optionsWithFade = new DisplayImageOptions.Builder()
            // Bitmaps in RGB_565 consume 2 times less memory than in ARGB_8888.
            .bitmapConfig(Bitmap.Config.RGB_565).displayer(new FadeInBitmapDisplayer(500))
            .imageScaleType(ImageScaleType.EXACTLY).cacheInMemory(false).showImageOnLoading(R.color.black)
            .showImageForEmptyUri(R.color.black).showImageOnFail(R.color.black).cacheOnDisk(true).build();
    optionsWithoutFade = new DisplayImageOptions.Builder()
            // Bitmaps in RGB_565 consume 2 times less memory than in ARGB_8888.
            .bitmapConfig(Bitmap.Config.RGB_565).imageScaleType(ImageScaleType.EXACTLY).cacheInMemory(false)
            .showImageOnLoading(R.color.black).showImageForEmptyUri(R.color.black)
            .showImageOnFail(R.color.black).cacheOnDisk(true).build();

    // Options used for the backdrop image in movie and tv details and gallery
    backdropOptionsWithFade = new DisplayImageOptions.Builder()
            // Bitmaps in RGB_565 consume 2 times less memory than in ARGB_8888.
            .bitmapConfig(Bitmap.Config.RGB_565).displayer(new FadeInBitmapDisplayer(500))
            .imageScaleType(ImageScaleType.EXACTLY).cacheInMemory(false)
            .showImageOnLoading(R.drawable.placeholder_backdrop)
            .showImageForEmptyUri(R.drawable.placeholder_backdrop)
            .showImageOnFail(R.drawable.placeholder_backdrop).cacheOnDisk(true).build();
    backdropOptionsWithoutFade = new DisplayImageOptions.Builder()
            // Bitmaps in RGB_565 consume 2 times less memory than in ARGB_8888.
            .bitmapConfig(Bitmap.Config.RGB_565).imageScaleType(ImageScaleType.EXACTLY).cacheInMemory(false)
            .showImageOnLoading(R.drawable.placeholder_backdrop)
            .showImageForEmptyUri(R.drawable.placeholder_backdrop)
            .showImageOnFail(R.drawable.placeholder_backdrop).cacheOnDisk(true).build();

    trailerListView = new TrailerList();
    galleryListView = new GalleryList();

    if (currOrientation != getResources().getConfiguration().orientation)
        orientationChanged = true;

    currOrientation = getResources().getConfiguration().orientation;

    iconConstantSpecialCase = 0;
    if (phone) {
        iconMarginConstant = 0;
        iconMarginLandscape = 0;
        DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
        int width = displayMetrics.widthPixels;
        int height = displayMetrics.heightPixels;
        if (width <= 480 && height <= 800)
            iconConstantSpecialCase = -70;

        // used in MovieDetails, CastDetails, TVDetails onMoreIconClick
        // to check whether the animation should be in up or down direction
        threeIcons = 128;
        threeIconsToolbar = 72;
        twoIcons = 183;
        twoIconsToolbar = 127;
        oneIcon = 238;
        oneIconToolbar = 182;
    } else {
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            iconMarginConstant = 232;
            iconMarginLandscape = 300;

            threeIcons = 361;
            threeIconsToolbar = 295;
            twoIcons = 416;
            twoIconsToolbar = 351;
            oneIcon = 469;
            oneIconToolbar = 407;
        } else {
            iconMarginConstant = 82;
            iconMarginLandscape = 0;

            threeIcons = 209;
            threeIconsToolbar = 146;
            twoIcons = 264;
            twoIconsToolbar = 200;
            oneIcon = 319;
            oneIconToolbar = 256;
        }

    }

    dateFormat = android.text.format.DateFormat.getDateFormat(this);
}