List of usage examples for java.io File toURL
@Deprecated public URL toURL() throws MalformedURLException
file:
URL. From source file:se.jguru.nazgul.tools.plugin.checkstyle.exec.DefaultCheckstyleExecutor.java
public CheckstyleResults executeCheckstyle(CheckstyleExecutorRequest request) throws CheckstyleExecutorException, CheckstyleException { // Checkstyle will always use the context classloader in order // to load resources (dtds), so we have to fix it // olamy this hack is not anymore needed in Maven 3.x ClassLoader checkstyleClassLoader = PackageNamesLoader.class.getClassLoader(); Thread.currentThread().setContextClassLoader(checkstyleClassLoader); if (getLogger().isDebugEnabled()) { getLogger().debug("executeCheckstyle start headerLocation : " + request.getHeaderLocation()); }/*w w w .j a v a 2 s . co m*/ MavenProject project = request.getProject(); configureResourceLocator(locator, request, null); configureResourceLocator(licenseLocator, request, request.getLicenseArtifacts()); // Config is less critical than License, locator can still be used. // configureResourceLocator( configurationLocator, request, request.getConfigurationArtifacts() ); List<File> files; try { files = getFilesToProcess(request); } catch (IOException e) { throw new CheckstyleExecutorException("Error getting files to process", e); } final String suppressionsFilePath = getSuppressionsFilePath(request); FilterSet filterSet = getSuppressionsFilterSet(suppressionsFilePath); Checker checker = new Checker(); // setup classloader, needed to avoid "Unable to get class information for ..." errors List<String> classPathStrings = new ArrayList<>(); List<String> outputDirectories = new ArrayList<>(); // stand-alone Collection<File> sourceDirectories = null; Collection<File> testSourceDirectories = request.getTestSourceDirectories(); // aggregator Map<MavenProject, Collection<File>> sourceDirectoriesByProject = new HashMap<>(); Map<MavenProject, Collection<File>> testSourceDirectoriesByProject = new HashMap<>(); if (request.isAggregate()) { for (MavenProject childProject : request.getReactorProjects()) { sourceDirectories = new ArrayList<>(childProject.getCompileSourceRoots().size()); List<String> compileSourceRoots = childProject.getCompileSourceRoots(); for (String compileSourceRoot : compileSourceRoots) { sourceDirectories.add(new File(compileSourceRoot)); } sourceDirectoriesByProject.put(childProject, sourceDirectories); testSourceDirectories = new ArrayList<>(childProject.getTestCompileSourceRoots().size()); List<String> testCompileSourceRoots = childProject.getTestCompileSourceRoots(); for (String testCompileSourceRoot : testCompileSourceRoots) { testSourceDirectories.add(new File(testCompileSourceRoot)); } testSourceDirectoriesByProject.put(childProject, testSourceDirectories); prepareCheckstylePaths(request, childProject, classPathStrings, outputDirectories, sourceDirectories, testSourceDirectories); } } else { sourceDirectories = request.getSourceDirectories(); prepareCheckstylePaths(request, project, classPathStrings, outputDirectories, sourceDirectories, testSourceDirectories); } final List<URL> urls = new ArrayList<>(classPathStrings.size()); for (String path : classPathStrings) { try { urls.add(new File(path).toURL()); } catch (MalformedURLException e) { throw new CheckstyleExecutorException(e.getMessage(), e); } } for (String outputDirectoryString : outputDirectories) { try { if (outputDirectoryString != null) { File outputDirectoryFile = new File(outputDirectoryString); if (outputDirectoryFile.exists()) { URL outputDirectoryUrl = outputDirectoryFile.toURL(); getLogger().debug("Adding the outputDirectory " + outputDirectoryUrl.toString() + " to the Checkstyle class path"); urls.add(outputDirectoryUrl); } } } catch (MalformedURLException e) { throw new CheckstyleExecutorException(e.getMessage(), e); } } URLClassLoader projectClassLoader = AccessController.doPrivileged(new PrivilegedAction<URLClassLoader>() { public URLClassLoader run() { return new URLClassLoader(urls.toArray(new URL[urls.size()]), null); } }); checker.setClassLoader(projectClassLoader); checker.setModuleClassLoader(Thread.currentThread().getContextClassLoader()); if (filterSet != null) { checker.addFilter(filterSet); } Configuration configuration = getConfiguration(request); checker.configure(configuration); AuditListener listener = request.getListener(); if (listener != null) { checker.addListener(listener); } if (request.isConsoleOutput()) { checker.addListener(request.getConsoleListener()); } CheckstyleCheckerListener checkerListener = new CheckstyleCheckerListener(configuration); if (request.isAggregate()) { for (MavenProject childProject : request.getReactorProjects()) { sourceDirectories = sourceDirectoriesByProject.get(childProject); testSourceDirectories = testSourceDirectoriesByProject.get(childProject); addSourceDirectory(checkerListener, sourceDirectories, testSourceDirectories, childProject.getResources(), request); } } else { addSourceDirectory(checkerListener, sourceDirectories, testSourceDirectories, request.getResources(), request); } checker.addListener(checkerListener); int nbErrors = checker.process(files); checker.destroy(); if (projectClassLoader instanceof Closeable) { try { ((Closeable) projectClassLoader).close(); } catch (IOException ex) { // Nothing we can do - and not detrimental to the build (save running out of file handles). getLogger().info("Failed to close custom Classloader - this indicated a bug in the code.", ex); } } if (request.getStringOutputStream() != null) { String message = request.getStringOutputStream().toString().trim(); if (message.length() > 0) { getLogger().info(message); } } if (nbErrors > 0) { StringBuilder message = new StringBuilder("There "); if (nbErrors == 1) { message.append("is"); } else { message.append("are"); } message.append(" "); message.append(nbErrors); message.append(" error"); if (nbErrors != 1) { message.append("s"); } message.append(" reported by Checkstyle"); String version = getCheckstyleVersion(); if (version != null) { message.append(" "); message.append(version); } message.append(" with "); message.append(request.getConfigLocation()); message.append(" ruleset."); if (request.isFailsOnError()) { // TODO: should be a failure, not an error. Report is not meant to // throw an exception here (so site would // work regardless of config), but should record this information throw new CheckstyleExecutorException(message.toString()); } else { getLogger().info(message.toString()); } } return checkerListener.getResults(); }
From source file:org.geoserver.spatialite.SpatiaLiteOutputFormat.java
/** * Creates a shapefile data store for the specified schema * @param tempDir// w w w . j a v a 2 s . c o m * @param charset * @param schema * @return * @throws MalformedURLException * @throws FileNotFoundException * @throws IOException */ private ShapefileDataStore buildStore(File tempDir, Charset charset, SimpleFeatureType schema) throws MalformedURLException, FileNotFoundException, IOException { File file = new File(tempDir, schema.getTypeName() + ".shp"); ShapefileDataStore sfds = new ShapefileDataStore(file.toURL()); // handle shapefile encoding // and dump the charset into a .cst file, for debugging and control purposes // (.cst is not a standard extension) sfds.setStringCharset(charset); File charsetFile = new File(tempDir, schema.getTypeName() + ".cst"); PrintWriter pw = null; try { pw = new PrintWriter(charsetFile); pw.write(charset.name()); } finally { if (pw != null) pw.close(); } try { sfds.createSchema(schema); } catch (NullPointerException e) { LOGGER.warning( "Error in shapefile schema. It is possible you don't have a geometry set in the output. \n" + "Please specify a <wfs:PropertyName>geom_column_name</wfs:PropertyName> in the request"); throw new ServiceException( "Error in shapefile schema. It is possible you don't have a geometry set in the output."); } try { if (schema.getCoordinateReferenceSystem() != null) sfds.forceSchemaCRS(schema.getCoordinateReferenceSystem()); } catch (Exception e) { LOGGER.log(Level.WARNING, "Could not properly create the .prj file", e); } return sfds; }
From source file:org.dataconservancy.ui.dcpmap.DataFileMapperTest.java
@Test public void testFromDcp() throws Exception { final String arxIdRootDu = "arx:root:1"; final String arxIdStateDu = "arx:state:1"; final String arxIdStateMan = "arx:stateMan:1"; final String arxIdDfMan = "arx:dfMan:2"; final String arxIdStateFileId = "arx:stateFile:1"; final String arxIdDfFileId = "arx:dataFile:1"; final String arxLineageId1 = "arx:lineage:1"; final String arxLineageId2 = "arx:lineage:2"; final String busDfId = "businessId:df:1"; final Dcp dcp = new Dcp(); final File dfSource = createTemp(); final DataFile dataFile = createDataFile(busDfId, dfSource); final DcsDeliverableUnit rootDu = new DcsDeliverableUnit(); final DcsDeliverableUnit stateDu = new DcsDeliverableUnit(); final DcsManifestation stateMan = new DcsManifestation(); final DcsManifestation dfMan = new DcsManifestation(); // Set up the DcsFiles final DcsFile dfFile = new DcsFile(); dfFile.setId(arxIdDfFileId);/*from w ww .j a va2 s . com*/ dfFile.setExtant(true); dfFile.setName(dfSource.getName()); dfFile.setSource(dfSource.toURL().toExternalForm()); dfFile.setSizeBytes(dfSource.length()); final DcsFile stateFile = new DcsFile(); final File stateSource = createStateFile(dataFile); stateFile.setId(arxIdStateFileId); stateFile.setExtant(true); stateFile.setName(stateSource.getName()); stateFile.setSource(stateSource.toURL().toExternalForm()); stateFile.setSizeBytes(stateSource.length()); // Set up the DeliverableUnits rootDu.setId(arxIdRootDu); rootDu.addFormerExternalRef(busDfId); rootDu.setLineageId(arxLineageId1); rootDu.setTitle(DU_TITLE); rootDu.setType(ROOT_DU_TYPE); stateDu.setId(arxIdStateDu); stateDu.addFormerExternalRef(busDfId); stateDu.setLineageId(arxLineageId2); stateDu.setTitle(DU_TITLE); stateDu.setType(STATE_DU_TYPE); stateDu.addParent(new DcsDeliverableUnitRef(rootDu.getId())); // Set up the Manifestations stateMan.setId(arxIdStateMan); stateMan.setDeliverableUnit(stateDu.getId()); stateMan.setType(STATE_MANIFESTATION_TYPE); DcsManifestationFile stateManMf = new DcsManifestationFile(); stateManMf.setPath(stateSource.getPath()); stateManMf.setRef(new DcsFileRef(stateFile.getId())); stateMan.addManifestationFile(stateManMf); dfMan.setId(arxIdDfMan); dfMan.setDeliverableUnit(stateDu.getId()); dfMan.setType(DATAFILE_MAN_TYPE); DcsManifestationFile dfManMf = new DcsManifestationFile(); dfManMf.setPath(dfSource.getPath()); dfManMf.setRef(new DcsFileRef(dfFile.getId())); dfMan.addManifestationFile(dfManMf); // Set up the DCP dcp.addEntity(rootDu, stateDu, stateMan, dfMan, dfFile, stateFile); // Perform the test final DataFile actual = underTest.fromDcp(dcp); assertEquals(dataFile, actual); dataFile.setSize(-1); assertFalse(dataFile.equals(actual)); }
From source file:org.apache.struts2.jasper.JspC.java
/** * Initializes the classloader as/if needed for the given * compilation context.//from ww w .j av a 2 s . c om * * @param clctxt The compilation context * @throws IOException If an error occurs */ private void initClassLoader(JspCompilationContext clctxt) throws IOException { classPath = getClassPath(); ClassLoader jspcLoader = getClass().getClassLoader(); // Turn the classPath into URLs ArrayList urls = new ArrayList(); StringTokenizer tokenizer = new StringTokenizer(classPath, File.pathSeparator); while (tokenizer.hasMoreTokens()) { String path = tokenizer.nextToken(); try { File libFile = new File(path); urls.add(libFile.toURL()); } catch (IOException ioe) { // Failing a toCanonicalPath on a file that // exists() should be a JVM regression test, // therefore we have permission to freak uot throw new RuntimeException(ioe.toString()); } } //TODO: add .tld files to the URLCLassLoader URL urlsA[] = new URL[urls.size()]; urls.toArray(urlsA); loader = new URLClassLoader(urlsA, this.getClass().getClassLoader()); }
From source file:org.apache.catalina.servlets.HTMLManagerServlet.java
/** * Process a POST request for the specified resource. * * @param request The servlet request we are processing * @param response The servlet response we are creating * * @exception IOException if an input/output error occurs * @exception ServletException if a servlet-specified error occurs *//* www. j av a2 s .c om*/ public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // Identify the request parameters that we need String command = request.getPathInfo(); if (command == null || !command.equals("/upload")) { doGet(request, response); return; } // Prepare our output writer to generate the response message Locale locale = Locale.getDefault(); String charset = context.getCharsetMapper().getCharset(locale); response.setLocale(locale); response.setContentType("text/html; charset=" + charset); String message = ""; // Create a new file upload handler DiskFileUpload upload = new DiskFileUpload(); // Get the tempdir File tempdir = (File) getServletContext().getAttribute("javax.servlet.context.tempdir"); // Set upload parameters upload.setSizeMax(-1); upload.setRepositoryPath(tempdir.getCanonicalPath()); // Parse the request String war = null; FileItem warUpload = null; try { List items = upload.parseRequest(request); // Process the uploaded fields Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField()) { if (item.getFieldName().equals("installWar") && warUpload == null) { warUpload = item; } else { item.delete(); } } } while (true) { if (warUpload == null) { message = sm.getString("htmlManagerServlet.installUploadNoFile"); break; } war = warUpload.getName(); if (!war.toLowerCase().endsWith(".war")) { message = sm.getString("htmlManagerServlet.installUploadNotWar", war); break; } // Get the filename if uploaded name includes a path if (war.lastIndexOf('\\') >= 0) { war = war.substring(war.lastIndexOf('\\') + 1); } if (war.lastIndexOf('/') >= 0) { war = war.substring(war.lastIndexOf('/') + 1); } // Identify the appBase of the owning Host of this Context // (if any) String appBase = null; File appBaseDir = null; appBase = ((Host) context.getParent()).getAppBase(); appBaseDir = new File(appBase); if (!appBaseDir.isAbsolute()) { appBaseDir = new File(System.getProperty("catalina.base"), appBase); } File file = new File(appBaseDir, war); if (file.exists()) { message = sm.getString("htmlManagerServlet.installUploadWarExists", war); break; } warUpload.write(file); try { URL url = file.toURL(); war = url.toString(); war = "jar:" + war + "!/"; } catch (MalformedURLException e) { file.delete(); throw e; } break; } } catch (Exception e) { message = sm.getString("htmlManagerServlet.installUploadFail", e.getMessage()); log(message, e); } finally { if (warUpload != null) { warUpload.delete(); } warUpload = null; } // If there were no errors, install the WAR if (message.length() == 0) { message = install(null, null, war); } list(request, response, message); }
From source file:com.aurel.track.util.PluginUtils.java
/** * Transforms the given URL which may contain escaping characters (like %20 for space) * to an URL which may conatin illegal URL characters (like space) but is valid for creating a file based on the resulting URL * The escape characters will be changed back to characters that are illegal in URLs (like space) because the file could be * constructed just in such a way in some servlet containers like Tomcat5.5 * @param url// w ww . j ava2s.c o m * @return */ public static URL createValidFileURL(URL url) { File file; URL fileUrl; if (url == null) { return null; } if (url.getPath() != null) { file = new File(url.getPath()); //we have no escape characters or the servlet container can deal with escape characters if (file.exists()) { //valid url return url; } } //valid file through URI? //see Bug ID: 4466485 (http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4466485) URI uri = null; try { //get rid of spaces uri = new URI(url.toString()); } catch (URISyntaxException e1) { } if (uri == null) { return null; } if (uri.getPath() != null) { //the decoded path component of this URI file = new File(uri.getPath()); if (file.exists()) { try { //file.toURL() does not automatically escape characters that are illegal in URLs fileUrl = file.toURL(); // revert, problems with Windows? if (fileUrl != null) { return fileUrl; } } catch (MalformedURLException e) { } } } //back to URL from URI try { url = uri.toURL(); } catch (MalformedURLException e) { } if (url != null && url.getPath() != null) { file = new File(url.getPath()); if (file.exists()) { //valid url return url; } } return null; }
From source file:org.apache.archiva.converter.artifact.LegacyToDefaultConverterTest.java
private void createModernSourceRepository() throws Exception { ArtifactRepositoryFactory factory = plexusSisuBridge.lookup(ArtifactRepositoryFactory.class); ArtifactRepositoryLayout layout = plexusSisuBridge.lookup(ArtifactRepositoryLayout.class, "default"); File sourceBase = getTestFile("src/test/source-modern-repository"); sourceRepository = factory.createArtifactRepository("source", sourceBase.toURL().toString(), layout, null, null);/*from w ww. jav a 2 s . co m*/ }
From source file:org.apache.archiva.converter.artifact.LegacyToDefaultConverterTest.java
@Before public void init() throws Exception { super.setUp(); ArtifactRepositoryFactory factory = plexusSisuBridge.lookup(ArtifactRepositoryFactory.class); Map<String, ArtifactRepositoryLayout> layoutsMap = plexusSisuBridge .lookupMap(ArtifactRepositoryLayout.class); System.out.println("hints " + layoutsMap.keySet().toString()); ArtifactRepositoryLayout layout = plexusSisuBridge.lookup(ArtifactRepositoryLayout.class, "legacy"); File sourceBase = getTestFile("src/test/source-repository"); sourceRepository = factory.createArtifactRepository("source", sourceBase.toURL().toString(), layout, null, null);/*from w ww .j a v a 2s . c om*/ layout = plexusSisuBridge.lookup(ArtifactRepositoryLayout.class, "default"); File targetBase = getTestFile("target/test-target-repository"); copyDirectoryStructure(getTestFile("src/test/target-repository"), targetBase); targetRepository = factory.createArtifactRepository("target", targetBase.toURL().toString(), layout, null, null); artifactConverter = applicationContext.getBean("artifactConverter#legacy-to-default", ArtifactConverter.class); artifactConverter.clearWarnings(); artifactFactory = (ArtifactFactory) plexusSisuBridge.lookup(ArtifactFactory.class); }
From source file:org.apache.jasper.JspC.java
private void initClassLoader(JspCompilationContext clctxt) throws IOException { classPath = getClassPath();//ww w . j a va 2 s .c om ClassLoader jspcLoader = getClass().getClassLoader(); if (jspcLoader instanceof AntClassLoader) { classPath += File.pathSeparator + ((AntClassLoader) jspcLoader).getClasspath(); } // Turn the classPath into URLs ArrayList urls = new ArrayList(); StringTokenizer tokenizer = new StringTokenizer(classPath, File.pathSeparator); while (tokenizer.hasMoreTokens()) { String path = tokenizer.nextToken(); try { File libFile = new File(path); urls.add(libFile.toURL()); } catch (IOException ioe) { // Failing a toCanonicalPath on a file that // exists() should be a JVM regression test, // therefore we have permission to freak uot throw new RuntimeException(ioe.toString()); } } File webappBase = new File(uriRoot); if (webappBase.exists()) { File classes = new File(webappBase, "/WEB-INF/classes"); try { if (classes.exists()) { classPath = classPath + File.pathSeparator + classes.getCanonicalPath(); urls.add(classes.getCanonicalFile().toURL()); } } catch (IOException ioe) { // failing a toCanonicalPath on a file that // exists() should be a JVM regression test, // therefore we have permission to freak out throw new RuntimeException(ioe.toString()); } File lib = new File(webappBase, "/WEB-INF/lib"); if (lib.exists() && lib.isDirectory()) { String[] libs = lib.list(); for (int i = 0; i < libs.length; i++) { if (libs[i].length() < 5) continue; String ext = libs[i].substring(libs[i].length() - 4); if (!".jar".equalsIgnoreCase(ext)) { if (".tld".equalsIgnoreCase(ext)) { log.warn("TLD files should not be placed in " + "/WEB-INF/lib"); } continue; } try { File libFile = new File(lib, libs[i]); classPath = classPath + File.pathSeparator + libFile.getCanonicalPath(); urls.add(libFile.getCanonicalFile().toURL()); } catch (IOException ioe) { // failing a toCanonicalPath on a file that // exists() should be a JVM regression test, // therefore we have permission to freak out throw new RuntimeException(ioe.toString()); } } } } // What is this ?? urls.add(new File(clctxt.getRealPath("/")).getCanonicalFile().toURL()); URL urlsA[] = new URL[urls.size()]; urls.toArray(urlsA); loader = new URLClassLoader(urlsA, this.getClass().getClassLoader()); Thread.currentThread().setContextClassLoader(loader); }
From source file:org.apache.axis2.deployment.ModuleDeployer.java
public void deploy(DeploymentFileData deploymentFileData) { File deploymentFile = deploymentFileData.getFile(); boolean isDirectory = deploymentFile.isDirectory(); if (isDirectory && deploymentFileData.getName().startsWith(".")) { // Ignore special meta directories starting with . return;/*from w w w . j ava 2s. c o m*/ } ArchiveReader archiveReader = new ArchiveReader(); String moduleStatus = ""; StringWriter errorWriter = new StringWriter(); try { deploymentFileData.setClassLoader(isDirectory, axisConfig.getModuleClassLoader(), (File) axisConfig.getParameterValue(Constants.Configuration.ARTIFACTS_TEMP_DIR), this.axisConfig.isChildFirstClassLoading()); AxisModule metaData = new AxisModule(); metaData.setModuleClassLoader(deploymentFileData.getClassLoader()); metaData.setParent(axisConfig); archiveReader.readModuleArchive(deploymentFileData, metaData, isDirectory, axisConfig); URL url = deploymentFile.toURL(); metaData.setFileName(url); DeploymentEngine.addNewModule(metaData, axisConfig); super.deploy(deploymentFileData); log.info(Messages.getMessage(DeploymentErrorMsgs.DEPLOYING_MODULE, metaData.getArchiveName(), url.toString())); } catch (DeploymentException e) { log.error(Messages.getMessage(DeploymentErrorMsgs.INVALID_MODULE, deploymentFileData.getName(), e.getMessage()), e); PrintWriter error_ptintWriter = new PrintWriter(errorWriter); e.printStackTrace(error_ptintWriter); moduleStatus = "Error:\n" + errorWriter.toString(); } catch (AxisFault axisFault) { log.error(Messages.getMessage(DeploymentErrorMsgs.INVALID_MODULE, deploymentFileData.getName(), axisFault.getMessage()), axisFault); PrintWriter error_ptintWriter = new PrintWriter(errorWriter); axisFault.printStackTrace(error_ptintWriter); moduleStatus = "Error:\n" + errorWriter.toString(); } catch (MalformedURLException e) { log.error(Messages.getMessage(DeploymentErrorMsgs.INVALID_MODULE, deploymentFileData.getName(), e.getMessage()), e); PrintWriter error_ptintWriter = new PrintWriter(errorWriter); e.printStackTrace(error_ptintWriter); moduleStatus = "Error:\n" + errorWriter.toString(); } catch (Throwable t) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); t.printStackTrace(pw); log.error(Messages.getMessage(DeploymentErrorMsgs.INVALID_MODULE, deploymentFileData.getName(), t.getMessage()), t); PrintWriter error_ptintWriter = new PrintWriter(errorWriter); t.printStackTrace(error_ptintWriter); moduleStatus = "Error:\n" + errorWriter.toString(); } finally { if (moduleStatus.startsWith("Error:")) { axisConfig.getFaultyModules().put(DeploymentEngine.getAxisServiceName(deploymentFileData.getName()), moduleStatus); } } }