/** * Set up the execution classpath for Jasper. * * <p>Put everything in the classesDirectory and all of the dependencies on the classpath. * * @returns a list of the urls of the dependencies * @throws Exception */ private List<URL> setUpWebAppClassPath() throws Exception { // add any classes from the webapp List<URL> urls = new ArrayList<URL>(); String classesDir = classesDirectory.getCanonicalPath(); classesDir = classesDir + (classesDir.endsWith(File.pathSeparator) ? "" : File.separator); urls.add(Resource.toURL(new File(classesDir))); if (getLog().isDebugEnabled()) getLog().debug("Adding to classpath classes dir: " + classesDir); // add the dependencies of the webapp (which will form WEB-INF/lib) for (Iterator<Artifact> iter = project.getArtifacts().iterator(); iter.hasNext(); ) { Artifact artifact = (Artifact) iter.next(); // Include runtime and compile time libraries if (!Artifact.SCOPE_TEST.equals(artifact.getScope()) && !Artifact.SCOPE_PROVIDED.equals(artifact.getScope())) { String filePath = artifact.getFile().getCanonicalPath(); if (getLog().isDebugEnabled()) getLog().debug("Adding to classpath dependency file: " + filePath); urls.add(Resource.toURL(artifact.getFile())); } } return urls; }
/** @return */ private List<File> getDependencyFiles() { List<File> dependencyFiles = new ArrayList<File>(); for (Iterator<Artifact> iter = projectArtifacts.iterator(); iter.hasNext(); ) { Artifact artifact = (Artifact) iter.next(); // Include runtime and compile time libraries, and possibly test libs too if (artifact.getType().equals("war")) { continue; } if (Artifact.SCOPE_PROVIDED.equals(artifact.getScope())) continue; // never add dependencies of scope=provided to the webapp's classpath (see also // <useProvidedScope> param) if (Artifact.SCOPE_TEST.equals(artifact.getScope()) && !useTestScope) continue; // only add dependencies of scope=test if explicitly required dependencyFiles.add(artifact.getFile()); getLog() .debug( "Adding artifact " + artifact.getFile().getName() + " with scope " + artifact.getScope() + " for WEB-INF/lib "); } return dependencyFiles; }
private void addDependencies(final MavenProject project, final JettyWebAppContext webAppConfig) throws Exception { List<File> dependencyFiles = new ArrayList<File>(); List<Resource> overlays = new ArrayList<Resource>(); for (Artifact artifact : project.getArtifacts()) { if (artifact.getType().equals("war")) { overlays.add(Resource.newResource("jar:" + artifact.getFile().toURL().toString() + "!/")); } else if ((!Artifact.SCOPE_PROVIDED.equals(artifact.getScope())) && (!Artifact.SCOPE_TEST.equals(artifact.getScope()))) { File dependencyFile = artifact.getFile(); if (dependencyFile == null || !dependencyFile.exists()) { String coordinates = String.format( "%s:%s:%s", artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion()); LOG.log( Level.WARNING, "Dependency '" + coordinates + "' does not exist in repository. Skipping!"); continue; } dependencyFiles.add(artifact.getFile()); } } webAppConfig.setOverlays(overlays); webAppConfig.setWebInfLib(dependencyFiles); }
/** @return */ private List<File> getDependencyFiles() { List<File> dependencyFiles = new ArrayList<File>(); for (Iterator<Artifact> iter = project.getArtifacts().iterator(); iter.hasNext(); ) { Artifact artifact = (Artifact) iter.next(); if (((!Artifact.SCOPE_PROVIDED.equals(artifact.getScope())) && (!Artifact.SCOPE_TEST.equals(artifact.getScope()))) || (useTestScope && Artifact.SCOPE_TEST.equals(artifact.getScope()))) { dependencyFiles.add(artifact.getFile()); getLog().debug("Adding artifact " + artifact.getFile().getName() + " for WEB-INF/lib "); } } return dependencyFiles; }
private Artifact XcreateArtifact( String groupId, String artifactId, VersionRange versionRange, String type, String classifier, String scope, String inheritedScope, boolean optional) { String desiredScope = Artifact.SCOPE_RUNTIME; if (inheritedScope == null) { desiredScope = scope; } else if (Artifact.SCOPE_TEST.equals(scope) || Artifact.SCOPE_PROVIDED.equals(scope)) { return null; } else if (Artifact.SCOPE_COMPILE.equals(scope) && Artifact.SCOPE_COMPILE.equals(inheritedScope)) { // added to retain compile artifactScope. Remove if you want compile inherited as runtime desiredScope = Artifact.SCOPE_COMPILE; } if (Artifact.SCOPE_TEST.equals(inheritedScope)) { desiredScope = Artifact.SCOPE_TEST; } if (Artifact.SCOPE_PROVIDED.equals(inheritedScope)) { desiredScope = Artifact.SCOPE_PROVIDED; } if (Artifact.SCOPE_SYSTEM.equals(scope)) { // system scopes come through unchanged... desiredScope = Artifact.SCOPE_SYSTEM; } ArtifactHandler handler = artifactHandlerManager.getArtifactHandler(type); return new DefaultArtifact( groupId, artifactId, versionRange, desiredScope, type, classifier, handler, optional); }
private Set<Artifact> getNotProvidedDependencies() throws Exception { final Set<Artifact> result = new HashSet<Artifact>(); for (final Artifact artifact : getIncludedArtifacts()) { if (Artifact.SCOPE_PROVIDED.equals(artifact.getScope()) || Artifact.SCOPE_TEST.equals(artifact.getScope())) { continue; } if (artifact.isOptional()) { continue; } result.add(artifact); } return result; }
public boolean isReferenceFromEar(IClasspathEntryDescriptor descriptor) { IClasspathEntry entry = descriptor.getClasspathEntry(); String scope = descriptor.getScope(); // these dependencies aren't added to the manifest cp // retain optional dependencies here, they might be used just to express the // dependency to be used in the manifest if (Artifact.SCOPE_PROVIDED.equals(scope) || Artifact.SCOPE_TEST.equals(scope) || Artifact.SCOPE_SYSTEM.equals(scope)) { return false; } // calculate in regard to includes/excludes whether this jar is // to be packaged into WEB-INF/lib String jarFileName = "WEB-INF/lib/" + entry.getPath().lastSegment(); return isExcludedFromWebInfLib(jarFileName); }
@Override public void execute() throws MojoExecutionException { getLog().info("Unpacking dependencies..."); IProjectPhpExecution config = null; File targetDir = null; IDependencyConfiguration depConfig = null; try { depConfig = factory.lookup( IDependencyConfiguration.class, IComponentFactory.EMPTY_CONFIG, this.getSession()); config = factory.lookup( IProjectPhpExecution.class, IComponentFactory.EMPTY_CONFIG, this.getSession()); if (Artifact.SCOPE_TEST.equals(getTargetScope())) { targetDir = config.getTestDepsDir(); } else { targetDir = config.getDepsDir(); } } catch (ComponentLookupException ex) { throw new MojoExecutionException(ex.getMessage(), ex); } catch (PlexusConfigurationException ex) { throw new MojoExecutionException(ex.getMessage(), ex); } catch (ExpressionEvaluationException ex) { throw new MojoExecutionException(ex.getMessage(), ex); } try { // TODO move this to a plugin (f.e. maven-php-project) // TODO verify integrity of dependencies config this.getPhpHelper() .prepareDependencies( this.factory, this.getSession(), targetDir, getTargetScope(), depConfig); } catch (MultiException e) { throw new MojoExecutionException(e.getMessage(), e); } catch (PhpException e) { throw new MojoExecutionException(e.getMessage(), e); } catch (IOException e) { throw new MojoExecutionException(e.getMessage(), e); } }
public void configureClasspath( IProject project, MavenProject mavenProject, IClasspathDescriptor classpath, IProgressMonitor monitor) throws CoreException { // Improve skinny war support by generating the manifest classpath // similar to mvn eclipse:eclipse // http://maven.apache.org/plugins/maven-war-plugin/examples/skinny-wars.html WarPluginConfiguration config = new WarPluginConfiguration(mavenProject, project); WarPackagingOptions opts = new WarPackagingOptions(config); StringBuilder manifestCp = new StringBuilder(); /* * Need to take care of three separate cases * * 1. remove any project dependencies (they are represented as J2EE module dependencies) * 2. add non-dependency attribute for entries originated by artifacts with * runtime, system, test scopes or optional dependencies (not sure about the last one) * 3. make sure all dependency JAR files have unique file names, i.e. artifactId/version collisions */ Set<String> dups = new LinkedHashSet<String>(); Set<String> names = new HashSet<String>(); // first pass removes projects, adds non-dependency attribute and collects colliding filenames Iterator<IClasspathEntryDescriptor> iter = classpath.getEntryDescriptors().iterator(); while (iter.hasNext()) { IClasspathEntryDescriptor descriptor = iter.next(); IClasspathEntry entry = descriptor.getClasspathEntry(); String scope = descriptor.getScope(); String key = ArtifactUtils.versionlessKey(descriptor.getGroupId(), descriptor.getArtifactId()); Artifact artifact = mavenProject.getArtifactMap().get(key); String extension = artifact.getArtifactHandler().getExtension(); if (IClasspathEntry.CPE_PROJECT == entry.getEntryKind() && Artifact.SCOPE_COMPILE.equals(scope)) { // get deployed name for project dependencies // TODO can this be done somehow more elegantly? IProject p = (IProject) ResourcesPlugin.getWorkspace().getRoot().findMember(entry.getPath()); IVirtualComponent component = ComponentCore.createComponent(p); boolean usedInEar = opts.isReferenceFromEar(component, extension); if (opts.isSkinnyWar() && usedInEar) { if (manifestCp.length() > 0) { manifestCp.append(" "); } // MNGECLIPSE-2393 prepend ManifestClasspath prefix if (config.getManifestClasspathPrefix() != null && !JEEPackaging.isJEEPackaging(artifact.getType())) { manifestCp.append(config.getManifestClasspathPrefix()); } manifestCp.append(component.getDeployedName()).append(".").append(extension); } if (!descriptor.isOptionalDependency() || usedInEar) { // remove mandatory project dependency from classpath iter.remove(); continue; } // else : optional dependency not used in ear -> need to trick ClasspathAttribute with // NONDEPENDENCY_ATTRIBUTE } if (opts.isSkinnyWar() && opts.isReferenceFromEar(descriptor)) { if (manifestCp.length() > 0) { manifestCp.append(" "); } if (config.getManifestClasspathPrefix() != null && !JEEPackaging.isJEEPackaging(artifact.getType())) { manifestCp.append(config.getManifestClasspathPrefix()); } manifestCp.append(entry.getPath().lastSegment()); // ear references aren't kept in the Maven Dependencies iter.remove(); continue; } // add non-dependency attribute // Check the scope & set WTP non-dependency as appropriate // Optional artifact shouldn't be deployed if (Artifact.SCOPE_PROVIDED.equals(scope) || Artifact.SCOPE_TEST.equals(scope) || Artifact.SCOPE_SYSTEM.equals(scope) || descriptor.isOptionalDependency()) { descriptor.addClasspathAttribute(NONDEPENDENCY_ATTRIBUTE); } // collect duplicate file names if (!names.add(entry.getPath().lastSegment())) { dups.add(entry.getPath().lastSegment()); } } String targetDir = mavenProject.getBuild().getDirectory(); // second pass disambiguates colliding entry file names iter = classpath.getEntryDescriptors().iterator(); while (iter.hasNext()) { IClasspathEntryDescriptor descriptor = iter.next(); IClasspathEntry entry = descriptor.getClasspathEntry(); if (dups.contains(entry.getPath().lastSegment())) { File src = new File(entry.getPath().toOSString()); String groupId = descriptor.getGroupId(); File dst = new File(targetDir, groupId + "-" + entry.getPath().lastSegment()); try { if (src.canRead()) { if (isDifferent(src, dst)) { // uses lastModified FileUtils.copyFile(src, dst); dst.setLastModified(src.lastModified()); } descriptor.setClasspathEntry( JavaCore.newLibraryEntry( Path.fromOSString(dst.getCanonicalPath()), // entry.getSourceAttachmentPath(), // entry.getSourceAttachmentRootPath(), // entry.getAccessRules(), // entry.getExtraAttributes(), // entry.isExported())); } } catch (IOException ex) { MavenLogger.log("File copy failed", ex); } } } if (opts.isSkinnyWar()) { // writing the manifest only works when the project has been properly created // placing this check on the top of the method broke 2 other tests // thats why its placed here now. if (ComponentCore.createComponent(project) == null) { return; } // write manifest, using internal API - seems ok for 3.4/3.5, though ArchiveManifest mf = J2EEProjectUtilities.readManifest(project); if (mf == null) { mf = new ArchiveManifestImpl(); } mf.addVersionIfNecessary(); mf.setClassPath(manifestCp.toString()); try { J2EEProjectUtilities.writeManifest(project, mf); } catch (Exception ex) { MavenLogger.log("Could not write web module manifest file", ex); } } }
/** * Resolve project dependencies. Manual resolution is needed in order to avoid resoltion of * multiproject artifacts (if projects will be linked each other an installed jar is not needed) * and to avoid a failure when a jar is missing. * * @throws MojoExecutionException if dependencies can't be resolved * @return resoved IDE dependencies, with attached jars for non-reactor dependencies */ protected IdeDependency[] doDependencyResolution() throws MojoExecutionException { MavenProject project = getProject(); ArtifactRepository localRepo = getLocalRepository(); List dependencies = getProject().getDependencies(); // Collect the list of resolved IdeDependencies. List dependencyList = new ArrayList(); if (dependencies != null) { Map managedVersions = createManagedVersionMap( getArtifactFactory(), project.getId(), project.getDependencyManagement()); ArtifactResolutionResult artifactResolutionResult = null; try { List listeners = new ArrayList(); if (logger.isDebugEnabled()) { listeners.add(new DebugResolutionListener(logger)); } listeners.add(new WarningResolutionListener(logger)); artifactResolutionResult = artifactCollector.collect( getProjectArtifacts(), project.getArtifact(), managedVersions, localRepo, project.getRemoteArtifactRepositories(), getArtifactMetadataSource(), null, listeners); } catch (ArtifactResolutionException e) { getLog().debug(e.getMessage(), e); getLog() .error( Messages.getString( "artifactresolution", new Object[] { // $NON-NLS-1$ e.getGroupId(), e.getArtifactId(), e.getVersion(), e.getMessage() })); // if we are here artifactResolutionResult is null, create a project without dependencies // but don't fail // (this could be a reactor projects, we don't want to fail everything) return new IdeDependency[0]; } // keep track of added reactor projects in order to avoid duplicates Set emittedReactorProjectId = new HashSet(); for (Iterator i = artifactResolutionResult.getArtifactResolutionNodes().iterator(); i.hasNext(); ) { ResolutionNode node = (ResolutionNode) i.next(); Artifact art = node.getArtifact(); boolean isReactorProject = getUseProjectReferences() && isAvailableAsAReactorProject(art); // don't resolve jars for reactor projects if (!isReactorProject) { try { artifactResolver.resolve(art, node.getRemoteRepositories(), localRepository); } catch (ArtifactNotFoundException e) { getLog().debug(e.getMessage(), e); getLog() .warn( Messages.getString( "artifactdownload", new Object[] { // $NON-NLS-1$ e.getGroupId(), e.getArtifactId(), e.getVersion(), e.getMessage() })); } catch (ArtifactResolutionException e) { getLog().debug(e.getMessage(), e); getLog() .warn( Messages.getString( "artifactresolution", new Object[] { // $NON-NLS-1$ e.getGroupId(), e.getArtifactId(), e.getVersion(), e.getMessage() })); } } if (!isReactorProject || emittedReactorProjectId.add(art.getGroupId() + '-' + art.getArtifactId())) { IdeDependency dep = new IdeDependency( art.getGroupId(), art.getArtifactId(), art.getVersion(), isReactorProject, Artifact.SCOPE_TEST.equals(art.getScope()), Artifact.SCOPE_SYSTEM.equals(art.getScope()), Artifact.SCOPE_PROVIDED.equals(art.getScope()), art.getArtifactHandler().isAddedToClasspath(), art.getFile(), art.getType()); dependencyList.add(dep); } } // @todo a final report with the list of missingArtifacts? } IdeDependency[] deps = (IdeDependency[]) dependencyList.toArray(new IdeDependency[dependencyList.size()]); return deps; }
public void execute() throws MojoExecutionException { // find all the rules items and load them into a package try { // Need to load the build classpath @SuppressWarnings("unchecked") List<Dependency> dependencies = project.getDependencies(); List<URL> url = new ArrayList<URL>(); url.add(outputDirectory.toURI().toURL()); for (Dependency d : dependencies) { String scope = d.getScope(); if (!Artifact.SCOPE_TEST.equals(scope)) { Artifact artifact = getArtifact( d.getGroupId(), d.getArtifactId(), d.getVersion(), d.getType(), d.getClassifier()); url.add(artifact.getFile().toURI().toURL()); } } URL[] classpath = url.toArray(new URL[url.size()]); URLClassLoader uc = new URLClassLoader(classpath, this.getClass().getClassLoader()) { @Override public Class<?> loadClass(String name) throws ClassNotFoundException { getLog().debug("Loading Class for compile [" + name + "]"); Class<?> c = super.loadClass(name); getLog().debug("Loading Class for compile [" + name + "] found [" + c + "]"); return c; } @Override protected Class<?> findClass(String name) throws ClassNotFoundException { getLog().debug("Finding Class for compile [" + name + "]"); Class<?> c = super.findClass(name); getLog().debug("Finding Class for compile [" + name + "] found [" + c + "]"); return c; } }; URLClassLoader uc2 = new URLClassLoader(classpath, this.getClass().getClassLoader()) { @Override public Class<?> loadClass(String name) throws ClassNotFoundException { getLog().debug("Loading Class for runtime [" + name + "]"); Class<?> c = super.loadClass(name); getLog().debug("Loading Class for runtime [" + name + "] found [" + c + "]"); return c; } @Override protected Class<?> findClass(String name) throws ClassNotFoundException { getLog().debug("Finding Class for runtime [" + name + "]"); Class<?> c = super.findClass(name); getLog().debug("Finding Class for runtime [" + name + "] found [" + c + "]"); return c; } }; getLog().info("Package Class loader is using classpath " + Arrays.toString(uc.getURLs())); listClassloader(" ", uc); PackageBuilderConfiguration packageBuilderConfiguration = new PackageBuilderConfiguration(uc); PackageBuilder pb = new PackageBuilder(packageBuilderConfiguration); DirectoryScanner ds = new DirectoryScanner(); ds.setIncludes(includes); ds.setExcludes(excludes); ds.setBasedir(rulesdir); ds.setCaseSensitive(true); ds.scan(); String[] files = ds.getIncludedFiles(); for (String file : files) { File f = new File(rulesdir, file); Reader reader = new FileReader(f); try { if (file.endsWith(".drl")) { getLog().info("Adding Rules " + f); pb.addPackageFromDrl(reader); } else if (file.endsWith(".xml")) { getLog().info("Adding Package definition " + f); pb.addPackageFromXml(reader); } else if (file.endsWith(".rf")) { getLog().info("Adding Rule Flow " + f); pb.addRuleFlow(reader); } else { getLog().info("Ignored Resource " + f); } } finally { reader.close(); } } pb.compileAll(); PackageBuilderErrors errors = pb.getErrors(); if (errors.size() > 0) { for (KnowledgeBuilderError kberr : errors) { getLog().error(kberr.toString()); } throw new MojoExecutionException("Package is not valid"); } org.drools.rule.Package p = pb.getPackage(); if (!p.isValid()) { getLog().error("Package is not valid "); throw new MojoExecutionException("Package is not valid"); } File outputFile = getOutputFile(); getLog().info("Saving compiled package to " + outputFile.getPath()); outputFile.getParentFile().mkdirs(); FileOutputStream fout = new FileOutputStream(outputFile); DroolsStreamUtils.streamOut(fout, p); fout.close(); getLog().info("Testing Compiled package " + outputFile.getPath()); File inputFile = getOutputFile(); FileInputStream fin = new FileInputStream(inputFile); RuleBaseConfiguration config = new RuleBaseConfiguration(uc2); RuleBase ruleBase = RuleBaseFactory.newRuleBase(config); Object o = DroolsStreamUtils.streamIn(fin, uc); ruleBase.addPackage((Package) o); KnowledgeBase kb = new KnowledgeBaseImpl(ruleBase); @SuppressWarnings("unused") StatelessKnowledgeSession session = kb.newStatelessKnowledgeSession(); getLog().info("Testing passed "); } catch (Exception e) { getLog().error(e); throw new MojoExecutionException(e.getMessage()); } }