Example usage for org.apache.commons.io.filefilter TrueFileFilter INSTANCE

List of usage examples for org.apache.commons.io.filefilter TrueFileFilter INSTANCE

Introduction

In this page you can find the example usage for org.apache.commons.io.filefilter TrueFileFilter INSTANCE.

Prototype

IOFileFilter INSTANCE

To view the source code for org.apache.commons.io.filefilter TrueFileFilter INSTANCE.

Click Source Link

Document

Singleton instance of true filter.

Usage

From source file:mx.itesm.imb.EcoreImbEditor.java

@SuppressWarnings("unchecked")
private static void writeSelectionAspect(final File ecoreProject, final String typesPackage,
        final List<String> types) {
    Writer writer;//  www .ja  v a2 s. com
    String packageName;
    VelocityContext context;
    StringBuilder validTypes;
    Collection<File> contributorFiles;

    try {
        validTypes = new StringBuilder();
        for (String type : types) {
            if (!type.toLowerCase().equals("system")) {
                validTypes.append("validTypes.add(\"" + type + "\");\n");
            }
        }

        contributorFiles = FileUtils.listFiles(
                new File(ecoreProject.getParent(), ecoreProject.getName() + ".editor"), new IOFileFilter() {
                    @Override
                    public boolean accept(File dir, String file) {
                        return file.endsWith("Contributor.java");
                    }

                    @Override
                    public boolean accept(File file) {
                        return file.getName().endsWith("Contributor.java");
                    }
                }, TrueFileFilter.INSTANCE);

        for (File contributor : contributorFiles) {
            context = new VelocityContext();
            packageName = contributor.getPath()
                    .substring(contributor.getPath().indexOf("src") + "src".length() + 1,
                            contributor.getPath().indexOf(contributor.getName().replace(".java", "")) - 1)
                    .replace('/', '.');

            context.put("validTypes", validTypes);
            context.put("packageName", packageName);
            context.put("typesPackage", typesPackage);
            context.put("contributor", contributor.getName().replace(".java", ""));

            writer = new FileWriter(new File(contributor.getParentFile(), "SelectionAspect.aj"));
            EcoreImbEditor.selectionTemplate.merge(context, writer);
            writer.close();
            break;
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("Unable to update selection service: " + e.getMessage());
    }
}

From source file:betullam.xmlmodifier.XMLmodifier.java

private void makeBackupFiles(Set<File> filesToModify) {

    for (File fileToModify : filesToModify) {

        String fileToModifyName = fileToModify.getName();
        File backupDirectory = fileToModify.getParentFile();

        // Copy existing backup file to a new temporary file (add + 1 to number-suffix), so that nothing gets overwritten
        for (File existingBackupFile : FileUtils.listFiles(backupDirectory,
                new RegexFileFilter(fileToModifyName + "(\\.\\d+)"), TrueFileFilter.INSTANCE)) {
            String fileName = existingBackupFile.getName();

            // Get number-suffix from existing backup-files and add 1
            Pattern p = Pattern.compile("xml\\.\\d+");
            Matcher m = p.matcher(fileName);
            boolean b = m.find();
            int oldBackupNo = 0;
            int newBackupNo = 0;
            if (b) {
                oldBackupNo = Integer.parseInt(m.group(0).replace("xml.", ""));
                newBackupNo = oldBackupNo + 1;
            }// w w  w .j  a va 2s. c  o  m

            // Create temporary files:
            String newTempBackupFilename = "";
            File newTempBackupFile = null;

            if (fileName.matches(fileToModifyName + ".[\\d]*")) {
                newTempBackupFilename = fileToModifyName + "." + newBackupNo + ".temp";
                newTempBackupFile = new File(backupDirectory + File.separator + newTempBackupFilename);
            }

            try {
                // Copy existing file to temporary backup-file with new filename:
                FileUtils.copyFile(existingBackupFile, newTempBackupFile);
            } catch (IOException e) {
                e.printStackTrace();
            }

            // Delete the existing old backup file:
            existingBackupFile.delete();
        }

        // Remove the ".temp" suffix from the newly created temporary backup-files
        for (File tempBackupFile : FileUtils.listFiles(backupDirectory, new RegexFileFilter(".*\\.temp"),
                TrueFileFilter.INSTANCE)) {
            String newBackupFilename = tempBackupFile.getName().replace(".temp", "");
            File newBackupFile = new File(backupDirectory + File.separator + newBackupFilename);

            try {
                // Copy temporary file to real backup-file with new filename:
                FileUtils.copyFile(tempBackupFile, newBackupFile);
            } catch (IOException e) {
                e.printStackTrace();
            }

            // Delete temporary backup file:
            tempBackupFile.delete();
        }

        // Copy meta.xml and/or meta_anchor.xml and append the suffix ".1" to it, so that it becomes the newest backup file
        for (File productiveFile : FileUtils.listFiles(backupDirectory,
                new WildcardFileFilter(fileToModifyName, IOCase.INSENSITIVE), TrueFileFilter.INSTANCE)) {
            // Copy current productive file and append ".1" so that it gets the newes backup-file: 
            File newBackupFile = new File(productiveFile.getAbsoluteFile() + ".1");
            try {
                FileUtils.copyFile(productiveFile, newBackupFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // Remove all files with a suffix bigger than 9, because Goobi keeps only max. 9 backup files:
        for (File backupFileHigher9 : FileUtils.listFiles(backupDirectory,
                new RegexFileFilter(fileToModifyName + "(\\.\\d{2,})"), TrueFileFilter.INSTANCE)) {
            backupFileHigher9.delete();
        }
    }
}

From source file:bioLockJ.AppController.java

private static void recursiveFileDelete(final File dir) {
    final Collection<File> files = FileUtils.listFiles(dir, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE);
    for (final File f : files) {
        Log.addMsg("Delete: " + f.getAbsolutePath());
        f.delete();//from w  w  w  . j a  va 2 s.  co  m
    }
}

From source file:com.revetkn.ios.analyzer.ArtworkAnalyzer.java

/** @return Mapping of files that could potentially include image references -> their textual contents. */
protected Map<File, String> extractContentsOfReferencingFiles(File projectRootDirectory) throws IOException {
    Map<File, String> referencingFilesToContents = new HashMap<File, String>();

    for (File textFile : listFiles(projectRootDirectory,
            new SuffixFileFilter(new ArrayList<String>(referencingFileSuffixes())), TrueFileFilter.INSTANCE)) {
        String contents = readFileToString(textFile);

        if (contents.length() > 0)
            referencingFilesToContents.put(textFile, contents);
    }//from   w  w w  .j  av  a  2s  .  c  o m

    return referencingFilesToContents;
}

From source file:ching.icecreaming.action.ViewAction.java

@Action(value = "view", results = { @Result(name = "login", location = "edit.jsp"),
        @Result(name = "input", location = "view.jsp"), @Result(name = "success", location = "view.jsp"),
        @Result(name = "error", location = "error.jsp") })
public String execute() throws Exception {
    Enumeration enumerator = null;
    String[] array1 = null, array2 = null;
    int int1 = -1, int2 = -1, int3 = -1;
    InputStream inputStream1 = null;
    OutputStream outputStream1 = null;
    java.io.File file1 = null, file2 = null, dir1 = null;
    List<File> files = null;
    HttpHost httpHost1 = null;//from   w ww . j  a v a 2  s.  c  o  m
    HttpGet httpGet1 = null, httpGet2 = null;
    HttpPut httpPut1 = null;
    URI uri1 = null;
    URL url1 = null;
    DefaultHttpClient httpClient1 = null;
    URIBuilder uriBuilder1 = null, uriBuilder2 = null;
    HttpResponse httpResponse1 = null, httpResponse2 = null;
    HttpEntity httpEntity1 = null, httpEntity2 = null;
    List<NameValuePair> nameValuePair1 = null;
    String string1 = null, string2 = null, string3 = null, string4 = null, return1 = LOGIN;
    XMLConfiguration xmlConfiguration = null;
    List<HierarchicalConfiguration> list1 = null, list2 = null;
    HierarchicalConfiguration hierarchicalConfiguration2 = null;
    DataModel1 dataModel1 = null;
    DataModel2 dataModel2 = null;
    List<DataModel1> listObject1 = null, listObject3 = null;
    org.joda.time.DateTime dateTime1 = null, dateTime2 = null;
    org.joda.time.Period period1 = null;
    PeriodFormatter periodFormatter1 = new PeriodFormatterBuilder().appendYears()
            .appendSuffix(String.format(" %s", getText("year")), String.format(" %s", getText("years")))
            .appendSeparator(" ").appendMonths()
            .appendSuffix(String.format(" %s", getText("month")), String.format(" %s", getText("months")))
            .appendSeparator(" ").appendWeeks()
            .appendSuffix(String.format(" %s", getText("week")), String.format(" %s", getText("weeks")))
            .appendSeparator(" ").appendDays()
            .appendSuffix(String.format(" %s", getText("day")), String.format(" %s", getText("days")))
            .appendSeparator(" ").appendHours()
            .appendSuffix(String.format(" %s", getText("hour")), String.format(" %s", getText("hours")))
            .appendSeparator(" ").appendMinutes()
            .appendSuffix(String.format(" %s", getText("minute")), String.format(" %s", getText("minutes")))
            .appendSeparator(" ").appendSeconds().minimumPrintedDigits(2)
            .appendSuffix(String.format(" %s", getText("second")), String.format(" %s", getText("seconds")))
            .printZeroNever().toFormatter();
    if (StringUtils.isBlank(urlString) || StringUtils.isBlank(wsType)) {
        urlString = portletPreferences.getValue("urlString", "/");
        wsType = portletPreferences.getValue("wsType", "folder");
    }
    Configuration propertiesConfiguration1 = new PropertiesConfiguration("system.properties");
    timeZone1 = portletPreferences.getValue("timeZone", TimeZone.getDefault().getID());
    enumerator = portletPreferences.getNames();
    if (enumerator.hasMoreElements()) {
        array1 = portletPreferences.getValues("server", null);
        if (array1 != null) {
            if (ArrayUtils.isNotEmpty(array1)) {
                for (int1 = 0; int1 < array1.length; int1++) {
                    switch (int1) {
                    case 0:
                        sid = array1[int1];
                        break;
                    case 1:
                        uid = array1[int1];
                        break;
                    case 2:
                        pid = array1[int1];
                        break;
                    case 3:
                        alias1 = array1[int1];
                        break;
                    default:
                        break;
                    }
                }
                sid = new String(Base64.decodeBase64(sid.getBytes()));
                uid = new String(Base64.decodeBase64(uid.getBytes()));
                pid = new String(Base64.decodeBase64(pid.getBytes()));
            }
            return1 = INPUT;
        } else {
            return1 = LOGIN;
        }
    } else {
        return1 = LOGIN;
    }

    if (StringUtils.equals(urlString, "/")) {

        if (listObject1 != null) {
            listObject1.clear();
        }
        if (session.containsKey("breadcrumbs")) {
            session.remove("breadcrumbs");
        }
    } else {
        array2 = StringUtils.split(urlString, "/");
        listObject1 = (session.containsKey("breadcrumbs")) ? (List<DataModel1>) session.get("breadcrumbs")
                : new ArrayList<DataModel1>();
        int2 = array2.length - listObject1.size();
        if (int2 > 0) {
            listObject1.add(new DataModel1(urlString, label1));
        } else {
            int2 += listObject1.size();
            for (int1 = listObject1.size() - 1; int1 >= int2; int1--) {
                listObject1.remove(int1);
            }
        }
        session.put("breadcrumbs", listObject1);
    }
    switch (wsType) {
    case "folder":
        break;
    case "reportUnit":
        try {
            dateTime1 = new org.joda.time.DateTime();
            return1 = INPUT;
            httpClient1 = new DefaultHttpClient();
            if (StringUtils.equals(button1, getText("Print"))) {
                nameValuePair1 = new ArrayList<NameValuePair>();
                if (listObject2 != null) {
                    if (listObject2.size() > 0) {
                        for (DataModel2 dataObject2 : listObject2) {
                            listObject3 = dataObject2.getOptions();
                            if (listObject3 == null) {
                                string2 = dataObject2.getValue1();
                                if (StringUtils.isNotBlank(string2))
                                    nameValuePair1.add(new BasicNameValuePair(dataObject2.getId(), string2));
                            } else {
                                for (int1 = listObject3.size() - 1; int1 >= 0; int1--) {
                                    dataModel1 = (DataModel1) listObject3.get(int1);
                                    string2 = dataModel1.getString2();
                                    if (StringUtils.isNotBlank(string2))
                                        nameValuePair1
                                                .add(new BasicNameValuePair(dataObject2.getId(), string2));
                                }
                            }
                        }
                    }
                }
                url1 = new URL(sid);
                uriBuilder1 = new URIBuilder(sid);
                uriBuilder1.setUserInfo(uid, pid);
                if (StringUtils.isBlank(format1))
                    format1 = "pdf";
                uriBuilder1.setPath(url1.getPath() + "/rest_v2/reports" + urlString + "." + format1);
                if (StringUtils.isNotBlank(locale2)) {
                    nameValuePair1.add(new BasicNameValuePair("userLocale", locale2));
                }
                if (StringUtils.isNotBlank(page1)) {
                    if (NumberUtils.isNumber(page1)) {
                        nameValuePair1.add(new BasicNameValuePair("page", page1));
                    }
                }
                if (nameValuePair1.size() > 0) {
                    uriBuilder1.setQuery(URLEncodedUtils.format(nameValuePair1, "UTF-8"));
                }
                uri1 = uriBuilder1.build();
                httpGet1 = new HttpGet(uri1);
                httpResponse1 = httpClient1.execute(httpGet1);
                int1 = httpResponse1.getStatusLine().getStatusCode();
                if (int1 == HttpStatus.SC_OK) {
                    string3 = System.getProperty("java.io.tmpdir") + File.separator
                            + httpServletRequest.getSession().getId();
                    dir1 = new File(string3);
                    if (!dir1.exists()) {
                        dir1.mkdir();
                    }
                    httpEntity1 = httpResponse1.getEntity();
                    file1 = new File(string3, StringUtils.substringAfterLast(urlString, "/") + "." + format1);
                    if (StringUtils.equalsIgnoreCase(format1, "html")) {
                        result1 = EntityUtils.toString(httpEntity1);
                        FileUtils.writeStringToFile(file1, result1);
                        array1 = StringUtils.substringsBetween(result1, "<img src=\"", "\"");
                        if (ArrayUtils.isNotEmpty(array1)) {
                            dir1 = new File(
                                    string3 + File.separator + FilenameUtils.getBaseName(file1.getName()));
                            if (dir1.exists()) {
                                FileUtils.deleteDirectory(dir1);
                            }
                            file2 = new File(FilenameUtils.getFullPath(file1.getAbsolutePath())
                                    + FilenameUtils.getBaseName(file1.getName()) + ".zip");
                            if (file2.exists()) {
                                if (FileUtils.deleteQuietly(file2)) {
                                }
                            }
                            for (int2 = 0; int2 < array1.length; int2++) {
                                try {
                                    string2 = url1.getPath() + "/rest_v2/reports" + urlString + "/"
                                            + StringUtils.substringAfter(array1[int2], "/");
                                    uriBuilder1.setPath(string2);
                                    uri1 = uriBuilder1.build();
                                    httpGet1 = new HttpGet(uri1);
                                    httpResponse1 = httpClient1.execute(httpGet1);
                                    int1 = httpResponse1.getStatusLine().getStatusCode();
                                } finally {
                                    if (int1 == HttpStatus.SC_OK) {
                                        try {
                                            string2 = StringUtils.substringBeforeLast(array1[int2], "/");
                                            dir1 = new File(string3 + File.separator + string2);
                                            if (!dir1.exists()) {
                                                dir1.mkdirs();
                                            }
                                            httpEntity1 = httpResponse1.getEntity();
                                            inputStream1 = httpEntity1.getContent();
                                        } finally {
                                            string1 = StringUtils.substringAfterLast(array1[int2], "/");
                                            file2 = new File(string3 + File.separator + string2, string1);
                                            outputStream1 = new FileOutputStream(file2);
                                            IOUtils.copy(inputStream1, outputStream1);
                                        }
                                    }
                                }
                            }
                            outputStream1 = new FileOutputStream(
                                    FilenameUtils.getFullPath(file1.getAbsolutePath())
                                            + FilenameUtils.getBaseName(file1.getName()) + ".zip");
                            ArchiveOutputStream archiveOutputStream1 = new ArchiveStreamFactory()
                                    .createArchiveOutputStream(ArchiveStreamFactory.ZIP, outputStream1);
                            archiveOutputStream1.putArchiveEntry(new ZipArchiveEntry(file1, file1.getName()));
                            IOUtils.copy(new FileInputStream(file1), archiveOutputStream1);
                            archiveOutputStream1.closeArchiveEntry();
                            dir1 = new File(FilenameUtils.getFullPath(file1.getAbsolutePath())
                                    + FilenameUtils.getBaseName(file1.getName()));
                            files = (List<File>) FileUtils.listFiles(dir1, TrueFileFilter.INSTANCE,
                                    TrueFileFilter.INSTANCE);
                            for (File file3 : files) {
                                archiveOutputStream1.putArchiveEntry(new ZipArchiveEntry(file3, StringUtils
                                        .substringAfter(file3.getCanonicalPath(), string3 + File.separator)));
                                IOUtils.copy(new FileInputStream(file3), archiveOutputStream1);
                                archiveOutputStream1.closeArchiveEntry();
                            }
                            archiveOutputStream1.close();
                        }
                        bugfixGateIn = propertiesConfiguration1.getBoolean("bugfixGateIn", false);
                        string4 = bugfixGateIn
                                ? String.format("<img src=\"%s/namespace1/file-link?sessionId=%s&fileName=",
                                        portletRequest.getContextPath(),
                                        httpServletRequest.getSession().getId())
                                : String.format("<img src=\"%s/namespace1/file-link?fileName=",
                                        portletRequest.getContextPath());
                        result1 = StringUtils.replace(result1, "<img src=\"", string4);
                    } else {
                        inputStream1 = httpEntity1.getContent();
                        outputStream1 = new FileOutputStream(file1);
                        IOUtils.copy(inputStream1, outputStream1);
                        result1 = file1.getAbsolutePath();
                    }
                    return1 = SUCCESS;
                } else {
                    addActionError(String.format("%s %d: %s", getText("Error"), int1,
                            getText(Integer.toString(int1))));
                }
                dateTime2 = new org.joda.time.DateTime();
                period1 = new Period(dateTime1, dateTime2.plusSeconds(1));
                message1 = getText("Execution.time") + ": " + periodFormatter1.print(period1);
            } else {
                url1 = new URL(sid);
                uriBuilder1 = new URIBuilder(sid);
                uriBuilder1.setUserInfo(uid, pid);
                uriBuilder1.setPath(url1.getPath() + "/rest_v2/reports" + urlString + "/inputControls");
                uri1 = uriBuilder1.build();
                httpGet1 = new HttpGet(uri1);
                httpResponse1 = httpClient1.execute(httpGet1);
                int1 = httpResponse1.getStatusLine().getStatusCode();
                switch (int1) {
                case HttpStatus.SC_NO_CONTENT:
                    break;
                case HttpStatus.SC_OK:
                    httpEntity1 = httpResponse1.getEntity();
                    if (httpEntity1 != null) {
                        inputStream1 = httpEntity1.getContent();
                        if (inputStream1 != null) {
                            xmlConfiguration = new XMLConfiguration();
                            xmlConfiguration.load(inputStream1);
                            list1 = xmlConfiguration.configurationsAt("inputControl");
                            if (list1.size() > 0) {
                                listObject2 = new ArrayList<DataModel2>();
                                for (HierarchicalConfiguration hierarchicalConfiguration1 : list1) {
                                    string2 = hierarchicalConfiguration1.getString("type");
                                    dataModel2 = new DataModel2();
                                    dataModel2.setId(hierarchicalConfiguration1.getString("id"));
                                    dataModel2.setLabel1(hierarchicalConfiguration1.getString("label"));
                                    dataModel2.setType1(string2);
                                    dataModel2.setMandatory(hierarchicalConfiguration1.getBoolean("mandatory"));
                                    dataModel2.setReadOnly(hierarchicalConfiguration1.getBoolean("readOnly"));
                                    dataModel2.setVisible(hierarchicalConfiguration1.getBoolean("visible"));
                                    switch (string2) {
                                    case "bool":
                                    case "singleValueText":
                                    case "singleValueNumber":
                                    case "singleValueDate":
                                    case "singleValueDatetime":
                                        hierarchicalConfiguration2 = hierarchicalConfiguration1
                                                .configurationAt("state");
                                        dataModel2.setValue1(hierarchicalConfiguration2.getString("value"));
                                        break;
                                    case "singleSelect":
                                    case "singleSelectRadio":
                                    case "multiSelect":
                                    case "multiSelectCheckbox":
                                        hierarchicalConfiguration2 = hierarchicalConfiguration1
                                                .configurationAt("state");
                                        list2 = hierarchicalConfiguration2.configurationsAt("options.option");
                                        if (list2.size() > 0) {
                                            listObject3 = new ArrayList<DataModel1>();
                                            for (HierarchicalConfiguration hierarchicalConfiguration3 : list2) {
                                                dataModel1 = new DataModel1(
                                                        hierarchicalConfiguration3.getString("label"),
                                                        hierarchicalConfiguration3.getString("value"));
                                                if (hierarchicalConfiguration3.getBoolean("selected")) {
                                                    dataModel2.setValue1(
                                                            hierarchicalConfiguration3.getString("value"));
                                                }
                                                listObject3.add(dataModel1);
                                            }
                                            dataModel2.setOptions(listObject3);
                                        }
                                        break;
                                    default:
                                        break;
                                    }
                                    listObject2.add(dataModel2);
                                }
                            }
                        }
                    }
                    break;
                default:
                    addActionError(String.format("%s %d: %s", getText("Error"), int1,
                            getText(Integer.toString(int1))));
                    break;
                }
                if (httpEntity1 != null) {
                    EntityUtils.consume(httpEntity1);
                }
                uriBuilder1.setPath(url1.getPath() + "/rest/resource" + urlString);
                uri1 = uriBuilder1.build();
                httpGet1 = new HttpGet(uri1);
                httpResponse1 = httpClient1.execute(httpGet1);
                int2 = httpResponse1.getStatusLine().getStatusCode();
                if (int2 == HttpStatus.SC_OK) {
                    httpEntity1 = httpResponse1.getEntity();
                    inputStream1 = httpEntity1.getContent();
                    xmlConfiguration = new XMLConfiguration();
                    xmlConfiguration.load(inputStream1);
                    list1 = xmlConfiguration.configurationsAt("resourceDescriptor");
                    for (HierarchicalConfiguration hierarchicalConfiguration4 : list1) {
                        if (StringUtils.equalsIgnoreCase(
                                StringUtils.trim(hierarchicalConfiguration4.getString("[@wsType]")), "prop")) {
                            if (map1 == null)
                                map1 = new HashMap<String, String>();
                            string2 = StringUtils.substringBetween(
                                    StringUtils.substringAfter(
                                            hierarchicalConfiguration4.getString("[@uriString]"), "_files/"),
                                    "_", ".properties");
                            map1.put(string2,
                                    StringUtils.isBlank(string2) ? getText("Default") : getText(string2));
                        }
                    }
                }
                if (httpEntity1 != null) {
                    EntityUtils.consume(httpEntity1);
                }
            }
        } catch (IOException | ConfigurationException | URISyntaxException exception1) {
            exception1.printStackTrace();
            addActionError(exception1.getLocalizedMessage());
            httpGet1.abort();
            return ERROR;
        } finally {
            httpClient1.getConnectionManager().shutdown();
            IOUtils.closeQuietly(inputStream1);
        }
        break;
    default:
        addActionError(getText("This.file.type.is.not.supported"));
        break;
    }
    if (return1 != LOGIN) {
        sid = new String(Base64.encodeBase64(sid.getBytes()));
        uid = new String(Base64.encodeBase64(uid.getBytes()));
        pid = new String(Base64.encodeBase64(pid.getBytes()));
    }
    return return1;
}

From source file:com.taobao.android.tools.TPatchTool.java

public void doBundleResPatch(String bundleName, File destPatchBundleDir, File newBundleUnzipFolder,
        File baseBundleUnzipFolder) throws IOException {
    // compare resource changes
    Collection<File> newBundleResFiles = FileUtils.listFiles(newBundleUnzipFolder, new IOFileFilter() {

        @Override// w w  w  .  j  a  v a2s  . c o  m
        public boolean accept(File file) {
            // ?dex
            if (file.getName().endsWith(".dex")) {
                return false;
            }
            String relativePath = PathUtils.toRelative(newBundleUnzipFolder, file.getAbsolutePath());
            if (null != ((TpatchInput) (input)).notIncludeFiles
                    && pathMatcher.match(((TpatchInput) (input)).notIncludeFiles, relativePath)) {
                return false;
            }
            return true;
        }

        @Override
        public boolean accept(File file, String s) {
            return accept(new File(file, s));
        }
    }, TrueFileFilter.INSTANCE);

    for (File newBundleResFile : newBundleResFiles) {
        String resPath = PathUtils.toRelative(newBundleUnzipFolder, newBundleResFile.getAbsolutePath());
        File baseBundleResFile = new File(baseBundleUnzipFolder, resPath);
        File destResFile = new File(destPatchBundleDir, resPath);
        if (baseBundleResFile.exists()) {
            if (isFileModify(newBundleResFile, baseBundleResFile, bundleName, resPath)) { // modify resource
                if (baseBundleResFile.getName().endsWith(".so")) {
                    if (((TpatchInput) input).diffNativeSo && ((TpatchInput) input).diffBundleSo) {
                        destResFile = new File(destPatchBundleDir, resPath.concat(".patch"));
                        SoDiffUtils.diffSo(baseBundleResFile.getParentFile(), baseBundleResFile,
                                newBundleResFile, destResFile);

                    } else {
                        FileUtils.copyFile(newBundleResFile, destResFile);
                    }

                } else {
                    FileUtils.copyFile(newBundleResFile, destResFile);
                }
            }
        } else {// new resource
            FileUtils.copyFile(newBundleResFile, destResFile);
        }
    }
}

From source file:com.ikanow.aleph2.storage_service_hdfs.services.TestMockHdfsStorageSystem.java

@Test
public void test_ageOut() throws IOException, InterruptedException, ExecutionException {
    // 0) Setup/*from  w w w . j av  a2 s . c  o  m*/
    final String temp_dir = System.getProperty("java.io.tmpdir") + File.separator;

    final GlobalPropertiesBean globals = BeanTemplateUtils.build(GlobalPropertiesBean.class)
            .with(GlobalPropertiesBean::local_yarn_config_dir, temp_dir)
            .with(GlobalPropertiesBean::distributed_root_dir, temp_dir)
            .with(GlobalPropertiesBean::local_root_dir, temp_dir)
            .with(GlobalPropertiesBean::distributed_root_dir, temp_dir).done().get();

    final MockHdfsStorageService storage_service = new MockHdfsStorageService(globals);

    // 1) Set up bucket (code taken from management_db_service)
    final DataBucketBean bucket = BeanTemplateUtils.build(DataBucketBean.class)
            .with(DataBucketBean::full_name, "/test/age/out/bucket")
            .with(DataBucketBean::data_schema, BeanTemplateUtils.build(DataSchemaBean.class)
                    .with(DataSchemaBean::storage_schema, BeanTemplateUtils.build(StorageSchemaBean.class)
                            .with(StorageSchemaBean::raw,
                                    BeanTemplateUtils.build(StorageSchemaBean.StorageSubSchemaBean.class)
                                            .with(StorageSchemaBean.StorageSubSchemaBean::exist_age_max,
                                                    "9 days")
                                            .done().get())
                            .with(StorageSchemaBean::json,
                                    BeanTemplateUtils.build(StorageSchemaBean.StorageSubSchemaBean.class)
                                            .with(StorageSchemaBean.StorageSubSchemaBean::exist_age_max,
                                                    "6 days")
                                            .done().get())
                            .with(StorageSchemaBean::processed,
                                    BeanTemplateUtils.build(StorageSchemaBean.StorageSubSchemaBean.class)
                                            .with(StorageSchemaBean.StorageSubSchemaBean::exist_age_max,
                                                    "1 week")
                                            .done().get())
                            .done().get())
                    .done().get())
            .done().get();

    FileUtils.deleteDirectory(new File(System.getProperty("java.io.tmpdir") + File.separator + "/data/"
            + File.separator + bucket.full_name()));
    setup_bucket(storage_service, bucket, Arrays.asList("$sec_test"));
    final String bucket_path = System.getProperty("java.io.tmpdir") + File.separator + "/data/" + File.separator
            + bucket.full_name();
    assertTrue("The file path has been created", new File(bucket_path + "/managed_bucket").exists());

    final long now = new Date().getTime();
    IntStream.range(4, 10).boxed().map(i -> now - (i * 1000L * 3600L * 24L))
            .forEach(Lambdas.wrap_consumer_u(n -> {
                final String pattern = TimeUtils.getTimeBasedSuffix(TimeUtils.getTimePeriod("1 day").success(),
                        Optional.empty());
                final String dir = DateUtils.formatDate(new Date(n), pattern);

                FileUtils.forceMkdir(
                        new File(bucket_path + "/" + IStorageService.STORED_DATA_SUFFIX_RAW + "/" + dir));
                FileUtils.forceMkdir(
                        new File(bucket_path + "/" + IStorageService.STORED_DATA_SUFFIX_JSON + "/" + dir));
                FileUtils.forceMkdir(
                        new File(bucket_path + "/" + IStorageService.STORED_DATA_SUFFIX_PROCESSED + "/" + dir));
                FileUtils.forceMkdir(new File(bucket_path + "/"
                        + IStorageService.STORED_DATA_SUFFIX_PROCESSED_SECONDARY + "/sec_test/" + dir)); // (mini test for secondary)
            }));

    // (7 cos includes root)
    assertEquals(7,
            FileUtils.listFilesAndDirs(new File(bucket_path + "/" + IStorageService.STORED_DATA_SUFFIX_RAW),
                    DirectoryFileFilter.DIRECTORY, TrueFileFilter.INSTANCE).size());
    assertEquals(7,
            FileUtils.listFilesAndDirs(new File(bucket_path + "/" + IStorageService.STORED_DATA_SUFFIX_JSON),
                    DirectoryFileFilter.DIRECTORY, TrueFileFilter.INSTANCE).size());
    assertEquals(7,
            FileUtils.listFilesAndDirs(
                    new File(bucket_path + "/" + IStorageService.STORED_DATA_SUFFIX_PROCESSED),
                    DirectoryFileFilter.DIRECTORY, TrueFileFilter.INSTANCE).size());
    assertEquals(7,
            FileUtils.listFilesAndDirs(new File(
                    bucket_path + "/" + IStorageService.STORED_DATA_SUFFIX_PROCESSED_SECONDARY + "/sec_test/"),
                    DirectoryFileFilter.DIRECTORY, TrueFileFilter.INSTANCE).size());

    // 1) Normal run:

    CompletableFuture<BasicMessageBean> cf = storage_service.getDataService().get().handleAgeOutRequest(bucket);

    BasicMessageBean res = cf.get();

    assertEquals(true, res.success());
    assertTrue("sensible message: " + res.message(), res.message().contains("raw: deleted 1 "));
    assertTrue("sensible message: " + res.message(), res.message().contains("json: deleted 4 "));
    assertTrue("sensible message: " + res.message(), res.message().contains("processed: deleted 3 "));

    assertTrue("Message marked as loggable: " + res.details(),
            Optional.ofNullable(res.details()).filter(m -> m.containsKey("loggable")).isPresent());

    System.out.println("Return from to delete: " + res.message());

    //(+1 including root)
    assertEquals(6,
            FileUtils.listFilesAndDirs(new File(bucket_path + "/" + IStorageService.STORED_DATA_SUFFIX_RAW),
                    DirectoryFileFilter.DIRECTORY, TrueFileFilter.INSTANCE).size());
    assertEquals(3,
            FileUtils.listFilesAndDirs(new File(bucket_path + "/" + IStorageService.STORED_DATA_SUFFIX_JSON),
                    DirectoryFileFilter.DIRECTORY, TrueFileFilter.INSTANCE).size());
    assertEquals(4,
            FileUtils.listFilesAndDirs(
                    new File(bucket_path + "/" + IStorageService.STORED_DATA_SUFFIX_PROCESSED),
                    DirectoryFileFilter.DIRECTORY, TrueFileFilter.INSTANCE).size());
    assertEquals(4,
            FileUtils.listFilesAndDirs(new File(
                    bucket_path + "/" + IStorageService.STORED_DATA_SUFFIX_PROCESSED_SECONDARY + "/sec_test/"),
                    DirectoryFileFilter.DIRECTORY, TrueFileFilter.INSTANCE).size());

    // 2) Run it again, returns success but not loggable:

    CompletableFuture<BasicMessageBean> cf2 = storage_service.getDataService().get()
            .handleAgeOutRequest(bucket);

    BasicMessageBean res2 = cf2.get();

    assertEquals(true, res2.success());
    assertTrue("sensible message: " + res2.message(), res2.message().contains("raw: deleted 0 "));
    assertTrue("sensible message: " + res2.message(), res2.message().contains("json: deleted 0 "));
    assertTrue("sensible message: " + res2.message(), res2.message().contains("processed: deleted 0 "));
    assertTrue("Message _not_ marked as loggable: " + res2.details(),
            !Optional.ofNullable(res2.details()).map(m -> m.get("loggable")).isPresent());

    // 3) No temporal settings

    final DataBucketBean bucket3 = BeanTemplateUtils.build(DataBucketBean.class)
            .with("full_name", "/test/handle/age/out/delete/not/temporal")
            .with(DataBucketBean::data_schema, BeanTemplateUtils.build(DataSchemaBean.class).done().get())
            .done().get();

    CompletableFuture<BasicMessageBean> cf3 = storage_service.getDataService().get()
            .handleAgeOutRequest(bucket3);
    BasicMessageBean res3 = cf3.get();
    // no temporal settings => returns success
    assertEquals(true, res3.success());

    // 4) Unparseable temporal settings (in theory won't validate but we can test here)

    final DataBucketBean bucket4 = BeanTemplateUtils.build(DataBucketBean.class)
            .with("full_name", "/test/handle/age/out/delete/temporal/malformed")
            .with(DataBucketBean::data_schema,
                    BeanTemplateUtils.build(DataSchemaBean.class).with(DataSchemaBean::storage_schema,
                            BeanTemplateUtils.build(StorageSchemaBean.class).with(StorageSchemaBean::json,
                                    BeanTemplateUtils.build(StorageSchemaBean.StorageSubSchemaBean.class)
                                            .with(StorageSchemaBean.StorageSubSchemaBean::exist_age_max,
                                                    "bananas")
                                            .done().get())
                                    .done().get())
                            .done().get())
            .done().get();

    CompletableFuture<BasicMessageBean> cf4 = storage_service.getDataService().get()
            .handleAgeOutRequest(bucket4);
    BasicMessageBean res4 = cf4.get();
    // no temporal settings => returns success
    assertEquals(false, res4.success());

}

From source file:betullam.xmlmodifier.XMLmodifier.java

private Set<File> getFilesForInsertion(String condStructureElements, String mdDirectory) {
    Set<File> filesForInsertion = new HashSet<File>();
    List<String> lstStructureElements = Arrays.asList(condStructureElements.split("\\s*,\\s*"));
    // Iterate over all files in the given directory and it's subdirectories. Works with "FileUtils" in Apache "commons-io" library.

    //for (File mdFile : FileUtils.listFiles(new File(mdDirectory), new WildcardFileFilter(new String[]{"meta.xml", "meta_anchor.xml"}, IOCase.INSENSITIVE), TrueFileFilter.INSTANCE)) {
    for (File mdFile : FileUtils.listFiles(new File(mdDirectory),
            new WildcardFileFilter("*.xml", IOCase.INSENSITIVE), TrueFileFilter.INSTANCE)) {
        // DOM Parser:
        String filePath = mdFile.getAbsolutePath();
        DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = null;
        Document xmlDoc = null;/*from  w  w  w .  java2  s  . c  o m*/
        try {
            documentBuilder = documentFactory.newDocumentBuilder();
            xmlDoc = documentBuilder.parse(filePath);

            // Only get files with a structure element that is listed in condStructureElements
            for (String structureElement : lstStructureElements) {

                String xPathString = "/mets/structMap[@TYPE='LOGICAL']//div[@TYPE='" + structureElement + "']";
                XPathFactory xPathFactory = XPathFactory.newInstance();
                XPath xPath = xPathFactory.newXPath();
                XPathExpression xPathExpr = xPath.compile(xPathString);
                NodeList nodeList = (NodeList) xPathExpr.evaluate(xmlDoc, XPathConstants.NODESET);

                if (nodeList.getLength() > 0) {
                    filesForInsertion.add(mdFile);
                } else {
                }
            }

        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (XPathExpressionException e) {
            e.printStackTrace();
        }
    }
    return filesForInsertion;

}

From source file:com.taobao.android.TPatchTool.java

private File createTPatchFile(File outPatchDir, File patchTmpDir) throws IOException {
    // bundle,bundle
    File mainBundleFoder = new File(patchTmpDir, mainBundleName);
    File mainBundleFile = new File(patchTmpDir, mainBundleName + ".so");
    if (FileUtils.listFiles(mainBundleFoder, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE).size() > 0) {
        hasMainBundle = true;/*from   ww  w.jav a  2  s.c o m*/
        zipBundle(mainBundleFoder, mainBundleFile);
    }
    FileUtils.deleteDirectory(mainBundleFoder);

    // ??bundle
    File patchFile = new File(outPatchDir,
            "patch-" + newApkBO.getVersionName() + "@" + baseApkBO.getVersionName() + ".tpatch");
    if (patchFile.exists()) {
        FileUtils.deleteQuietly(patchFile);
    }
    zipBundle(patchTmpDir, patchFile);
    FileUtils.deleteDirectory(patchTmpDir);
    return patchFile;
}

From source file:com.dycody.android.idealnote.async.DataBackupIntentService.java

private void importNotes(File backupDir) {
    for (File file : FileUtils.listFiles(backupDir, new RegexFileFilter("\\d{13}"), TrueFileFilter.INSTANCE)) {
        try {//from  ww  w .  j  a  v  a 2  s.  co  m
            Note note = new Note();
            note.buildFromJson(FileUtils.readFileToString(file));
            if (note.getCategory() != null) {
                DbHelper.getInstance().updateCategory(note.getCategory());
            }
            for (Attachment attachment : note.getAttachmentsList()) {
                DbHelper.getInstance().updateAttachment(attachment);
            }
            DbHelper.getInstance().updateNote(note, false);
        } catch (IOException e) {
            Log.e(Constants.TAG, "Error parsing note json");
        }
    }
}