# HG changeset patch # Parent 1f3d80540815ba617f8dbe78f48f43abb4f7d33e # User Jesse Glick #186939: rewrite PluginIndexManager to use the regular Nexus index. diff --git a/maven.indexer/nbproject/project.xml b/maven.indexer/nbproject/project.xml --- a/maven.indexer/nbproject/project.xml +++ b/maven.indexer/nbproject/project.xml @@ -164,6 +164,11 @@ + + org.openide.util + + + diff --git a/maven.indexer/src/org/netbeans/modules/maven/indexer/api/PluginIndexManager.java b/maven.indexer/src/org/netbeans/modules/maven/indexer/api/PluginIndexManager.java --- a/maven.indexer/src/org/netbeans/modules/maven/indexer/api/PluginIndexManager.java +++ b/maven.indexer/src/org/netbeans/modules/maven/indexer/api/PluginIndexManager.java @@ -39,98 +39,33 @@ * * Portions Copyrighted 2009 Sun Microsystems, Inc. */ + package org.netbeans.modules.maven.indexer.api; -import org.codehaus.plexus.util.Base64; -import org.codehaus.plexus.util.FileUtils; -import org.codehaus.plexus.util.IOUtil; -import org.codehaus.plexus.util.StringUtils; -import java.io.BufferedOutputStream; import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.BitSet; +import java.util.Collections; import java.util.Comparator; -import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; -import java.util.zip.ZipEntry; -import java.util.zip.ZipInputStream; -import org.apache.lucene.document.Document; -import org.apache.lucene.document.Field; -import org.apache.lucene.index.IndexReader; -import org.apache.lucene.index.Term; -import org.apache.lucene.search.BooleanClause; -import org.apache.lucene.search.BooleanQuery; -import org.apache.lucene.search.Collector; -import org.apache.lucene.search.IndexSearcher; -import org.apache.lucene.search.PrefixQuery; -import org.apache.lucene.search.Scorer; -import org.apache.lucene.search.TermQuery; -import org.apache.lucene.store.FSDirectory; -import org.openide.filesystems.FileUtil; -import org.openide.util.Exceptions; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.apache.maven.index.ArtifactInfo; +import org.netbeans.api.annotations.common.CheckForNull; +import org.netbeans.api.annotations.common.NullAllowed; import org.openide.util.NbBundle; +import org.openide.xml.XMLUtil; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.InputSource; /** * Provides information about available plugins, including their goals and parameters. - * @author mkleint */ public class PluginIndexManager { - private static final String ZIP_LOCATION = "org/netbeans/modules/maven/indexer/pluginz.zip"; //NOI18N - - private static final String INDEX_PATH = "maven-plugins-index"; //NOI18N - private static IndexReader indexReader; - - /** - * groupId + "|" + artifactId + "|" + version; - */ - private static String FIELD_ID = "id";//NOI18N - /** - * 2.0.x or similar name of maven core. a document has either this or id field. - */ - private static String FIELD_MVN_VERSION = "mvn";//NOI18N - /** - * space separated list of goal names - */ - private static String FIELD_GOALS = "gls";//NOI18N - /** - * goal prefix - */ - private static String FIELD_PREFIX = "prfx";//NOI18N - - /** - * | is the separator - * [0] - name - * [1] - editable - * [2] - required - * [3] - expression or "null" - * [4] - default value or "null" - */ - private static String PREFIX_FIELD_GOAL = "mj_";//NOI18N - /** - * space separated list of lifecycles/packagings - */ - private static String FIELD_CYCLES = "ccls";//NOI18N - private static String PREFIX_FIELD_CYCLE = "ccl_";//NOI18N - - - final static int BUFFER = 2048; - - private static synchronized IndexSearcher getIndexSearcher() throws Exception { - if (indexReader == null) { - FSDirectory dir = FSDirectory.open(getDefaultIndexLocation()); - indexReader = IndexReader.open(dir); - } - //TODO shall the searcher be stored as field?? - return new IndexSearcher(indexReader); - } + private static final Logger LOG = Logger.getLogger(PluginIndexManager.class.getName()); /** * Gets available goals from known plugins. @@ -138,27 +73,48 @@ * @return e.g. {@code [..., dependency:copy, ..., release:perform, ...]} */ public static Set getPluginGoalNames(Set groups) throws Exception { - IndexSearcher searcher = getIndexSearcher(); - BooleanQuery bq = new BooleanQuery(); - for (String grp : groups) { - PrefixQuery pq = new PrefixQuery(new Term(FIELD_ID, grp)); - bq.add(new BooleanClause(pq, BooleanClause.Occur.SHOULD)); - } - final BitSetCollector searchRes = new BitSetCollector(); - searcher.search(bq, searchRes); - final BitSet bitSet = searchRes.getMatchedDocs(); - TreeSet toRet = new TreeSet(); - for (int docNum = bitSet.nextSetBit(0); docNum >= 0; docNum = bitSet.nextSetBit(docNum+1)) { - Document doc = searcher.getIndexReader().document(docNum); - //TODO shall we somehow pick just one version fom a given plugin here? how? - String prefix = doc.getField(FIELD_PREFIX).stringValue(); - String goals = doc.getField(FIELD_GOALS).stringValue(); - String[] gls = StringUtils.split(goals, " ");//NOI18N - for (String goal : gls) { - toRet.add(prefix + ":" + goal); //NOI18N + Set result = new TreeSet(); + RepositoryInfo[] infos = RepositoryQueries.getLoadedContexts().toArray(new RepositoryInfo[0]); + // XXX rather use ArtifactInfo.PLUGIN_GOALS + for (String groupId : groups) { + for (String artifactId : RepositoryQueries.filterPluginArtifactIds(groupId, "", infos)) { + for (NBVersionInfo v : RepositoryQueries.getVersions(groupId, artifactId, infos)) { + if (v.getVersion().endsWith("-SNAPSHOT") && !v.getRepoId().equals("local")) { + continue; + } + File jar = RepositoryUtil.downloadArtifact(v); + Document pluginXml = loadPluginXml(jar); + if (pluginXml == null) { + continue; + } + Element root = pluginXml.getDocumentElement(); + Element goalPrefix = XMLUtil.findElement(root, "goalPrefix", null); + if (goalPrefix == null) { + LOG.log(Level.WARNING, "no goalPrefix in {0}", jar); + continue; + } + Element mojos = XMLUtil.findElement(root, "mojos", null); + if (mojos == null) { + LOG.log(Level.WARNING, "no mojos in {0}", jar); + continue; + } + for (Element mojo : XMLUtil.findSubElements(mojos)) { + if (!mojo.getTagName().equals("mojo")) { + continue; + } + Element goal = XMLUtil.findElement(mojo, "goal", null); + if (goal == null) { + LOG.log(Level.WARNING, "mojo missing goal in {0}", jar); + continue; + } + result.add(XMLUtil.findText(goalPrefix) + ':' + XMLUtil.findText(goal)); + } + break; + } } } - return toRet; + LOG.log(Level.FINE, "found goal names: {0}", result); + return result; } /** @@ -170,25 +126,37 @@ */ public static Set getPluginGoals(String groupId, String artifactId, String version) throws Exception { assert groupId != null && artifactId != null && version != null; - IndexSearcher searcher = getIndexSearcher(); - String id = groupId + "|" + artifactId + "|" + version; //NOI18N - TermQuery tq = new TermQuery(new Term(FIELD_ID, id)); - final BitSetCollector searchRes = new BitSetCollector(); - searcher.search(tq, searchRes); - final BitSet bitSet = searchRes.getMatchedDocs(); - if (bitSet.isEmpty()) { - return null; + for (NBVersionInfo v : RepositoryQueries.getVersions(groupId, artifactId, RepositoryQueries.getLoadedContexts().toArray(new RepositoryInfo[0]))) { + if (!v.getVersion().equals(version)) { + continue; + } + File jar = RepositoryUtil.downloadArtifact(v); + Document pluginXml = loadPluginXml(jar); + if (pluginXml == null) { + continue; + } + Element root = pluginXml.getDocumentElement(); + Element mojos = XMLUtil.findElement(root, "mojos", null); + if (mojos == null) { + LOG.log(Level.WARNING, "no mojos in {0}", jar); + continue; + } + Set goals = new TreeSet(); + for (Element mojo : XMLUtil.findSubElements(mojos)) { + if (!mojo.getTagName().equals("mojo")) { + continue; + } + Element goal = XMLUtil.findElement(mojo, "goal", null); + if (goal == null) { + LOG.log(Level.WARNING, "mojo missing goal in {0}", jar); + continue; + } + goals.add(XMLUtil.findText(goal)); + } + LOG.log(Level.FINE, "found goals: {0}", goals); + return goals; } - TreeSet toRet = new TreeSet(); - for (int docNum = bitSet.nextSetBit(0); docNum >= 0; docNum = bitSet.nextSetBit(docNum+1)) { - Document doc = searcher.getIndexReader().document(docNum); - String goals = doc.getField(FIELD_GOALS).stringValue(); - String[] gls = StringUtils.split(goals, " "); //NOI18N - for (String goal : gls) { - toRet.add(goal); - } - } - return toRet; + return Collections.emptySet(); } /** @@ -199,57 +167,82 @@ * @param mojo e.g. {@code "compile"} * @return null if not found, else e.g. {@code [..., ${maven.compiler.verbose}=false, ...]} */ - public static Set getPluginParameters(String groupId, String artifactId, String version, String mojo) throws Exception { + public static @CheckForNull Set getPluginParameters(String groupId, String artifactId, String version, @NullAllowed String mojo) throws Exception { assert groupId != null && artifactId != null && version != null; - IndexSearcher searcher = getIndexSearcher(); - String id = groupId + "|" + artifactId + "|" + version; //NOI18N - TermQuery tq = new TermQuery(new Term(FIELD_ID, id)); - final BitSetCollector searchRes = new BitSetCollector(); - searcher.search(tq, searchRes); - final BitSet bitSet = searchRes.getMatchedDocs(); - if (bitSet.isEmpty()) { - return null; - } - TreeSet toRet = new TreeSet(new PComparator()); - for (int docNum = bitSet.nextSetBit(0); docNum >= 0; docNum = bitSet.nextSetBit(docNum+1)) { - Document doc = searcher.getIndexReader().document(docNum); - String goals = doc.getField(FIELD_GOALS).stringValue(); - String[] gls = StringUtils.split(goals, " "); //NOI18N - for (String goal : gls) { - if (mojo == null || mojo.equals(goal)) { - String params = doc.getField(PREFIX_FIELD_GOAL + goal).stringValue(); - String[] lines = StringUtils.split(params, "\n"); //NOI18N - for (String line : lines) { - String[] paramDet = StringUtils.split(line, "|"); //NOI18N - String name = paramDet[0]; - String editable = paramDet[1]; - String required = paramDet[2]; - boolean req = "true".equals(required); //NOI18N - if ("true".equals(editable)) { //NOI18N - String expr = paramDet[3]; - if (expr != null && "null".equals(expr)) { //NOI18N - expr = null; + for (NBVersionInfo v : RepositoryQueries.getVersions(groupId, artifactId, RepositoryQueries.getLoadedContexts().toArray(new RepositoryInfo[0]))) { + if (!v.getVersion().equals(version)) { + continue; + } + File jar = RepositoryUtil.downloadArtifact(v); + Document pluginXml = loadPluginXml(jar); + if (pluginXml == null) { + continue; + } + Element root = pluginXml.getDocumentElement(); + Element mojos = XMLUtil.findElement(root, "mojos", null); + if (mojos == null) { + LOG.log(Level.WARNING, "no mojos in {0}", jar); + continue; + } + for (Element mojoEl : XMLUtil.findSubElements(mojos)) { + if (!mojoEl.getTagName().equals("mojo")) { + continue; + } + Element goal = XMLUtil.findElement(mojoEl, "goal", null); + if (goal == null) { + LOG.log(Level.WARNING, "mojo missing goal in {0}", jar); + continue; + } + if (mojo != null && !mojo.equals(XMLUtil.findText(goal))) { + continue; + } + Set params = new TreeSet(new Comparator() { + @Override public int compare(ParameterDetail o1, ParameterDetail o2) { + return o1.getName().compareTo(o2.getName()); + } + }); + Element parameters = XMLUtil.findElement(mojoEl, "parameters", null); + Element configuration = XMLUtil.findElement(mojoEl, "configuration", null); + if (parameters != null) { + for (Element parameter : XMLUtil.findSubElements(parameters)) { + if (!parameter.getTagName().equals("parameter")) { + continue; + } + Element name = XMLUtil.findElement(parameter, "name", null); + if (name == null) { + LOG.log(Level.WARNING, "parameter missing name in {0}", jar); + } + Element description = XMLUtil.findElement(parameter, "description", null); + if (description == null) { + LOG.log(Level.WARNING, "parameter missing description in {0}", jar); + } + Element required = XMLUtil.findElement(parameter, "required", null); + if (required == null) { + LOG.log(Level.WARNING, "parameter missing required in {0}", jar); + } + String defaultValue = null; + String expression = null; + if (configuration != null) { + Element sample = XMLUtil.findElement(configuration, XMLUtil.findText(name), null); + if (sample != null) { + defaultValue = sample.getAttribute("default-value"); + if (defaultValue.isEmpty()) { + defaultValue = null; + } + String expressionWithSheBraces = XMLUtil.findText(sample); + if (expressionWithSheBraces != null && expressionWithSheBraces.matches("[$][{].+[}]")) { + expression = expressionWithSheBraces.substring(2, expressionWithSheBraces.length() - 1); + } } - String defVal = paramDet[4]; - if (defVal != null && "null".equals(defVal)) { //NOI18N - defVal = null; - } - String desc; - if (paramDet.length > 5) { - desc = paramDet[5]; - byte[] dec = Base64.decodeBase64(desc.getBytes()); - desc = new String(dec, "UTF-8"); //NOI18N - } else { - desc = null; - } - ParameterDetail pm = new ParameterDetail(name, expr, defVal, req, desc); - toRet.add(pm); } + params.add(new ParameterDetail(XMLUtil.findText(name), expression, defaultValue, Boolean.parseBoolean(XMLUtil.findText(required)), XMLUtil.findText(description))); } } + LOG.log(Level.FINE, "found params {0}", params); + return params; } } - return toRet; + return null; } @@ -261,21 +254,19 @@ */ public static Set getPluginsForGoalPrefix(String prefix) throws Exception { assert prefix != null; - IndexSearcher searcher = getIndexSearcher(); - TermQuery tq = new TermQuery(new Term(FIELD_PREFIX, prefix)); - final BitSetCollector searchRes = new BitSetCollector(); - searcher.search(tq, searchRes); - final BitSet bitSet = searchRes.getMatchedDocs(); - if (bitSet.isEmpty()) { - return null; + Set result = new TreeSet(); + RepositoryInfo[] infos = RepositoryQueries.getLoadedContexts().toArray(new RepositoryInfo[0]); + QueryField qf = new QueryField(); + qf.setField(ArtifactInfo.PLUGIN_PREFIX); + qf.setValue(prefix); + qf.setOccur(QueryField.OCCUR_MUST); + qf.setMatch(QueryField.MATCH_EXACT); + // XXX why does this not work in fresh userdir? + for (NBVersionInfo v : RepositoryQueries.find(Collections.singletonList(qf), infos)) { + result.add(v.getGroupId() + '|' + v.getArtifactId() + '|' + v.getVersion()); } - TreeSet toRet = new TreeSet(); - for (int docNum = bitSet.nextSetBit(0); docNum >= 0; docNum = bitSet.nextSetBit(docNum+1)) { - Document doc = searcher.getIndexReader().document(docNum); - String id = doc.getField(FIELD_ID).stringValue(); - toRet.add(id); - } - return toRet; + LOG.log(Level.FINE, "found plugins {0}", result); + return result; } /** @@ -287,162 +278,19 @@ */ public static Map> getLifecyclePlugins(String packaging, String mvnVersion, String[] extensionPlugins) throws Exception { assert packaging != null; - IndexSearcher searcher = getIndexSearcher(); - BooleanQuery bq = new BooleanQuery(); - TermQuery tq = new TermQuery(new Term(FIELD_CYCLES, packaging)); - bq.add(tq, BooleanClause.Occur.MUST); - if (mvnVersion == null) { - mvnVersion = "2.0.9"; //oh well we need something.. //NOI18N - } - BooleanQuery bq2 = new BooleanQuery(); - tq = new TermQuery(new Term(FIELD_MVN_VERSION, mvnVersion)); - bq2.add(tq, BooleanClause.Occur.SHOULD); + return Collections.emptyMap();//XXX + } - for (String ext : extensionPlugins) { - tq = new TermQuery(new Term(FIELD_ID, ext)); - bq2.add(tq, BooleanClause.Occur.SHOULD); - } - bq.add(bq2, BooleanClause.Occur.SHOULD); //why doesn't MUST work? - - final BitSetCollector searchRes = new BitSetCollector(); - searcher.search(bq, searchRes); - final BitSet bitSet = searchRes.getMatchedDocs(); - if (bitSet.isEmpty()) { + private static @CheckForNull Document loadPluginXml(File jar) { + if (!jar.isFile() || !jar.getName().endsWith(".jar")) { return null; } - LinkedHashMap> toRet = new LinkedHashMap>(); - for (int docNum = bitSet.nextSetBit(0); docNum >= 0; docNum = bitSet.nextSetBit(docNum+1)) { - Document doc = searcher.getIndexReader().document(docNum); - Field prefixed = doc.getField(PREFIX_FIELD_CYCLE + packaging); - if (prefixed != null) { - String mapping = prefixed.stringValue(); - String[] phases = StringUtils.split(mapping, "\n"); //NOI18N - for (String phase : phases) { - String[] ph = StringUtils.split(phase, "="); //NOI18N - String[] plugins = StringUtils.split(ph[1], ","); //NOI18N - List plgs = new ArrayList(Arrays.asList(plugins)); - toRet.put(ph[0], plgs); - } - } - } - return toRet; - } - - - private static int checkLocalVersion(File[] fls) { - for (File fl : fls) { + LOG.log(Level.FINE, "parsing plugin.xml from {0}", jar); try { - int intVersion = Integer.parseInt(fl.getName()); - return intVersion; - } catch (NumberFormatException e) { - Exceptions.printStackTrace(e); - } - } - //if there is a folder, but not a number, return max value to be sure - //we don't overwrite stuff.. - return fls.length > 0 ? Integer.MAX_VALUE : 0; - } - - private static int checkZipVersion(File cacheDir) { - InputStream is = null; - try { - is = PluginIndexManager.class.getClassLoader().getResourceAsStream(ZIP_LOCATION); //NOI18N - ZipInputStream zis = new ZipInputStream(is); - ZipEntry entry = zis.getNextEntry(); - if (entry != null) { - File fl = new File(cacheDir, entry.getName()); - if (!fl.getParentFile().equals(cacheDir)) { - String version = fl.getParentFile().getName(); - try { - int intVersion = Integer.parseInt(version); - return intVersion; - } catch (NumberFormatException e) { - Exceptions.printStackTrace(e); - } - } - } - } catch (IOException io) { - Exceptions.printStackTrace(io); - } finally { - IOUtil.close(is); - } - return 0; //a fallback - } - - private static File getDefaultIndexLocation() { - String userdir = System.getProperty("netbeans.user"); //NOI18N - File cacheDir; - if (userdir != null) { - cacheDir = new File(new File(new File(userdir, "var"), "cache"), INDEX_PATH);//NOI18N - } else { - File root = FileUtil.toFile(FileUtil.getConfigRoot()); - cacheDir = new File(root, INDEX_PATH);//NOI18N - } - cacheDir.mkdirs(); - File[] fls = cacheDir.listFiles(); - if (fls == null || fls.length == 0) { - //copy the preexisting index in module into place.. - InputStream is = null; - try { - is = PluginIndexManager.class.getClassLoader().getResourceAsStream(ZIP_LOCATION); //NOI18N - ZipInputStream zis = new ZipInputStream(is); - unzip(zis, cacheDir); - } finally { - IOUtil.close(is); - } - } else { - int zipped = checkZipVersion(cacheDir); - int local = checkLocalVersion(fls); - if (zipped > local && local > 0) { - try { - FileUtils.deleteDirectory(new File(cacheDir, "" + local)); - //copy the preexisting index in module into place.. - InputStream is = null; - try { - is = PluginIndexManager.class.getClassLoader().getResourceAsStream(ZIP_LOCATION); //NOI18N - ZipInputStream zis = new ZipInputStream(is); - unzip(zis, cacheDir); - } finally { - IOUtil.close(is); - } - } catch (IOException ex) { - Exceptions.printStackTrace(ex); - } - } - } - File[] files = cacheDir.listFiles(); - assert files != null && files.length == 1; - cacheDir = files[0]; - return cacheDir; - } - - private static void unzip(ZipInputStream zis, File cacheDir) { - try { - BufferedOutputStream dest = null; - ZipEntry entry; - while ((entry = zis.getNextEntry()) != null) { - int count; - byte data[] = new byte[BUFFER]; - File fl = new File(cacheDir, entry.getName()); - fl.getParentFile().mkdirs(); - FileOutputStream fos = new FileOutputStream(fl); - dest = new BufferedOutputStream(fos, BUFFER); - while ((count = zis.read(data, 0, BUFFER)) != -1) { - dest.write(data, 0, count); - } - dest.flush(); - dest.close(); - } - } catch (Exception e) { - e.printStackTrace(); - } finally { - IOUtil.close(zis); - } - } - - private static class PComparator implements Comparator { - public int compare(ParameterDetail o1, ParameterDetail o2) { - return o1.getName().compareTo(o2.getName()); + return XMLUtil.parse(new InputSource("jar:" + jar.toURI() + "!/META-INF/maven/plugin.xml"), false, false, XMLUtil.defaultErrorHandler(), null); + } catch (Exception x) { + LOG.log(Level.INFO, "could not parse " + jar, x); + return null; } } @@ -451,12 +299,12 @@ */ public static class ParameterDetail { private String name; - private String expression; - private String defaultValue; + private @NullAllowed String expression; + private @NullAllowed String defaultValue; private boolean required; private String description; - private ParameterDetail(String name, String expression, String defaultValue, boolean required, String description) { + private ParameterDetail(String name, @NullAllowed String expression, @NullAllowed String defaultValue, boolean required, String description) { this.name = name; this.expression = expression; this.defaultValue = defaultValue; @@ -467,7 +315,7 @@ /** * @return null, or e.g. {@code false} */ - public String getDefaultValue() { + @CheckForNull public String getDefaultValue() { return defaultValue; } @@ -478,12 +326,12 @@ /** * @return null, or e.g. {@code maven.compiler.verbose} */ - public String getExpression() { + @CheckForNull public String getExpression() { return expression; } /** - * @return null, or e.g. {@code verbose} + * e.g. {@code verbose} */ public String getName() { return name; @@ -506,39 +354,6 @@ } - - private static final class BitSetCollector extends Collector { - - private int docBase; - private final BitSet bits = new BitSet(); - - public BitSet getMatchedDocs() { - return this.bits; - } - - - @Override - public void setScorer(Scorer scorer) { - //Todo: ignoring scorer for now, if ordering accoring to score needed - // this will need to be implemented - } - - // accept docs out of order (for a BitSet it doesn't matter) - @Override - public boolean acceptsDocsOutOfOrder() { - return true; - } - - @Override - public void collect(int doc) { - bits.set(doc + docBase); - } - - @Override - public void setNextReader(IndexReader reader, int docBase) { - this.docBase = docBase; - } - - } + private PluginIndexManager() {} } diff --git a/maven.indexer/src/org/netbeans/modules/maven/indexer/api/RepositoryUtil.java b/maven.indexer/src/org/netbeans/modules/maven/indexer/api/RepositoryUtil.java --- a/maven.indexer/src/org/netbeans/modules/maven/indexer/api/RepositoryUtil.java +++ b/maven.indexer/src/org/netbeans/modules/maven/indexer/api/RepositoryUtil.java @@ -48,8 +48,11 @@ import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; +import java.util.Collections; +import java.util.List; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.repository.ArtifactRepository; +import org.apache.maven.artifact.resolver.AbstractArtifactResolutionException; import org.netbeans.modules.maven.embedder.EmbedderFactory; import org.codehaus.plexus.util.IOUtil; import org.netbeans.modules.maven.embedder.MavenEmbedder; @@ -94,6 +97,26 @@ return art; } + /** + * Tries to download an artifact. + * @param info a version of an artifact + * @return the file in the local repository (might not exist if download failed) + * @throws AbstractArtifactResolutionException currently never? + */ + static File downloadArtifact(NBVersionInfo info) throws AbstractArtifactResolutionException { + Artifact a = createArtifact(info); + MavenEmbedder online = EmbedderFactory.getOnlineEmbedder(); + List remotes; + RepositoryInfo repo = RepositoryPreferences.getInstance().getRepositoryInfoById(info.getRepoId()); + if (repo != null && repo.isRemoteDownloadable()) { + remotes = Collections.singletonList(EmbedderFactory.createRemoteRepository(online, repo.getRepositoryUrl(), repo.getId())); + } else { + remotes = Collections.emptyList(); + } + online.resolve(createArtifact(info), remotes, online.getLocalRepository()); + return a.getFile(); + } + public static String calculateSHA1Checksum(File file) throws IOException { byte[] buffer = readFile(file); MessageDigest digest; diff --git a/maven.indexer/src/org/netbeans/modules/maven/indexer/pluginz.zip b/maven.indexer/src/org/netbeans/modules/maven/indexer/pluginz.zip deleted file mode 100644 Binary file maven.indexer/src/org/netbeans/modules/maven/indexer/pluginz.zip has changed diff --git a/maven.indexer/test/unit/src/org/netbeans/modules/maven/indexer/api/RepositoryQueriesTest.java b/maven.indexer/test/unit/src/org/netbeans/modules/maven/indexer/api/RepositoryQueriesTest.java new file mode 100644 --- /dev/null +++ b/maven.indexer/test/unit/src/org/netbeans/modules/maven/indexer/api/RepositoryQueriesTest.java @@ -0,0 +1,106 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright 2011 Oracle and/or its affiliates. All rights reserved. + * + * Oracle and Java are registered trademarks of Oracle and/or its affiliates. + * Other names may be trademarks of their respective owners. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common + * Development and Distribution License("CDDL") (collectively, the + * "License"). You may not use this file except in compliance with the + * License. You can obtain a copy of the License at + * http://www.netbeans.org/cddl-gplv2.html + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the + * specific language governing permissions and limitations under the + * License. When distributing the software, include this License Header + * Notice in each file and include the License file at + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the GPL Version 2 section of the License file that + * accompanied this code. If applicable, add the following below the + * License Header, with the fields enclosed by brackets [] replaced by + * your own identifying information: + * "Portions Copyrighted [year] [name of copyright owner]" + * + * If you wish your version of this file to be governed by only the CDDL + * or only the GPL Version 2, indicate your decision by adding + * "[Contributor] elects to include this software in this distribution + * under the [CDDL or GPL Version 2] license." If you do not indicate a + * single choice of license, a recipient has the option to distribute + * your version of this file under either the CDDL, the GPL Version 2 or + * to extend the choice of license to its licensees as provided above. + * However, if you add GPL Version 2 code and therefore, elected the GPL + * Version 2 license, then the option applies only if the new code is + * made subject to such option by the copyright holder. + * + * Contributor(s): + * + * Portions Copyrighted 2011 Sun Microsystems, Inc. + */ + +package org.netbeans.modules.maven.indexer.api; + +import java.io.File; +import java.util.Collections; +import org.apache.maven.artifact.installer.ArtifactInstaller; +import org.apache.maven.artifact.repository.ArtifactRepository; +import org.apache.maven.artifact.repository.layout.DefaultRepositoryLayout; +import org.apache.maven.index.ArtifactInfo; +import org.netbeans.junit.NbTestCase; +import org.netbeans.modules.maven.embedder.EmbedderFactory; +import org.netbeans.modules.maven.embedder.MavenEmbedder; +import org.openide.util.test.TestFileUtils; + +public class RepositoryQueriesTest extends NbTestCase { + + public RepositoryQueriesTest(String n) { + super(n); + } + + private ArtifactRepository defaultArtifactRepository; + private MavenEmbedder embedder; + private ArtifactInstaller artifactInstaller; + private RepositoryInfo info; + + @SuppressWarnings("deprecation") // no documented replacement + @Override protected void setUp() throws Exception { + clearWorkDir(); + System.setProperty("netbeans.user", getWorkDirPath()); + File repo = new File(getWorkDir(), "repo"); + defaultArtifactRepository = new org.apache.maven.artifact.repository.DefaultArtifactRepository("test", repo.toURI().toString(), new DefaultRepositoryLayout()); + embedder = EmbedderFactory.getProjectEmbedder(); + embedder.setUpLegacySupport(); + artifactInstaller = embedder.lookupComponent(ArtifactInstaller.class); + info = new RepositoryInfo("test", RepositoryPreferences.TYPE_NEXUS, "Test", repo.getAbsolutePath(), null); + RepositoryPreferences.getInstance().addOrModifyRepositoryInfo(info); + } + + @SuppressWarnings("deprecation") // no documented replacement + private void install(File f, String groupId, String artifactId, String version, String packaging) throws Exception { + artifactInstaller.install(f, embedder.lookupComponent(org.apache.maven.artifact.factory.ArtifactFactory.class).createBuildArtifact(groupId, artifactId, version, packaging), defaultArtifactRepository); + } + + public void testFilterGroupIds() throws Exception { + install(File.createTempFile("whatever", ".txt", getWorkDir()), "test", "spin", "1.1", "txt"); + assertEquals(Collections.singleton("test"), RepositoryQueries.filterGroupIds("", info)); + } + + public void testFind() throws Exception { + install(TestFileUtils.writeFile(new File(getWorkDir(), "plugin.pom"), + "4.0.0" + + "testplugin" + + "0maven-plugin"), "test", "plugin", "0", "pom"); + File jar = new File(getWorkDir(), "plugin.jar"); + TestFileUtils.writeZipFile(jar, "META-INF/maven/plugin.xml:stuff"); + install(jar, "test", "plugin", "0", "maven-plugin"); + QueryField qf = new QueryField(); + qf.setField(ArtifactInfo.PLUGIN_PREFIX); + qf.setValue("stuff"); + qf.setOccur(QueryField.OCCUR_MUST); + qf.setMatch(QueryField.MATCH_EXACT); + assertEquals("[test:plugin:0:test]", RepositoryQueries.find(Collections.singletonList(qf), info).toString()); + } + +}