List of usage examples for java.io File toString
public String toString()
From source file:com.wavemaker.StudioInstallService.java
public static File unzipFile(File zipfile) { int BUFFER = 2048; String zipname = zipfile.getName(); int extindex = zipname.lastIndexOf("."); try {/*from w ww . j av a2 s. c o m*/ File zipFolder = new File(zipfile.getParentFile(), zipname.substring(0, extindex)); if (zipFolder.exists()) org.apache.commons.io.FileUtils.deleteDirectory(zipFolder); zipFolder.mkdir(); File currentDir = zipFolder; //File currentDir = zipfile.getParentFile(); BufferedOutputStream dest = null; FileInputStream fis = new FileInputStream(zipfile.toString()); ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis)); ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { System.out.println("Extracting: " + entry); if (entry.isDirectory()) { File f = new File(currentDir, entry.getName()); if (f.exists()) f.delete(); // relevant if this is the top level folder f.mkdir(); } else { int count; byte data[] = new byte[BUFFER]; //needed for non-dir file ace/ace.js created by 7zip File destFile = new File(currentDir, entry.getName()); // write the files to the disk FileOutputStream fos = new FileOutputStream(currentDir.toString() + "/" + entry.getName()); dest = new BufferedOutputStream(fos, BUFFER); while ((count = zis.read(data, 0, BUFFER)) != -1) { dest.write(data, 0, count); } dest.flush(); dest.close(); } } zis.close(); return currentDir; } catch (Exception e) { e.printStackTrace(); } return (File) null; }
From source file:com.ericsson.eif.hansoft.HansoftManager.java
/** * Hansoft adapter properties from adapter.properties * @param servletContext//from w ww . j ava 2 s . c o m */ private static void init(ServletContext servletContext) { Properties props = new Properties(); try { PROVIDER_CONTEXT_PATH = servletContext.getContextPath(); if (PROVIDER_CONTEXT_PATH.isEmpty()) { String message = "No servlet context name provided, will exit."; logger.error(message); throw new RuntimeException(message); } String adapterHome = System.getenv("ADAPTER_HOME"); if (adapterHome == null) { // default to user home adapterHome = System.getProperty("user.home"); } // The PROVIDER_CONTEXT_PATH has a beginning "/" - remove String contextPath = PROVIDER_CONTEXT_PATH.substring(1); adapterServletHome = adapterHome + File.separator + contextPath; // Need the properties file - if not found, exit try { File propsPath = new File(adapterServletHome + File.separator + "adapter.properties"); if (propsPath.exists()) { props.load(new FileInputStream(propsPath.toString())); } else { String message = "The adapter.properties file not found, will exit."; logger.error(message); throw new RuntimeException(message); } } catch (Exception e) { String message = "Failed to read the adapter.properties file, will exit."; logger.error(message, e); throw new RuntimeException(message); } // It is ok not having a log4j configuration file, but recommended try { File log4jPropsPath = new File(adapterServletHome + File.separator + "log4j.properties"); if (log4jPropsPath.exists()) { // Allow using adapter home path in log4j file System.setProperty("hansoft.adapter_servlet_home", adapterServletHome); PropertyConfigurator.configure(log4jPropsPath.getPath()); } else { logger.warn("The log4j.properties file not found."); } } catch (Exception e) { logger.warn("Failed to read the log4j.properties file.", e); } logger.info("Initialize of Hansoft adapter started ..."); // We need to set the JNI path early, and failed when trying to // pass as input argument. Solution as below is working: // // From // http://blog.cedarsoft.com/2010/11/setting-java-library-path-programmatically/ // // At first the system property is updated with the new value. // This might be a relative path or maybe you want to create that // path dynamically. // // The Classloader has a static field (sys_paths) that contains the // paths. If that field is set to null, it is initialized // automatically. Therefore forcing that field to null will result // into the reevaluation of the library path as soon as // loadLibrary() is called hansoftSDKVersion = props.getProperty("hansoft_sdk_version", "").trim(); if (hansoftSDKVersion == "") { String message = "SDK version not set, will exit."; logger.error(message); throw new RuntimeException(message); } try { hansoftLib = adapterHome + File.separator + "hansoft_libs" + File.separator + hansoftSDKVersion; File libPath = new File(hansoftLib); if (libPath.exists()) { System.setProperty("java.library.path", libPath.toString()); Field fieldSysPath = ClassLoader.class.getDeclaredField("sys_paths"); fieldSysPath.setAccessible(true); fieldSysPath.set(null, null); } else { String message = "Hansoft libs for SDK version: " + hansoftSDKVersion + " not found, will exit."; logger.error(message); throw new RuntimeException(message); } } catch (Exception e) { String message = "Failed configuring path for libs for SDK version: " + hansoftSDKVersion + ", will exit."; logger.error(message); throw new RuntimeException(message); } hansoftWorkingDir = props.getProperty("hansoft_working_dir", "").trim(); hansoftChangeLogDir = props.getProperty("hansoft_change_log_dir", "").trim(); hansoftLogDir = props.getProperty("hansoft_log_dir", "").trim(); hansoftServer = props.getProperty("hansoft_server", "").trim(); hansoftPort = Integer.parseInt(props.getProperty("hansoft_port", "-1")); hansoftDatabase = props.getProperty("hansoft_database", "").trim(); hansoftSDK = props.getProperty("hansoft_sdk_user", "").trim(); hansoftSDKPassword = props.getProperty("hansoft_sdk_password", "").trim(); hansoftAdapterServer = props.getProperty("hansoft_adapter_server", "").trim(); hansoftAdapterServerScheme = props.getProperty("hansoft_adapter_server_scheme", "http").trim(); hansoftAdapterServerPort = props.getProperty("hansoft_adapter_server_port", "8080").trim(); validate_h2h_config = props.getProperty("validate_h2h_config", "false").trim(); h2h_config_validation_output_to_file = props.getProperty("h2h_config_validation_output_to_file", "true") .trim(); h2h_config_validation_output_on_screen = props .getProperty("h2h_config_validation_output_on_screen", "true").trim(); OSLC_BACKLINK_COL_NAME = props.getProperty("hansoft_backlink", "OSLC Reference").trim(); String FPs = props.getProperty("hansoft_fps", "").trim(); setHansoftFPs(FPs); logger.log(Level.INFO, "Property hansoft_adapter_server = " + hansoftAdapterServer); logger.log(Level.INFO, "Property hansoft_adapter_server_scheme = " + hansoftAdapterServerScheme); logger.log(Level.INFO, "Property hansoft_adapter_server_port = " + hansoftAdapterServerPort); logger.log(Level.INFO, "Property hansoft_working_dir = " + hansoftWorkingDir); logger.log(Level.INFO, "Property hansoft_change_log_dir = " + hansoftChangeLogDir); logger.log(Level.INFO, "Property hansoft_log_dir = " + hansoftLogDir); logger.log(Level.INFO, "Property hansoft_server = " + hansoftServer); logger.log(Level.INFO, "Property hansoft_port = " + hansoftPort); logger.log(Level.INFO, "Property hansoft_database = " + hansoftDatabase); logger.log(Level.INFO, "Property hansoft_sdk_user = " + hansoftSDK); logger.log(Level.INFO, "Property hansoft_sdk_version = " + hansoftSDKVersion); logger.log(Level.INFO, "Property validate_h2h_config = " + validate_h2h_config); logger.log(Level.INFO, "Property h2h_config_validation_output_to_file = " + h2h_config_validation_output_to_file); logger.log(Level.INFO, "Property h2h_config_validation_output_on_screen = " + h2h_config_validation_output_on_screen); getMainSession(); loadH2HConfiguration(); if (validate_h2h_config.equalsIgnoreCase("true")) { validateH2Hconfiguration(); } QSchedule.getInstance(); } catch (SecurityException | IllegalArgumentException | HPMSdkException | HPMSdkJavaException e) { logger.error("Failed during static init of Hansoft Adapter", e); } }
From source file:com.ngdata.hbaseindexer.mr.TestUtils.java
private static EmbeddedSolrServer createEmbeddedSolrServer(File solrHomeDir, FileSystem fs, Path outputShardDir) throws IOException { LOG.info("Creating embedded Solr server with solrHomeDir: " + solrHomeDir + ", fs: " + fs + ", outputShardDir: " + outputShardDir); // copy solrHomeDir to ensure it isn't modified across multiple unit tests or multiple EmbeddedSolrServer instances File tmpDir = Files.createTempDir(); tmpDir.deleteOnExit();//w w w . j ava2s.c o m FileUtils.copyDirectory(solrHomeDir, tmpDir); solrHomeDir = tmpDir; Path solrDataDir = new Path(outputShardDir, "data"); String dataDirStr = solrDataDir.toUri().toString(); SolrResourceLoader loader = new SolrResourceLoader(Paths.get(solrHomeDir.toString()), null, null); LOG.info(String.format(Locale.ENGLISH, "Constructed instance information solr.home %s (%s), instance dir %s, conf dir %s, writing index to solr.data.dir %s, with permdir %s", solrHomeDir, solrHomeDir.toURI(), loader.getInstancePath(), loader.getConfigDir(), dataDirStr, outputShardDir)); // TODO: This is fragile and should be well documented System.setProperty("solr.directoryFactory", HdfsDirectoryFactory.class.getName()); System.setProperty("solr.lock.type", DirectoryFactory.LOCK_TYPE_HDFS); System.setProperty("solr.hdfs.nrtcachingdirectory", "false"); System.setProperty("solr.hdfs.blockcache.enabled", "false"); System.setProperty("solr.autoCommit.maxTime", "600000"); System.setProperty("solr.autoSoftCommit.maxTime", "-1"); CoreContainer container = new CoreContainer(loader); container.load(); SolrCore core = container.create("core1", Paths.get(solrHomeDir.toString()), ImmutableMap.of(CoreDescriptor.CORE_DATADIR, dataDirStr), false); if (!(core.getDirectoryFactory() instanceof HdfsDirectoryFactory)) { throw new UnsupportedOperationException( "Invalid configuration. Currently, the only DirectoryFactory supported is " + HdfsDirectoryFactory.class.getSimpleName()); } EmbeddedSolrServer solr = new EmbeddedSolrServer(container, "core1"); return solr; }
From source file:de.julielab.jtbd.TokenizerApplication.java
/** * check the file format/*from ww w. ja v a 2 s. c om*/ * * @param orgSentencesFile * @param tokSentencesFile */ private static void doCheck(final File orgSentencesFile, final File tokSentencesFile) { final Tokenizer tokenizer = new Tokenizer(); System.out.println("checking on files: \n * " + orgSentencesFile.toString() + "\n * " + tokSentencesFile.toString() + "\n"); final ArrayList<String> orgSentences = readFile(orgSentencesFile); final ArrayList<String> tokSentences = readFile(tokSentencesFile); final InstanceList trainData = tokenizer.makeTrainingData(orgSentences, tokSentences); final Pipe myPipe = trainData.getPipe(); // System.out.println("\n" + myPipe.getDataAlphabet().toString()); System.out.println("\n\n\n# Features resulting from training data: " + myPipe.getDataAlphabet().size()); System.out.println("(critical sentences were omitted for feature generation)"); System.out.println("Done."); }
From source file:deployer.TestUtils.java
public static File getTargetDir() throws IOException { File currentPath = Files.get("").getAbsoluteFile(); while (currentPath != null && currentPath.getName() != null && !currentPath.getName().equals("target")) { File targetMaybe = Files.resolve(currentPath, "target"); if (Files.exists(targetMaybe)) { return targetMaybe; }// w w w. j ava2 s. co m currentPath = currentPath.getParentFile(); } if (currentPath == null || currentPath.toString().equals("/")) { // target Not found anywhere up the tree. currentPath = Files.resolve(Files.get("").getAbsoluteFile(), "target"); Files.createDirectories(currentPath); } return currentPath; }
From source file:io.druid.java.util.common.CompressionUtils.java
/** * Unzip the byteSource to the output directory. If cacheLocally is true, the byteSource is cached to local disk before unzipping. * This may cause more predictable behavior than trying to unzip a large file directly off a network stream, for example. * * @param byteSource The ByteSource which supplies the zip data * * @param byteSource The ByteSource which supplies the zip data * @param outDir The output directory to put the contents of the zip * @param shouldRetry A predicate expression to determine if a new InputStream should be acquired from ByteSource and the copy attempted again * @param cacheLocally A boolean flag to indicate if the data should be cached locally * * @return A FileCopyResult containing the result of writing the zip entries to disk * * @throws IOException/*from w ww.ja v a 2s . c o m*/ */ public static FileUtils.FileCopyResult unzip(final ByteSource byteSource, final File outDir, final Predicate<Throwable> shouldRetry, boolean cacheLocally) throws IOException { if (!cacheLocally) { try { return RetryUtils.retry(() -> unzip(byteSource.openStream(), outDir), shouldRetry, DEFAULT_RETRY_COUNT); } catch (Exception e) { throw Throwables.propagate(e); } } else { final File tmpFile = File.createTempFile("compressionUtilZipCache", ZIP_SUFFIX); try { FileUtils.retryCopy(byteSource, tmpFile, shouldRetry, DEFAULT_RETRY_COUNT); return unzip(tmpFile, outDir); } finally { if (!tmpFile.delete()) { log.warn("Could not delete zip cache at [%s]", tmpFile.toString()); } } } }
From source file:fr.ens.biologie.genomique.eoulsan.actions.ExecAction.java
/** * Run Eoulsan/*ww w . ja v a 2s . c o m*/ * @param workflowFile workflow file * @param designFile design file * @param jobDescription job description */ private static void run(final File workflowFile, final File designFile, final String jobDescription) { checkNotNull(workflowFile, "paramFile is null"); checkNotNull(designFile, "designFile is null"); final String desc; if (jobDescription == null) { desc = "no job description"; } else { desc = jobDescription.trim(); } getLogger().info("Workflow file: " + workflowFile); getLogger().info("Design file: " + designFile); try { // Test if workflow file exists if (!workflowFile.exists()) { throw new FileNotFoundException(workflowFile.toString()); } // Test if design file exists if (!designFile.exists()) { throw new FileNotFoundException(designFile.toString()); } // Create execution context // Set job environment final String env = "Local Mode on " + new LinuxCpuInfo().getModelName() + ", " + Runtime.getRuntime().availableProcessors() + " CPU(s)/thread(s), " + new LinuxMemInfo().getMemTotal(); // Create ExecutionArgument object final ExecutorArguments arguments = new ExecutorArguments(workflowFile, designFile); arguments.setJobDescription(desc); arguments.setJobEnvironment(env); // Create the log Files Main.getInstance().createLogFiles(arguments.logPath(Globals.LOG_FILENAME), arguments.logPath(Globals.OTHER_LOG_FILENAME)); // Create executor final Executor e = new Executor(arguments); // Launch executor e.execute(); } catch (FileNotFoundException e) { Common.errorExit(e, "File not found: " + e.getMessage()); } catch (Throwable e) { Common.errorExit(e, "Error while executing " + Globals.APP_NAME_LOWER_CASE + ": " + e.getMessage()); } }
From source file:com.apatar.ui.Actions.java
private static File saveAs() throws IOException { fileChooser.setMultiSelectionEnabled(false); fileChooser.setFileFilter(FF);//w w w.j av a2s . co m int returnValue = fileChooser.showSaveDialog(ApatarUiMain.MAIN_FRAME); File fileSrc = null; if (returnValue == JFileChooser.APPROVE_OPTION) { fileSrc = fileChooser.getSelectedFile(); ReadWriteXMLDataUi rwXMLdata = new ReadWriteXMLDataUi(); rwXMLdata.writeXMLData(fileSrc.toString(), ApplicationData.getProject(), false); ApplicationData.PROJECT_PATH = fileSrc.getPath(); } ApatarUiMain.MAIN_FRAME.setTitle(String.format(JApatarMainUIFrame.FRAME_TITLE, fileSrc.getName() + " - ")); return fileSrc; }
From source file:edu.umass.cs.contextservice.installer.CSInstaller.java
private static void loadConfig(String configName) { File configFile = fileSomewhere(configName + FILESEPARATOR + INSTALLER_CONFIG_FILENAME, confFolderPath); InstallConfig installConfig = new InstallConfig(configFile.toString()); keyFile = installConfig.getKeyFile(); System.out.println("Key File: " + keyFile); userName = installConfig.getUsername(); System.out.println("User Name: " + userName); hostType = installConfig.getHostType(); System.out.println("Host Type: " + hostType); installPath = installConfig.getInstallPath(); if (installPath == null) { installPath = DEFAULT_INSTALL_PATH; }//from ww w . j a va 2 s . c o m System.out.println("Install Path: " + installPath); // javaCommand = installConfig.getJavaCommand(); if (javaCommand == null) { javaCommand = DEFAULT_JAVA_COMMAND; } System.out.println("Java Command: " + javaCommand); }
From source file:Exec.java
static Process execWindows(String[] cmdarray, String[] envp, File directory) throws IOException { if (envp != null || directory != null) { if (isJview()) // jview doesn't support JNI, so can't call putenv/chdir throw new IOException("can't use Exec.exec() under Microsoft JVM"); if (!linked) { try { System.loadLibrary("win32exec"); linked = true;//from www .j a va 2s .c om } catch (LinkageError e) { throw new IOException("can't use Exec.exec(): " + e.getMessage()); } } if (envp != null) { for (int i = 0; i < envp.length; ++i) putenv(envp[i]); } if (directory != null) chdir(directory.toString()); } return Runtime.getRuntime().exec(cmdarray); }