List of usage examples for java.io File toURI
public URI toURI()
From source file:net.jmhertlein.alphonseirc.MSTDeskEngRunner.java
private static void loadConfig() { boolean read = false; File f = CONFIG_FILE; if (!f.exists()) { read = true;/* w ww .j a va 2 s . c o m*/ try { f.getParentFile().mkdirs(); f.createNewFile(); java.nio.file.Files.setPosixFilePermissions(Paths.get(f.toURI()), PosixFilePermissions.fromString("rw-------")); } catch (IOException ex) { Logger.getLogger(MSTDeskEngRunner.class.getName()).log(Level.SEVERE, null, ex); System.err.println("Error writing empty config.yml!"); } } Map<String, Object> config; if (read) { Console console = System.console(); console.printf("Nick: \n->"); nick = console.readLine(); console.printf("\nPassword: \n-|"); pass = new String(console.readPassword()); console.printf("\nServer: \n->"); server = console.readLine(); console.printf("\nChannels: (ex: #java,#linux,#gnome)\n->"); channels = Arrays.asList(console.readLine().split(",")); System.out.println("Fetching max XKCD..."); maxXKCD = fetchMaxXKCD(); System.out.println("Fetched."); cachedUTC = System.currentTimeMillis(); dadLeaveTimes = new HashMap<>(); noVoiceNicks = new HashSet<>(); writeConfig(); System.out.println("Wrote config to file: " + CONFIG_FILE.getAbsolutePath()); } else { try (FileInputStream fis = new FileInputStream(f)) { Yaml y = new Yaml(); config = y.loadAs(fis, Map.class); } catch (IOException ex) { Logger.getLogger(MSTDeskEngRunner.class.getName()).log(Level.SEVERE, null, ex); System.err.println("Error parsing config!"); return; } nick = (String) config.get("nick"); pass = (String) config.get("password"); server = (String) config.get("server"); channels = (List<String>) config.get("channels"); maxXKCD = (Integer) config.get("cachedMaxXKCD"); cachedUTC = (Long) config.get("cachedUTC"); noVoiceNicks = (Set<String>) config.get("noVoiceNicks"); masters = (Set<String>) config.get("masters"); if (masters == null) { masters = new HashSet<>(); masters.add("Everdras"); } if (noVoiceNicks == null) noVoiceNicks = new HashSet<>(); noVoiceNicks.stream().forEach((s) -> System.out.println("Loaded novoice nick: " + s)); masters.stream().forEach((s) -> System.out.println("Loaded master nick: " + s)); if (checkXKCDUpdate()) writeConfig(); else System.out.println("Loaded cached XKCD."); Map<String, Object> serialDadLeaveTimes = (Map<String, Object>) config.get("dadLeaveTimes"); dadLeaveTimes = new HashMap<>(); if (serialDadLeaveTimes != null) serialDadLeaveTimes.keySet().stream().forEach((time) -> { dadLeaveTimes.put(LocalDate.parse(time), LocalTime.parse((String) serialDadLeaveTimes.get(time))); }); } }
From source file:com.asakusafw.testdriver.DirectIoUtil.java
private static <T> DataModelSourceFactory load0(DataModelDefinition<T> definition, HadoopFileFormat<? super T> format, File source) throws IOException, InterruptedException { try (ModelInput<? super T> input = format.createInput(definition.getModelClass(), org.apache.hadoop.fs.FileSystem.getLocal(format.getConf()), new org.apache.hadoop.fs.Path(source.toURI()), new Counter())) { return collect(definition, input); }//from w w w.ja va 2s . c om }
From source file:com.googlecode.dex2jar.test.TestUtils.java
public static File dex(List<File> files, File distFile) throws Exception { String dxJar = "src/test/resources/dx.jar"; File dxFile = new File(dxJar); if (!dxFile.exists()) { throw new RuntimeException("dx.jar?"); }/*from w w w. ja v a 2 s . c o m*/ URLClassLoader cl = new URLClassLoader(new URL[] { dxFile.toURI().toURL() }); Class<?> c = cl.loadClass("com.android.dx.command.Main"); Method m = c.getMethod("main", String[].class); if (distFile == null) { distFile = File.createTempFile("dex", ".dex"); } List<String> args = new ArrayList<String>(); args.addAll(Arrays.asList("--dex", "--no-strict", "--output=" + distFile.getCanonicalPath())); for (File f : files) { args.add(f.getCanonicalPath()); } m.invoke(null, new Object[] { args.toArray(new String[0]) }); return distFile; }
From source file:au.org.ala.delta.intkey.model.StartupUtils.java
/** * Save a copy of a dataset that was opened from a remote location * /*from ww w .ja v a 2 s .com*/ * @param context * Intkey context * @param saveDir * Directory in which to save a copy of the dataset * @return A copy of the JNLP-style dataset startup file to use to open the * saved copy of the dataset. * @throws IOException * If saving to disk failed. */ public static File saveRemoteDataset(IntkeyContext context, File saveDir) throws IOException { StartupFileData startupFileData = context.getStartupFileData(); File datasetZip = startupFileData.getDataFileLocalCopy(); // Copy the zipped dataset as downloaded from the web // FileUtils.copyFileToDirectory(datasetZip, saveDir); // Copy the zipped dataset as downloaded from the web // Use utility method to avoid overwriting existing files with the same // name File copyZipFile = Utils.getSaveFileForDirectory(saveDir, datasetZip.getName()); FileUtils.copyFile(datasetZip, copyZipFile); // Write a new .ink file // Use utility method to avoid overwriting existing files with the same // name File newInkFile = Utils.getSaveFileForDirectory(saveDir, FilenameUtils.getName(startupFileData.getInkFileLocation().getFile())); FileWriter fw = new FileWriter(newInkFile); BufferedWriter bufFW = new BufferedWriter(fw); bufFW.append(INIT_FILE_INK_FILE_KEYWORD); bufFW.append("="); bufFW.append(newInkFile.toURI().toURL().toString()); bufFW.append("\n"); bufFW.append(INIT_FILE_DATA_FILE_KEYWORD); bufFW.append("="); bufFW.append(copyZipFile.toURI().toURL().toString()); bufFW.append("\n"); bufFW.append(INIT_FILE_INITIALIZATION_FILE_KEYWORD); bufFW.append("="); bufFW.append(startupFileData.getInitializationFileLocation()); bufFW.append("\n"); String imagePath = startupFileData.getImagePath(); if (imagePath != null) { bufFW.append(INIT_FILE_IMAGE_PATH_KEYWORD); bufFW.append("="); bufFW.append(imagePath); bufFW.append("\n"); } String infoPath = startupFileData.getInfoPath(); if (infoPath != null) { bufFW.append(INIT_FILE_INFO_PATH_KEYWORD); bufFW.append("="); bufFW.append(infoPath); bufFW.append("\n"); } bufFW.flush(); bufFW.close(); return newInkFile; }
From source file:com.offbynull.coroutines.instrumenter.testhelpers.TestUtils.java
/** * Opens up a ZIP resource, instruments the classes within, and returns a {@link URLClassLoader} object with access to those classes. * @param path path of zip resource//from w w w .ja v a 2 s . c o m * @return class loader able to access instrumented classes * @throws NullPointerException if any argument is {@code null} * @throws IOException if an IO error occurs */ public static URLClassLoader loadClassesInZipResourceAndInstrument(String path) throws IOException { Validate.notNull(path); // Load original class Map<String, byte[]> classContents = readZipFromResource(path); // Create JAR out of original classes so it can be found by the instrumenter List<JarEntry> originalJarEntries = new ArrayList<>(classContents.size()); for (Entry<String, byte[]> entry : classContents.entrySet()) { originalJarEntries.add(new JarEntry(entry.getKey(), entry.getValue())); } File originalJarFile = createJar(originalJarEntries.toArray(new JarEntry[0])); // Get classpath used to run this Java process and addIndividual the jar file we created to it (used by the instrumenter) List<File> classpath = getClasspath(); classpath.add(originalJarFile); // Instrument classes and write out new jar Instrumenter instrumenter = new Instrumenter(classpath); List<JarEntry> instrumentedJarEntries = new ArrayList<>(classContents.size()); for (Entry<String, byte[]> entry : classContents.entrySet()) { byte[] content = entry.getValue(); if (entry.getKey().endsWith(".class")) { content = instrumenter.instrument(content); } instrumentedJarEntries.add(new JarEntry(entry.getKey(), content)); } File instrumentedJarFile = createJar(instrumentedJarEntries.toArray(new JarEntry[0])); // Load up classloader with instrumented jar return URLClassLoader.newInstance(new URL[] { instrumentedJarFile.toURI().toURL() }, TestUtils.class.getClassLoader()); }
From source file:net.bpelunit.util.ZipUtil.java
public static void zipDirectory(File directory, File zipFile) throws IOException { @SuppressWarnings("unchecked") Collection<File> files = FileUtils.listFiles(directory, null, true); FileOutputStream fzos = null; ZipOutputStream zos = null;/* w ww. j av a2 s . c om*/ try { fzos = new FileOutputStream(zipFile); zos = new ZipOutputStream(fzos); for (File f : files) { String fileNameInZIP = directory.toURI().relativize(f.toURI()).getPath(); ZipEntry zipEntry = new ZipEntry(fileNameInZIP); zos.putNextEntry(zipEntry); FileInputStream fileInputStream = new FileInputStream(f); try { IOUtils.copy(fileInputStream, zos); } finally { IOUtils.closeQuietly(fileInputStream); } } } finally { IOUtils.closeQuietly(zos); IOUtils.closeQuietly(fzos); } }
From source file:org.eclipse.virgo.ide.manifest.core.BundleManifestUtils.java
/** * Converts a given {@link IResource} into a full qualified {@link URI} honoring eventual used Eclipse variables in * the path expression.//from w w w .j a v a 2s.c o m */ private static URI convertResourceToUrl(IResource resource) { if (resource != null) { URI uri = resource.getRawLocationURI(); if (uri != null) { String scheme = uri.getScheme(); if (FILE_SCHEME.equalsIgnoreCase(scheme)) { return uri; } else if ("sourcecontrol".equals(scheme)) { // special case of Rational Team Concert IPath path = resource.getLocation(); File file = path.toFile(); if (file.exists()) { return file.toURI(); } } else { IPathVariableManager variableManager = ResourcesPlugin.getWorkspace().getPathVariableManager(); return variableManager.resolveURI(uri); } } } return null; }
From source file:de.xwic.sandbox.base.model.util.ConfigurationUtil.java
/** * */// w ww . j a va 2 s .c o m public static void reloadConfiguration() { // load product configuration File path = new File(SandboxModelConfig.getWebRootDirectory(), "config"); Setup setup; try { setup = XmlConfigLoader.loadSetup(path.toURI().toURL()); } catch (Exception e) { log.error("Error loading product configuration", e); throw new RuntimeException("Error loading product configuration: " + e, e); } // merge server specific settings InputStream in = null; Properties srvProp = new Properties(); try { File serverPropertiesFile = new File(SandboxModelConfig.getWebRootDirectory(), "WEB-INF/server.properties"); if (!serverPropertiesFile.exists()) { throw new RuntimeException("server.properties not found."); } in = new FileInputStream(serverPropertiesFile); if (in != null) { srvProp.load(in); for (Object prop : srvProp.keySet()) { String key = (String) prop; setup.setProperty(key, srvProp.getProperty(key)); } } } catch (Exception e) { log.error("Error loading Server properties", e); throw new RuntimeException("Error loading Server properties", e); } finally { if (in != null) { try { in.close(); } catch (final IOException e) { log.error("Failed to close the input stream!", e); } } } ConfigurationManager.setSetup(setup); log.info("Configuration loaded: " + setup.getAppTitle() + " version " + setup.getVersion()); }
From source file:org.wso2.carbon.identity.jwt.client.extension.util.JWTClientUtil.java
public static void initialize(JWTClientManagerService jwtClientManagerService) throws RegistryException, IOException, JWTClientConfigurationException { File configFile = new File(SUPERTENANT_JWT_CONFIG_LOCATION); if (configFile.exists()) { InputStream propertyStream = null; try {//from w w w . java 2 s . com propertyStream = configFile.toURI().toURL().openStream(); Properties properties = new Properties(); properties.load(propertyStream); jwtClientManagerService.setDefaultJWTClient(properties); } finally { if (propertyStream != null) { propertyStream.close(); } } } }
From source file:com.ejisto.util.IOUtils.java
public static URL[] toUrlArray(WebApplicationDescriptor descriptor) throws MalformedURLException { List<URL> urls = new ArrayList<>(); File base = new File(descriptor.getInstallationPath(), "WEB-INF"); File classes = new File(base, "classes"); File lib = new File(base, "lib"); if (classes.exists()) { urls.add(classes.toURI().toURL()); }/*ww w .ja v a 2 s. com*/ for (WebApplicationDescriptorElement element : descriptor.getClassPathElements()) { urls.add(new File(lib, element.getPath()).toURI().toURL()); } return urls.toArray(new URL[urls.size()]); }