org.netbeans.modules.maven.model.pom.POMModel Java Examples

The following examples show how to use org.netbeans.modules.maven.model.pom.POMModel. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MavenSchemaCompiler.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public void compileSchema(final WizardDescriptor wiz) {
    final String schemaName = (String) wiz.getProperty(JAXBWizModuleConstants.SCHEMA_NAME);
    ModelOperation<POMModel> operation = new ModelOperation<POMModel>() {
        @Override
        public void performOperation(POMModel model) {
            org.netbeans.modules.maven.model.pom.Plugin plugin = addJaxb2Plugin(model); //NOI18N
            String packageName =
                    (String)wiz.getProperty(JAXBWizModuleConstants.PACKAGE_NAME);
            if (packageName != null && packageName.trim().length() == 0) {
                packageName = null;
            }
            addJaxb2Execution(plugin, schemaName, packageName);
        }
    };
    Utilities.performPOMModelOperations(project.getProjectDirectory().getFileObject("pom.xml"),
            Collections.singletonList(operation));
}
 
Example #2
Source File: POMModelVisitor.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private List<POMCutHolder> rescan(POMModelVisitor visitor) {
    try {
        Method m = POMModelVisitor.class.getMethod("visit", type); //NOI18N
        POMModel[] models = parentHolder.getSource();
        Object[] cuts = parentHolder.getCutValues();
        for (int i = 0; i < cuts.length; i++) {
            Object cut = cuts[i];
            // prevent deadlock 185923
            if (cut != null && !type.isInstance(cut)) {
                LOG.log(Level.WARNING, "#185428: {0} is not assignable to {1}", new Object[] {cut, type});
                continue;
            }
            synchronized (i < models.length ? models[i] : /*#192042*/new Object()) {
                m.invoke(visitor, cut);
            }
        }
    } catch (Exception x) {
        LOG.log(Level.WARNING, null, x);
    }
    children = Arrays.asList(visitor.getChildValues());
    return children;
}
 
Example #3
Source File: POMModelVisitor.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public String getShortDescription() {
    Object[] values = getLookup().lookup(POMCutHolder.class).getCutValues();
    POMModel[] mdls = getLookup().lookup(POMCutHolder.class).getSource();
    StringBuilder buff = new StringBuilder();
    int index = 0;
    buff.append("<html>").
            append(TOOLTIP_Defined_in()).append("<p><table><thead><tr><th>").
            append(TOOLTIP_ArtifactId()).append("</th><th>").
            append(TOOLTIP_IS_DEFINED()).append("</th></tr></thead><tbody>"); //NOI18N
    for (POMModel mdl : mdls) {
        String artifact = mdl.getProject().getArtifactId();
        buff.append("<tr><td>"); //NOI18N
        buff.append(artifact != null ? artifact : "project");
        buff.append("</td><td>"); //NOI18N
        buff.append(values[index] != null ? TOOLTIP_YES() : TOOLTIP_NO());
        buff.append("</td></tr>");//NOI18N
        index++;
    }
    buff.append("</tbody></table>");//NOI18N

    return buff.toString();
}
 
Example #4
Source File: AddMavenCompilerPlugin.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public void performOperation(final POMModel model) {
    factory = model.getFactory();
    project = model.getProject();
    Build build = project.getBuild();
    if (build == null) {
        build = factory.createBuild();
        project.setBuild(build);
    }

    Plugin plugin = searchMavenCompilerPlugin(build);
    if (plugin == null) {
        build.addPlugin(createMavenEclipseCompilerPlugin());
    } else {
        Plugin newPlugin = createMavenEclipseCompilerPlugin(plugin);

        build.removePlugin(plugin);
        build.addPlugin(newPlugin);
    }
}
 
Example #5
Source File: OverrideDependencyManagementError.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public List<ErrorDescription> getErrorsForDocument(POMModel model, Project prj) {
    assert model != null;
    List<ErrorDescription> toRet = new ArrayList<ErrorDescription>();
    if (prj == null) {
        return toRet;
    }
    Map<String, String> managed = collectManaged(prj);
    if (managed.isEmpty()) {
        return toRet;
    }

    checkDependencyList(model.getProject().getDependencies(), model, toRet, managed);
    List<Profile> profiles = model.getProject().getProfiles();
    if (profiles != null) {
        for (Profile prof : profiles) {
            checkDependencyList(prof.getDependencies(), model, toRet, managed);
        }
    }
    return toRet;

}
 
Example #6
Source File: NetBeansRunParamsIDEChecker.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static ModelOperation<POMModel> createUpgradePluginOperation() {
    return new ModelOperation<POMModel>() {
        public @Override
        void performOperation(POMModel model) {
            POMComponentFactory factory = model.getFactory();
            Project project = model.getProject();
            Build bld = project.getBuild();
            if (bld == null) {
                bld = factory.createBuild();
                project.setBuild(bld);
            }
            Plugin plg = PluginBackwardPropertyUtils.findPluginFromBuild(bld);
            if (plg == null) {
                plg = factory.createPlugin();
                plg.setGroupId(MavenNbModuleImpl.GROUPID_APACHE);
                plg.setArtifactId(MavenNbModuleImpl.NBM_PLUGIN);
                plg.setExtensions(Boolean.TRUE);
                bld.addPlugin(plg);
            }
            plg.setVersion(MavenNbModuleImpl.getLatestNbmPluginVersion()); //
        }
    };
}
 
Example #7
Source File: CPExtender.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public @Override boolean addRoots(final URL[] urls, SourceGroup grp, String type) throws IOException {
    final AtomicBoolean added = new AtomicBoolean();
    final String scope = findScope(grp, type);
    ModelOperation<POMModel> operation = new ModelOperation<POMModel>() {
        public @Override void performOperation(POMModel model) {
            for (URL url : urls) {
                File jar = FileUtil.archiveOrDirForURL(url);
                if (jar != null && jar.isFile()) {
                    try {
                        added.compareAndSet(false, addRemoveJAR(jar, model, scope, true));
                    } catch (IOException ex) {
                        Exceptions.printStackTrace(ex);
                    }
                } else {
                    Logger.getLogger(CPExtender.class.getName()).log(Level.INFO, "Adding non-jar root to Maven projects makes no sense. ({0})", url); //NOI18N
                }
            }
        }
    };
    FileObject pom = project.getProjectDirectory().getFileObject(POM_XML);//NOI18N
    org.netbeans.modules.maven.model.Utilities.performPOMModelOperations(pom, Collections.singletonList(operation));
    if (added.get()) {
        project.getLookup().lookup(NbMavenProject.class).triggerDependencyDownload();
    }
    return added.get();
}
 
Example #8
Source File: EmbeddableEJBContainerHint.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
    public ChangeInfo implement() throws Exception {
        final Boolean[] added = new Boolean[1];
        ModelOperation<POMModel> operation = new ModelOperation<POMModel>() {
            @Override
            public void performOperation(POMModel model) {
                added[0] = checkAndAddPom(pomUrl, model, file);
            }
        };
        FileObject pom = project.getProjectDirectory().getFileObject("pom.xml");//NOI18N
        org.netbeans.modules.maven.model.Utilities.performPOMModelOperations(pom, Collections.singletonList(operation));
        //TODO is the manual reload necessary if pom.xml file is being saved?
//                NbMavenProject.fireMavenProjectReload(project);
        if (added[0]) {
            project.getLookup().lookup(NbMavenProject.class).triggerDependencyDownload();
        }
        return null;
    }
 
Example #9
Source File: ReleaseVersionError.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void checkPluginList(List<Plugin> plugins, POMModel model, List<ErrorDescription> toRet, boolean release, boolean latest, boolean snapshot) {
    if (plugins != null) {
        for (Plugin plg : plugins) {
            String ver = plg.getVersion();
            if (ver != null && ((release && "RELEASE".equals(ver)) ||  //NOI18N
                    (latest &&"LATEST".equals(ver)) || //NOI18N
                    (snapshot && ver.endsWith("SNAPSHOT")) //NOI18N
                )) {
                int position = plg.findChildElementPosition(model.getPOMQNames().VERSION.getQName());
                Line line = NbEditorUtilities.getLine(model.getBaseDocument(), position, false);
                toRet.add(ErrorDescriptionFactory.createErrorDescription(
                               configuration.getSeverity(configuration.getPreferences()).toEditorSeverity(),
                        NbBundle.getMessage(ReleaseVersionError.class, "DESC_RELEASE_VERSION"),
                        Collections.<Fix>emptyList(), //Collections.<Fix>singletonList(new ReleaseFix(plg)),
                        model.getBaseDocument(), line.getLineNumber() + 1));
            }
        }
    }
}
 
Example #10
Source File: MavenModelUtils.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static void removeWsimportExecution(POMModel model, String id) {
    assert model.isIntransaction();
    Build bld = model.getProject().getBuild();
    if (bld == null) {
        return;
    }
    Plugin plugin = bld.findPluginById(JAXWS_GROUP_ID, JAXWS_ARTIFACT_ID);
    if (plugin != null) {
        List<PluginExecution> executions = plugin.getExecutions();
        if (executions != null) {
            for (PluginExecution exec : executions) {
                String execId = WSIPMORT_GENERATE_PREFIX+id;
                if (execId.equals(exec.getId())) {
                    plugin.removeExecution(exec);
                    break;
                }
            }
        }
    }
}
 
Example #11
Source File: MavenGroovyExtender.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public boolean activate() {
    try {
        pom.getFileSystem().runAtomicAction(new FileSystem.AtomicAction() {
            @Override
            public void run() throws IOException {
                List<ModelOperation<POMModel>> operations = new ArrayList<ModelOperation<POMModel>>();
                operations.add(new AddGroovyDependency());
                operations.add(new AddMavenCompilerPlugin());
                operations.add(new AddGroovyEclipseCompiler());
                Utilities.performPOMModelOperations(pom, operations);
            }
        });
    } catch (IOException ex) {
        return false;
    }
    return true;
}
 
Example #12
Source File: OperationsImpl.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public void notifyMoved(Project original, File originalLoc, final String newName) throws IOException {
    if (original == null) {
        //old project call..
        project.getLookup().lookup(ProjectState.class).notifyDeleted();
    } else {
        if (original.getProjectDirectory().equals(project.getProjectDirectory())) {
            // oh well, just change the name in the pom when rename is invoked.
            FileObject pomFO = project.getProjectDirectory().getFileObject("pom.xml"); //NOI18N
            ModelOperation<POMModel> operation = new ModelOperation<POMModel>() {
                @Override
                public void performOperation(POMModel model) {
                    model.getProject().setName(newName);
                }
            };
            Utilities.performPOMModelOperations(pomFO, Collections.singletonList(operation));
            NbMavenProject.fireMavenProjectReload(project);
        }
        checkParentProject(project.getProjectDirectory(), false, newName, originalLoc.getName());
    }
}
 
Example #13
Source File: NbmWizardIterator.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static ModelOperation<POMModel> addNbmPluginOsgiParameter(File projFile) throws IOException {
     FileObject prjDir = FileUtil.toFileObject(projFile);
     if (prjDir != null) {
         FileObject pom = prjDir.getFileObject("pom.xml");
         if (pom != null) {
             Project prj = ProjectManager.getDefault().findProject(prjDir);
             if (prj == null) {
                 return null; // invalid? #184466
             }
             NbMavenProject mav = prj.getLookup().lookup(NbMavenProject.class);
             return  new AddOSGiParamToNbmPluginConfiguration(true, mav.getMavenProject());
         }
     }
     //TODO report inability to create? or if the file doesn't exist, it was already
     //reported?
     return null;
}
 
Example #14
Source File: ParentVersionErrorTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testSpecialRelativePath() throws Exception { // #194281
    TestFileUtils.writeFile(work, "common.xml", "<project xmlns='http://maven.apache.org/POM/4.0.0' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd'>\n" +
            "    <modelVersion>4.0.0</modelVersion>\n" +
            "    <groupId>grp</groupId>\n" +
            "    <artifactId>common</artifactId>\n" +
            "    <version>1.0</version>\n" +
            "</project>\n");
    FileObject pom = TestFileUtils.writeFile(work, "prj/pom.xml", "<project xmlns='http://maven.apache.org/POM/4.0.0' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd'>\n" +
            "    <modelVersion>4.0.0</modelVersion>\n" +
            "    <parent>\n" +
            "        <groupId>grp</groupId>\n" +
            "        <artifactId>common</artifactId>\n" +
            "        <relativePath>../common.xml</relativePath>\n" +
            "    </parent>\n" +
            "    <artifactId>prj</artifactId>\n" +
            "</project>\n");
    POMModel model = POMModelFactory.getDefault().getModel(Utilities.createModelSource(pom));
    Project prj = ProjectManager.getDefault().findProject(pom.getParent());
    assertEquals(Collections.<ErrorDescription>emptyList(), new ParentVersionError().getErrorsForDocument(model, prj));
}
 
Example #15
Source File: EAWizardIterator.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Creates dependencies between EAR ---> Ejb module and EAR ---> Web module
 *
 * @param earDir ear module directory
 * @param ejbInfo ejb project informations
 * @param webInfo web project informations
 */
private void addEARDependencies(File earDir, ProjectInfo ejbInfo, ProjectInfo webInfo) {
    FileObject earDirFO = FileUtil.toFileObject(FileUtil.normalizeFile(earDir));
    if (earDirFO == null) {
        return;
    }
    List<ModelOperation<POMModel>> operations = new ArrayList<>();
    if (ejbInfo != null) {
        operations.add(ArchetypeWizards.addDependencyOperation(ejbInfo, "ejb")); // NOI18N
    }
    if (webInfo != null) {
        operations.add(ArchetypeWizards.addDependencyOperation(webInfo, "war")); // NOI18N
    }

    FileObject earPom = earDirFO.getFileObject("pom.xml"); // NOI18N
    if (earPom != null) {
        Utilities.performPOMModelOperations(earPom, operations);
    }
}
 
Example #16
Source File: POMModelVisitor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public POMModel[] getSource() {
    if (models != null) {
        return models;
    }
    if (parent != null) {
        return parent.getSource();
    }
    throw new IllegalStateException();
}
 
Example #17
Source File: PluginGenerator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public List<? extends CodeGenerator> create(Lookup context) {
    ArrayList<CodeGenerator> toRet = new ArrayList<CodeGenerator>();
    POMModel model = context.lookup(POMModel.class);
    JTextComponent component = context.lookup(JTextComponent.class);
    if (model != null) {
        toRet.add(new PluginGenerator(model, component));
    }
    return toRet;
}
 
Example #18
Source File: CPExtender.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void addJarToPrivateRepo(File jar, POMModel mdl, NBVersionInfo dep) throws IOException {
    //first add the local repo to
    List<Repository> repos = mdl.getProject().getRepositories();
    boolean found = false;
    String path = null;
    if (repos != null) {
        for (Repository repo : repos) {
            if ("unknown-jars-temp-repo".equals(repo.getId())) { //NOI18N
                found = true;
                String url = repo.getUrl();
                if (url.startsWith("file:${project.basedir}/")) { //NOI18N
                    path = url.substring("file:${project.basedir}/".length()); //NOI18N
                } else {
                    path = "lib"; //NOI18N
                }
                break;
            }
        }
    }
    if (!found) {
        Repository repo = mdl.getFactory().createRepository();
        repo.setId("unknown-jars-temp-repo"); //NOI18N
        repo.setName("A temporary repository created by NetBeans for libraries and jars it could not identify. Please replace the dependencies in this repository with correct ones and delete this repository."); //NOI18N
        repo.setUrl("file:${project.basedir}/lib"); //NOI18N
        mdl.getProject().addRepository(repo);
        path = "lib"; //NOI18N
    }
    assert path != null;
    FileObject root = FileUtil.createFolder(project.getProjectDirectory(), path);
    FileObject grp = FileUtil.createFolder(root, dep.getGroupId().replace('.', '/')); //NOI18N
    FileObject art = FileUtil.createFolder(grp, dep.getArtifactId());
    FileObject ver = FileUtil.createFolder(art, dep.getVersion());
    String name = dep.getArtifactId() + '-' + dep.getVersion();
    FileObject file = FileUtil.toFileObject(jar);
    if (ver.getFileObject(name, file.getExt()) == null) { //#160803
        FileUtil.copyFile(file, ver, name, file.getExt());
    }
}
 
Example #19
Source File: ModelUtilsTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testAddModelRepository() throws Exception { // #212336
    FileObject pom = TestFileUtils.writeFile(FileUtil.toFileObject(getWorkDir()), "pom.xml",
            "<project xmlns='http://maven.apache.org/POM/4.0.0'>\n"
            + "    <modelVersion>4.0.0</modelVersion>\n"
            + "    <groupId>grp</groupId>\n"
            + "    <artifactId>art</artifactId>\n"
            + "    <version>1.0</version>\n"
            + "</project>\n");
    final MavenProject mp = ProjectManager.getDefault().findProject(pom.getParent()).getLookup().lookup(NbMavenProject.class).getMavenProject();
    Utilities.performPOMModelOperations(pom, Collections.singletonList(new ModelOperation<POMModel>() {
        @Override public void performOperation(POMModel model) {
            Repository added = ModelUtils.addModelRepository(mp, model, "http://repo1.maven.org/maven2/");
            assertNull(added);
            added = ModelUtils.addModelRepository(mp, model, "http://nowhere.net/maven2/");
            assertNotNull(added);
            added.setId("nowhere.net");
            added = ModelUtils.addModelRepository(mp, model, "http://nowhere.net/maven2/");
            assertNull(added);
        }
    }));
    assertEquals("<project xmlns='http://maven.apache.org/POM/4.0.0'>\n"
            + "    <modelVersion>4.0.0</modelVersion>\n"
            + "    <groupId>grp</groupId>\n"
            + "    <artifactId>art</artifactId>\n"
            + "    <version>1.0</version>\n"
            + "    <repositories>\n"
            + "        <repository>\n"
            + "            <url>http://nowhere.net/maven2/</url>\n"
            // XXX would be nice to fix IdPOMComponentImpl to put <id> first
            + "            <id>nowhere.net</id>\n"
            + "        </repository>\n"
            + "    </repositories>\n"
            + "</project>\n",
            pom.asText().replace("\r\n", "\n"));
}
 
Example #20
Source File: StatusProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static void runMavenValidation(final POMModel model, final List<ErrorDescription> err) {
    File pom = model.getModelSource().getLookup().lookup(File.class);
    if (pom == null) {
        return;
    }
    
    List<ModelProblem> problems = runMavenValidationImpl(pom);
    for (ModelProblem problem : problems) {
        if (!problem.getSource().equals(pom.getAbsolutePath())) {
            LOG.log(Level.FINE, "found problem not in {0}: {1}", new Object[] {pom, problem.getSource()});
            continue;
        }
        int line = problem.getLineNumber();
        if (line <= 0) { // probably from a parent POM
            /* probably more irritating than helpful:
            line = 1; // fallback
            Parent parent = model.getProject().getPomParent();
            if (parent != null) {
                Line l = NbEditorUtilities.getLine(model.getBaseDocument(), parent.findPosition(), false);
                if (l != null) {
                    line = l.getLineNumber() + 1;
                }
            }
            */
            continue;
        }
        if (problem.getException() instanceof UnresolvableModelException) {
            // If a <parent> reference cannot be followed because e.g. no projects are opened (so no repos registered), just ignore it.
            continue;
        }
        try {
            err.add(ErrorDescriptionFactory.createErrorDescription(problem.getSeverity() == ModelProblem.Severity.WARNING ? Severity.WARNING : Severity.ERROR, problem.getMessage(), model.getBaseDocument(), line));
        } catch (IndexOutOfBoundsException x) {
            LOG.log(Level.WARNING, "improper line number: {0}", problem);
        }
    }
    
}
 
Example #21
Source File: POMModelVisitor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
SingleObjectCH(POMModel[] models, POMQNames names, POMQName qname, Class type, POMModelPanel.Configuration config) {
    super(models, names);
    this.qname = qname;
    this.display = "root"; //NOI18N
    this.type = type;
    this.configuration = config;
}
 
Example #22
Source File: TaskListBridge.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public List<? extends Task> scan(FileObject resource) {
    if (Constants.POM_MIME_TYPE.equals(resource.getMIMEType()) //NOI18N
            && "pom.xml".equals(resource.getNameExt())) { //NOI18N
        Project prj = FileOwnerQuery.getOwner(resource);
        if (prj != null && prj.getLookup().lookup(NbMavenProject.class) != null) {
            ModelSource ms = Utilities.createModelSource(resource);
            POMModel model = POMModelFactory.getDefault().getModel(ms);
            model.setAutoSyncActive(false);
            List<ErrorDescription> errs = StatusProvider.StatusProviderImpl.findHints(model, prj, -1, -1, -1);
            List<Task> tasks = new ArrayList<Task>();

            for (ErrorDescription error : errs) {
                try {
                    Task task = Task.create(resource,
                            severityToTaskListString(error.getSeverity()),
                            error.getDescription(),
                            error.getRange().getBegin().getLine() + 1);

                    tasks.add(task);
                } catch (IOException e) {
                    Logger.getLogger(TaskListBridge.class.getName()).
                            log(Level.INFO, "Error while converting errors to tasklist", e);
                }
            }
            return tasks;
        }
    }
    return Collections.<Task>emptyList();
}
 
Example #23
Source File: POMModelVisitor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
@Messages({"ACT_Show=Show in POM", 
    "# {0} - artifactid of a project",
    "ACT_Current=Current: {0}",
    "# {0} - artifactid of a project",
    "ACT_PARENT=Parent: {0}"})
public JMenuItem getPopupPresenter() {
    JMenu menu = new JMenu();
    menu.setText(ACT_Show());
    POMCutHolder pch = node.getLookup().lookup(POMCutHolder.class);
    POMModel[] mdls = pch.getSource();
    Object[] val = pch.getCutValues();
    int index = 0;
    for (POMModel mdl : mdls) {
        String artifact = mdl.getProject().getArtifactId();
        JMenuItem item = new JMenuItem();
        item.setAction(new SelectAction(node, index));
        if (index == 0) {
            item.setText(ACT_Current(artifact != null ? artifact : "project"));
        } else {
            item.setText(ACT_PARENT(artifact != null ? artifact : "project"));
        }
        item.setEnabled(/* #199345 */index < val.length && val[index] != null);
        menu.add(item);
        index++;
    }
    return menu;
}
 
Example #24
Source File: MavenModelUtils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * adds jaxws plugin, requires the model to have a transaction started,
 * eg. by calling as part of Utilities.performPOMModelOperations(ModelOperation<POMModel>)
 * @param model POMModel
 * @param jaxWsVersion version of sources to generate. Value null means default version.
 * @return JAX-WS Plugin instance
 */
public static Plugin addJaxWSPlugin(POMModel model, String jaxWsVersion) {
    assert model.isIntransaction() : "need to call model modifications under transaction."; //NOI18N
    Build bld = model.getProject().getBuild();
    if (bld == null) {
        bld = model.getFactory().createBuild();
        model.getProject().setBuild(bld);
    }
    Plugin plugin = bld.findPluginById(JAXWS_GROUP_ID, JAXWS_ARTIFACT_ID);
    if (plugin != null) {
        //TODO CHECK THE ACTUAL PARAMETER VALUES..
        return plugin;
    }
    plugin = model.getFactory().createPlugin();
    plugin.setGroupId(JAXWS_GROUP_ID);
    plugin.setArtifactId(JAXWS_ARTIFACT_ID);
    plugin.setVersion(JAX_WS_PLUGIN_VERSION); 
    bld.addPlugin(plugin);

    // setup global configuration
    Configuration config = plugin.getConfiguration();
    if (config == null) {
        config = model.getFactory().createConfiguration();
        plugin.setConfiguration(config);
    }
    config.setSimpleParameter("sourceDestDir", "${project.build.directory}/generated-sources/jaxws-wsimport"); //NOI18N
    config.setSimpleParameter("xnocompile", "true"); //NOI18N
    config.setSimpleParameter("verbose", "true"); //NOI18N
    config.setSimpleParameter("extension", "true"); //NOI18N
    config.setSimpleParameter("catalog", "${basedir}/" + MavenJAXWSSupportImpl.CATALOG_PATH);
    if (jaxWsVersion != null) {
        config.setSimpleParameter("target", jaxWsVersion); //NOI18N
    }
    Dependency webservicesDep = model.getFactory().createDependency();
    webservicesDep.setGroupId("javax.xml"); //NOI18N
    webservicesDep.setArtifactId("webservices-api"); //NOI18N
    webservicesDep.setVersion("2.0"); //NOI18N
    plugin.addDependency(webservicesDep);
    return plugin; 
}
 
Example #25
Source File: LicenseGenerator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public List<? extends CodeGenerator> create(Lookup context) {
    ArrayList<CodeGenerator> toRet = new ArrayList<CodeGenerator>();
    POMModel model = context.lookup(POMModel.class);
    JTextComponent component = context.lookup(JTextComponent.class);
    if (model != null) {
        toRet.add(new LicenseGenerator(model, component));
    }
    return toRet;
}
 
Example #26
Source File: EnablePreviewMavenProj.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public ChangeInfo implement() throws Exception {

    try {

        final FileObject pom = prj.getProjectDirectory().getFileObject("pom.xml"); // NOI18N
        pom.getFileSystem().runAtomicAction(new FileSystem.AtomicAction() {
            @Override
            public void run() throws IOException {
                List<ModelOperation<POMModel>> operations = new ArrayList<ModelOperation<POMModel>>();
                operations.add(new AddMvnCompilerPluginForEnablePreview());
                org.netbeans.modules.maven.model.Utilities.performPOMModelOperations(pom, operations);
            }
        });

    } catch (IOException ex) {
    }
    ProjectConfiguration cfg = prj.getLookup().lookup(ProjectConfigurationProvider.class).getActiveConfiguration();

    for (String action : new String[]{"run", "debug", "profile"}) { // NOI18N

        NetbeansActionMapping mapp = ModelHandle2.getMapping(action, prj, cfg);
        Map<String, String> properties = mapp.getProperties();

        for (Entry<String, String> entry : properties.entrySet()) {
            if (entry.getKey().equals("exec.args")) { // NOI18Nl
                if (!entry.getValue().contains(ENABLE_PREVIEW_FLAG + " ")) {
                    properties.put(entry.getKey(), ENABLE_PREVIEW_FLAG + " " + entry.getValue());
                }
            }
        }
        if (mapp != null) {
            ModelHandle2.putMapping(mapp, prj, cfg);
        }

    }

    return null;
}
 
Example #27
Source File: DependencyNode.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void actionPerformed(ActionEvent event) {
    final Collection<? extends Artifact> artifacts = lkp.lookupAll(Artifact.class);
    if (artifacts.isEmpty()) {
        return;
    }
    Collection<? extends NbMavenProjectImpl> res = lkp.lookupAll(NbMavenProjectImpl.class);
    Set<NbMavenProjectImpl> prjs = new HashSet<NbMavenProjectImpl>(res);
    if (prjs.size() != 1) {
        return;
    }

    final NbMavenProjectImpl project = prjs.iterator().next();
    final List<Artifact> unremoved = new ArrayList<Artifact>();

    final ModelOperation<POMModel> operation = new ModelOperation<POMModel>() {
        @Override
        public void performOperation(POMModel model) {
            for (Artifact art : artifacts) {
                org.netbeans.modules.maven.model.pom.Dependency dep =
                        model.getProject().findDependencyById(art.getGroupId(), art.getArtifactId(), null);
                if (dep != null) {
                    model.getProject().removeDependency(dep);
                } else {
                    unremoved.add(art);
                }
            }
        }
    };
    RP.post(new Runnable() {
        @Override
        public void run() {
            FileObject fo = FileUtil.toFileObject(project.getPOMFile());
            Utilities.performPOMModelOperations(fo, Collections.singletonList(operation));
            if (unremoved.size() > 0) {
                StatusDisplayer.getDefault().setStatusText(NbBundle.getMessage(DependencyNode.class, "MSG_Located_In_Parent", unremoved.size()), Integer.MAX_VALUE);
            }
        }
    });
}
 
Example #28
Source File: ModulesNode.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Messages("MSG_Remove_Module=Do you want to remove the module from the parent POM?")
@Override public void actionPerformed(ActionEvent e) {
    NotifyDescriptor nd = new NotifyDescriptor.Confirmation(MSG_Remove_Module(), NotifyDescriptor.YES_NO_OPTION);
    Object ret = DialogDisplayer.getDefault().notify(nd);
    if (ret == NotifyDescriptor.YES_OPTION) {
        FileObject fo = FileUtil.toFileObject(parent.getPOMFile());
        ModelOperation<POMModel> operation = new ModelOperation<POMModel>() {
            @Override
            public void performOperation(POMModel model) {
                List<String> modules = model.getProject().getModules();
                if (modules != null) {
                    for (String path : modules) {
                        File rel = new File(parent.getPOMFile().getParent(), path);
                        File norm = FileUtil.normalizeFile(rel);
                        FileObject folder = FileUtil.toFileObject(norm);
                        if (folder != null && folder.equals(project.getProjectDirectory())) {
                            model.getProject().removeModule(path);
                            break;
                        }
                    }
                }
            }
        };
        org.netbeans.modules.maven.model.Utilities.performPOMModelOperations(fo, Collections.singletonList(operation));
        //TODO is the manual reload necessary if pom.xml file is being saved?
        NbMavenProject.fireMavenProjectReload(project);
    }
}
 
Example #29
Source File: AddGroovyDependency.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void performOperation(final POMModel model) {
    model.refresh();
    if (ModelUtils.hasModelDependency(model, MavenConstants.GROOVY_GROUP_ID, MavenConstants.GROOVY_ARTIFACT_ID)) {
        return;
    }

    Dependency dependency = model.getFactory().createDependency();
    dependency.setGroupId(MavenConstants.GROOVY_GROUP_ID);
    dependency.setArtifactId(MavenConstants.GROOVY_ARTIFACT_ID);
    dependency.setVersion(MavenConstants.GROOVY_VERSION);

    model.getProject().addDependency(dependency);
}
 
Example #30
Source File: CPExtender.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private boolean addRemoveJAR(File jar, POMModel mdl, String scope, boolean add) throws IOException {
    if (!add) {
        throw new UnsupportedOperationException("removing JARs not yet supported");
    }
    NBVersionInfo dep = null;
    for (NBVersionInfo _dep : RepositoryQueries.findBySHA1Result(jar, RepositoryPreferences.getInstance().getRepositoryInfos()).getResults()) {
        if (!"unknown.binary".equals(_dep.getGroupId())) {
            dep = _dep;
            break;
        }
    }
    if (dep == null) {
        dep = new NBVersionInfo(null, "unknown.binary", jar.getName().replaceFirst("[.]jar$", ""), "SNAPSHOT", null, null, null, null, null);
        addJarToPrivateRepo(jar, mdl, dep);
    }
    //if not found anywhere, add to a custom file:// based repository structure within the project's directory.
    boolean added = false;
    Dependency dependency = ModelUtils.checkModelDependency(mdl, dep.getGroupId(), dep.getArtifactId(), false);
    if (dependency == null) {
        dependency = ModelUtils.checkModelDependency(mdl, dep.getGroupId(), dep.getArtifactId(), true);
        LOG.log(Level.FINE, "added new dep {0} as {1}", new Object[] {jar, dep});
        added = true;
    }
    if (!Utilities.compareObjects(dep.getVersion(), dependency.getVersion())) {
        dependency.setVersion(dep.getVersion());
        LOG.log(Level.FINE, "upgraded version on {0} as {1}", new Object[] {jar, dep});
        added = true;
    }
    if (!Utilities.compareObjects(scope, dependency.getScope())) {
        dependency.setScope(scope);
        LOG.log(Level.FINE, "changed scope on {0} as {1}", new Object[] {jar, dep});
        added = true;
    }
    return added;
}