/** * reads lib command line argument to add more classes in CP considers its as pathSeparator * separated string, looks in directories */ List<URL> getExtendClassPath() { String extraClassPaths = parameters.get("-lib"); if (extraClassPaths == null) return null; String libPaths[] = extraClassPaths.split(File.pathSeparator); List<URL> extraUrls = new ArrayList<URL>(); for (String path : libPaths) { File filePath = new File(path); if (filePath.isDirectory()) { File[] files = filePath.listFiles( new FilenameFilter() { public boolean accept(File arg0, String name) { return Misc.hasValidClassLibExtension(name); } }); for (File file : files) { try { extraUrls.add(file.toURL()); } catch (MalformedURLException e) { logger.warning("Skipped :'" + file + "', because:" + e); } } } else if (filePath.isFile()) if (Misc.hasValidClassLibExtension(filePath.getName())) try { extraUrls.add(filePath.toURL()); } catch (MalformedURLException e) { logger.warning("Skipped :'" + filePath + "', because:" + e); } } return extraUrls; }
/** @see java.net.URLStreamHandler#openConnection(URL) */ protected URLConnection openConnection(URL u) throws IOException { try { URL otherURL = new URL(u.getFile()); String host = otherURL.getHost(); String protocol = otherURL.getProtocol(); int port = otherURL.getPort(); String file = otherURL.getFile(); String query = otherURL.getQuery(); // System.out.println("Trying to load: " + u.toExternalForm()); String internalFile = null; if (file.indexOf("!/") != -1) { internalFile = file.substring(file.indexOf("!/") + 2); file = file.substring(0, file.indexOf("!/")); } URL subURL = new URL(protocol, host, port, file); File newFile; if (cacheList.containsKey(subURL.toExternalForm())) { newFile = cacheList.get(subURL.toExternalForm()); } else { InputStream is = (InputStream) subURL.getContent(); String update = subURL.toExternalForm().replace(":", "_"); update = update.replace("/", "-"); File f = File.createTempFile("pack", update); f.deleteOnExit(); FileOutputStream fostream = new FileOutputStream(f); copyStream(new BufferedInputStream(is), fostream); // Unpack newFile = File.createTempFile("unpack", update); newFile.deleteOnExit(); fostream = new FileOutputStream(newFile); BufferedOutputStream bos = new BufferedOutputStream(fostream, 50 * 1024); JarOutputStream jostream = new JarOutputStream(bos); Unpacker unpacker = Pack200.newUnpacker(); long start = System.currentTimeMillis(); unpacker.unpack(f, jostream); printMessage( "Unpack of " + update + " took " + (System.currentTimeMillis() - start) + "ms"); jostream.close(); fostream.close(); cacheList.put(subURL.toExternalForm(), newFile); } if (internalFile != null) { URL directoryURL = new URL("jar:" + newFile.toURL().toExternalForm() + "!/" + internalFile); printMessage("Using DirectoryURL:" + directoryURL); return directoryURL.openConnection(); } else return newFile.toURL().openConnection(); } catch (Exception ex) { ex.printStackTrace(); } printMessage("Returning null for: " + u.toExternalForm()); return null; }
private static ClassLoader toolsClassLoader() { File javaHome = new File(System.getProperty("java.home")); File classesDir = new File(javaHome, "classes"); File libDir = new File(javaHome.getParentFile(), "lib"); File toolsJar = new File(libDir, "tools.jar"); try { return new URLClassLoader(new URL[] {classesDir.toURL(), toolsJar.toURL()}); } catch (MalformedURLException e) { throw new AssertionError(e); } }
/** * Method to read in a vector layer * * @param layer * @param filename * @param layerDescription * @param attributes - optional: include only the given attributes */ synchronized void readInVectorLayer( GeomVectorField layer, String filename, String layerDescription, Bag attributes) { try { System.out.print("Reading in " + layerDescription + "from " + filename + "..."); File file = new File(filename); if (attributes == null || attributes.size() == 0) ShapeFileImporter.read(file.toURL(), layer); else ShapeFileImporter.read(file.toURL(), layer, attributes); System.out.println("done"); } catch (Exception e) { e.printStackTrace(); } }
/** * Setting the internal field {@link #document} directly (bypassing {@link #setDocument(URL)}) is * used to deplay the document loading until {@link #ready()}. */ @Override protected void initialize(final String[] as) { if ("Linux".equals(System.getProperty("os.name"))) getContext().getResourceManager().setPlatform("linux"); final Class<?> mc = this.getClass(); { final ResourceMap r = Application.getInstance().getContext().getResourceMap(); initialScene = mc.getResource("/" + r.getResourcesDir() + r.getString("Application.defaultDocument")); templateScene = mc.getResource("/" + r.getResourcesDir() + r.getString("Application.templateDocument")); } // schedule the document to load in #ready() document = initialScene; for (final String p : as) { // ignore javaws parameters if ("-open".equals(p) || "-print".equals(p)) continue; try { document = new URL(p); break; } catch (final MalformedURLException e) { final File f = new File(p); if (f.canRead()) try { document = f.toURL(); break; } catch (final MalformedURLException e2) { log.warn("Cannot load '" + p + "'.", e); } else log.warn("Cannot load '" + p + "'.", e); } } }
public URL loadGroovySource(String className) throws MalformedURLException { if (className == null) return null; File file = getSourceFile(className); if (file != null) { return file.toURL(); } file = new File(className); if (file.exists()) { return file.toURL(); } return null; }
@SuppressWarnings("deprecation") private ByteArray duplicateByteArray(File initFile) { ByteArray byteArray = PropertiesFactory.eINSTANCE.createByteArray(); InputStream stream = null; try { stream = initFile.toURL().openStream(); byte[] innerContent = new byte[stream.available()]; stream.read(innerContent); byteArray.setInnerContent(innerContent); } catch (IOException e) { ExceptionHandler.process(e); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { // } } } String routineContent = new String(byteArray.getInnerContent()); byteArray.setInnerContent(routineContent.getBytes()); return byteArray; }
public void initialise() throws InitialisationException { try { GroovyClassLoader loader = new GroovyClassLoader(getClass().getClassLoader()); // defaults to the logical name of the Transformer can be changed by explicit setting of the // scriptName if (script == null) { script = getName() + ".groovy"; } if (scriptLocation == null) { scriptLocation = loader.getResource(script); } if (scriptLocation == null) { File file = new File(script); if (file.exists()) { scriptLocation = file.toURL(); } else { throw new InitialisationException( new Message(Messages.CANT_LOAD_X_FROM_CLASSPATH_FILE, "Groovy Script: " + script), this); } } logger.info("Loading Groovy transformer with script " + scriptLocation.toExternalForm()); Class groovyClass = loader.parseClass(new GroovyCodeSource(scriptLocation)); transformer = (GroovyObject) groovyClass.newInstance(); } catch (Exception e) { throw new InitialisationException( new Message(Messages.FAILED_TO_CREATE_X, "Groovy transformer"), e, this); } }
public void testLoadFromLibraryGroup() throws UnableToCompleteException, IOException, IncompatibleLibraryVersionException { // Create the library zip file. File zipFile = File.createTempFile("FooLib", ".gwtlib"); zipFile.deleteOnExit(); // Put data in the library and save it. ZipLibraryWriter zipLibraryWriter = new ZipLibraryWriter(zipFile.getPath()); zipLibraryWriter.setLibraryName("FooLib"); MockResource userXmlResource = new MockResource("com/google/gwt/user/User.gwt.xml") { @Override public CharSequence getContent() { return "<module></module>"; } }; zipLibraryWriter.addBuildResource(userXmlResource); zipLibraryWriter.write(); // Read data back from disk. ZipLibrary zipLibrary = new ZipLibrary(zipFile.getPath()); // Prepare the LibraryGroup and ResourceLoader. compilerContext = compilerContextBuilder .libraryGroup( LibraryGroup.fromLibraries(Lists.<Library>newArrayList(zipLibrary), false)) .build(); ResourceLoader resourceLoader = ResourceLoaders.wrap(new URLClassLoader(new URL[] {zipFile.toURL()}, null)); // Will throw an exception if com.google.gwt.user.User can't be found and parsed. ModuleDefLoader.loadFromResources( TreeLogger.NULL, compilerContext, "com.google.gwt.user.User", resourceLoader, false); }
/** * This over-ridden method is same as super method except this does a axisConfig.getRepository() * == null before setting the repo. This is done because with Stratos, we can not set the repo * twice. * * @param repoDir * @throws DeploymentException */ @Override public void loadRepository(String repoDir) throws DeploymentException { File axisRepo = new File(repoDir); if (!axisRepo.exists()) { throw new DeploymentException(Messages.getMessage("cannotfindrepo", repoDir)); } setDeploymentFeatures(); prepareRepository(repoDir); // setting the CLs setClassLoaders(repoDir); repoListener = new RepositoryListener(this, false); org.apache.axis2.util.Utils.calculateDefaultModuleVersion(axisConfig.getModules(), axisConfig); try { try { if (axisConfig.getRepository() == null) { // we set axisConfig.setRepository(axisRepo.toURL()); } } catch (MalformedURLException e) { log.info(e.getMessage()); } axisConfig.validateSystemPredefinedPhases(); } catch (AxisFault axisFault) { throw new DeploymentException(axisFault); } }
/** * Returns a map containing all sources found by a recursive search. * * @param src start directory * @param extension only files with this extension are added * @return */ protected Map<String, URL> findFiles(String base, String src, String extension) { Map<String, URL> result = new TreeMap<String, URL>(); File searchbase = new File(base, src); File[] files = searchbase.listFiles(); if (files != null) { for (File singlefile : files) { if (singlefile.isDirectory()) { result.putAll(findFiles(base, src + File.separator + singlefile.getName(), extension)); } if (singlefile.isFile()) { if (singlefile.getName().endsWith(extension)) { try { String filename = src + File.separator + singlefile.getName(); filename = filename.replaceAll("^/", ""); // remove leading slash filename = filename.replaceAll(extension + "$", ""); // remove extension result.put(filename, singlefile.toURL()); } catch (MalformedURLException e) { e.printStackTrace(); } } } } } return result; }
public BundleInfo[] save(Manipulator manipulator, boolean backup) throws IOException { List setToInitialConfig = new LinkedList(); List setToSimpleConfig = new LinkedList(); ConfigData configData = manipulator.getConfigData(); if (!divideBundleInfos( manipulator, setToInitialConfig, setToSimpleConfig, configData.getInitialBundleStartLevel())) return configData.getBundles(); File outputFile = getConfigFile(manipulator); URI installArea = ParserUtils.getOSGiInstallArea( Arrays.asList(manipulator.getLauncherData().getProgramArgs()), manipulator.getConfigData().getProperties(), manipulator.getLauncherData()) .toURI(); saveConfiguration( (BundleInfo[]) setToSimpleConfig.toArray(new BundleInfo[setToSimpleConfig.size()]), outputFile, installArea, backup); configData.setProperty( SimpleConfiguratorManipulatorImpl.PROP_KEY_CONFIGURL, outputFile.toURL().toExternalForm()); return orderingInitialConfig(setToInitialConfig); }
// TODO: Do not swallow exception public void initializeResources() throws PlexusConfigurationException { PlexusConfiguration[] resourceConfigs = configuration.getChild("resources").getChildren(); for (int i = 0; i < resourceConfigs.length; ++i) { try { String name = resourceConfigs[i].getName(); if (name.equals("jar-repository")) { addJarRepository(new File(resourceConfigs[i].getValue())); } else if (name.equals("directory")) { File directory = new File(resourceConfigs[i].getValue()); if (directory.exists() && directory.isDirectory()) { plexusRealm.addConstituent(directory.toURL()); } } else { getLogger().warn("Unknown resource type: " + name); } } catch (MalformedURLException e) { getLogger() .error( "Error configuring resource: " + resourceConfigs[i].getName() + "=" + resourceConfigs[i].getValue(), e); } } }
protected static DOMWrapper makeDOMWrapper(final File file) { try { return makeDOMWrapper(file.toURL()); } catch (MalformedURLException e) { throw mres.AggRuleParse.ex(file.getName(), e); } }
public URL getFileURL() { try { return file.toURL(); } catch (MalformedURLException e) { return null; } }
@SuppressWarnings("deprecation") public URL getResource(String path) throws MalformedURLException { if (path == null) { return null; } path = adjustPath(path); File src = ResourceUtil.getResourceAsFile("."); File root = src.getParentFile(); if (root.getName().equalsIgnoreCase("WEB-INF")) { root = root.getParentFile(); } while (root != null) { File file = new File(root, path); if (file.exists()) { return file.toURL(); } root = root.getParentFile(); } if (ResourceUtil.isExist(path)) { return ResourceUtil.getResource(path); } if (path.startsWith("WEB-INF")) { path = path.substring("WEB-INF".length()); return getResource(path); } return null; }
static String getMavenVersion(File mavenHome) { File mavenLib = new File(mavenHome, "lib"); File[] jarFiles = mavenLib.listFiles( new FilenameFilter() { public boolean accept(File dir, String name) { return name.endsWith(".jar"); } }); for (File file : jarFiles) { try { @SuppressWarnings("deprecation") URL url = new URL( "jar:" + file.toURL().toExternalForm() + "!/META-INF/maven/org.apache.maven/maven-core/pom.properties"); Properties properties = new Properties(); properties.load(url.openStream()); String version = StringUtils.trim(properties.getProperty("version")); if (version != null) { return version; } } catch (MalformedURLException e) { // ignore } catch (IOException e) { // ignore } } return null; }
protected static XMLStreamReader2 constructStreamReaderForFile(XMLInputFactory f, String filename) throws IOException, XMLStreamException { File inf = new File(filename); XMLStreamReader sr = f.createXMLStreamReader(inf.toURL().toString(), new FileReader(inf)); assertEquals(sr.getEventType(), START_DOCUMENT); return (XMLStreamReader2) sr; }
@Override protected void handleArchiveByFile(File file, final Set<String> classes, final Set<URL> urls) throws IOException { log.tracev("archive: {0}", file); //noinspection deprecation handleURL(file.toURL(), classes, urls); }
/** * Load image from resource path (using getResource). Note that GIFs are loaded as _translucent_ * indexed images. Images are cached: loading an image with the same name twice will get the * cached image the second time. If you want to remove an image from the cache, use purgeImage. * Throws JGError when there was an error. */ @SuppressWarnings({"deprecation", "unchecked"}) public JGImage loadImage(String imgfile) { Image img = (Image) loadedimages.get(imgfile); if (img == null) { URL imgurl = getClass().getResource(imgfile); if (imgurl == null) { try { File imgf = new File(imgfile); if (imgf.canRead()) { imgurl = imgf.toURL(); } else { imgurl = new URL(imgfile); // throw new JGameError( // "File "+imgfile+" not found.",true); } } catch (MalformedURLException e) { // e.printStackTrace(); throw new JGameError("File not found or malformed path or URL '" + imgfile + "'.", true); } } img = output_comp.getToolkit().createImage(imgurl); loadedimages.put(imgfile, img); } try { ensureLoaded(img); } catch (Exception e) { // e.printStackTrace(); throw new JGameError("Error loading image " + imgfile); } return new JREImage(img); }
package com.oyl.base.util; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import org.apache.commons.configuration.Configuration; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.ConfigurationFactory; import org.apache.commons.configuration.ConversionException; public class BaseXmlConfig { public static final String MODE_DEV = "development"; protected static final String ERR_NOELEMENT = "###NO SUCH ELEMENT###"; protected static final String ERR_CONVERT = "###CONVERSION ERROR###"; protected static final String ERR_GENERAL = "###ERROR###"; protected static final String NUMERIC_ERR_IND = "-1"; protected static final String BLANKS = " "; // 40 spaces protected static final String NL = System.getProperty("line.separator"); protected static final List EMPTY_LIST = new ArrayList(); protected static Map configReg = new HashMap(); protected Map configMap; protected Configuration config; // ------------------ CONSTRUCTORS --------------------*/ protected BaseXmlConfig(File cfgFile) throws ConfigurationException, MalformedURLException { ConfigurationFactory factory = new ConfigurationFactory(); URL configURL = cfgFile.toURL(); factory.setConfigurationURL(configURL); config = factory.getConfiguration(); configMap = new HashMap(); }
private URL validateStoreURL(String storeURL) throws IOException { URL url = null; // First see if this is a URL try { url = new URL(storeURL); } catch (MalformedURLException e) { // Not a URL or a protocol without a handler } // Next try to locate this as file path if (url == null) { File tst = new File(storeURL); if (tst.exists() == true) url = tst.toURL(); } // Last try to locate this as a classpath resource if (url == null) { ClassLoader loader = SubjectActions.getContextClassLoader(); url = loader.getResource(storeURL); } // Fail if no valid key store was located if (url == null) { String msg = "Failed to find url=" + storeURL + " as a URL, file or resource"; throw new MalformedURLException(msg); } return url; }
/** * Mise à jour du classpath courant par ajout des jars spécifiés (s'ils ne sont pas déjà présents * au sein du classpath). * * @param neededJars Liste des jars à charger * @throws SonosException Error */ protected void updateCurrentClasspath(final List<File> neededJars) throws SonosException { File jar = null; final Iterator<File> itr = neededJars.iterator(); final Method m = getAddUrlMethod(); final URLClassLoader l = getURLClassLoader(); final List<String> alreadyLoadedJars = getAlreadyLoadedJar(l); while (itr.hasNext()) { jar = itr.next(); if (!jar.exists()) { throw new SonosException("Expected jar not found [" + jar.getAbsolutePath() + "]"); } // CHECKSTYLE:OFF TODO later if ((alreadyLoadedJars != null) && alreadyLoadedJars.contains(jar.getAbsolutePath())) { // doublon // CHECKSTYLE:ON } else { try { m.invoke(l, new Object[] {jar.toURL()}); } catch (final IllegalArgumentException e) { throw new SonosException(e); } catch (final MalformedURLException e) { throw new SonosException(e); } catch (final IllegalAccessException e) { throw new SonosException(e); } catch (final InvocationTargetException e) { throw new SonosException(e); } } } }
/** * Returns an InputStream pointed at an imported wsdl pathname relative to the parent document. * * @param importPath identifies the WSDL file within the context * @return a stream of the WSDL file */ protected InputStream getInputStream(String importPath) throws IOException { URL importURL = null; InputStream is = null; try { importURL = new URL(importPath); is = importURL.openStream(); } catch (Throwable t) { // No FFDC required } if (is == null) { try { is = classLoader.getResourceAsStream(importPath); } catch (Throwable t) { // No FFDC required } } if (is == null) { try { File file = new File(importPath); is = file.toURL().openStream(); } catch (Throwable t) { // No FFDC required } } if (is == null) { try { URI uri = new URI(importPath); is = uri.toURL().openStream(); } catch (Throwable t) { // No FFDC required } } return is; }
/** Load preferences, saving defaults if file not present */ public void load() { File propsFile = new File(path + File.separatorChar + "repgcode.properties"); if (propsFile.exists()) { try { p.load(propsFile.toURL().openStream()); } catch (Exception e) { } } // Try and intelligently guess port name String osName = System.getProperty("os.name").toLowerCase(); String defaultPort; if (osName.length() >= 7 && osName.substring(0, 7).equals("windows")) { defaultPort = "COM1"; } else { defaultPort = "/dev/ttyS0"; } p.setProperty("Port(name)", p.getProperty("Port(name)", defaultPort)); p.setProperty("Units", p.getProperty("Units", "mm")); p.setProperty("JogIncrement", p.getProperty("JogIncrement", "1.0")); p.setProperty("JogFeedRate", p.getProperty("JogFeedRate", "300.0")); p.setProperty("CoordMode", p.getProperty("CoordMode", "absolute")); save(); }
/** * Obtiene la URL de un fichero. La búsqueda de realiza en el orden siguiente: * * <ul> * <li>Classpath de la aplicación * <li>Classpath del sistema * <li>Ruta absoluta * </ul> * * @param resource Nombre del fichero. * @return URL del fichero. */ public static URL getFileURL(String resource) { URL url = null; if (resource != null) { // Comprobar el fichero en el classpath de la aplicación url = ISPACConfigLocation.class.getClassLoader().getResource(resource); if (url == null) { // Comprobar el fichero en el classpath del sistema url = ClassLoader.getSystemResource(resource); if (url == null) { try { // Fichero con path relativo a la aplicación String appPath = ISPACConfigLocation.getInstance().get(APP_PATH); if (StringUtils.isNotBlank(appPath)) { File file = new File(appPath + resource); if (file.isFile()) { url = file.toURL(); } } } catch (Exception e) { url = null; } if (url == null) { try { // Fichero con path absoluto File file = new File(resource); if (file.isFile()) { url = file.toURL(); } } catch (Exception e) { url = null; } } } } } return url; }
public XmlMapping(File file) { properties = new Properties(); try { properties.loadFromXML(file.toURL().openStream()); } catch (Exception e) { } }
private InputSource fileToInputSource(File source) { try { String url = source.toURL().toExternalForm(); return new InputSource(Util.escapeSpace(url)); } catch (MalformedURLException e) { return new InputSource(source.getPath()); } }
private URL getWsdl() throws Exception { String wsdlLocation = "/test/org/apache/axis2/jaxws/provider/addressing/META-INF/AddressingProvider.wsdl"; String baseDir = new File(System.getProperty("basedir", ".")).getCanonicalPath(); wsdlLocation = new File(baseDir + wsdlLocation).getAbsolutePath(); File file = new File(wsdlLocation); return file.toURL(); }
private URL copyLocation(Map map) throws Exception { MapEnvironment env = new MapEnvironment(map); File file = File.createTempFile("votcopy", ".vot"); file.deleteOnExit(); env.setValue("out", file.toString()).setValue("href", "false"); new VotCopy().createExecutable(env).execute(); return file.toURL(); }