List of usage examples for org.apache.commons.io.filefilter TrueFileFilter INSTANCE
IOFileFilter INSTANCE
To view the source code for org.apache.commons.io.filefilter TrueFileFilter INSTANCE.
Click Source Link
From source file:cloudExplorer.CLI.java
void syncToS3(String folder) { if (folder != null) { System.out.print("\n\nStarting sync from: " + destination + " to bucket: " + bucket + " in folder: " + folder + " \n"); } else {// w ww .ja v a2 s .c o m System.out.print("\n\nStarting sync from: " + destination + " to bucket: " + bucket + "\n"); } File dir = new File(destination); reloadObjects(); String[] extensions = new String[] { " " }; List<File> files = (List<File>) FileUtils.listFiles(dir, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE); for (File file_found : files) { int found = 0; for (int y = 1; y != object_array.length; y++) { if (object_array[y].contains(makeDirectory(file_found.getAbsolutePath().toString()))) { found++; } } if (found == 0) { String object = makeDirectory(file_found.getAbsolutePath().toString()); String[] cut = object.split(file_found.getName()); String[] cut2 = null; object = object.replace(cut[0], ""); String win = "\\"; String lin = "/"; if (cut[0].contains(win)) { cut2 = cut[0].split(win); object = cut2[cut2.length - 1] + win + object; } else { cut2 = cut[0].split(lin); object = cut2[cut2.length - 1] + lin + object; } if (folder != null) { object = folder + File.separator + object; } put = new Put(file_found.getAbsolutePath().toString(), access_key, secret_key, bucket, endpoint, object, false, false); put.run(); found = 0; } } System.out.print("\nSync operation complete.\n\n\n"); }
From source file:com.sangupta.jerry.util.FileUtils.java
/** * List the files in the given path string with wild cards. * /*w ww .j av a2 s.c o m*/ * @param baseDir * the base directory to search for files in * * @param filePathWithWildCards * the file path to search in - can be absolute * * @param recursive * whether to look in sub-directories or not * * @param additionalFilters * additional file filters that need to be used when scanning for * files * * @return the list of files and directories that match the criteria */ public static List<File> listFiles(File baseDir, String filePathWithWildCards, boolean recursive, List<IOFileFilter> additionalFilters) { if (filePathWithWildCards == null) { throw new IllegalArgumentException("Filepath cannot be null"); } // change *.* to * filePathWithWildCards = filePathWithWildCards.replace("*.*", "*"); // normalize filePathWithWildCards = FilenameUtils.normalize(filePathWithWildCards); if (filePathWithWildCards.endsWith(File.pathSeparator)) { filePathWithWildCards += "*"; } // check if this is an absolute path or not String prefix = FilenameUtils.getPrefix(filePathWithWildCards); final boolean isAbsolute = !prefix.isEmpty(); // change the base dir if absolute directory if (isAbsolute) { baseDir = new File(filePathWithWildCards); if (!baseDir.isDirectory()) { // not a directory - get the base directory filePathWithWildCards = baseDir.getName(); if (filePathWithWildCards.equals("~")) { filePathWithWildCards = "*"; } if (AssertUtils.isEmpty(filePathWithWildCards)) { filePathWithWildCards = "*"; } baseDir = baseDir.getParentFile(); if (baseDir == null) { baseDir = getUsersHomeDirectory(); } } } // check if the provided argument is a directory File dir = new File(filePathWithWildCards); if (dir.isDirectory()) { baseDir = dir.getAbsoluteFile(); filePathWithWildCards = "*"; } else { // let's check for base directory File parent = dir.getParentFile(); if (parent != null) { baseDir = parent.getAbsoluteFile(); filePathWithWildCards = dir.getName(); } } // check for user home String basePath = baseDir.getPath(); if (basePath.startsWith("~")) { basePath = getUsersHomeDirectory().getAbsolutePath() + File.separator + basePath.substring(1); basePath = FilenameUtils.normalize(basePath); baseDir = new File(basePath); } // now read the files WildcardFileFilter wildcardFileFilter = new WildcardFileFilter(filePathWithWildCards, IOCase.SYSTEM); IOFileFilter finalFilter = wildcardFileFilter; if (AssertUtils.isNotEmpty(additionalFilters)) { additionalFilters.add(0, wildcardFileFilter); finalFilter = new AndFileFilter(additionalFilters); } Collection<File> files = org.apache.commons.io.FileUtils.listFiles(baseDir, finalFilter, recursive ? TrueFileFilter.INSTANCE : FalseFileFilter.INSTANCE); return (List<File>) files; }
From source file:com.btoddb.fastpersitentqueue.InMemorySegmentMgrTest.java
@Test public void testThreading() throws IOException, ExecutionException { final int entrySize = 1000; final int numEntries = 3000; final int numPushers = 3; int numPoppers = 3; final Random pushRand = new Random(1000L); final Random popRand = new Random(1000000L); final AtomicInteger pusherFinishCount = new AtomicInteger(); final AtomicInteger numPops = new AtomicInteger(); final AtomicLong pushSum = new AtomicLong(); final AtomicLong popSum = new AtomicLong(); mgr.setMaxSegmentSizeInBytes(10000); mgr.init();//from w w w . j a v a2s. com ExecutorService execSrvc = Executors.newFixedThreadPool(numPushers + numPoppers); Set<Future> futures = new HashSet<Future>(); // start pushing for (int i = 0; i < numPushers; i++) { Future future = execSrvc.submit(new Runnable() { @Override public void run() { for (int i = 0; i < numEntries; i++) { try { long x = idGen.incrementAndGet(); pushSum.addAndGet(x); FpqEntry entry = new FpqEntry(x, new byte[entrySize]); mgr.push(entry); if (x % 500 == 0) { System.out.println("pushed ID = " + x); } Thread.sleep(pushRand.nextInt(5)); } catch (Exception e) { e.printStackTrace(); } } pusherFinishCount.incrementAndGet(); } }); futures.add(future); } // start popping for (int i = 0; i < numPoppers; i++) { Future future = execSrvc.submit(new Runnable() { @Override public void run() { while (pusherFinishCount.get() < numPushers || !mgr.isEmpty()) { try { FpqEntry entry; while (null != (entry = mgr.pop())) { if (entry.getId() % 500 == 0) { System.out.println("popped ID = " + entry.getId()); } popSum.addAndGet(entry.getId()); numPops.incrementAndGet(); Thread.sleep(popRand.nextInt(5)); } } catch (Exception e) { e.printStackTrace(); } } } }); futures.add(future); } boolean finished = false; while (!finished) { try { for (Future f : futures) { f.get(); } finished = true; } catch (InterruptedException e) { // ignore Thread.interrupted(); } } assertThat(numPops.get(), is(numEntries * numPushers)); assertThat(popSum.get(), is(pushSum.get())); assertThat(mgr.getNumberOfEntries(), is(0L)); assertThat(mgr.getNumberOfActiveSegments(), is(1)); assertThat(mgr.getSegments(), hasSize(1)); assertThat(FileUtils.listFiles(theDir, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE), is(empty())); // make sure we tested paging in/out assertThat(mgr.getNumberOfSwapOut(), is(greaterThan(0L))); assertThat(mgr.getNumberOfSwapIn(), is(mgr.getNumberOfSwapOut())); }
From source file:fll.scheduler.TournamentScheduleTest.java
/** * Test loading all schedules in the repository. * This depends on being able to find the schedules. * The test assumes that it is executing from the base build directory or the * root of the repository.//from www.j a v a 2 s . c o m * All schedule files that end in '.xls' will be loaded. * * @throws ScheduleParseException * @throws ParseException * @throws IOException * @throws InvalidFormatException */ @Test public void testLoadAllSchedules() throws InvalidFormatException, IOException, ParseException, ScheduleParseException { File baseScheduleDir = new File("../../scheduling/blank-schedules"); if (!baseScheduleDir.exists()) { baseScheduleDir = new File("scheduling/blank-schedules"); } Assert.assertTrue("Can't find schedules in " + baseScheduleDir.getAbsolutePath(), baseScheduleDir.exists()); Assert.assertTrue("Schedules path isn't a directory: " + baseScheduleDir.getAbsolutePath(), baseScheduleDir.isDirectory()); final Collection<File> schedules = FileUtils.listFiles(baseScheduleDir, new SuffixFileFilter(".xls"), TrueFileFilter.INSTANCE); Assert.assertTrue("Didn't find any schedules", !schedules.isEmpty()); final Collection<String> possibleSubjectiveHeaders = new LinkedList<String>(); possibleSubjectiveHeaders.add("Core Values"); possibleSubjectiveHeaders.add("Design"); possibleSubjectiveHeaders.add("Project"); for (final File file : schedules) { final URL resource = file.toURI().toURL(); final TournamentSchedule schedule = loadSchedule(resource, possibleSubjectiveHeaders); // make sure there are some schedule entries Assert.assertTrue("No entries for schedule: " + file.getName(), !schedule.getSchedule().isEmpty()); Assert.assertTrue("No division for schedule: " + file.getName(), !schedule.getAwardGroups().isEmpty()); Assert.assertTrue("No judging groups for schedule: " + file.getName(), !schedule.getJudgingGroups().isEmpty()); } }
From source file:io.github.jeremgamer.editor.panels.Others.java
protected void updateList() { data.clear();/*w ww.j a v a 2 s . co m*/ File dir = new File("projects/" + Editor.getProjectName() + "/others"); if (!dir.exists()) { dir.mkdirs(); } for (File file : FileUtils.listFiles(dir, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE)) { data.addElement(file.getName().replace(".rbd", "")); } otherList = new JList<String>(data); }
From source file:com.github.blindpirate.gogradle.task.go.GoTest.java
private void rewritePackageName(File reportDir) { Collection<File> htmlFiles = filterFilesRecursively(reportDir, new SuffixFileFilter(".html"), TrueFileFilter.INSTANCE); String rewriteScript = IOUtils .toString(GoTest.class.getClassLoader().getResourceAsStream(REWRITE_SCRIPT_RESOURCE)); htmlFiles.forEach(htmlFile -> {// w w w . j av a 2s . c om String content = IOUtils.toString(htmlFile); content = content.replace("</body>", "</body>" + rewriteScript); IOUtils.write(htmlFile, content); }); }
From source file:com.taobao.android.builder.tools.diff.DiffResExtractor.java
/** * assets : apk//from w w w .j a v a 2 s. c o m * res : diffResFiles ?apk ? * * @param diffResFiles * @param currentApk * @param baseApk * @param fullResDir * @param destDir * @throws IOException */ public static void extractDiff(Set<String> diffResFiles, File currentApk, File baseApk, File fullResDir, File destDir) throws IOException { if (!currentApk.exists() || !baseApk.exists() || !fullResDir.exists()) { return; } FileUtils.deleteDirectory(destDir); destDir.mkdirs(); File tmpFolder = new File(destDir.getParentFile(), "tmp-diffRes"); FileUtils.deleteDirectory(tmpFolder); tmpFolder.mkdirs(); File apkDir = new File(tmpFolder, "newApkDir"); File baseApkDir = new File(tmpFolder, "baseApkDir"); ZipUtils.unzip(currentApk, apkDir.getAbsolutePath()); ZipUtils.unzip(baseApk, baseApkDir.getAbsolutePath()); //compare res and assets Collection<File> files = FileUtils.listFiles(apkDir, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE); int basePathLength = apkDir.getAbsolutePath().length(); List<String> diffResPath = new ArrayList<String>(); //assets for (File file : files) { String relativePath = file.getAbsolutePath().substring(basePathLength); if (!relativePath.startsWith("/assets/")) { continue; } File baseFile = new File(baseApkDir, relativePath); if (!baseFile.exists()) { diffResPath.add(relativePath); continue; } if (!MD5Util.getFileMD5(file).equals(MD5Util.getFileMD5(baseFile))) { File rawFile = new File(apkDir, relativePath); FileUtils.copyFile(rawFile, new File(destDir, relativePath)); } } //res for (String diffFile : diffResFiles) { File baseFile = new File(baseApkDir, diffFile); File currentFile = new File(apkDir, diffFile); if (baseFile.exists() && currentFile.exists() && MD5Util.getFileMD5(baseFile).equals(MD5Util.getFileMD5(currentFile))) { continue; } //copy file File rawFile = new File(fullResDir, diffFile); if (rawFile.exists()) { FileUtils.copyFile(rawFile, new File(destDir, diffFile)); } } //?resource.arsc File assetsDir = new File(destDir, "assets"); File resDir = new File(destDir, "res"); if (assetsDir.exists() && !resDir.exists()) { File valuesDir = new File(resDir, "values"); FileUtils.forceMkdir(valuesDir); File stringsFile = new File(valuesDir, "strings.xml"); UUID uuid = UUID.randomUUID(); FileUtils.writeStringToFile(stringsFile, String.format( "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n <string name=\"%s\">%s</string>\n</resources>\n", uuid, uuid), "UTF-8", false); } final Pattern densityOnlyPattern = Pattern.compile("[a-zA-Z]+-[a-zA-Z]+dpi"); if (resDir.exists()) { File[] resDirs = resDir.listFiles(); if (resDirs != null) { for (File file : resDirs) { Matcher m = densityOnlyPattern.matcher(file.getName()); if (m.matches()) { FileUtils.moveDirectory(file, new File(file.getAbsolutePath() + "-v4")); } } } } }
From source file:de.mprengemann.intellij.plugin.androidicons.dialogs.AndroidMultiDrawableImporter.java
private void importZipArchive(VirtualFile virtualFile) { final String filePath = virtualFile.getCanonicalPath(); if (filePath == null) { return;// ww w. java 2s .c o m } final File tempDir = new File(ImageInformation.getTempDir(), virtualFile.getNameWithoutExtension()); final String archiveName = virtualFile.getName(); new Task.Modal(project, "Importing Archive...", true) { @Override public void run(@NotNull final ProgressIndicator progressIndicator) { progressIndicator.setIndeterminate(true); try { FileUtils.forceMkdir(tempDir); ZipUtil.extract(new File(filePath), tempDir, new FilenameFilter() { @Override public boolean accept(File dir, String name) { final String mimeType = new MimetypesFileTypeMap().getContentType(name); final String type = mimeType.split("/")[0]; return type.equals("image"); } }, true); progressIndicator.checkCanceled(); final Iterator<File> fileIterator = FileUtils.iterateFiles(tempDir, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE); while (fileIterator.hasNext()) { File file = fileIterator.next(); if (file.isDirectory() || file.isHidden()) { continue; } final String fileRoot = file.getParent().toUpperCase(); final String name = FilenameUtils.getBaseName(file.toString()); if (name.startsWith(".") || fileRoot.contains("__MACOSX")) { continue; } for (Resolution resolution : RESOLUTIONS) { if (name.toUpperCase().contains("-" + resolution) || name.toUpperCase().contains("_" + resolution) || fileRoot.contains(resolution.toString())) { controller.addZipImage(file, resolution); break; } } } progressIndicator.checkCanceled(); final Map<Resolution, List<ImageInformation>> zipImages = controller.getZipImages(); final List<Resolution> foundResolutions = new ArrayList<Resolution>(); int foundAssets = 0; for (Resolution resolution : zipImages.keySet()) { final List<ImageInformation> assetInformation = zipImages.get(resolution); if (assetInformation != null && assetInformation.size() > 0) { foundAssets += assetInformation.size(); foundResolutions.add(resolution); } } progressIndicator.checkCanceled(); final int finalFoundAssets = foundAssets; UIUtil.invokeLaterIfNeeded(new DumbAwareRunnable() { public void run() { final String title = String.format("Import '%s'", archiveName); if (foundResolutions.size() == 0 || finalFoundAssets == 0) { Messages.showErrorDialog("No assets found.", title); FileUtils.deleteQuietly(tempDir); return; } final String[] options = new String[] { "Import", "Cancel" }; final String description = String.format("Import %d assets for %s to %s.", finalFoundAssets, StringUtils.join(foundResolutions, ", "), controller.getTargetRoot()); final int selection = Messages.showDialog(description, title, options, 0, Messages.getQuestionIcon()); if (selection == 0) { controller.getZipTask(project, tempDir).queue(); close(0); } else { FileUtils.deleteQuietly(tempDir); } } }); } catch (ProcessCanceledException e) { FileUtils.deleteQuietly(tempDir); } catch (IOException e) { LOGGER.error(e); } } }.queue(); }
From source file:isl.FIMS.servlet.imports.ImportXML.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.initVars(request); String username = getUsername(request); Config conf = new Config("EisagwghXML_RDF"); String xsl = ApplicationConfig.SYSTEM_ROOT + "formating/xsl/import/ImportXML.xsl"; String displayMsg = ""; response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); StringBuilder xml = new StringBuilder( this.xmlStart(this.topmenu, username, this.pageTitle, this.lang, "", request)); // ArrayList<String> notValidMXL = new ArrayList<String>(); HashMap<String, ArrayList> notValidMXL = new <String, ArrayList>HashMap(); if (!ServletFileUpload.isMultipartContent(request)) { displayMsg = "form"; } else {//w ww.ja v a 2s . c o m // configures some settings String filePath = this.export_import_Folder; java.util.Date date = new java.util.Date(); Timestamp t = new Timestamp(date.getTime()); String currentDir = filePath + t.toString().replaceAll(":", ""); File saveDir = new File(currentDir); if (!saveDir.exists()) { saveDir.mkdir(); } DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD); factory.setRepository(saveDir); ArrayList<String> savedIDs = new ArrayList<String>(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(REQUEST_SIZE); // constructs the directory path to store upload file String uploadPath = currentDir; int xmlCount = 0; String[] id = null; try { // parses the request's content to extract file data List formItems = upload.parseRequest(request); Iterator iter = formItems.iterator(); // iterates over form's fields File storeFile = null; while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); // processes only fields that are not form fields if (!item.isFormField()) { String fileName = new File(item.getName()).getName(); filePath = uploadPath + File.separator + fileName; storeFile = new File(filePath); item.write(storeFile); Utils.unzip(fileName, uploadPath); File dir = new File(uploadPath); String[] extensions = new String[] { "xml", "x3ml" }; List<File> files = (List<File>) FileUtils.listFiles(dir, extensions, true); xmlCount = files.size(); for (File file : files) { // saves the file on disk Document doc = ParseXMLFile.parseFile(file.getPath()); String xmlContent = doc.getDocumentElement().getTextContent(); String uri_name = ""; try { uri_name = DMSTag.valueOf("uri_name", "target", type, this.conf)[0]; } catch (DMSException ex) { ex.printStackTrace(); } String uriValue = this.URI_Reference_Path + uri_name + "/"; boolean insertEntity = false; if (xmlContent.contains(uriValue) || file.getName().contains(type)) { insertEntity = true; } Element root = doc.getDocumentElement(); Node admin = Utils.removeNode(root, "admin", true); // File rename = new File(uploadPath + File.separator + id[0] + ".xml"); // boolean isRename = storeFile.renameTo(rename); // ParseXMLFile.saveXMLDocument(rename.getPath(), doc); String schemaFilename = ""; schemaFilename = type; SchemaFile sch = new SchemaFile(schemaFolder + schemaFilename + ".xsd"); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(doc), new StreamResult(writer)); String xmlString = writer.getBuffer().toString().replaceAll("\r", ""); //without admin boolean isValid = sch.validate(xmlString); if ((!isValid && insertEntity)) { notValidMXL.put(file.getName(), null); } else if (insertEntity) { id = initInsertFile(type, false); doc = createAdminPart(id[0], type, doc, username); writer = new StringWriter(); transformer.transform(new DOMSource(doc), new StreamResult(writer)); xmlString = writer.getBuffer().toString().replaceAll("\r", ""); DBCollection col = new DBCollection(this.DBURI, id[1], this.DBuser, this.DBpassword); DBFile dbF = col.createFile(id[0] + ".xml", "XMLDBFile"); dbF.setXMLAsString(xmlString); dbF.store(); ArrayList<String> externalFiles = new <String>ArrayList(); ArrayList<String> externalDBFiles = new <String>ArrayList(); String q = "//*["; for (String attrSet : this.uploadAttributes) { String[] temp = attrSet.split("#"); String func = temp[0]; String attr = temp[1]; if (func.contains("text")) { q += "@" + attr + "]/text()"; } else { q = "data(//*[@" + attr + "]/@" + attr + ")"; } String[] res = dbF.queryString(q); for (String extFile : res) { externalFiles.add(extFile + "#" + attr); } } q = "//"; if (!dbSchemaPath[0].equals("")) { for (String attrSet : this.dbSchemaPath) { String[] temp = attrSet.split("#"); String func = temp[0]; String path = temp[1]; if (func.contains("text")) { q += path + "//text()"; } else { q = "data(//" + path + ")"; } String[] res = dbF.queryString(q); for (String extFile : res) { externalDBFiles.add(extFile); } } } ArrayList<String> missingExternalFiles = new <String>ArrayList(); for (String extFile : externalFiles) { extFile = extFile.substring(0, extFile.lastIndexOf("#")); List<File> f = (List<File>) FileUtils.listFiles(dir, FileFilterUtils.nameFileFilter(extFile), TrueFileFilter.INSTANCE); if (f.size() == 0) { missingExternalFiles.add(extFile); } } if (missingExternalFiles.size() > 0) { notValidMXL.put(file.getName(), missingExternalFiles); } XMLEntity xmlNew = new XMLEntity(this.DBURI, this.systemDbCollection + type, this.DBuser, this.DBpassword, type, id[0]); ArrayList<String> worngFiles = Utils.checkReference(xmlNew, this.DBURI, id[0], type, this.DBuser, this.DBpassword); if (worngFiles.size() > 0) { //dbF.remove(); notValidMXL.put(file.getName(), worngFiles); } //remove duplicates from externalFiles if any HashSet hs = new HashSet(); hs.addAll(missingExternalFiles); missingExternalFiles.clear(); missingExternalFiles.addAll(hs); if (missingExternalFiles.isEmpty() && worngFiles.isEmpty()) { for (String extFile : externalFiles) { String attr = extFile.substring(extFile.lastIndexOf("#") + 1, extFile.length()); extFile = extFile.substring(0, extFile.lastIndexOf("#")); List<File> f = (List<File>) FileUtils.listFiles(dir, FileFilterUtils.nameFileFilter(extFile), TrueFileFilter.INSTANCE); File uploadFile = f.iterator().next(); String content = FileUtils.readFileToString(uploadFile); DBFile uploadsDBFile = new DBFile(this.DBURI, this.adminDbCollection, "Uploads.xml", this.DBuser, this.DBpassword); String mime = Utils.findMime(uploadsDBFile, uploadFile.getName(), attr); String uniqueName = Utils.createUniqueFilename(uploadFile.getName()); File uploadFileUnique = new File(uploadFile.getPath().substring(0, uploadFile.getPath().lastIndexOf(File.separator)) + File.separator + uniqueName); uploadFile.renameTo(uploadFileUnique); xmlString = xmlString.replaceAll(uploadFile.getName(), uniqueName); String upload_path = this.systemUploads + type; File upload_dir = null; ; if (mime.equals("Photos")) { upload_path += File.separator + mime + File.separator + "original" + File.separator; upload_dir = new File(upload_path + uniqueName); FileUtils.copyFile(uploadFileUnique, upload_dir); Utils.resizeImage(uniqueName, upload_path, upload_path.replaceAll("original", "thumbs"), thumbSize); Utils.resizeImage(uniqueName, upload_path, upload_path.replaceAll("original", "normal"), normalSize); xmlString = xmlString.replace("</versions>", "</versions>" + "\n" + "<type>Photos</type>"); } else { upload_path += File.separator + mime + File.separator; upload_dir = new File(upload_path + uniqueName); FileUtils.copyFile(uploadFileUnique, upload_dir); } if (!dbSchemaFolder.equals("")) { if (externalDBFiles.contains(extFile)) { try { DBCollection colSchema = new DBCollection(this.DBURI, dbSchemaFolder, this.DBuser, this.DBpassword); DBFile dbFSchema = colSchema.createFile(uniqueName, "XMLDBFile"); dbFSchema.setXMLAsString(content); dbFSchema.store(); } catch (Exception e) { } } } uploadFileUnique.renameTo(uploadFile); } dbF.setXMLAsString(xmlString); dbF.store(); Utils.updateReferences(xmlNew, this.DBURI, id[0].split(type)[1], type, this.DBpassword, this.DBuser); Utils.updateVocabularies(xmlNew, this.DBURI, id[0].split(type)[1], type, this.DBpassword, this.DBuser, lang); savedIDs.add(id[0]); } else { dbF.remove(); } } } } } Document doc = ParseXMLFile.parseFile(ApplicationConfig.SYSTEM_ROOT + "formating/multi_lang.xml"); Element root = doc.getDocumentElement(); Element contextTag = (Element) root.getElementsByTagName("context").item(0); String uri_name = ""; try { uri_name = DMSTag.valueOf("uri_name", "target", type, this.conf)[0]; } catch (DMSException ex) { } if (notValidMXL.size() == 0) { xsl = conf.DISPLAY_XSL; displayMsg = Messages.ACTION_SUCCESS; displayMsg += Messages.NL + Messages.NL + Messages.URI_ID; String uriValue = ""; xml.append("<Display>").append(displayMsg).append("</Display>\n"); xml.append("<backPages>").append('2').append("</backPages>\n"); for (String saveId : savedIDs) { uriValue = this.URI_Reference_Path + uri_name + "/" + saveId + Messages.NL; xml.append("<codeValue>").append(uriValue).append("</codeValue>\n"); } } else if (notValidMXL.size() >= 1) { xsl = ApplicationConfig.SYSTEM_ROOT + "formating/xsl/import/ImportXML.xsl"; Iterator it = notValidMXL.keySet().iterator(); while (it.hasNext()) { String key = (String) it.next(); ArrayList<String> value = notValidMXL.get(key); if (value != null) { displayMsg += "<line>"; Element select = (Element) contextTag.getElementsByTagName("missingReferences").item(0); displayMsg += select.getElementsByTagName(lang).item(0).getTextContent(); displayMsg = displayMsg.replace("?", key); for (String mis_res : value) { displayMsg += mis_res + ","; } displayMsg = displayMsg.substring(0, displayMsg.length() - 1); displayMsg += "."; displayMsg += "</line>"; } else { displayMsg += "<line>"; Element select = (Element) contextTag.getElementsByTagName("NOT_VALID_XML").item(0); displayMsg += select.getElementsByTagName(lang).item(0).getTextContent(); displayMsg = displayMsg.replace(";", key); displayMsg += "</line>"; } displayMsg += "<line>"; displayMsg += "</line>"; } if (notValidMXL.size() < xmlCount) { displayMsg += "<line>"; Element select = (Element) contextTag.getElementsByTagName("rest_valid").item(0); displayMsg += select.getElementsByTagName(lang).item(0).getTextContent(); displayMsg += "</line>"; for (String saveId : savedIDs) { displayMsg += "<line>"; String uriValue = this.URI_Reference_Path + uri_name + "/" + saveId; select = (Element) contextTag.getElementsByTagName("URI_ID").item(0); displayMsg += select.getElementsByTagName(lang).item(0).getTextContent() + ": " + uriValue; displayMsg += "</line>"; } } } Utils.deleteDir(currentDir); } catch (Exception ex) { ex.printStackTrace(); displayMsg += Messages.NOT_VALID_IMPORT; } } xml.append("<Display>").append(displayMsg).append("</Display>\n"); xml.append("<EntityType>").append(type).append("</EntityType>\n"); xml.append(this.xmlEnd()); try { XMLTransform xmlTrans = new XMLTransform(xml.toString()); xmlTrans.transform(out, xsl); } catch (DMSException e) { e.printStackTrace(); } out.close(); }
From source file:net.rptools.tokentool.controller.ManageOverlays_Controller.java
private boolean confirmDelete(File dir) { String confirmationText = I18N.getString("ManageOverlays.dialog.delete.dir.confirmation"); long dirSize = FileUtils.listFiles(dir, ImageUtil.SUPPORTED_FILE_FILTER, TrueFileFilter.INSTANCE).size(); if (dirSize == 0) { confirmationText += dir.getName() + I18N.getString("ManageOverlays.dialog.delete.dir.confirmation.directory"); } else {//from w w w . j a v a2 s. c om confirmationText += dir.getName() + I18N.getString("ManageOverlays.dialog.delete.dir.directory_containing") + dirSize + I18N.getString("ManageOverlays.dialog.delete.dir.overlays"); } Alert alert = new Alert(AlertType.CONFIRMATION); alert.setTitle(I18N.getString("ManageOverlays.dialog.delete.dir.title")); alert.setContentText(confirmationText); Optional<ButtonType> result = alert.showAndWait(); if ((result.isPresent()) && (result.get() == ButtonType.OK)) { return true; } return false; }