List of usage examples for org.apache.commons.io FileUtils cleanDirectory
public static void cleanDirectory(File directory) throws IOException
From source file:com.alibaba.jstorm.daemon.nimbus.ServiceHandler.java
/** * create local topology files /local-dir/nimbus/topologyId/stormjar.jar * /local-dir/nimbus/topologyId/stormcode.ser * /local-dir/nimbus/topologyId/stormconf.ser * * @param conf// ww w . java 2 s.co m * @param topologyId * @param tmpJarLocation * @param stormConf * @param topology * @throws IOException */ private void setupStormCode(Map<Object, Object> conf, String topologyId, String tmpJarLocation, Map<Object, Object> stormConf, StormTopology topology) throws IOException { // local-dir/nimbus/stormdist/topologyId String stormroot = StormConfig.masterStormdistRoot(conf, topologyId); FileUtils.forceMkdir(new File(stormroot)); FileUtils.cleanDirectory(new File(stormroot)); // copy jar to /local-dir/nimbus/topologyId/stormjar.jar setupJar(conf, tmpJarLocation, stormroot); // serialize to file /local-dir/nimbus/topologyId/stormcode.ser FileUtils.writeByteArrayToFile(new File(StormConfig.stormcode_path(stormroot)), Utils.serialize(topology)); // serialize to file /local-dir/nimbus/topologyId/stormconf.ser FileUtils.writeByteArrayToFile(new File(StormConfig.stormconf_path(stormroot)), Utils.serialize(stormConf)); // Update downloadCode timeStamp StormConfig.write_nimbus_topology_timestamp(data.getConf(), topologyId, System.currentTimeMillis()); }
From source file:com.taobao.android.tools.TPatchTool.java
@Override public PatchFile doPatch() throws Exception { TpatchInput tpatchInput = (TpatchInput) input; TpatchFile tpatchFile = new TpatchFile(); File hisPatchJsonFile = new File(tpatchInput.outPutJson.getParentFile(), "patchs-" + input.newApkBo.getVersionName() + ".json"); hisTpatchFolder = new File( tpatchInput.outPatchDir.getParentFile().getParentFile().getParentFile().getParentFile(), "hisTpatch"); tpatchFile.diffJson = new File(((TpatchInput) input).outPatchDir, "diff.json"); tpatchFile.patchInfo = new File(((TpatchInput) input).outPatchDir, "patchInfo.json"); final File patchTmpDir = new File(((TpatchInput) input).outPatchDir, "tpatch-tmp"); final File mainDiffFolder = new File(patchTmpDir, ((TpatchInput) input).mainBundleName); patchTmpDir.mkdirs();//from w w w .j ava2 s. c om FileUtils.cleanDirectory(patchTmpDir); mainDiffFolder.mkdirs(); File lastPatchFile = null; readWhiteList(((TpatchInput) input).bundleWhiteList); lastPatchFile = getLastPatchFile(input.baseApkBo.getVersionName(), ((TpatchInput) input).productName, ((TpatchInput) input).outPatchDir); PatchUtils.getTpatchClassDef(lastPatchFile, bundleClassMap); Profiler.release(); Profiler.enter("unzip apks"); // unzip apk File unzipFolder = unzipApk(((TpatchInput) input).outPatchDir); final File newApkUnzipFolder = new File(unzipFolder, NEW_APK_UNZIP_NAME); final File baseApkUnzipFolder = new File(unzipFolder, BASE_APK_UNZIP_NAME); Profiler.release(); ExecutorServicesHelper executorServicesHelper = new ExecutorServicesHelper(); String taskName = "diffBundleTask"; // Collection<File> soFiles = FileUtils.listFiles(newApkUnzipFolder, new String[] { "so" }, true); //process remote bumdle if ((((TpatchInput) input).splitDiffBundle != null)) { for (final Pair<BundleBO, BundleBO> bundle : ((TpatchInput) input).splitDiffBundle) { if (bundle.getFirst() == null || bundle.getSecond() == null) { logger.warning("remote bundle is not set to splitDiffBundles"); continue; } executorServicesHelper.submitTask(taskName, new Callable<Boolean>() { @Override public Boolean call() throws Exception { TPatchTool.this.processBundleFiles(bundle.getSecond().getBundleFile(), bundle.getFirst().getBundleFile(), patchTmpDir); return true; } }); } } Profiler.enter("awbspatch"); Collection<File> retainFiles = FileUtils.listFiles(newApkUnzipFolder, new IOFileFilter() { @Override public boolean accept(File file) { String relativePath = PathUtils.toRelative(newApkUnzipFolder, file.getAbsolutePath()); if (pathMatcher.match(DEFAULT_NOT_INCLUDE_RESOURCES, relativePath)) { return false; } 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); executorServicesHelper.submitTask(taskName, new Callable<Boolean>() { @Override public Boolean call() throws Exception { // bundledex diff // File mianDiffDestDex = new File(mainDiffFolder, DEX_NAME); // File tmpDexFolder = new File(patchTmpDir, ((TpatchInput)input).mainBundleName + "-dex"); createBundleDexPatch(newApkUnzipFolder, baseApkUnzipFolder, mainDiffFolder, // tmpDexFolder, true); // ??bundle? if (isRetainMainBundleRes()) { copyMainBundleResources(newApkUnzipFolder, baseApkUnzipFolder, new File(patchTmpDir, ((TpatchInput) input).mainBundleName), retainFiles); } return true; } }); for (final File soFile : soFiles) { System.out.println("do patch:" + soFile.getAbsolutePath()); final String relativePath = PathUtils.toRelative(newApkUnzipFolder, soFile.getAbsolutePath()); if (null != ((TpatchInput) input).notIncludeFiles && pathMatcher.match(((TpatchInput) input).notIncludeFiles, relativePath)) { continue; } executorServicesHelper.submitTask(taskName, new Callable<Boolean>() { @Override public Boolean call() throws Exception { File destFile = new File(patchTmpDir, ((TpatchInput) input).mainBundleName + "/" + relativePath); File baseSoFile = new File(baseApkUnzipFolder, relativePath); if (isBundleFile(soFile)) { processBundleFiles(soFile, baseSoFile, patchTmpDir); } else if (isFileModify(soFile, baseSoFile)) { if (destFile.exists()) { FileUtils.deleteQuietly(destFile); } if (!baseSoFile.exists() || !((TpatchInput) input).diffNativeSo) { // FileUtils.copyFile(soFile, destFile); } else { destFile = new File(destFile.getParentFile(), destFile.getName() + ".patch"); SoDiffUtils.diffSo(patchTmpDir, baseSoFile, soFile, destFile); soFileDefs.add(new SoFileDef(baseSoFile, soFile, destFile, relativePath)); } } return true; } }); } executorServicesHelper.waitTaskCompleted(taskName); executorServicesHelper.stop(); Profiler.release(); Profiler.enter("ziptpatchfile"); // zip file File patchFile = createTPatchFile(((TpatchInput) input).outPatchDir, patchTmpDir); tpatchFile.patchFile = patchFile; PatchInfo curPatchInfo = createBasePatchInfo(patchFile); Profiler.release(); Profiler.enter("createhistpatch"); BuildPatchInfos buildPatchInfos = createIncrementPatchFiles(((TpatchInput) input).productName, patchFile, ((TpatchInput) input).outPatchDir, newApkUnzipFolder, curPatchInfo, ((TpatchInput) input).hisPatchUrl); Profiler.release(); Profiler.enter("writejson"); buildPatchInfos.getPatches().add(curPatchInfo); buildPatchInfos.setBaseVersion(input.baseApkBo.getVersionName()); buildPatchInfos.setDiffBundleDex(input.diffBundleDex); FileUtils.writeStringToFile(((TpatchInput) input).outPutJson, JSON.toJSONString(buildPatchInfos)); BuildPatchInfos testForBuildPatchInfos = new BuildPatchInfos(); testForBuildPatchInfos.setBaseVersion(buildPatchInfos.getBaseVersion()); List<PatchInfo> patchInfos = new ArrayList<>(); testForBuildPatchInfos.setPatches(patchInfos); testForBuildPatchInfos.setDiffBundleDex(buildPatchInfos.isDiffBundleDex()); for (PatchInfo patchInfo : buildPatchInfos.getPatches()) { if (patchInfo.getTargetVersion().equals(buildPatchInfos.getBaseVersion())) { patchInfos.add(patchInfo); } } FileUtils.writeStringToFile(hisPatchJsonFile, JSON.toJSONString(testForBuildPatchInfos)); tpatchFile.updateJsons = new ArrayList<File>(); Map<String, List<String>> map = new HashMap<>(); for (PatchInfo patchInfo : buildPatchInfos.getPatches()) { UpdateInfo updateInfo = new UpdateInfo(patchInfo, buildPatchInfos.getBaseVersion()); // System.out.println("start to check:"+patchInfo.getTargetVersion()+"......"); // List<PatchChecker.ReasonMsg> msgs = new PatchChecker(updateInfo,bundleInfos.get(patchInfo.getTargetVersion()),new File(((TpatchInput) input).outPatchDir,patchInfo.getFileName())).check(); // map.put(patchInfo.getFileName(),msgToString(msgs)); File updateJson = new File(((TpatchInput) input).outPatchDir, "update-" + patchInfo.getTargetVersion() + ".json"); FileUtils.writeStringToFile(updateJson, JSON.toJSONString(updateInfo, true)); tpatchFile.updateJsons.add(updateJson); } // tpatchFile.patchChecker = new File(((TpatchInput) input).outPatchDir,"patch-check.json"); // FileUtils.writeStringToFile(tpatchFile.patchChecker, JSON.toJSONString(map, true)); // FileUtils.deleteDirectory(patchTmpDir); apkDiff.setBaseApkVersion(input.baseApkBo.getVersionName()); apkDiff.setNewApkVersion(input.newApkBo.getVersionName()); apkDiff.setBundleDiffResults(bundleDiffResults); boolean newApkFileExist = input.newApkBo.getApkFile().exists() && input.newApkBo.getApkFile().isFile(); if (newApkFileExist) { apkDiff.setNewApkMd5(MD5Util.getFileMD5String(input.newApkBo.getApkFile())); } apkDiff.setFileName(input.newApkBo.getApkName()); apkPatchInfos.setBaseApkVersion(input.baseApkBo.getVersionName()); apkPatchInfos.setNewApkVersion(input.newApkBo.getVersionName()); apkPatchInfos.setBundleDiffResults(diffPatchInfos); apkPatchInfos.setFileName(patchFile.getName()); apkPatchInfos.setNewApkMd5(MD5Util.getFileMD5String(patchFile)); FileUtils.writeStringToFile(tpatchFile.diffJson, JSON.toJSONString(apkDiff)); FileUtils.writeStringToFile(tpatchFile.patchInfo, JSON.toJSONString(apkPatchInfos)); FileUtils.copyFileToDirectory(tpatchFile.diffJson, ((TpatchInput) input).outPatchDir.getParentFile(), true); if (newApkFileExist) { FileUtils.copyFileToDirectory(input.newApkBo.getApkFile(), ((TpatchInput) input).outPatchDir.getParentFile(), true); } Profiler.release(); logger.warning(Profiler.dump()); return tpatchFile; }
From source file:com.edgenius.core.repository.SimpleRepositoryServiceImpl.java
public void afterPropertiesSet() throws Exception { if (homeDirResource == null) { throw new BeanInitializationException("Must specify a repository homeDirResource property"); }/*from w ww.j av a2 s . com*/ try { md5Digest = MessageDigest.getInstance("MD5"); } catch (Exception e) { log.error("Unable to initialize MD digest API. Digest function is disabled in Repository method", e); } //check if Repository root exists, if no, create one File locationDir = homeDirResource.getFile(); if (!locationDir.exists()) { if (!locationDir.mkdirs()) { throw new BeanInitializationException("Repository home dir can not created " + homeDirResource); } } this.homeDir = locationDir.getAbsolutePath(); //clean all lock files when system start. File lockDir = new File(FileUtil.getFullPath(homeDir, LOCK_DIR)); if (!lockDir.exists()) { lockDir.mkdir(); } else { FileUtils.cleanDirectory(lockDir); } }
From source file:com.bibisco.test.ProjectManagerTest.java
@After public void cleanExportAndTempDirectory() throws IOException, ConfigurationException { FileUtils.cleanDirectory(new File(AllTests.getExportPath())); FileUtils.cleanDirectory(new File(AllTests.getTempPath())); AllTests.cleanTestProjectDB();//w w w . ja va2 s.c om }
From source file:com.crushpaper.DbLogic.java
/** * API method. Deletes the database from disk. If it has been used in the * lifetime of this process it can not be deleted due to design of windows * and java. This is because the DB memory maps files and java unmaps files * in finalizers for security reasons. The finalizers can not be guaranteed * to be run before the next DB is created in the same place. If the * finalizers have not been run, then the files have not been unmapped and * are still on disk. On windows the files will be locked and can not be * deleted. See: http://bugs.java.com/bugdatabase/view_bug.do?bug_id=4724038 *///from www . j a va 2s . com public boolean deleteDb() { if (aDbHasEverBeenCreatedInThisProcess) { return false; } try { FileUtils.cleanDirectory(dbDirectory); } catch (final IOException e) { return false; } return true; }
From source file:com.aerohive.nms.web.config.lbs.services.HmFolderServiceImpl.java
private boolean extractTarFile(Long folderId, Long ownerId, boolean overrideBg, String originalFilename, InputStream fileInput, Map<String, String> imageNameMapping) throws InternalServerException { boolean flag = false; final String tar_gz_ext = ".tar.gz"; final String file_prefix = "" + new Date().getTime(); String destPath = getFolderFileBasePath(file_prefix, ownerId); String filePath = destPath + file_prefix + tar_gz_ext; File folder = new File(filePath); if (!folder.getParentFile().exists()) { folder.getParentFile().mkdirs(); }/*from w w w . j ava 2s . co m*/ InputStream input = null; try (FileOutputStream outputStream = new FileOutputStream(folder)) { int read = 0; byte[] bytes = new byte[2048]; while ((read = fileInput.read(bytes)) != -1) { outputStream.write(bytes, 0, read); } outputStream.flush(); outputStream.close(); new TarArchive().unzipGZipFile(filePath, destPath); //delete gzip file if (folder.exists()) { FileUtils.deleteQuietly(folder); } folder = new File(destPath); File[] files = folder.listFiles(); for (File file : files) { if (file.isFile()) { try { input = new FileInputStream(file); parseXmlFile(folderId, ownerId, file.getName(), input, overrideBg, imageNameMapping); } catch (Exception e) { logger.error(String.format("Upload file %s failed: %s", originalFilename, e.getMessage())); throw new InternalServerException(e, ErrorCodes.fileUploadFailed, new Object[][] { { "fileName", originalFilename } }); } finally { if (input != null) { try { input.close(); } catch (Exception e) { logger.error(String.format("Upload file %s failed: %s", originalFilename, e.getMessage())); throw new InternalServerException(e, ErrorCodes.fileUploadFailed, new Object[][] { { "fileName", originalFilename } }); } } } } else { File[] imageFiles = file.listFiles(); // copy map background images if (null != imageFiles) { String imagepath = destPath + "bgImages" + File.separator; if (overrideBg) { for (File imageFile : imageFiles) { try { input = new FileInputStream(imageFile); imageService.uploadImage(ownerId, imageFile.getName(), IOUtils.toByteArray(input)); } catch (Exception e) { logger.error(String.format("Upload file %s failed: %s", originalFilename, e.getMessage())); throw new InternalServerException(e, ErrorCodes.fileUploadFailed, new Object[][] { { "fileName", originalFilename } }); } finally { if (input != null) { try { input.close(); } catch (Exception e) { logger.error(String.format("Upload file %s failed: %s", originalFilename, e.getMessage())); throw new InternalServerException(e, ErrorCodes.fileUploadFailed, new Object[][] { { "fileName", originalFilename } }); } } } } } else { for (File imageFile : imageFiles) { String fileName = checkImageNameForImportFolder(imageFile.getName(), ownerId, imageNameMapping); if (!fileName.equalsIgnoreCase(imageFile.getName())) { try { File destFile = new File(imagepath + fileName); FileUtils.moveFile(imageFile, destFile); input = new FileInputStream(destFile); imageService.uploadImage(ownerId, destFile.getName(), IOUtils.toByteArray(input)); } catch (Exception e) { logger.error(String.format("Upload file %s failed: %s", originalFilename, e.getMessage())); throw new InternalServerException(e, ErrorCodes.fileUploadFailed, new Object[][] { { "fileName", originalFilename } }); } finally { if (input != null) { try { input.close(); } catch (Exception e) { logger.error(String.format("Upload file %s failed: %s", originalFilename, e.getMessage())); throw new InternalServerException(e, ErrorCodes.fileUploadFailed, new Object[][] { { "fileName", originalFilename } }); } } } } else { try { input = new FileInputStream(imageFile); imageService.uploadImage(ownerId, imageFile.getName(), IOUtils.toByteArray(input)); } catch (Exception e) { logger.error(String.format("Upload file %s failed: %s", originalFilename, e.getMessage())); throw new InternalServerException(e, ErrorCodes.fileUploadFailed, new Object[][] { { "fileName", originalFilename } }); } finally { if (input != null) { try { input.close(); } catch (Exception e) { logger.error(String.format("Upload file %s failed: %s", originalFilename, e.getMessage())); throw new InternalServerException(e, ErrorCodes.fileUploadFailed, new Object[][] { { "fileName", originalFilename } }); } } } } } } } } } flag = true; } catch (Exception e) { logger.error(String.format("Upload file %s failed: %s", originalFilename, e.getMessage())); throw new InternalServerException(e, ErrorCodes.fileUploadFailed, new Object[][] { { "fileName", originalFilename } }); } finally { if (input != null) { try { input.close(); } catch (IOException e) { logger.error(String.format("Upload file %s failed: %s", originalFilename, e.getMessage())); throw new InternalServerException(e, ErrorCodes.fileUploadFailed, new Object[][] { { "fileName", originalFilename } }); } } try { FileUtils.cleanDirectory(folder); FileUtils.deleteDirectory(folder); } catch (IOException e) { logger.error(String.format("Upload file %s failed: %s", originalFilename, e.getMessage())); throw new InternalServerException(e, ErrorCodes.fileUploadFailed, new Object[][] { { "fileName", originalFilename } }); } } return flag; }
From source file:com.linkedin.databus.core.DbusEventBuffer.java
public void cleanUpPersistedBuffers() { if (_allocationPolicy != AllocationPolicy.MMAPPED_MEMORY) { _log.info("Not cleaning up buffer mmap directory because allocation policy is " + _allocationPolicy + "; bufferPersistenceEnabled:" + _bufferPersistenceEnabled); return;/*from w w w . j a va2s . com*/ } // remove all the content of the session id for this buffer _log.warn("Removing mmap directory for buffer(" + _physicalPartition + "): " + _mmapSessionDirectory); if (!_mmapSessionDirectory.exists() || !_mmapSessionDirectory.isDirectory()) { _log.warn("cannot cleanup _mmap=" + _mmapSessionDirectory + " directory because it doesn't exist or is not a directory"); return; } try { FileUtils.cleanDirectory(_mmapSessionDirectory); } catch (IOException e) { _log.error("failed to cleanup buffer session directory " + _mmapSessionDirectory); } // delete the directory itself if (!_mmapSessionDirectory.delete()) { _log.error("failed to delete buffer session directory " + _mmapSessionDirectory); } File metaFile = new File(_mmapDirectory, metaFileName()); if (metaFile.exists()) { _log.warn("Removing meta file " + metaFile); if (!metaFile.delete()) { _log.error("failed to delete metafile " + metaFile); } } }
From source file:edu.ku.brc.specify.utilapps.BuildSampleDatabase.java
/** * Drops, Creates and Builds the Database. * //from w w w . ja v a 2 s. c o m * @throws SQLException * @throws IOException */ public boolean buildEmptyDatabase(final Properties props, final boolean doFromWizard) { createProgressFrame("Building Specify Database"); final String dbName = props.getProperty("dbName"); frame.adjustProgressFrame(); frame.setTitle("Building Specify Database"); if (!hideFrame) { UIHelper.centerWindow(frame); frame.setVisible(true); ImageIcon imgIcon = IconManager.getIcon("AppIcon", IconManager.IconSize.Std16); if (imgIcon != null) { frame.setIconImage(imgIcon.getImage()); } } else { System.out.println("Building Specify Database Username[" + props.getProperty("dbUserName") + "]"); } frame.setProcessPercent(true); frame.setOverall(0, 4); frame.getCloseBtn().setVisible(false); steps = 0; SwingUtilities.invokeLater(new Runnable() { public void run() { frame.getProcessProgress().setIndeterminate(true); frame.getProcessProgress().setString(""); frame.setDesc("Creating Database Schema for " + dbName); frame.setOverall(steps++); } }); DatabaseDriverInfo driverInfo = (DatabaseDriverInfo) props.get("driver"); try { if (hideFrame) System.out.println("Creating schema"); String itUsername = props.getProperty("dbUserName"); String itPassword = props.getProperty("dbPassword"); boolean doBuild = true; if (doBuild) { SpecifySchemaGenerator.generateSchema(driverInfo, props.getProperty("hostName"), dbName, itUsername, itPassword); } SwingUtilities.invokeLater(new Runnable() { public void run() { frame.getProcessProgress().setIndeterminate(true); frame.getProcessProgress().setString(""); frame.setDesc("Logging into " + dbName + "...."); frame.setOverall(steps++); } }); String connStr = driverInfo.getConnectionStr(DatabaseDriverInfo.ConnectionType.Create, props.getProperty("hostName"), dbName); if (connStr == null) { connStr = driverInfo.getConnectionStr(DatabaseDriverInfo.ConnectionType.Open, props.getProperty("hostName"), dbName); } if (!UIHelper.tryLogin(driverInfo.getDriverClassName(), driverInfo.getDialectClassName(), dbName, connStr, itUsername, itPassword)) { if (hideFrame) System.out.println("Login Failed!"); return false; } String saUserName = props.getProperty("saUserName"); // Master Username String saPassword = props.getProperty("saPassword"); // Master Password createSpecifySAUser(props.getProperty("hostName"), itUsername, itPassword, saUserName, saPassword, dbName); if (!UIHelper.tryLogin(driverInfo.getDriverClassName(), driverInfo.getDialectClassName(), dbName, connStr, saUserName, saPassword)) { if (hideFrame) System.out.println("Login Failed!"); return false; } setSession(HibernateUtil.getCurrentSession()); //DataBuilder.setSession(session); SwingUtilities.invokeLater(new Runnable() { public void run() { frame.getProcessProgress().setIndeterminate(true); frame.getProcessProgress().setString(""); frame.setDesc("Creating database " + dbName + "...."); frame.setOverall(steps++); } }); Thumbnailer thumb = Thumbnailer.getInstance(); File thumbFile = XMLHelper.getConfigDir("thumbnail_generators.xml"); thumb.registerThumbnailers(thumbFile); thumb.setQuality(0.5f); thumb.setMaxSize(128, 128); File attLoc = getAppDataSubDir("AttachmentStorage", true); FileUtils.cleanDirectory(attLoc); AttachmentManagerIface attachMgr = new FileStoreAttachmentManager(attLoc); AttachmentUtils.setAttachmentManager(attachMgr); AttachmentUtils.setThumbnailer(thumb); if (hideFrame) System.out.println("Creating Empty Database"); createEmptyInstitution(props, true, true, doFromWizard, getTreeDirForClass(props, StorageTreeDef.class)); SwingUtilities.invokeLater(new Runnable() { public void run() { frame.getProcessProgress().setIndeterminate(true); frame.getProcessProgress().setString(""); frame.setDesc("Saving data into " + dbName + "...."); frame.setOverall(steps++); } }); if (hideFrame) System.out.println("Persisting Data..."); HibernateUtil.getCurrentSession().close(); if (hideFrame) System.out.println("Done."); frame.setVisible(false); frame.dispose(); SpecifyDeleteHelper.showTableCounts("EmptyDB.txt", true); return true; } catch (Exception ex) { throw new RuntimeException(ex); } }
From source file:edu.ku.brc.specify.utilapps.BuildSampleDatabase.java
/** * Drops, Creates and Builds the Database. * /*from w ww . j av a 2s . c om*/ * @throws SQLException */ protected void build(final String dbName, final String driverName, final Pair<String, String> dbUser, final Pair<String, String> saUser, final Pair<String, String> cmUser) throws SQLException { frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); frame.pack(); Dimension size = frame.getSize(); size.width = Math.max(size.width, 500); frame.setSize(size); frame.setTitle("Building Specify Database"); if (!hideFrame) { UIHelper.centerWindow(frame); frame.setVisible(true); ImageIcon imgIcon = IconManager.getIcon("AppIcon", IconManager.IconSize.Std16); if (imgIcon != null) { frame.setIconImage(imgIcon.getImage()); } } frame.setProcessPercent(true); frame.setOverall(0, 7 + this.selectedChoices.size()); frame.getCloseBtn().setVisible(false); String databaseHost = initPrefs.getProperty("initializer.host", "localhost"); frame.setTitle("Building -> Database: " + dbName + " Driver: " + driverName + " User: " + cmUser.first); steps = 0; SwingUtilities.invokeLater(new Runnable() { public void run() { frame.getProcessProgress().setIndeterminate(true); frame.getProcessProgress().setString(""); frame.setDesc("Creating Database Schema for " + dbName); frame.setOverall(steps++); } }); DatabaseDriverInfo driverInfo = DatabaseDriverInfo.getDriver(driverName); if (driverInfo == null) { String msg = "Couldn't find driver by name [" + driverInfo + "] in driver list."; showError(msg); throw new RuntimeException(msg); } String newConnStr = driverInfo.getConnectionStr(DatabaseDriverInfo.ConnectionType.Open, databaseHost, dbName, saUser.first, saUser.second, driverInfo.getName()); DBConnection.checkForEmbeddedDir(newConnStr); if (DBConnection.isEmbedded(newConnStr)) { try { Class.forName(driverInfo.getDriverClassName()); DBConnection testDB = DBConnection.createInstance(driverInfo.getDriverClassName(), driverInfo.getDialectClassName(), dbName, newConnStr, saUser.first, saUser.second); testDB.getConnection(); } catch (Exception ex) { ex.printStackTrace(); } DBConnection.getInstance().setDatabaseName(null); } SpecifySchemaGenerator.generateSchema(driverInfo, databaseHost, dbName, dbUser.first, dbUser.second); SwingUtilities.invokeLater(new Runnable() { public void run() { frame.setDesc("Logging in..."); frame.setOverall(steps++); } }); if (UIHelper.tryLogin(driverInfo.getDriverClassName(), driverInfo.getDialectClassName(), dbName, driverInfo.getConnectionStr(DatabaseDriverInfo.ConnectionType.Open, databaseHost, dbName), saUser.first, saUser.second)) { createSpecifySAUser(databaseHost, dbUser.first, dbUser.second, saUser.first, saUser.second, dbName); boolean single = true; if (single) { SwingUtilities.invokeLater(new Runnable() { public void run() { frame.setDesc("Creating data..."); frame.setOverall(steps++); } }); try { Thumbnailer thumb = Thumbnailer.getInstance(); File thumbFile = XMLHelper.getConfigDir("thumbnail_generators.xml"); thumb.registerThumbnailers(thumbFile); thumb.setQuality(0.5f); thumb.setMaxSize(128, 128); frame.setDesc("Cleaning Attachment Cache..."); frame.setOverall(steps++); File attLoc = getAppDataSubDir("AttachmentStorage", true); try { FileUtils.cleanDirectory(attLoc); } catch (IOException e) { String msg = "failed to connect to directory location to delete directory: " + attLoc; log.warn(msg); showError(msg); } AttachmentManagerIface attachMgr = new FileStoreAttachmentManager(attLoc); AttachmentUtils.setAttachmentManager(attachMgr); AttachmentUtils.setThumbnailer(thumb); // save it all to the DB setSession(HibernateUtil.getCurrentSession()); //DataBuilder.setSession(session); createDisciplines(cmUser.first, cmUser.second); attachMgr.cleanup(); frame.setDesc("Done Saving data..."); frame.setOverall(steps++); frame.setDesc("Copying Preferences..."); frame.setOverall(steps++); AppPreferences remoteProps = AppPreferences.getRemote(); for (Object key : initPrefs.keySet()) { String keyStr = (String) key; if (!keyStr.startsWith("initializer.") && !keyStr.startsWith("useragent.")) { remoteProps.put(keyStr, (String) initPrefs.get(key)); } } AppPreferences.getRemote().flush(); frame.setDesc("Build Completed."); frame.setOverall(steps++); assignPermssions(); log.info("Done"); } catch (Exception e) { e.printStackTrace(); try { rollbackTx(); log.error("Failed to persist DB objects", e); showError("Failed to persist DB objects"); return; } catch (Exception e2) { log.error( "Failed to persist DB objects. Rollback failed. DB may be in inconsistent state.", e2); showError("Failed to persist DB objects. Rollback failed."); return; } } } } else { log.error("Login failed"); showError("Login failed"); return; } System.out.println("All done"); if (frame != null) { frame.processDone(); } // Set the Schema Size into Locale Prefs String schemaKey = "schemaSize"; int schemaFileSize = 0; File schemaFile = XMLHelper.getConfigDir("specify_datamodel.xml"); if (schemaFile != null) { schemaFileSize = (int) schemaFile.length(); AppPreferences.getLocalPrefs().putInt(schemaKey, schemaFileSize); } JOptionPane.showMessageDialog(getTopWindow(), "The build completed successfully.", "Complete", JOptionPane.INFORMATION_MESSAGE); }
From source file:net.technicpack.launchercore.install.InstalledPack.java
public void setPackDirectory(File packPath) { if (installedDirectory != null) { try {/*w w w .j a v a 2 s . co m*/ FileUtils.copyDirectory(installedDirectory, packPath); FileUtils.cleanDirectory(installedDirectory); } catch (IOException e) { e.printStackTrace(); return; } } installedDirectory = packPath; String path = installedDirectory.getAbsolutePath(); if (path.equals(Utils.getModpacksDirectory().getAbsolutePath())) { directory = MODPACKS_DIR; } else if (path.equals(Utils.getLauncherDirectory().getAbsolutePath())) { directory = LAUNCHER_DIR; } else if (path.startsWith(Utils.getModpacksDirectory().getAbsolutePath())) { directory = MODPACKS_DIR + path.substring(Utils.getModpacksDirectory().getAbsolutePath().length() + 1); } else if (path.startsWith(Utils.getLauncherDirectory().getAbsolutePath())) { directory = LAUNCHER_DIR + path.substring(Utils.getLauncherDirectory().getAbsolutePath().length() + 1); } initDirectories(); }