--- a/ant.freeform/src/org/netbeans/modules/ant/freeform/Actions.java +++ a/ant.freeform/src/org/netbeans/modules/ant/freeform/Actions.java @@ -111,6 +111,7 @@ */ private static final Set COMMON_IDE_GLOBAL_ACTIONS = new HashSet(Arrays.asList( ActionProvider.COMMAND_DEBUG, + ActionProvider.COMMAND_PROFILE, ActionProvider.COMMAND_DELETE, ActionProvider.COMMAND_COPY, ActionProvider.COMMAND_MOVE, @@ -193,7 +194,8 @@ // Check whether the context contains files all in this folder, // matching the pattern if any, and matching the arity (single/multiple). Map selection = findSelection(contextEl, context, project, - command.equals(SingleMethod.COMMAND_RUN_SINGLE_METHOD) || command.equals(SingleMethod.COMMAND_DEBUG_SINGLE_METHOD) ? new AtomicReference() : null); + command.equals(SingleMethod.COMMAND_RUN_SINGLE_METHOD) || + command.equals(SingleMethod.COMMAND_DEBUG_SINGLE_METHOD) ? new AtomicReference() : null); LOG.log(Level.FINE, "detected selection {0} for command {1} in {2}", new Object[] {selection, command, project}); if (selection.size() == 1) { // Definitely enabled. @@ -372,7 +374,8 @@ } Element contextEl = XMLUtil.findElement(actionEl, "context", FreeformProjectType.NS_GENERAL); // NOI18N if (contextEl != null) { - AtomicReference methodName = SingleMethod.COMMAND_RUN_SINGLE_METHOD.equals(command) || SingleMethod.COMMAND_DEBUG_SINGLE_METHOD.equals(command) ? + AtomicReference methodName = SingleMethod.COMMAND_RUN_SINGLE_METHOD.equals(command) || + SingleMethod.COMMAND_DEBUG_SINGLE_METHOD.equals(command) ? new AtomicReference() : null; Map selection = findSelection(contextEl, context, project, methodName); if (selection.isEmpty()) { --- a/ant.freeform/src/org/netbeans/modules/ant/freeform/Bundle.properties +++ a/ant.freeform/src/org/netbeans/modules/ant/freeform/Bundle.properties @@ -62,6 +62,7 @@ CMD_run=Run CMD_test=Test CMD_debug=Debug +CMD_profile=Profile CMD_javadoc=Generate Javadoc CMD_redeploy=Redeploy CMD_deploy=Deploy --- a/ant.freeform/src/org/netbeans/modules/ant/freeform/resources/layer.xml +++ a/ant.freeform/src/org/netbeans/modules/ant/freeform/resources/layer.xml @@ -74,10 +74,6 @@ - - - - --- a/apisupport.ant/src/org/netbeans/modules/apisupport/project/resources/layer.xml +++ a/apisupport.ant/src/org/netbeans/modules/apisupport/project/resources/layer.xml @@ -160,10 +160,6 @@ - - - - --- a/apisupport.ant/src/org/netbeans/modules/apisupport/project/ui/ModuleActions.java +++ a/apisupport.ant/src/org/netbeans/modules/apisupport/project/ui/ModuleActions.java @@ -46,16 +46,8 @@ import java.io.File; import java.io.IOException; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.Map; +import java.util.*; import java.util.Map.Entry; -import java.util.Properties; -import java.util.Set; import java.util.regex.Pattern; import javax.lang.model.element.TypeElement; import javax.swing.Action; @@ -116,7 +108,8 @@ static final Set bkgActions = new HashSet(Arrays.asList( COMMAND_RUN_SINGLE, - COMMAND_DEBUG_SINGLE + COMMAND_DEBUG_SINGLE, + COMMAND_PROFILE_SINGLE )); private static final String COMMAND_NBM = "nbm"; @@ -162,7 +155,7 @@ } globalCommands.put(ActionProvider.COMMAND_RUN, new String[] {"run"}); // NOI18N globalCommands.put(ActionProvider.COMMAND_DEBUG, new String[] {"debug"}); // NOI18N - globalCommands.put("profile", new String[] {"profile"}); // NOI18N + globalCommands.put(ActionProvider.COMMAND_PROFILE, new String[] {"profile"}); // NOI18N globalCommands.put(JavaProjectConstants.COMMAND_JAVADOC, new String[] {"javadoc-nb"}); // NOI18N globalCommands.put(ActionProvider.COMMAND_TEST, new String[] {"test-unit"}); // NOI18N globalCommands.put(COMMAND_NBM, new String[] {COMMAND_NBM}); @@ -172,8 +165,10 @@ if (!project.supportedTestTypes().isEmpty()) { supportedActionsSet.add(ActionProvider.COMMAND_TEST_SINGLE); supportedActionsSet.add(ActionProvider.COMMAND_DEBUG_TEST_SINGLE); + supportedActionsSet.add(ActionProvider.COMMAND_PROFILE_TEST_SINGLE); supportedActionsSet.add(ActionProvider.COMMAND_RUN_SINGLE); supportedActionsSet.add(ActionProvider.COMMAND_DEBUG_SINGLE); + supportedActionsSet.add(ActionProvider.COMMAND_PROFILE_SINGLE); supportedActionsSet.add(SingleMethod.COMMAND_RUN_SINGLE_METHOD); supportedActionsSet.add(SingleMethod.COMMAND_DEBUG_SINGLE_METHOD); } @@ -212,12 +207,22 @@ if (testSources == null) testSources = findTestSources(context, false); return testSources != null && testSources.isSingle(); + } else if (command.equals(COMMAND_PROFILE_TEST_SINGLE)) { + TestSources testSources = findTestSourcesForSources(context); + if (testSources == null) + testSources = findTestSources(context, false); + return testSources != null && testSources.isSingle(); } else if (command.equals(COMMAND_RUN_SINGLE)) { return findTestSources(context, false) != null; } else if (command.equals(COMMAND_DEBUG_SINGLE)) { TestSources testSources = findTestSources(context, false); return testSources != null && testSources.isSingle(); - } else if (command.equals(SingleMethod.COMMAND_RUN_SINGLE_METHOD) || command.equals(SingleMethod.COMMAND_DEBUG_SINGLE_METHOD)) { + } else if (command.equals(COMMAND_PROFILE_SINGLE)) { + TestSources testSources = findTestSources(context, false); + return testSources != null && testSources.isSingle(); + } else if (command.equals(SingleMethod.COMMAND_RUN_SINGLE_METHOD) || + command.equals(SingleMethod.COMMAND_DEBUG_SINGLE_METHOD) + ) { NbPlatform plaf = project.getPlatform(false); if (plaf == null || plaf.getHarnessVersion().compareTo(HarnessVersion.V70) < 0) { return false; @@ -396,6 +401,13 @@ } targetNames = setupDebugTestSingle(p, testSources); + } else if (command.equals(COMMAND_PROFILE_TEST_SINGLE)) { + TestSources testSources = findTestSourcesForSources(context); + if (testSources == null) { + testSources = findTestSources(context, false); + + } + targetNames = setupProfileTestSingle(p, testSources); } else if (command.equals(COMMAND_RUN_SINGLE)) { TestSources testSources = findTestSources(context, false); // TODO CoS String enableQuickTest = project.evaluator().getProperty("quick.test.single"); // NOI18N @@ -422,6 +434,15 @@ // fallback to "old" debug tests behavior targetNames = setupDebugTestSingle(p, testSources); } + } else if (command.equals(COMMAND_PROFILE_SINGLE)) { + TestSources testSources = findTestSources(context, false); + String clazz = getMainClass(context); + if (clazz != null) { + targetNames = setupProfileMain(p, testSources, context, clazz); + } else { + // fallback to "old" debug tests behavior + targetNames = setupProfileTestSingle(p, testSources); + } } else if (command.equals(SingleMethod.COMMAND_RUN_SINGLE_METHOD)) { TestSources testSources = findTestMethodSources(context); p.setProperty("test.class", testClassName(testSources)); // NOI18N @@ -461,7 +482,6 @@ return; } else { // XXX consider passing PM.fP(FU.toFO(SuiteUtils.suiteDirectory(project))) instead for a suite component project: - setRunArgsIde(project, SingleModuleProperties.getInstance(project), command, p, project.getTestUserDirLockFile()); if (command.equals(ActionProvider.COMMAND_REBUILD)) { p.setProperty("do.not.clean.module.config.xml", "true"); // #196192 } @@ -472,6 +492,7 @@ } } try { + setRunArgsIde(project, SingleModuleProperties.getInstance(project), command, p, project.getTestUserDirLockFile()); ActionUtils.runTarget(findBuildXml(project), targetNames, p); } catch (IOException e) { Util.err.notify(e); @@ -483,6 +504,12 @@ } else runnable.run(); } + + private String[] setupProfileTestSingle(Properties p, TestSources testSources) { + p.setProperty("test.includes", testSources.includes().replace("**", "**/*Test.java")); // NOI18N + p.setProperty("test.type", testSources.testType); // NOI18N + return new String[] {"profile-test-single-nb"}; // NOI18N + } static void setRunArgsIde(Project project, ModuleProperties modprops, String command, Properties p, File testUserDirLockFile) { StringBuilder runArgsIde = new StringBuilder(); @@ -491,27 +518,35 @@ mode = StartupExtender.StartMode.NORMAL; } else if (command.equals(COMMAND_DEBUG) || command.equals(COMMAND_DEBUG_SINGLE) || command.equals(COMMAND_DEBUG_STEP_INTO)) { mode = StartupExtender.StartMode.DEBUG; - } else if (command.equals("profile")) { + } else if (command.equals(COMMAND_PROFILE) || command.equals(COMMAND_PROFILE_SINGLE) || command.equals("profile-osgi")) { mode = StartupExtender.StartMode.PROFILE; } else if (command.equals(COMMAND_TEST) || command.equals(COMMAND_TEST_SINGLE)) { mode = StartupExtender.StartMode.TEST_NORMAL; } else if (command.equals(COMMAND_DEBUG_TEST_SINGLE)) { mode = StartupExtender.StartMode.TEST_DEBUG; - } else if (command.equals("profile-test-single-nb")) { + } else if (command.equals(COMMAND_PROFILE_TEST_SINGLE)) { mode = StartupExtender.StartMode.TEST_PROFILE; } else { mode = null; } + + boolean isTest = (EnumSet.of( + StartupExtender.StartMode.TEST_PROFILE, + StartupExtender.StartMode.TEST_NORMAL, + StartupExtender.StartMode.TEST_DEBUG).contains(mode) || + command.equals(COMMAND_PROFILE_SINGLE)); if (mode != null) { JavaPlatform plaf = modprops.getJavaPlatform(); Lookup context = Lookups.fixed(project, plaf != null ? plaf : JavaPlatformManager.getDefault().getDefaultPlatform()); for (StartupExtender group : StartupExtender.getExtenders(context, mode)) { for (String arg : group.getArguments()) { - runArgsIde.append("-J").append(arg).append(' '); + runArgsIde.append(isTest ? "" : "-J").append(arg).append(' '); } } } - if ((command.equals(ActionProvider.COMMAND_RUN) || command.equals(ActionProvider.COMMAND_DEBUG)) // #63652 + if ((command.equals(ActionProvider.COMMAND_RUN) || + command.equals(ActionProvider.COMMAND_DEBUG) || + command.equals(ActionProvider.COMMAND_PROFILE)) // #63652 && testUserDirLockFile.isFile()) { // #141069: lock file exists, run with bogus option runArgsIde.append(TEST_USERDIR_LOCK_PROP_VALUE); @@ -606,6 +641,12 @@ return new String[] {"debug-test-main-nb"}; // NOI18N } + private String[] setupProfileMain(Properties p, TestSources testSources, Lookup context, String mainClass) { + p.setProperty("main.class", mainClass); // NOI18N + p.setProperty("test.type", testSources.testType); // NOI18N + return new String[] {"profile-test-main-nb"}; // NOI18N + } + private String testClassName(TestSources testSources) { String path = testSources.includes(); assert path.endsWith(".java") && !path.contains(",") : path; @@ -622,12 +663,18 @@ private boolean bypassAntBuildScript(String command, FileObject[] files) throws IllegalArgumentException { FileObject toRun = null; - if (COMMAND_RUN_SINGLE.equals(command) || COMMAND_DEBUG_SINGLE.equals(command)) { + if (COMMAND_RUN_SINGLE.equals(command) || + COMMAND_DEBUG_SINGLE.equals(command) || + COMMAND_PROFILE_SINGLE.equals(command)) { toRun = files[0]; } if (toRun != null) { - String commandToExecute = COMMAND_RUN_SINGLE.equals(command) ? JavaRunner.QUICK_TEST : JavaRunner.QUICK_TEST_DEBUG; + String commandToExecute = COMMAND_RUN_SINGLE.equals(command) ? + JavaRunner.QUICK_TEST : + (COMMAND_DEBUG_SINGLE.equals(command) ? + JavaRunner.QUICK_TEST_DEBUG : + JavaRunner.QUICK_TEST_PROFILE); if (!JavaRunner.isSupported(commandToExecute, Collections.singletonMap(JavaRunner.PROP_EXECUTE_FILE, toRun))) { return false; } --- a/apisupport.ant/src/org/netbeans/modules/apisupport/project/ui/SuiteActions.java +++ a/apisupport.ant/src/org/netbeans/modules/apisupport/project/ui/SuiteActions.java @@ -109,7 +109,6 @@ private static final String COMMAND_DEBUG_JNLP = "debug-jnlp"; private static final String COMMAND_DEBUG_OSGI = "debug-osgi"; private static final String COMMAND_NBMS = "nbms"; - private static final String COMMAND_PROFILE = "profile"; private static final String COMMAND_PROFILE_OSGI = "profile-osgi"; private static final String COMMAND_RUN_JNLP = "run-jnlp"; private static final String COMMAND_RUN_OSGI = "run-osgi"; @@ -242,13 +241,13 @@ return ProjectSensitiveActions.projectCommandAction(COMMAND_DEBUG_OSGI, SUITE_ACTION_debug_osgi(), null); } - @ActionID(category="Project", id="org.netbeans.modules.apisupport.project.suite.profileOsgi") - @ActionRegistration(displayName="#SUITE_ACTION_profile_osgi", lazy=false) - @ActionReference(path=SUITE_OSGI_ACTIONS_PATH, position=500) - @Messages("SUITE_ACTION_profile_osgi=Profile in Felix") - public static Action profileOsgi() { - return ProjectSensitiveActions.projectCommandAction(COMMAND_PROFILE_OSGI, SUITE_ACTION_profile_osgi(), null); - } +// @ActionID(category="Project", id="org.netbeans.modules.apisupport.project.suite.profileOsgi") +// @ActionRegistration(displayName="#SUITE_ACTION_profile_osgi", lazy=false) +// @ActionReference(path=SUITE_OSGI_ACTIONS_PATH, position=500) +// @Messages("SUITE_ACTION_profile_osgi=Profile in Felix") +// public static Action profileOsgi() { +// return ProjectSensitiveActions.projectCommandAction(COMMAND_PROFILE_OSGI, SUITE_ACTION_profile_osgi(), null); +// } @ActionID(category="Project", id="org.netbeans.modules.apisupport.project.suite.branding") @ActionRegistration(displayName="#SUITE_ACTION_branding", lazy=false) --- a/apisupport.harness/release/jnlp.xml +++ a/apisupport.harness/release/jnlp.xml @@ -434,6 +434,20 @@ + + + + + + + + + + + + + + --- a/apisupport.harness/release/osgi.xml +++ a/apisupport.harness/release/osgi.xml @@ -159,8 +159,26 @@ - - + + + + + + + + + + + + + + + + + + + + This target only works when run from inside the NetBeans IDE. @@ -184,5 +202,4 @@ - --- a/apisupport.harness/release/run.xml +++ a/apisupport.harness/release/run.xml @@ -228,7 +228,23 @@ - + + + + + + + + + + + + + + + + + This target only works when run from inside the NetBeans IDE. - --- a/j2ee.ant/antsrc/org/netbeans/modules/j2ee/ant/Deploy.java +++ a/j2ee.ant/antsrc/org/netbeans/modules/j2ee/ant/Deploy.java @@ -65,6 +65,11 @@ */ private boolean debugmode = false; + /** + * Holds value of property profilemode. + */ + private boolean profilemode = false; + private boolean forceRedeploy = false; /** @@ -104,7 +109,7 @@ try { String clientUrl = Deployment.getDefault ().deploy (jmp, - debugmode ? Deployment.Mode.DEBUG : Deployment.Mode.RUN, + debugmode ? Deployment.Mode.DEBUG : (profilemode ? Deployment.Mode.PROFILE : Deployment.Mode.RUN), clientModuleUri, clientUrlPart, forceRedeploy, this); if (clientUrl != null) { getProject().setProperty("client.url", clientUrl); @@ -149,12 +154,28 @@ } /** + * Getter for property profilemode. + * @return Value of property profilemode. + */ + public boolean getProfilemode() { + return this.profilemode; + } + + /** * Setter for property debugmode. * @param debugmode New value of property debugmode. */ public void setDebugmode(boolean debugmode) { this.debugmode = debugmode; } + + /** + * Setter for property profilemode. + * @param debugmode New value of property profilemode. + */ + public void setProfilemode(boolean profilemode) { + this.profilemode = profilemode; + } public boolean getForceRedeploy() { return this.forceRedeploy; --- a/j2ee.ant/antsrc/org/netbeans/modules/j2ee/ant/StartProfiledServer.java +++ a/j2ee.ant/antsrc/org/netbeans/modules/j2ee/ant/StartProfiledServer.java @@ -109,11 +109,11 @@ String msg = NbBundle.getMessage(StartProfiledServer.class, "MSG_StartupFailed"); throw new BuildException(msg); } - log(NbBundle.getMessage(StartProfiledServer.class, "MSG_AttachingProfiler")); - if (!profiler.attachProfiler(getProject().getProperties())) { - String msg = NbBundle.getMessage(StartProfiledServer.class, "MSG_AttachFailed"); - throw new BuildException(msg); - } +// log(NbBundle.getMessage(StartProfiledServer.class, "MSG_AttachingProfiler")); +// if (!profiler.attachProfiler(getProject().getProperties())) { +// String msg = NbBundle.getMessage(StartProfiledServer.class, "MSG_AttachFailed"); +// throw new BuildException(msg); +// } log(NbBundle.getMessage(StartProfiledServer.class, "MSG_ProfilerAttached")); // wait for the server to finish its startup long timeout = System.currentTimeMillis() + startupTimeout; --- a/j2ee.ant/antsrc/org/netbeans/modules/j2ee/ant/StartServer.java +++ a/j2ee.ant/antsrc/org/netbeans/modules/j2ee/ant/StartServer.java @@ -69,6 +69,11 @@ */ private boolean debugmode = false; + /** + * Holds value of property profilemode. + */ + private boolean profilemode = false; + public void execute() throws BuildException { ClassLoader originalLoader = null; @@ -107,6 +112,8 @@ try { if (debugmode) { si.startDebug(ui); + } else if (profilemode) { + si.startProfile(false, ui); } else { si.start(ui); } @@ -156,6 +163,14 @@ public boolean getDebugmode() { return this.debugmode; } + + /** + * Getter for property profilemode. + * @return Value of property profilemode. + */ + public boolean getProfilemode() { + return this.profilemode; + } /** * Setter for property debugmode. @@ -164,4 +179,12 @@ public void setDebugmode(boolean debugmode) { this.debugmode = debugmode; } + + /** + * Setter for property profilemode. + * @param profilemode New value of property profilemode. + */ + public void setProfilemode(boolean profilemode) { + this.profilemode = profilemode; + } } --- a/j2ee.earproject/nbproject/project.xml +++ a/j2ee.earproject/nbproject/project.xml @@ -112,6 +112,15 @@ + org.netbeans.modules.extexecution + + + + 2 + 1.30 + + + org.netbeans.modules.j2ee.api.ejbmodule --- a/j2ee.earproject/src/org/netbeans/modules/j2ee/earproject/EarActionProvider.java +++ a/j2ee.earproject/src/org/netbeans/modules/j2ee/earproject/EarActionProvider.java @@ -45,8 +45,11 @@ package org.netbeans.modules.j2ee.earproject; import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; import java.util.Iterator; +import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; @@ -54,7 +57,9 @@ import org.netbeans.api.debugger.DebuggerManager; import org.netbeans.api.debugger.Session; import org.netbeans.api.debugger.jpda.AttachingDICookie; -import org.netbeans.api.j2ee.core.Profile; +import org.netbeans.api.extexecution.startup.StartupExtender; +import org.netbeans.api.java.platform.JavaPlatform; +import org.netbeans.api.java.platform.JavaPlatformManager; import org.netbeans.api.project.Project; import org.netbeans.modules.j2ee.api.ejbjar.EjbProjectConstants; import org.netbeans.modules.j2ee.common.project.ui.DeployOnSaveUtils; @@ -68,6 +73,7 @@ import org.netbeans.modules.j2ee.earproject.ui.customizer.CustomizerProviderImpl; import org.netbeans.modules.j2ee.earproject.ui.customizer.EarProjectProperties; import org.netbeans.modules.java.api.common.ant.UpdateHelper; +import org.netbeans.modules.java.api.common.util.CommonProjectUtils; import org.netbeans.modules.web.api.webmodule.WebModule; import org.netbeans.modules.web.spi.webmodule.WebModuleProvider; import org.netbeans.spi.project.ActionProvider; @@ -82,6 +88,7 @@ import org.openide.util.NbBundle; import org.openide.util.Task; import org.openide.util.TaskListener; +import org.openide.util.lookup.Lookups; /** * Action provider of the Enterprise Application project. @@ -101,6 +108,7 @@ COMMAND_REBUILD, COMMAND_RUN, COMMAND_DEBUG, + COMMAND_PROFILE, EjbProjectConstants.COMMAND_REDEPLOY, COMMAND_VERIFY, COMMAND_DELETE, @@ -124,6 +132,7 @@ commands.put(COMMAND_REBUILD, new String[] {"clean", "dist"}); // NOI18N commands.put(COMMAND_RUN, new String[] {"run"}); // NOI18N commands.put(COMMAND_DEBUG, new String[] {"debug"}); // NOI18N + commands.put(COMMAND_PROFILE, new String[]{"profile"}); // NOI18N commands.put(EjbProjectConstants.COMMAND_REDEPLOY, new String[] {"run-deploy"}); // NOI18N commands.put(COMMAND_DEBUG, new String[] {"debug"}); // NOI18N commands.put(COMMAND_COMPILE, new String[] {"compile"}); // NOI18N @@ -281,12 +290,52 @@ } p.setProperty("ear.docbase.dirs", edbd.toString()); // NOI18N } + // PROFILING PART + } else if (command.equals (COMMAND_PROFILE)) { + // TODO This is basically a copy of the debugging part for now. Figure out what to do here! + + if (!isSelectedServer ()) { + // no selected server => warning + String msg = NbBundle.getMessage( + EarActionProvider.class, "MSG_No_Server_Selected"); // NOI18N + DialogDisplayer.getDefault().notify( + new NotifyDescriptor.Message(msg, NotifyDescriptor.WARNING_MESSAGE)); + return null; + } + setDirectoryDeploymentProperty(p); +// +// if (isDebugged()) { +// p.setProperty("is.debugged", "true"); // NOI18N +// } + + SubprojectProvider spp = project.getLookup().lookup(SubprojectProvider.class); + if (null != spp) { + StringBuilder edbd = new StringBuilder(); + final Set s = spp.getSubprojects(); + Iterator iter = s.iterator(); + while (iter.hasNext()) { + Project proj = (Project) iter.next(); + WebModuleProvider wmp = proj.getLookup().lookup(WebModuleProvider.class); + if (null != wmp) { + WebModule wm = wmp.findWebModule(proj.getProjectDirectory()); + if (null != wm) { + FileObject fo = wm.getDocumentBase(); + if (null != fo) { + edbd.append(FileUtil.toFile(fo).getAbsolutePath()+":"); //NOI18N + } + } + } + } + p.setProperty("ear.docbase.dirs", edbd.toString()); // NOI18N + } //COMPILATION PART } else { if (targetNames == null) { throw new IllegalArgumentException(command); } } + + collectStartupExtenderArgs(p, command); return targetNames; } @@ -402,4 +451,43 @@ private boolean isCosEnabled() { return Boolean.parseBoolean(project.evaluator().getProperty(EarProjectProperties.J2EE_COMPILE_ON_SAVE)); } + + private void collectStartupExtenderArgs(Map p, String command) { + StringBuilder b = new StringBuilder(); + for (String arg : runJvmargsIde(command)) { + b.append(' ').append(arg); + } + if (b.length() > 0) { + p.put("run.jvmargs.ide", b.toString()); // NOI18N + } + } + + private List runJvmargsIde(String command) { + StartupExtender.StartMode mode; + if (command.equals(COMMAND_RUN) || command.equals(COMMAND_RUN_SINGLE)) { + mode = StartupExtender.StartMode.NORMAL; + } else if (command.equals(COMMAND_DEBUG) || command.equals(COMMAND_DEBUG_SINGLE) || command.equals(COMMAND_DEBUG_STEP_INTO)) { + mode = StartupExtender.StartMode.DEBUG; + } else if (command.equals(COMMAND_PROFILE) || command.equals(COMMAND_PROFILE_SINGLE)) { + mode = StartupExtender.StartMode.PROFILE; + } else if (command.equals(COMMAND_TEST) || command.equals(COMMAND_TEST_SINGLE)) { + mode = StartupExtender.StartMode.TEST_NORMAL; + } else if (command.equals(COMMAND_DEBUG_TEST_SINGLE)) { + mode = StartupExtender.StartMode.TEST_DEBUG; + } else if (command.equals(COMMAND_PROFILE_TEST_SINGLE)) { + mode = StartupExtender.StartMode.TEST_PROFILE; + } else { + return Collections.emptyList(); + } + List args = new ArrayList(); + JavaPlatform p = getActivePlatform(); + for (StartupExtender group : StartupExtender.getExtenders(Lookups.fixed(project, p != null ? p : JavaPlatformManager.getDefault().getDefaultPlatform()), mode)) { + args.addAll(group.getArguments()); + } + return args; + } + + private JavaPlatform getActivePlatform() { + return CommonProjectUtils.getActivePlatform(project.evaluator().getProperty("platform.active")); + } } --- a/j2ee.earproject/src/org/netbeans/modules/j2ee/earproject/resources/build-impl.xsl +++ a/j2ee.earproject/src/org/netbeans/modules/j2ee/earproject/resources/build-impl.xsl @@ -305,24 +305,35 @@ - - + + + pre NB7.2 profiling section; consider it deprecated + + + profiler.info.jvmargs.agent + Empty placeholder for easier customization. You can override this target in the ../build.xml file. + profiler.info.jvmargs.agent Empty placeholder for easier customization. You can override this target in the ../build.xml file. + profiler.info.jvmargs.agent -profile-pre-init, init, -profile-post-init Must set JVM to use for profiling in profiler.info.jvm Must set profiler agent JVM arguments in profiler.info.jvmargs.agent + profiler.info.jvmargs.agent - + + end of pre NB7.2 profiling section + + pre-init,init-private,init-userdir,init-user,init-project,do-init,post-init,init-check,-init-taskdefs @@ -848,7 +859,11 @@ ================= - + + pre NB7.2 profiling section; consider it deprecated + + + profiler.info.jvmargs.agent Profile a J2EE project in the IDE. profiler.startserver.target @@ -865,7 +880,7 @@ run - start-loadgen + -profile-start-loadgen @@ -899,12 +914,36 @@ + + end of pre NB7.2 profiling section + - - - ${profiler.loadgen.path} - - + + + + + + + + + + + Profile a J2EE project in the IDE. + + + + + + + -profile-start-loadgen + + + + + + ${profiler.loadgen.path} + + CLEANUP SECTION --- a/j2ee.earproject/src/org/netbeans/modules/j2ee/earproject/ui/resources/layer.xml +++ a/j2ee.earproject/src/org/netbeans/modules/j2ee/earproject/ui/resources/layer.xml @@ -174,8 +174,8 @@ - - + + --- a/j2ee.ejbjarproject/src/org/netbeans/modules/j2ee/ejbjarproject/EjbJarActionProvider.java +++ a/j2ee.ejbjarproject/src/org/netbeans/modules/j2ee/ejbjarproject/EjbJarActionProvider.java @@ -48,7 +48,6 @@ import org.netbeans.api.debugger.DebuggerManager; import org.netbeans.api.debugger.Session; import org.netbeans.api.debugger.jpda.AttachingDICookie; -import org.netbeans.api.j2ee.core.Profile; import org.netbeans.api.java.classpath.ClassPath; import org.netbeans.api.java.project.JavaProjectConstants; import org.netbeans.api.java.project.runner.JavaRunner; @@ -95,11 +94,14 @@ COMMAND_RUN_SINGLE, COMMAND_DEBUG, COMMAND_DEBUG_SINGLE, + COMMAND_PROFILE, + COMMAND_PROFILE_SINGLE, EjbProjectConstants.COMMAND_REDEPLOY, JavaProjectConstants.COMMAND_JAVADOC, COMMAND_TEST, COMMAND_TEST_SINGLE, COMMAND_DEBUG_TEST_SINGLE, + COMMAND_PROFILE_TEST_SINGLE, SingleMethod.COMMAND_RUN_SINGLE_METHOD, SingleMethod.COMMAND_DEBUG_SINGLE_METHOD, JavaProjectConstants.COMMAND_DEBUG_FIX, @@ -116,12 +118,14 @@ COMMAND_COMPILE_SINGLE, COMMAND_RUN_SINGLE, COMMAND_DEBUG_SINGLE, + COMMAND_PROFILE_SINGLE, JavaProjectConstants.COMMAND_JAVADOC, COMMAND_TEST, COMMAND_TEST_SINGLE, COMMAND_DEBUG_TEST_SINGLE, + COMMAND_PROFILE_TEST_SINGLE, SingleMethod.COMMAND_RUN_SINGLE_METHOD, - SingleMethod.COMMAND_DEBUG_SINGLE_METHOD, + SingleMethod.COMMAND_DEBUG_SINGLE_METHOD }; private final EjbJarProject project; @@ -153,6 +157,7 @@ commands.put(COMMAND_RUN_SINGLE, new String[] {"run-main"}); // NOI18N commands.put(EjbProjectConstants.COMMAND_REDEPLOY, new String[] {"run"}); // NOI18N commands.put(COMMAND_DEBUG, new String[] {"debug"}); // NOI18N + commands.put(COMMAND_PROFILE, new String[]{"profile"}); // NOI18N commands.put(JavaProjectConstants.COMMAND_JAVADOC, new String[] {"javadoc"}); // NOI18N commands.put(COMMAND_TEST, new String[] {"test"}); // NOI18N commands.put(COMMAND_TEST_SINGLE, new String[] {"test-single"}); // NOI18N @@ -160,6 +165,7 @@ commands.put(JavaProjectConstants.COMMAND_DEBUG_FIX, new String[] {"debug-fix"}); // NOI18N commands.put(COMMAND_VERIFY, new String[] {"verify"}); // NOI18N commands.put(COMMAND_DEBUG_SINGLE, new String[] {"debug-single"}); // NOI18N + commands.put(COMMAND_PROFILE_SINGLE, new String[]{"profile-single"}); // NOI18N this.bkgScanSensitiveActions = new HashSet(Arrays.asList( COMMAND_RUN_SINGLE )); @@ -209,7 +215,8 @@ protected void updateJavaRunnerClasspath(String command, Map execProperties) { if (COMMAND_TEST_SINGLE.equals(command) || COMMAND_DEBUG_TEST_SINGLE.equals(command) || SingleMethod.COMMAND_DEBUG_SINGLE_METHOD.equals(command) || SingleMethod.COMMAND_RUN_SINGLE_METHOD.equals(command) || - COMMAND_RUN_SINGLE.equals(command) || COMMAND_DEBUG_SINGLE.equals(command)) { + COMMAND_RUN_SINGLE.equals(command) || COMMAND_DEBUG_SINGLE.equals(command) || + COMMAND_PROFILE_SINGLE.equals(command) || COMMAND_PROFILE_TEST_SINGLE.equals(command)) { FileObject fo = (FileObject)execProperties.get(JavaRunner.PROP_EXECUTE_FILE); ClassPath cp = getCallback().findClassPath(fo, ClassPath.EXECUTE); ClassPath cp2 = ClassPathFactory.createClassPath( @@ -243,7 +250,9 @@ if (command.equals(COMMAND_RUN_SINGLE) ||command.equals(COMMAND_RUN) || command.equals(EjbProjectConstants.COMMAND_REDEPLOY) ||command.equals(COMMAND_DEBUG) || command.equals(COMMAND_DEBUG_SINGLE) || command.equals(JavaProjectConstants.COMMAND_DEBUG_FIX) || - command.equals( COMMAND_TEST_SINGLE) || command.equals(COMMAND_DEBUG_TEST_SINGLE)) { + command.equals( COMMAND_TEST_SINGLE) || command.equals(COMMAND_DEBUG_TEST_SINGLE) || + command.equals(COMMAND_PROFILE) || command.equals(COMMAND_PROFILE_SINGLE) || + command.equals(COMMAND_PROFILE_TEST_SINGLE)) { setDirectoryDeploymentProperty(p); } if (command.equals(COMMAND_RUN) || command.equals(EjbProjectConstants.COMMAND_REDEPLOY)) { --- a/j2ee.ejbjarproject/src/org/netbeans/modules/j2ee/ejbjarproject/resources/build-impl.xsl +++ a/j2ee.ejbjarproject/src/org/netbeans/modules/j2ee/ejbjarproject/resources/build-impl.xsl @@ -663,6 +663,7 @@ + @@ -858,24 +859,34 @@ - - + + + pre NB7.2 profiling section; consider it deprecated + + + profiler.info.jvmargs.agent + Empty placeholder for easier customization. You can override this target in the ../build.xml file. + profiler.info.jvmargs.agent Empty placeholder for easier customization. You can override this target in the ../build.xml file. + profiler.info.jvmargs.agent -profile-pre-init, init, -profile-post-init Must set JVM to use for profiling in profiler.info.jvm Must set profiler agent JVM arguments in profiler.info.jvmargs.agent + profiler.info.jvmargs.agent - + + end of pre NB7.2 profiling section + -pre-init,-init-private,-init-userdir,-init-user,-init-project,-do-init,-post-init,-init-check,-init-macrodef-property,-init-macrodef-javac,-init-macrodef-junit,-init-macrodef-java,-init-macrodef-nbjpda,-init-macrodef-debug,-init-taskdefs,-init-ap-cmdline @@ -1430,8 +1441,13 @@ ================= - + + pre NB7.2 profiling section; consider it deprecated + + + profiler.info.jvmargs.agent Profile a J2EE project in the IDE. + This target only works when run from inside the NetBeans IDE. profiler.startserver.target start-profiled-server-extraargs @@ -1447,9 +1463,38 @@ run - start-loadgen + -profile-start-loadgen + + + profiler.info.jvmargs.agent + profile-init,compile-test-single + This target only works when run from inside the NetBeans IDE. + + + + + + + + + + + + + + + + + + + + + + + + @@ -1481,11 +1526,42 @@ + + end of pre NB7.2 profiling section + - - - ${profiler.loadgen.path} - + + + + + + + + + + + Profile a J2EE project in the IDE. + + + + + + + -profile-start-loadgen + + + + + + + + + + + + + ${profiler.loadgen.path} + @@ -1760,41 +1836,6 @@ init,-pre-debug-fix,-do-debug-fix-test - - ========================= - TESTS PROFILING SECTION - ========================= - - - - netbeans.home - profile-init,compile-test-single - - - - - - - - - - - - - - - - - - - - - - - - - - CLEANUP SECTION --- a/j2ee.ejbjarproject/src/org/netbeans/modules/j2ee/ejbjarproject/ui/resources/layer.xml +++ a/j2ee.ejbjarproject/src/org/netbeans/modules/j2ee/ejbjarproject/ui/resources/layer.xml @@ -168,8 +168,8 @@ - - + + --- a/j2eeserver/src/org/netbeans/modules/j2ee/deployment/impl/ServerInstance.java +++ a/j2eeserver/src/org/netbeans/modules/j2ee/deployment/impl/ServerInstance.java @@ -67,6 +67,10 @@ import org.netbeans.modules.j2ee.deployment.devmodules.spi.ArtifactListener.Artifact; import org.netbeans.modules.j2ee.deployment.plugins.spi.JDBCDriverDeployer; import java.util.*; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.logging.Level; import java.util.logging.Logger; @@ -373,22 +377,8 @@ int oldState = getServerState(); setServerState(STATE_WAITING); if (ServerInstance.this == profiledServerInstance) { - int profState = ProfilerSupport.getState(); - if (profState == ProfilerSupport.STATE_STARTING) { - setServerState(ServerInstance.STATE_PROFILER_STARTING); - return; - } else if (profState == ProfilerSupport.STATE_BLOCKING) { - setServerState(ServerInstance.STATE_PROFILER_BLOCKING); - return; - } else if (profState == ProfilerSupport.STATE_PROFILING - || profState == ProfilerSupport.STATE_RUNNING) { - initCoTarget(); - setServerState(ServerInstance.STATE_PROFILING); - return; - } else { - // profiler is inactive - has been shutdown - profiledServerInstance = null; - } + updateStateFromProfiler(); + return; } if (isSuspended()) { setServerState(ServerInstance.STATE_SUSPENDED); @@ -1513,11 +1503,35 @@ profiledServerInstance = null; } - Profiler profiler = ServerRegistry.getProfiler(); + final Profiler profiler = ServerRegistry.getProfiler(); if (profiler == null) { // this should not occur, but better make sure throw new ServerException(NbBundle.getMessage(ServerInstance.class, "MSG_ProfilerNotRegistered")); } + + final ScheduledExecutorService statusUpdater = Executors.newSingleThreadScheduledExecutor(); + statusUpdater.scheduleAtFixedRate(new Runnable() { + + @Override + public void run() { + updateStateFromProfiler(); + } + }, 50, 100, TimeUnit.MILLISECONDS); + + final StateListener l = new StateListener() { + + @Override + public void stateChanged(int oldState, int newState) { + if (oldState != newState && newState == STATE_STOPPED) { + ServerInstance.this.removeStateListener(this); + statusUpdater.shutdownNow(); + profiledServerInstance = null; + } + } + }; + + this.addStateListener(l); + profiler.notifyStarting(); ProgressObject po = getStartServer().startProfiling(target); try { @@ -1995,4 +2009,19 @@ } } } + + private void updateStateFromProfiler() { + int profState = ProfilerSupport.getState(); + if (profState == ProfilerSupport.STATE_STARTING) { + setServerState(ServerInstance.STATE_PROFILER_STARTING); + } else if (profState == ProfilerSupport.STATE_BLOCKING) { + setServerState(ServerInstance.STATE_PROFILER_BLOCKING); + } else if (profState == ProfilerSupport.STATE_PROFILING + || profState == ProfilerSupport.STATE_RUNNING) { + initCoTarget(); + setServerState(ServerInstance.STATE_PROFILING); + } else { + setServerState(ServerInstance.STATE_STOPPED); + } + } } --- a/java.api.common/src/org/netbeans/modules/java/api/common/project/BaseActionProvider.java +++ a/java.api.common/src/org/netbeans/modules/java/api/common/project/BaseActionProvider.java @@ -456,7 +456,7 @@ } } - if (targetNames.length == 1 && ("run-applet".equals(targetNames[0]) || "debug-applet".equals(targetNames[0]))) { + if (targetNames.length == 1 && (JavaRunner.QUICK_RUN_APPLET.equals(targetNames[0]) || JavaRunner.QUICK_DEBUG_APPLET.equals(targetNames[0]) || JavaRunner.QUICK_PROFILE_APPLET.equals(targetNames[0]))) { try { final FileObject[] selectedFiles = findSources(context); if (selectedFiles != null) { @@ -464,7 +464,7 @@ String url = p.getProperty("applet.url"); execProperties.put("applet.url", url); execProperties.put(JavaRunner.PROP_EXECUTE_FILE, file); - prepareSystemProperties(execProperties, false); + prepareSystemProperties(execProperties, command, false); JavaRunner.execute(targetNames[0], execProperties); } } catch (IOException ex) { @@ -472,32 +472,34 @@ } return; } - if (!isServerExecution() && (COMMAND_RUN.equals(command) || COMMAND_DEBUG.equals(command) || COMMAND_DEBUG_STEP_INTO.equals(command))) { - prepareSystemProperties(execProperties, false); + if (!isServerExecution() && (COMMAND_RUN.equals(command) || COMMAND_DEBUG.equals(command) || COMMAND_DEBUG_STEP_INTO.equals(command) || COMMAND_PROFILE.equals(command))) { + prepareSystemProperties(execProperties, command, false); bypassAntBuildScript(command, context, execProperties); return ; } // for example RUN_SINGLE Java file with Servlet must be run on server and not locally boolean serverExecution = p.getProperty(PROPERTY_RUN_SINGLE_ON_SERVER) != null; p.remove(PROPERTY_RUN_SINGLE_ON_SERVER); - if (!serverExecution && (COMMAND_RUN_SINGLE.equals(command) || COMMAND_DEBUG_SINGLE.equals(command))) { - prepareSystemProperties(execProperties, false); + if (!serverExecution && (COMMAND_RUN_SINGLE.equals(command) || COMMAND_DEBUG_SINGLE.equals(command) || COMMAND_PROFILE_SINGLE.equals(command))) { + prepareSystemProperties(execProperties, command, false); if (COMMAND_RUN_SINGLE.equals(command)) { execProperties.put(JavaRunner.PROP_CLASSNAME, p.getProperty("run.class")); + } else if (COMMAND_DEBUG_SINGLE.equals(command)) { + execProperties.put(JavaRunner.PROP_CLASSNAME, p.getProperty("debug.class")); } else { - execProperties.put(JavaRunner.PROP_CLASSNAME, p.getProperty("debug.class")); + execProperties.put(JavaRunner.PROP_CLASSNAME, p.getProperty("profile.class")); } bypassAntBuildScript(command, context, execProperties); return; } - if (COMMAND_TEST_SINGLE.equals(command) || COMMAND_DEBUG_TEST_SINGLE.equals(command)) { + if (COMMAND_TEST_SINGLE.equals(command) || COMMAND_DEBUG_TEST_SINGLE.equals(command) || COMMAND_PROFILE_TEST_SINGLE.equals(command)) { FileObject[] files = findTestSources(context, true); try { - prepareSystemProperties(execProperties, true); + prepareSystemProperties(execProperties, command, true); execProperties.put(JavaRunner.PROP_EXECUTE_FILE, files[0]); execProperties.put("tmp.dir", updateHelper.getAntProjectHelper().resolvePath(evaluator.getProperty(ProjectProperties.BUILD_DIR))); //NOI18N updateJavaRunnerClasspath(command, execProperties); - JavaRunner.execute(COMMAND_TEST_SINGLE.equals(command) ? JavaRunner.QUICK_TEST : JavaRunner.QUICK_TEST_DEBUG, execProperties); + JavaRunner.execute(COMMAND_TEST_SINGLE.equals(command) ? JavaRunner.QUICK_TEST : (COMMAND_DEBUG_TEST_SINGLE.equals(command) ? JavaRunner.QUICK_TEST_DEBUG : JavaRunner.QUICK_TEST_PROFILE), execProperties); } catch (IOException ex) { Exceptions.printStackTrace(ex); } @@ -506,25 +508,20 @@ if (SingleMethod.COMMAND_RUN_SINGLE_METHOD.equals(command) || SingleMethod.COMMAND_DEBUG_SINGLE_METHOD.equals(command)) { SingleMethod methodSpec = findTestMethods(context)[0]; try { + prepareSystemProperties(execProperties, command, false); execProperties.put("methodname", methodSpec.getMethodName());//NOI18N execProperties.put(JavaRunner.PROP_EXECUTE_FILE, methodSpec.getFile()); execProperties.put("tmp.dir",updateHelper.getAntProjectHelper().resolvePath(evaluator.getProperty(ProjectProperties.BUILD_DIR))); //NOI18N updateJavaRunnerClasspath(command, execProperties); - JavaRunner.execute(command.equals(SingleMethod.COMMAND_RUN_SINGLE_METHOD) ? JavaRunner.QUICK_TEST : JavaRunner.QUICK_TEST_DEBUG, - execProperties); + JavaRunner.execute(command.equals(SingleMethod.COMMAND_RUN_SINGLE_METHOD) ? JavaRunner.QUICK_TEST : (SingleMethod.COMMAND_DEBUG_SINGLE_METHOD.equals(command) ? JavaRunner.QUICK_TEST_DEBUG :JavaRunner.QUICK_TEST_PROFILE), + execProperties); } catch (IOException ex) { Exceptions.printStackTrace(ex); } return; } } - StringBuilder b = new StringBuilder(); - for (String arg : runJvmargsIde()) { - b.append(' ').append(arg); - } - if (b.length() > 0) { - p.put(ProjectProperties.RUN_JVM_ARGS_IDE, b.toString()); - } + collectStartupExtenderArgs(p, command); if (targetNames.length == 0) { targetNames = null; } @@ -581,32 +578,6 @@ ErrorManager.getDefault().notify(e); } } - - private List runJvmargsIde() { - StartupExtender.StartMode mode; - if (command.equals(COMMAND_RUN) || command.equals(COMMAND_RUN_SINGLE)) { - mode = StartupExtender.StartMode.NORMAL; - } else if (command.equals(COMMAND_DEBUG) || command.equals(COMMAND_DEBUG_SINGLE) || command.equals(COMMAND_DEBUG_STEP_INTO)) { - mode = StartupExtender.StartMode.DEBUG; - } else if (command.equals("profile")) { - mode = StartupExtender.StartMode.PROFILE; - } else if (command.equals(COMMAND_TEST) || command.equals(COMMAND_TEST_SINGLE)) { - mode = StartupExtender.StartMode.TEST_NORMAL; - } else if (command.equals(COMMAND_DEBUG_TEST_SINGLE)) { - mode = StartupExtender.StartMode.TEST_DEBUG; - } else if (command.equals("profile-test-single")) { - mode = StartupExtender.StartMode.TEST_PROFILE; - } else { - return Collections.emptyList(); - } - List args = new ArrayList(); - JavaPlatform p = getActivePlatform(); - for (StartupExtender group : StartupExtender.getExtenders(Lookups.fixed(project, p != null ? p : JavaPlatformManager.getDefault().getDefaultPlatform()), mode)) { - args.addAll(group.getArguments()); - } - return args; - } - } final Action action = new Action(); @@ -705,6 +676,12 @@ return null; } targetNames = setupDebugTestSingle(p, files); + } else if ( command.equals( COMMAND_PROFILE_TEST_SINGLE ) ) { + final FileObject[] files = findTestSources(context, true); + if (files == null) { + return null; + } + targetNames = setupProfileTestSingle(p, files); } else if ( command.equals( SingleMethod.COMMAND_RUN_SINGLE_METHOD ) ) { SingleMethod[] methodSpecs = findTestMethods(context); if ((methodSpecs == null) || (methodSpecs.length != 1)) { @@ -737,7 +714,7 @@ } p.setProperty("fix.includes", path); // NOI18N p.setProperty("fix.classes", classes); // NOI18N - } else if (!isServerExecution() && (command.equals (COMMAND_RUN) || command.equals(COMMAND_DEBUG) || command.equals(COMMAND_DEBUG_STEP_INTO))) { + } else if (!isServerExecution() && (command.equals (COMMAND_RUN) || command.equals(COMMAND_DEBUG) || command.equals(COMMAND_DEBUG_STEP_INTO) || command.equals(COMMAND_PROFILE))) { String config = evaluator.getProperty(ProjectProperties.PROP_PROJECT_CONFIGURATION_CONFIG); String path; if (config == null || config.length() == 0) { @@ -789,7 +766,11 @@ } } if (!command.equals(COMMAND_RUN) && /* XXX should ideally look up proper mainClass in evaluator x config */ mainClass != null) { - p.setProperty("debug.class", mainClass); // NOI18N + if (command.equals(COMMAND_PROFILE)) { + p.setProperty("run.class", mainClass); // NOI18N + } else { + p.setProperty("debug.class", mainClass); // NOI18N + } } String[] targets = targetsFromConfig.get(command); targetNames = (targets != null) ? targets : getCommands().get(command); @@ -797,7 +778,7 @@ throw new IllegalArgumentException(command); } prepareDirtyList(p, false); - } else if (command.equals (COMMAND_RUN_SINGLE) || command.equals (COMMAND_DEBUG_SINGLE)) { + } else if (command.equals (COMMAND_RUN_SINGLE) || command.equals (COMMAND_DEBUG_SINGLE) || command.equals(COMMAND_PROFILE_SINGLE)) { FileObject[] files = findTestSources(context, false); FileObject[] rootz = projectTestRoots.getRoots(); boolean isTest = true; @@ -872,11 +853,14 @@ return null; } p.setProperty("applet.url", url.toString()); // NOI18N - if (command.equals (COMMAND_RUN_SINGLE)) { + if (COMMAND_RUN_SINGLE.equals(command)) { targetNames = new String[] {"run-applet"}; // NOI18N - } else { + } else if (COMMAND_DEBUG_SINGLE.equals(command)) { p.setProperty("debug.class", clazz); // NOI18N targetNames = new String[] {"debug-applet"}; // NOI18N + } else if (COMMAND_PROFILE_SINGLE.equals(command)) { + p.setProperty("run.class", clazz); // NOI18N + targetNames = new String[]{"profile-applet"}; // NOI18N } } else { List alternativeTargetNames = new ArrayList(); @@ -884,8 +868,10 @@ //Fallback to normal (non-main-method-based) unit test run if (command.equals(COMMAND_RUN_SINGLE)) { targetNames = setupTestSingle(p, files); + } else if (command.equals(COMMAND_DEBUG_SINGLE)) { + targetNames = setupDebugTestSingle(p, files); } else { - targetNames = setupDebugTestSingle(p, files); + targetNames = setupProfileTestSingle(p, files); } } else if (handleJavaClass(p, file, command, alternativeTargetNames)) { if (alternativeTargetNames.size() > 0) { @@ -916,10 +902,14 @@ p.setProperty("run.class", clazz); // NOI18N String[] targets = targetsFromConfig.get(command); targetNames = (targets != null) ? targets : (isTest ? new String[] { "run-test-with-main" } : getCommands().get(COMMAND_RUN_SINGLE)); - } else { + } else if (command.equals(COMMAND_DEBUG_SINGLE)) { p.setProperty("debug.class", clazz); // NOI18N String[] targets = targetsFromConfig.get(command); targetNames = (targets != null) ? targets : (isTest ? new String[] {"debug-test-with-main"} : getCommands().get(COMMAND_DEBUG_SINGLE)); + } else { + p.setProperty("run.class", clazz); // NOI18N + String[] targets = targetsFromConfig.get(command); + targetNames = (targets != null) ? targets : (isTest ? new String[] {"profile-test-with-main"} : getCommands().get(COMMAND_PROFILE_SINGLE)); } } } @@ -933,10 +923,14 @@ p.setProperty("run.class", clazz); // NOI18N String[] targets = targetsFromConfig.get(command); targetNames = (targets != null) ? targets : (isTest ? new String[] { "run-test-with-main" } : getCommands().get(COMMAND_RUN_SINGLE)); //NOI18N - } else { + } else if (command.equals(COMMAND_DEBUG_SINGLE)) { p.setProperty("debug.class", clazz); // NOI18N String[] targets = targetsFromConfig.get(command); targetNames = (targets != null) ? targets : (isTest ? new String[] {"debug-test-with-main"} : getCommands().get(COMMAND_DEBUG_SINGLE)); //NOI18N + } else { + p.setProperty("run.class", clazz); // NOI18N + String[] targets = targetsFromConfig.get(command); + targetNames = (targets != null) ? targets : (isTest ? new String[] {"profile-test-with-main"} : getCommands().get(COMMAND_DEBUG_SINGLE)); //NOI18N } } } else { @@ -958,6 +952,7 @@ dirty = null; } } + return targetNames; } @@ -1076,6 +1071,14 @@ p.setProperty("javac.includes", ActionUtils.antIncludesList(files, root)); // NOI18N return new String[] {"debug-test"}; // NOI18N } + + private String[] setupProfileTestSingle(Properties p, FileObject[] files) { + FileObject[] testSrcPath = projectTestRoots.getRoots(); + FileObject root = getRoot(testSrcPath, files[0]); + p.setProperty("test.includes", ActionUtils.antIncludesList(files, root)); // NOI18N + p.setProperty("javac.includes", ActionUtils.antIncludesList(files, root)); // NOI18N + return new String[] {"profile-test"}; // NOI18N + } private String[] setupRunSingleTestMethod(Properties p, SingleMethod methodSpec) { return setupTestSingle(p, new FileObject[] {methodSpec.getFile()}); @@ -1146,8 +1149,12 @@ else if ( command.equals( COMMAND_DEBUG_TEST_SINGLE ) ) { FileObject[] fos = findTestSources(context, true); return fos != null && fos.length == 1; + } else if ( command.equals( COMMAND_PROFILE_TEST_SINGLE ) ) { + FileObject[] fos = findTestSources(context, true); + return fos != null && fos.length == 1; } else if (command.equals(COMMAND_RUN_SINGLE) || command.equals(COMMAND_DEBUG_SINGLE) || + command.equals(COMMAND_PROFILE_SINGLE) || command.equals(JavaProjectConstants.COMMAND_DEBUG_FIX)) { FileObject fos[] = findSources(context); if (fos != null && fos.length == 1) { @@ -1356,7 +1363,7 @@ boolean run = true; boolean hasMainMethod = true; - if (COMMAND_RUN.equals(command) || COMMAND_DEBUG.equals(command) || COMMAND_DEBUG_STEP_INTO.equals(command)) { + if (COMMAND_RUN.equals(command) || COMMAND_DEBUG.equals(command) || COMMAND_DEBUG_STEP_INTO.equals(command) || COMMAND_PROFILE.equals(command)) { final String mainClass = evaluator.getProperty(ProjectProperties.MAIN_CLASS); p.put(JavaRunner.PROP_CLASSNAME, mainClass); @@ -1382,16 +1389,17 @@ p.put(JavaRunner.PROP_EXECUTE_FILE, files[0]); } boolean debug = COMMAND_DEBUG.equals(command) || COMMAND_DEBUG_SINGLE.equals(command) || COMMAND_DEBUG_STEP_INTO.equals(command); + boolean profile = COMMAND_PROFILE.equals(command) || COMMAND_PROFILE_SINGLE.equals(command); try { updateJavaRunnerClasspath(command, p); if (run) { copyMultiValue(ProjectProperties.APPLICATION_ARGS, p); - JavaRunner.execute(debug ? JavaRunner.QUICK_DEBUG : JavaRunner.QUICK_RUN, p); + JavaRunner.execute(debug ? JavaRunner.QUICK_DEBUG : (profile ? JavaRunner.QUICK_PROFILE : JavaRunner.QUICK_RUN), p); } else { if (hasMainMethod) { - JavaRunner.execute(debug ? JavaRunner.QUICK_DEBUG : JavaRunner.QUICK_RUN, p); + JavaRunner.execute(debug ? JavaRunner.QUICK_DEBUG : (profile ? JavaRunner.QUICK_PROFILE : JavaRunner.QUICK_RUN), p); } else { - JavaRunner.execute(debug ? JavaRunner.QUICK_TEST_DEBUG : JavaRunner.QUICK_TEST, p); + JavaRunner.execute(debug ? JavaRunner.QUICK_TEST_DEBUG : (profile ? JavaRunner.QUICK_TEST_PROFILE : JavaRunner.QUICK_TEST), p); } } } catch (IOException ex) { @@ -1428,7 +1436,42 @@ it.add(val); } - private void prepareSystemProperties(Map properties, boolean test) { + private List runJvmargsIde(String command) { + StartupExtender.StartMode mode; + if (command.equals(COMMAND_RUN) || command.equals(COMMAND_RUN_SINGLE)) { + mode = StartupExtender.StartMode.NORMAL; + } else if (command.equals(COMMAND_DEBUG) || command.equals(COMMAND_DEBUG_SINGLE) || command.equals(COMMAND_DEBUG_STEP_INTO)) { + mode = StartupExtender.StartMode.DEBUG; + } else if (command.equals(COMMAND_PROFILE) || command.equals(COMMAND_PROFILE_SINGLE)) { + mode = StartupExtender.StartMode.PROFILE; + } else if (command.equals(COMMAND_TEST) || command.equals(COMMAND_TEST_SINGLE)) { + mode = StartupExtender.StartMode.TEST_NORMAL; + } else if (command.equals(COMMAND_DEBUG_TEST_SINGLE)) { + mode = StartupExtender.StartMode.TEST_DEBUG; + } else if (command.equals(COMMAND_PROFILE_TEST_SINGLE)) { + mode = StartupExtender.StartMode.TEST_PROFILE; + } else { + return Collections.emptyList(); + } + List args = new ArrayList(); + JavaPlatform p = getActivePlatform(); + for (StartupExtender group : StartupExtender.getExtenders(Lookups.fixed(project, p != null ? p : JavaPlatformManager.getDefault().getDefaultPlatform()), mode)) { + args.addAll(group.getArguments()); + } + return args; + } + + private void collectStartupExtenderArgs(Map p, String command) { + StringBuilder b = new StringBuilder(); + for (String arg : runJvmargsIde(command)) { + b.append(' ').append(arg); + } + if (b.length() > 0) { + p.put(ProjectProperties.RUN_JVM_ARGS_IDE, b.toString()); + } + } + + private void prepareSystemProperties(Map properties, String command, boolean test) { String prefix = test ? ProjectProperties.SYSTEM_PROPERTIES_TEST_PREFIX : ProjectProperties.SYSTEM_PROPERTIES_RUN_PREFIX; Map evaluated = evaluator.getProperties(); @@ -1440,7 +1483,8 @@ if (e.getKey().startsWith(prefix) && e.getValue() != null) { putMultiValue(properties, JavaRunner.PROP_RUN_JVMARGS, "-D" + e.getKey().substring(prefix.length()) + "=" + e.getValue()); } - } + } + collectStartupExtenderArgs(properties, command); } private static enum MainClassStatus { --- a/java.api.common/src/org/netbeans/modules/java/api/common/project/Bundle.properties +++ a/java.api.common/src/org/netbeans/modules/java/api/common/project/Bundle.properties @@ -48,6 +48,9 @@ ACTION_debug.stepinto=Debug Project ACTION_debug.fix=Apply Code Changes ACTION_debug.test.single=Debug Test +ACTION_profile=Profile Project +ACTION_profile.single=Profile File +ACTION_profile.test.single=Profile Test ACTION_rebuild=Rebuild Project ACTION_build=Build Project ACTION_clean=Clean Project --- a/java.freeform/src/org/netbeans/modules/java/freeform/Bundle.properties +++ a/java.freeform/src/org/netbeans/modules/java/freeform/Bundle.properties @@ -61,6 +61,7 @@ ACTION_compile.single=Compile File ACTION_run.single=Run File ACTION_debug.single=Debug File +ACTION_profile.single=Profile File COMMENT_edit_target=TODO: edit the following target according to your needs COMMENT_more_info_x.single=(more info: http://www.netbeans.org/kb/articles/freeform-config.html#compilesingle) COMMENT_more_info_run.single=(more info: http://www.netbeans.org/kb/articles/freeform-config.html#runsingle) @@ -74,6 +75,9 @@ COMMENT_set_runtime_cp=TODO configure the runtime classpath for your project here: COMMENT_set_main_class=TODO configure the main class for your project here: +ACTION_profile=Profile Project +COMMENT_more_info_profile=(more info: http://www.netbeans.org/kb/articles/) + CTL_SetOutput=Set Output AD_SetOutput=N/A # {0} - action display name --- a/java.freeform/src/org/netbeans/modules/java/freeform/JavaActions.java +++ a/java.freeform/src/org/netbeans/modules/java/freeform/JavaActions.java @@ -118,8 +118,10 @@ private static final String[] ACTIONS = { ActionProvider.COMMAND_COMPILE_SINGLE, ActionProvider.COMMAND_DEBUG, + ActionProvider.COMMAND_PROFILE, ActionProvider.COMMAND_RUN_SINGLE, - ActionProvider.COMMAND_DEBUG_SINGLE + ActionProvider.COMMAND_DEBUG_SINGLE, + ActionProvider.COMMAND_PROFILE_SINGLE // XXX more }; @@ -162,10 +164,14 @@ return findPackageRoot(context) != null; } else if (command.equals(ActionProvider.COMMAND_DEBUG)) { return true; + } else if (command.equals(ActionProvider.COMMAND_PROFILE)) { + return true; } else if (command.equals(ActionProvider.COMMAND_RUN_SINGLE)) { return (findPackageRoot(context) != null) && isSingleJavaFileSelected(context); } else if (command.equals(ActionProvider.COMMAND_DEBUG_SINGLE)) { return (findPackageRoot(context) != null) && isSingleJavaFileSelected(context); + } else if (command.equals(ActionProvider.COMMAND_PROFILE_SINGLE)) { + return (findPackageRoot(context) != null) && isSingleJavaFileSelected(context); } else { throw new IllegalArgumentException(command); } @@ -180,10 +186,14 @@ handleCompileSingle(context); } else if (command.equals(ActionProvider.COMMAND_DEBUG)) { handleDebug(); + } else if (command.equals(ActionProvider.COMMAND_PROFILE)) { + handleProfile(); } else if (command.equals(ActionProvider.COMMAND_RUN_SINGLE)) { handleRunSingle(context); } else if (command.equals(ActionProvider.COMMAND_DEBUG_SINGLE)) { handleDebugSingle(context); + } else if (command.equals(ActionProvider.COMMAND_PROFILE_SINGLE)) { + handleProfileSingle(context); } else { throw new IllegalArgumentException(command); } @@ -462,6 +472,156 @@ return target; } + private void handleProfile() throws IOException, SAXException { + if (!this.setOutputsNotified) { + ProjectModel pm = ProjectModel.createModel(Util.getProjectLocation(this.helper, this.evaluator), + FileUtil.toFile(project.getProjectDirectory()), this.evaluator, this.helper); + List cuKeys = pm.createCompilationUnitKeys(); + assert cuKeys != null; + boolean hasOutputs = false; + for (Iterator it = cuKeys.iterator(); it.hasNext();) { + ProjectModel.CompilationUnitKey ck = (ProjectModel.CompilationUnitKey) it.next(); + JavaProjectGenerator.JavaCompilationUnit cu = pm.getCompilationUnit(ck,false); + if (cu.output != null && cu.output.size()>0) { + hasOutputs = true; + break; + } + } + if (!hasOutputs) { + alertOutputs (NbBundle.getMessage(JavaActions.class, "ACTION_profile")); // NOI18N + this.setOutputsNotified = true; + return; + } + } + String[] bindings = findCommandBinding(ActionProvider.COMMAND_RUN); + Element task = null; + Element origTarget = null; + if (bindings != null && bindings.length <= 2) { + origTarget = findExistingBuildTarget(ActionProvider.COMMAND_RUN); + //The origTarget may be null if the user has removed it from build.xml + if (origTarget != null) { + task = targetUsesTaskExactlyOnce(origTarget, "java"); // NOI18N + } + } + + if (!alert(NbBundle.getMessage(JavaActions.class, "ACTION_profile"), task != null ? GENERAL_SCRIPT_PATH : FILE_SCRIPT_PATH)) { // NOI18N + return; + } + + String generatedTargetName = "profile-nb"; // NOI18N + String generatedScriptPath; + Document doc; + Element generatedTarget; + if (task != null) { + // We can copy the original run target with some modifications. + generatedScriptPath = GENERAL_SCRIPT_PATH; + doc = readCustomScript(GENERAL_SCRIPT_PATH); + ensureImports(doc.getDocumentElement(), bindings[0]); + generatedTarget = createProfileTargetFromTemplate(generatedTargetName, origTarget, task, doc); + } else { + // No info, need to generate a dummy profile target. + generatedScriptPath = FILE_SCRIPT_PATH; + doc = readCustomScript(FILE_SCRIPT_PATH); + ensurePropertiesCopied(doc.getDocumentElement()); + generatedTarget = createProfileTargetFromScratch(generatedTargetName, doc); + } + Comment comm = doc.createComment(" " + NbBundle.getMessage(JavaActions.class, "COMMENT_edit_target") + " "); // NOI18N + doc.getDocumentElement().appendChild(comm); + comm = doc.createComment(" " + NbBundle.getMessage(JavaActions.class, "COMMENT_more_info_profile") + " "); // NOI18N + doc.getDocumentElement().appendChild(comm); + doc.getDocumentElement().appendChild(generatedTarget); + writeCustomScript(doc, generatedScriptPath); + addBinding(ActionProvider.COMMAND_PROFILE, generatedScriptPath, generatedTargetName, null, null, null, null, null); + jumpToBinding(ActionProvider.COMMAND_PROFILE); + jumpToBuildScript(generatedScriptPath, generatedTargetName); + } + + Element createProfileTargetFromTemplate(String generatedTargetName, Element origTarget, Element origTask, Document ownerDocument) { + NodeList tasks = origTarget.getChildNodes(); + int taskIndex = -1; + for (int i = 0; i < tasks.getLength(); i++) { + if (tasks.item(i) == origTask) { + taskIndex = i; + break; + } + } + assert taskIndex != -1; + Element target = (Element) ownerDocument.importNode(origTarget, true); + target.setAttribute("depends", "-profile-check,dist"); // NOI18N + target.setAttribute("if", "profiler.configured"); // NOI18N + addJdkInitDeps(target); + Element task = (Element) target.getChildNodes().item(taskIndex); + target.setAttribute("name", generatedTargetName); // NOI18N + addProfileInit(ownerDocument, ownerDocument.getDocumentElement()); + + addProfileVMArgs(task, ownerDocument); + return target; + } + + Element createProfileTargetFromScratch(String generatedTargetName, Document ownerDocument) { + Element target = ownerDocument.createElement("target"); // NOI18N + target.setAttribute("depends", "-profile-check,dist"); // NOI18N + target.setAttribute("if", "profiler.configured"); // NOI18N + addJdkInitDeps(target); + target.setAttribute("name", generatedTargetName); // NOI18N + Element path = ownerDocument.createElement("path"); // NOI18N + // XXX would be better to determine runtime CP from project.xml and put it here instead (if that is possible)... + path.setAttribute("id", "cp"); // NOI18N + path.appendChild(ownerDocument.createComment(" " + NbBundle.getMessage(JavaActions.class, "COMMENT_set_runtime_cp") + " ")); // NOI18N + target.appendChild(path); + addProfileInit(ownerDocument, ownerDocument.getDocumentElement()); + + target.appendChild(ownerDocument.createComment(" " + NbBundle.getMessage(JavaActions.class, "COMMENT_set_main_class") + " ")); // NOI18N + Element java = ownerDocument.createElement("java"); // NOI18N + java.setAttribute("classname", "some.main.Class"); // NOI18N + Element classpath = ownerDocument.createElement("classpath"); // NOI18N + classpath.setAttribute("refid", "cp"); // NOI18N + java.appendChild(classpath); + addProfileVMArgs(java, ownerDocument); + target.appendChild(java); + return target; + } + + private void addProfileInit(Document ownerDocument, Element parent) { + NodeList nl = ownerDocument.getElementsByTagName("target"); + for(int i=0;i\n"; assertEquals(expectedXml, xmlToString(doc.getDocumentElement())); } + + public void testCreateProfileTargetFromScratch() throws Exception { + Document doc = XMLUtil.createDocument("project", null, null, null); + Element genTarget = ja.createProfileTargetFromScratch("profile", doc); + doc.getDocumentElement().appendChild(genTarget); + String expectedXml = + "\n" + + "\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "\n"; + assertEquals(expectedXml, xmlToString(doc.getDocumentElement())); + } + + public void testCreateProfileTargetFromTemplate() throws Exception { + Document doc = XMLUtil.createDocument("project", null, null, null); + Document origDoc = XMLUtil.createDocument("target", null, null, null); + Element origTarget = origDoc.getDocumentElement(); + origTarget.setAttribute("name", "ignored"); + origTarget.setAttribute("depends", "compile"); + origTarget.appendChild(origDoc.createElement("task1")); + Element task = origDoc.createElement("java"); + // XXX also test nested : + task.setAttribute("classpath", "${cp}"); + task.appendChild(origDoc.createElement("stuff")); + origTarget.appendChild(task); + origTarget.appendChild(origDoc.createElement("task2")); + Element genTarget = ja.createProfileTargetFromTemplate("profile", origTarget, task, doc); + doc.getDocumentElement().appendChild(genTarget); + String expectedXml = + "\n" + + "\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "\n"; + assertEquals(expectedXml, xmlToString(doc.getDocumentElement())); + } public void testCreateRunSingleTargetElem() throws Exception { Document doc = XMLUtil.createDocument("project", null, null, null); --- a/java.j2seproject/src/org/netbeans/modules/java/j2seproject/J2SEActionProvider.java +++ a/java.j2seproject/src/org/netbeans/modules/java/j2seproject/J2SEActionProvider.java @@ -80,10 +80,13 @@ COMMAND_RUN_SINGLE, COMMAND_DEBUG, COMMAND_DEBUG_SINGLE, + COMMAND_PROFILE, + COMMAND_PROFILE_SINGLE, JavaProjectConstants.COMMAND_JAVADOC, COMMAND_TEST, COMMAND_TEST_SINGLE, COMMAND_DEBUG_TEST_SINGLE, + COMMAND_PROFILE_TEST_SINGLE, SingleMethod.COMMAND_RUN_SINGLE_METHOD, SingleMethod.COMMAND_DEBUG_SINGLE_METHOD, JavaProjectConstants.COMMAND_DEBUG_FIX, @@ -103,10 +106,13 @@ COMMAND_RUN_SINGLE, COMMAND_DEBUG, COMMAND_DEBUG_SINGLE, + COMMAND_PROFILE, + COMMAND_PROFILE_SINGLE, JavaProjectConstants.COMMAND_JAVADOC, COMMAND_TEST, COMMAND_TEST_SINGLE, COMMAND_DEBUG_TEST_SINGLE, + COMMAND_PROFILE_TEST_SINGLE, SingleMethod.COMMAND_RUN_SINGLE_METHOD, SingleMethod.COMMAND_DEBUG_SINGLE_METHOD, JavaProjectConstants.COMMAND_DEBUG_FIX, @@ -139,10 +145,13 @@ commands.put(COMMAND_RUN_SINGLE, new String[] {"run-single"}); // NOI18N commands.put(COMMAND_DEBUG, new String[] {"debug"}); // NOI18N commands.put(COMMAND_DEBUG_SINGLE, new String[] {"debug-single"}); // NOI18N + commands.put(COMMAND_PROFILE, new String[] {"profile"}); // NOI18N + commands.put(COMMAND_PROFILE_SINGLE, new String[] {"profile-single"}); // NOI18N commands.put(JavaProjectConstants.COMMAND_JAVADOC, new String[] {"javadoc"}); // NOI18N commands.put(COMMAND_TEST, new String[] {"test"}); // NOI18N commands.put(COMMAND_TEST_SINGLE, new String[] {"test-single"}); // NOI18N commands.put(COMMAND_DEBUG_TEST_SINGLE, new String[] {"debug-test"}); // NOI18N + commands.put(COMMAND_PROFILE_TEST_SINGLE, new String[]{"profile-test"}); // NOI18N commands.put(JavaProjectConstants.COMMAND_DEBUG_FIX, new String[] {"debug-fix"}); // NOI18N commands.put(COMMAND_DEBUG_STEP_INTO, new String[] {"debug-stepinto"}); // NOI18N @@ -151,7 +160,9 @@ COMMAND_RUN_SINGLE, COMMAND_DEBUG, COMMAND_DEBUG_SINGLE, - COMMAND_DEBUG_STEP_INTO + COMMAND_DEBUG_STEP_INTO, + COMMAND_PROFILE, + COMMAND_PROFILE_SINGLE )); this.needJavaModelActions = new HashSet(Arrays.asList( --- a/java.j2seproject/src/org/netbeans/modules/java/j2seproject/resources/build-impl.xsl +++ a/java.j2seproject/src/org/netbeans/modules/java/j2seproject/resources/build-impl.xsl @@ -718,20 +718,28 @@ - - + + + pre NB7.2 profiling section; consider it deprecated + + + profiler.info.jvmargs.agent + + profiler.info.jvmargs.agent Empty placeholder for easier customization. You can override this target in the ../build.xml file. + profiler.info.jvmargs.agent Empty placeholder for easier customization. You can override this target in the ../build.xml file. + profiler.info.jvmargs.agent resolve @@ -779,9 +787,13 @@ -profile-pre-init, init, -profile-post-init, -profile-init-macrodef-profile + profiler.info.jvmargs.agent Must set JVM to use for profiling in profiler.info.jvm Must set profiler agent JVM arguments in profiler.info.jvmargs.agent + + end of pre NB7.2 profiling section + @@ -914,6 +926,10 @@ classpath ${run.classpath} + + jvm + jvm + customize true @@ -1456,11 +1472,11 @@ PROFILING SECTION ================= - - - netbeans.home - profile-init,compile - Profile a project in the IDE. + + pre NB7.2 profiler integration + + + This target only works when run from inside the NetBeans IDE. @@ -1468,74 +1484,96 @@ - - - netbeans.home - profile-init,compile-single - Profile a selected class in the IDE. + Must select one file in the IDE or set profile.class + This target only works when run from inside the NetBeans IDE. - + - - - ========================= - APPLET PROFILING SECTION - ========================= - - - - netbeans.home - profile-init,compile-single + + This target only works when run from inside the NetBeans IDE. - - + + This target only works when run from inside the NetBeans IDE. + + + + + + + + + + + + + + + + + + + + + - ========================= - TESTS PROFILING SECTION - ========================= + end of pre NB72 profiling section - - - netbeans.home - profile-init,compile-test-single - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + Must select one file in the IDE or set run.class + + + + + + + + Must select some files in the IDE or set test.includes + + + + + + Must select one file in the IDE or set run.class + + + + + + Must select one file in the IDE or set applet.url + + + + =============== JAVADOC SECTION --- a/java.j2seproject/src/org/netbeans/modules/java/j2seproject/ui/resources/layer.xml +++ a/java.j2seproject/src/org/netbeans/modules/java/j2seproject/ui/resources/layer.xml @@ -108,10 +108,6 @@ - - - - --- a/java.j2seproject/test/unit/src/org/netbeans/modules/java/j2seproject/J2SEActionProviderTest.java +++ a/java.j2seproject/test/unit/src/org/netbeans/modules/java/j2seproject/J2SEActionProviderTest.java @@ -296,6 +296,18 @@ assertEquals("There must be two target parameters", 2, p.keySet().size()); assertEquals("There must be be target parameter", "foo.BarTest", p.getProperty("test.class")); assertEquals("There must be be target parameter", "foo/BarTest.java", p.getProperty("javac.includes")); + + // test COMMAND_PROFILE_TEST_SINGLE + + p = new Properties(); + context = Lookups.fixed(someSource1); + targets = actionProvider.getTargetNames(ActionProvider.COMMAND_PROFILE_TEST_SINGLE, context, p); + assertNotNull("Must found some targets for COMMAND_PROFILE_TEST_SINGLE", targets); + assertEquals("There must be one target for COMMAND_PROFILE_TEST_SINGLE", 1, targets.length); + assertEquals("Unexpected target name", "profile-test", targets[0]); + assertEquals("There must be two target parameters", 2, p.keySet().size()); + assertEquals("There must be be target parameter", "foo/BarTest.java", p.getProperty("javac.includes")); + assertEquals("There must be be target parameter", "foo/BarTest.java", p.getProperty("test.includes")); // test COMMAND_DEBUG_FIX actionProvider.unitTestingSupport_fixClasses = "foo/Bar"; @@ -422,6 +434,58 @@ assertEquals("There must be two target parameters", 2, p.keySet().size()); assertEquals("There must be be target parameter", "foo.BarTest", p.getProperty("debug.class")); assertEquals("There must be be target parameter", "foo/BarTest.java", p.getProperty("javac.includes")); + + // test COMMAND_PROFILE_SINGLE + + p = new Properties(); + context = Lookups.fixed(someSource2); + MainClassChooser.unitTestingSupport_hasMainMethodResult = Boolean.TRUE; + try { + targets = actionProvider.getTargetNames(ActionProvider.COMMAND_PROFILE_SINGLE, context, p); + } finally { + MainClassChooser.unitTestingSupport_hasMainMethodResult = null; + } + assertNotNull("Must found some targets for COMMAND_PROFILE_SINGLE", targets); + assertEquals("There must be one target for COMMAND_PROFILE_SINGLE", 1, targets.length); + assertEquals("Unexpected target name", "profile-single", targets[0]); + assertEquals("There must be one target parameter", 2, p.keySet().size()); + assertEquals("There must be be target parameter", "foo/Main.java", p.getProperty("javac.includes")); + assertEquals("There must be be target parameter", "foo.Main", p.getProperty("run.class")); + p = new Properties(); + context = Lookups.fixed(someSource2); + MainClassChooser.unitTestingSupport_hasMainMethodResult = Boolean.FALSE; + AppletSupport.unitTestingSupport_isApplet = Boolean.TRUE; + try { + targets = actionProvider.getTargetNames(ActionProvider.COMMAND_PROFILE_SINGLE, context, p); + } finally { + MainClassChooser.unitTestingSupport_hasMainMethodResult = null; + AppletSupport.unitTestingSupport_isApplet = null; + } + assertNotNull("Must found some targets for COMMAND_PROFILE_SINGLE", targets); + assertEquals("There must be one target for COMMAND_PROFILE_SINGLE", 1, targets.length); + assertEquals("Unexpected target name", "profile-applet", targets[0]); + assertEquals("There must be one target parameter", 3, p.keySet().size()); + assertEquals("There must be be target parameter", "foo/Main.java", p.getProperty("javac.includes")); + appletHtml = build.getFileObject("Main", "html"); + assertNotNull("Applet HTML page must be generated", appletHtml); + appletUrl = URLMapper.findURL(appletHtml, URLMapper.EXTERNAL); + assertEquals("There must be be target parameter", appletUrl.toExternalForm(), p.getProperty("applet.url")); + p = new Properties(); + context = Lookups.fixed(someTest1); + MainClassChooser.unitTestingSupport_hasMainMethodResult = Boolean.TRUE; + AppletSupport.unitTestingSupport_isApplet = Boolean.TRUE; + try { + targets = actionProvider.getTargetNames(ActionProvider.COMMAND_PROFILE_SINGLE, context, p); + } finally { + MainClassChooser.unitTestingSupport_hasMainMethodResult = null; + AppletSupport.unitTestingSupport_isApplet = null; + } + assertNotNull("Must found some targets for COMMAND_PROFILE_SINGLE", targets); + assertEquals("There must be one target for COMMAND_PROFILE_SINGLE", 1, targets.length); + assertEquals("Unexpected target name", "profile-test-with-main", targets[0]); + assertEquals("There must be two target parameters", 2, p.keySet().size()); + assertEquals("There must be be target parameter", "foo.BarTest", p.getProperty("run.class")); + assertEquals("There must be be target parameter", "foo/BarTest.java", p.getProperty("javac.includes")); // test COMMAND_RUN @@ -478,6 +542,25 @@ //See issue #61244: Main class setting not saved for J2SE Project during IDE session assertEquals("There must be one target parameter", 1, p.keySet().size()); assertEquals("There must be be target parameter", "foo.Main", p.getProperty("debug.class")); + + // test COMMAND_PROFILE + + p = new Properties(); + context = Lookup.EMPTY; + MainClassChooser.unitTestingSupport_hasMainMethodResult = Boolean.TRUE; + try { + targets = actionProvider.getTargetNames(ActionProvider.COMMAND_PROFILE, context, p); + } finally { + MainClassChooser.unitTestingSupport_hasMainMethodResult = null; + } + assertNotNull("Must found some targets for COMMAND_PROFILE", targets); + assertEquals("There must be one target for COMMAND_PROFILE", 1, targets.length); + assertEquals("Unexpected target name", "profile", targets[0]); + //The project is saved after the main.class property was added into the project's properties, + //it is no more needed to pass it in the properties. + //See issue #61244: Main class setting not saved for J2SE Project during IDE session + assertEquals("There must be one target parameter", 1, p.keySet().size()); + assertEquals("There must be be target parameter", "foo.Main", p.getProperty("run.class")); } public void testGetTargetNamesFromConfig() throws Exception { --- a/java.project/src/org/netbeans/api/java/project/runner/JavaRunner.java +++ a/java.project/src/org/netbeans/api/java/project/runner/JavaRunner.java @@ -108,6 +108,8 @@ */ public static final String QUICK_DEBUG = "debug"; + public static final String QUICK_PROFILE = "profile"; + /** *

"Test" run the given test. Classfiles produced by the Java infrastructure will be * executed.

@@ -134,6 +136,8 @@ */ public static final String QUICK_TEST_DEBUG = "junit-debug"; + public static final String QUICK_TEST_PROFILE = "junit-profile"; + /**

"Test" run the given applet. Classfiles produced by the Java infrastructure will be * executed.

* @@ -156,6 +160,8 @@ */ public static final String QUICK_DEBUG_APPLET = "debug-applet"; + public static final String QUICK_PROFILE_APPLET = "profile-applet"; + /** Clean classfiles produced by the Java infrastructure. * * @since 1.22 --- a/java.source.ant/src/org/netbeans/modules/java/source/ant/resources/junit-debug-snippet.xml +++ a/java.source.ant/src/org/netbeans/modules/java/source/ant/resources/junit-debug-snippet.xml @@ -43,58 +43,40 @@ Version 2 license, then the option applies only if the new code is made subject to such option by the copyright holder. --> - + + + + + + + + + + Execution of a single test method is not supported by this version of Ant. - - - - - - - - - - - - - - - - - - - - - + - + - - - - - - - - + + - - + @@ -106,22 +88,21 @@ - - + + - + - - + + - + - + - --- a/java.source.ant/src/org/netbeans/modules/java/source/ant/resources/debug-applet-snippet.xml +++ a/java.source.ant/src/org/netbeans/modules/java/source/ant/resources/debug-applet-snippet.xml @@ -43,44 +43,25 @@ Version 2 license, then the option applies only if the new code is made subject to such option by the copyright holder. --> - - - - + + + - - - - + + - - - - - - - - - - - + + - - - - - - - - + + - - + --- a/java.source.ant/src/org/netbeans/modules/java/source/ant/resources/debug-snippet.xml +++ a/java.source.ant/src/org/netbeans/modules/java/source/ant/resources/debug-snippet.xml @@ -43,48 +43,28 @@ Version 2 license, then the option applies only if the new code is made subject to such option by the copyright holder. --> - - - - + + + - - - - + + - - - - - - - - - - - + + - - - - - - - - - + + - - + --- a/maven.apisupport/src/org/netbeans/modules/maven/apisupport/NetBeansStartupArgs.java +++ a/maven.apisupport/src/org/netbeans/modules/maven/apisupport/NetBeansStartupArgs.java @@ -70,7 +70,7 @@ mode = StartupExtender.StartMode.NORMAL; } else if (ActionProvider.COMMAND_DEBUG.equals(actionName)) { mode = StartupExtender.StartMode.DEBUG; - } else if ("profile".equals(actionName)) { + } else if (ActionProvider.COMMAND_PROFILE.equals(actionName)) { mode = StartupExtender.StartMode.PROFILE; } else { return true; --- a/maven.profiler/nbproject/project.xml +++ a/maven.profiler/nbproject/project.xml @@ -121,6 +121,14 @@ + org.openide.execution + + + + 1.25 + + + org.openide.filesystems @@ -129,6 +137,22 @@ + org.openide.loaders + + + + 7.33 + + + + org.openide.nodes + + + + 7.27 + + + org.openide.util --- a/maven.profiler/src/org/netbeans/modules/maven/profiler/ActionMappings.xml +++ a/maven.profiler/src/org/netbeans/modules/maven/profiler/ActionMappings.xml @@ -56,9 +56,8 @@ org.codehaus.mojo:exec-maven-plugin:1.2:exec - ${profiler.args} -classpath %classpath ${packageClassName} - ${profiler.java} - profile + -classpath %classpath ${packageClassName} + java @@ -88,8 +87,7 @@ nbm:run-ide - ${profiler.args.prefixed} ${profiler.jdkhome.opt} - profile + @@ -102,30 +100,28 @@ nbm:run-platform - ${profiler.args.prefixed} ${profiler.jdkhome.opt} - profile + - profile-single + profile.single - jar + * process-classes org.codehaus.mojo:exec-maven-plugin:1.2:exec - ${profiler.args} -classpath %classpath ${packageClassName} - ${profiler.java} + -classpath %classpath ${packageClassName} + java ${classPathScope} - profile-single - profile-single.deploy + profile.single.deploy war @@ -140,7 +136,7 @@ - profile-tests + profile.test.single * @@ -149,13 +145,11 @@ surefire:test - ${className} + ${packageClassName} once - ${profiler.args} -classpath %classpath - - profile-tests + ${exec.args} + + --- a/maven.profiler/src/org/netbeans/modules/maven/profiler/MavenProjectProfilingSupportProvider.java +++ a/maven.profiler/src/org/netbeans/modules/maven/profiler/MavenProjectProfilingSupportProvider.java @@ -77,7 +77,7 @@ }; - public JavaPlatform getProjectJavaPlatform() { + public JavaPlatform resolveProjectJavaPlatform() { return JavaPlatform.getDefaultPlatform(); } @@ -92,30 +92,30 @@ @Override public boolean startProfilingSession(final FileObject profiledClassFile, final boolean isTest, final Properties properties) { - RequestProcessor.getDefault().post(new Runnable() { - public void run() { startMaven(getProject().getLookup().lookup(Project.class), profiledClassFile, isTest, properties); } - }); +// RequestProcessor.getDefault().post(new Runnable() { +// public void run() { startMaven(getProject().getLookup().lookup(Project.class), profiledClassFile, isTest, properties); } +// }); return true; } - private void startMaven(Project project, FileObject profiledClassFile, boolean isTest, Properties properties) { - ProfilingSettings lastProfilingSettings = new ProfilingSettings(); - SessionSettings lastSessionSettings = new SessionSettings(); - Properties lastSessionProperties = new Properties(properties); - - lastProfilingSettings.load(properties); - lastSessionSettings.load(properties); - - RunCheckerImpl.configureProject(project, lastSessionProperties, lastProfilingSettings, lastSessionSettings); - - NetBeansProfiler.getDefaultNB().setProfiledProject(project, profiledClassFile); - - String packaging = project.getLookup().lookup(NbMavenProject.class).getPackagingType(); - - if (profiledClassFile != null) ProjectUtilities.invokeAction(project, isTest ? "profile-tests": (packaging.equals("war") ? "profile-single.deploy" : "profile-single")); //NOI18N - else ProjectUtilities.invokeAction(project, isTest ? "profile-tests" : "profile"); //NOI18N - } +// private void startMaven(Project project, FileObject profiledClassFile, boolean isTest, Properties properties) { +// ProfilingSettings lastProfilingSettings = new ProfilingSettings(); +// SessionSettings lastSessionSettings = new SessionSettings(); +// Properties lastSessionProperties = new Properties(properties); +// +// lastProfilingSettings.load(properties); +// lastSessionSettings.load(properties); +// +// RunCheckerImpl.configureProject(project, lastSessionProperties, lastProfilingSettings, lastSessionSettings); +// +// NetBeansProfiler.getDefaultNB().setProfiledProject(project, profiledClassFile); +// +// String packaging = project.getLookup().lookup(NbMavenProject.class).getPackagingType(); +// +// if (profiledClassFile != null) ProjectUtilities.invokeAction(project, isTest ? "profile-tests": (packaging.equals("war") ? "profile-single.deploy" : "profile-single")); //NOI18N +// else ProjectUtilities.invokeAction(project, isTest ? "profile-tests" : "profile"); //NOI18N +// } public MavenProjectProfilingSupportProvider(Project project) { --- a/maven.profiler/src/org/netbeans/modules/maven/profiler/ProfilerActionsProvider.java +++ a/maven.profiler/src/org/netbeans/modules/maven/profiler/ProfilerActionsProvider.java @@ -48,6 +48,7 @@ import org.netbeans.modules.maven.api.NbMavenProject; import org.netbeans.modules.maven.spi.actions.AbstractMavenActionsProvider; import org.netbeans.api.project.Project; +import org.netbeans.spi.project.ActionProvider; import org.openide.util.Lookup; /** @@ -68,7 +69,7 @@ @Override public boolean isActionEnable(String action, Project project, Lookup lookup) { - if (!(action.equals("profile") || action.startsWith("profile-single") || action.equals("profile-tests"))) { + if (!(action.equals(ActionProvider.COMMAND_PROFILE) || action.startsWith(ActionProvider.COMMAND_PROFILE_SINGLE) || action.equals(ActionProvider.COMMAND_PROFILE_TEST_SINGLE))) { return false; } NbMavenProject mavenprj = project.getLookup().lookup(NbMavenProject.class); @@ -81,9 +82,9 @@ @Override protected InputStream getActionDefinitionStream() { - String path = "/org/netbeans/modules/maven/profiler/ActionMappings.xml"; //NOI18N - InputStream in = getClass().getResourceAsStream(path); - assert in != null : "no instream for " + path; //NOI18N - return in; + String path = "/org/netbeans/modules/maven/profiler/ActionMappings.xml"; //NOI18N + InputStream in = getClass().getResourceAsStream(path); + assert in != null : "no instream for " + path; //NOI18N + return in; } } --- a/maven.profiler/src/org/netbeans/modules/maven/profiler/RunCheckerImpl.java +++ a/maven.profiler/src/org/netbeans/modules/maven/profiler/RunCheckerImpl.java @@ -43,35 +43,40 @@ package org.netbeans.modules.maven.profiler; import java.io.File; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.WeakHashMap; +import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; +import org.netbeans.api.project.FileOwnerQuery; import org.netbeans.api.project.Project; import org.netbeans.lib.profiler.common.Profiler; import org.netbeans.lib.profiler.common.ProfilingSettings; import org.netbeans.lib.profiler.common.SessionSettings; import org.netbeans.modules.maven.api.execute.ExecutionContext; import org.netbeans.modules.maven.api.execute.LateBoundPrerequisitesChecker; +import org.netbeans.modules.maven.api.execute.PrerequisitesChecker; import org.netbeans.modules.maven.api.execute.RunConfig; +import org.netbeans.modules.maven.api.execute.RunUtils; +import org.netbeans.modules.profiler.NetBeansProfiler; +import org.netbeans.modules.profiler.nbimpl.actions.ProfilerLauncher; +import org.netbeans.modules.profiler.nbimpl.actions.ProfilerLauncher.Launcher; +import org.netbeans.modules.profiler.nbimpl.actions.ProfilerLauncher.Session; +import org.netbeans.spi.project.ActionProvider; import org.netbeans.spi.project.ProjectServiceProvider; +import org.openide.filesystems.FileObject; +import org.openide.loaders.DataObject; +import org.openide.loaders.DataObjectNotFoundException; +import org.openide.util.Lookup; import org.openide.util.RequestProcessor; import org.openide.util.Utilities; +import org.openide.util.lookup.Lookups; /** * * @author mkleint * @author Jiri Sedlacek */ -@ProjectServiceProvider(service=LateBoundPrerequisitesChecker.class, projectType="org-netbeans-modules-maven") +@ProjectServiceProvider(service={LateBoundPrerequisitesChecker.class}, projectType="org-netbeans-modules-maven") public class RunCheckerImpl implements LateBoundPrerequisitesChecker { - - private static final String ACTION_PROFILE = "profile"; // NOI18N - private static final String ACTION_PROFILE_SINGLE = "profile-single"; // NOI18N - private static final String ACTION_PROFILE_TESTS = "profile-tests"; // NOI18N private static final Logger LOG = Logger.getLogger(RunCheckerImpl.class.getName()); @@ -83,90 +88,114 @@ private static final String PROFILER_JDKHOME_OPT = "${profiler.jdkhome.opt}"; // NOI18N private final Project project; - private static final Map properties = new WeakHashMap(); - private static final Map profilingSettings = new WeakHashMap(); - private static final Map sessionSettings = new WeakHashMap(); + @ProjectServiceProvider(service=ProfilerLauncher.LauncherFactory.class, projectType="org-netbeans-modules-maven") + final public static class MavenLauncherFactory implements ProfilerLauncher.LauncherFactory { + @Override + public Launcher createLauncher(final Session session) { + return new Launcher() { + + @Override + public void launch(boolean rerun) { + if (rerun) { + RunConfig config = (RunConfig)session.getAttribute("mvn-run-checker.config"); + if (config != null) { + RunUtils.executeMaven(config); + } + } else { + Project p = session.getProject(); + if (p == null) { + FileObject f = session.getFile(); + if (f != null) { + p = FileOwnerQuery.getOwner(f); + } + } + if (p != null) { + ActionProvider ap = p.getLookup().lookup(ActionProvider.class); + if (ap != null) { + ap.invokeAction(session.getCommand(), session.getContext()); + } + } + } + } + }; + } + + } public RunCheckerImpl(Project prj) { project = prj; } - static void configureProject(Project project, Properties p, ProfilingSettings ps, SessionSettings ss) { - properties.put(project, p); - profilingSettings.put(project, ps); - sessionSettings.put(project, ss); - } +// static void configureProject(Project project, Properties p, ProfilingSettings ps, SessionSettings ss) { +// properties.put(project, p); +// profilingSettings.put(project, ps); +// sessionSettings.put(project, ss); +// } +// +// private void configureProfiler(RunConfig config, Properties props) { +// ProfilingSettings lastProfilingSettings = new ProfilingSettings(); +// SessionSettings lastSessionSettings = new SessionSettings(); +// +// lastProfilingSettings.load(props); +// lastSessionSettings.load(props); +// +// NetBeansProfiler.getDefaultNB().setProfiledProject(config.getProject(), config.getSelectedFileObject()); +// } + +// @Override +// public boolean checkRunConfig(RunConfig config) { +// if (ActionProvider.COMMAND_PROFILE.equals(config.getActionName()) || +// ActionProvider.COMMAND_PROFILE_TEST_SINGLE.equals(config.getActionName()) || +// (config.getActionName() != null && config.getActionName().startsWith(ActionProvider.COMMAND_PROFILE_SINGLE))) { +// isFirstRun = true; +// } +// +// return true; +// } - public boolean checkRunConfig(RunConfig config, ExecutionContext context) { + @Override + public boolean checkRunConfig(final RunConfig config, ExecutionContext context) { Map configProperties = config.getProperties(); + + if (ActionProvider.COMMAND_PROFILE.equals(config.getActionName()) || + ActionProvider.COMMAND_PROFILE_TEST_SINGLE.equals(config.getActionName()) || + (config.getActionName() != null && config.getActionName().startsWith(ActionProvider.COMMAND_PROFILE_SINGLE))) { + Map props = new HashMap(); + props.putAll(configProperties); - if ( ACTION_PROFILE.equals(config.getActionName()) || - ACTION_PROFILE_TESTS.equals(config.getActionName()) || - (config.getActionName() != null && config.getActionName().startsWith(ACTION_PROFILE_SINGLE))) { // action "profile" - // Resolve profiling configuration - Properties sessionProperties = properties.get(project); - if (sessionProperties == null) return false; - // Resolve profiling session properties - for (Object k : configProperties.keySet()) { - String key = (String)k; - - String value = configProperties.get(key); - if (value.contains(PROFILER_ARGS)) { - value = value.replace(PROFILER_ARGS, profilerArgs(sessionProperties, false)); - config.setProperty(key, value.trim()); - } - if (value.contains(PROFILER_ARGS_PREFIXED)) { - value = value.replace(PROFILER_ARGS_PREFIXED, profilerArgs(sessionProperties, true)); - config.setProperty(key, value.trim()); - } - if (value.contains(PROFILER_JAVA)) { - String profilerJava = sessionProperties.getProperty("profiler.info.jvm"); // NOI18N - value = value.replace(PROFILER_JAVA, - (profilerJava != null && new File(profilerJava).isFile()) ? profilerJava : "java"); // NOI18N - config.setProperty(key, value.trim()); - } - if (value.contains(PROFILER_JDKHOME_OPT)) { - String opt = ""; - String profilerJava = sessionProperties.getProperty("profiler.info.jvm"); // NOI18N - if (profilerJava != null) { - File binJava = new File(profilerJava); - if (binJava.isFile() && binJava.getName().matches("java([.]exe)?") && binJava.getParentFile().getName().equals("bin")) { - String jdkhome = binJava.getParentFile().getParent(); - opt = Utilities.escapeParameters(new String[] {"--jdkhome", jdkhome}); - LOG.log(Level.FINE, "from {0} escaped {1}", new Object[] {jdkhome, opt}); - } - } - value = value.replace(PROFILER_JDKHOME_OPT, opt); - config.setProperty(key, value.trim()); - } + ProfilerLauncher.Session session = ProfilerLauncher.getLastSession(); + + if (session == null) { + return false; } + + Map sProps = session.getProperties(); + if (sProps == null) return false; + props.putAll(sProps); + + session.setAttribute("mvn-run-checker.config", config); + + final ProfilerLauncher.Session s = session; // Attach profiler engine (in separate thread) to profiled process RequestProcessor.getDefault().post(new Runnable() { public void run() { - ProfilingSettings ps = profilingSettings.get(project); - SessionSettings ss = sessionSettings.get(project); - Profiler.getDefault().connectToStartedApp(ps, ss); + Profiler.getDefault().connectToStartedApp(s.getProfilingSettings(), s.getSessionSettings()); } }); - -// } else if (ACTION_PROFILE_SINGLE.equals(actionName)) { // action "profile-single" -// // profile-single not supported yet, shouldn't get here -// } else if (ACTION_PROFILE_TESTS.equals(actionName)) { -// // profile-tests not supported yet, shouldn't get here // action "profile-tests" } return true; } - private String profilerArgs(Properties sessionProperties, boolean prefixed) { + private String profilerArgs(Map sessionProperties, boolean prefixed) { List args = new ArrayList(); - String jvmargs = sessionProperties.getProperty("profiler.info.jvmargs"); + String jvmargs = sessionProperties.get("profiler.info.jvmargs"); for (String arg : Utilities.parseParameters(jvmargs)) { args.add(prefixed ? "-J" + arg : arg); } - String agentarg = sessionProperties.getProperty("profiler.info.jvmargs.agent"); + String agentarg = sessionProperties.get("agent.jvmargs"); if (Utilities.isWindows()) { agentarg = agentarg.replace('\\', '/'); // XXX is this still necessary given quoting? } --- a/maven/src/org/netbeans/modules/maven/ActionProviderImpl.java +++ a/maven/src/org/netbeans/modules/maven/ActionProviderImpl.java @@ -128,7 +128,10 @@ COMMAND_DEBUG_SINGLE, COMMAND_DEBUG_TEST_SINGLE, "debug.fix", //NOI18N - + COMMAND_PROFILE, + COMMAND_PROFILE_SINGLE, + COMMAND_PROFILE_TEST_SINGLE, + //operations COMMAND_DELETE, COMMAND_RENAME, @@ -181,7 +184,8 @@ @Messages("run_single_method_disabled=Surefire 2.8+ with JUnit 4 needed to run a single test method without Compile on Save.") @Override public void invokeAction(final String action, final Lookup lookup) { - if (action.equals(SingleMethod.COMMAND_RUN_SINGLE_METHOD) || action.equals(SingleMethod.COMMAND_DEBUG_SINGLE_METHOD)) { + if (action.equals(SingleMethod.COMMAND_RUN_SINGLE_METHOD) || + action.equals(SingleMethod.COMMAND_DEBUG_SINGLE_METHOD)) { if (!runSingleMethodEnabled()) { StatusDisplayer.getDefault().setStatusText(run_single_method_disabled()); return; @@ -251,6 +255,7 @@ @Messages({ "# {0} - artifactId", "TXT_Run=Run {0}", "# {0} - artifactId", "TXT_Debug=Debug {0}", + "# {0} - artifactId", "TXT_Profile=Profile {0}", "# {0} - artifactId", "TXT_Test=Test {0}", "# {0} - artifactId", "TXT_Build=Build {0}" }) @@ -267,12 +272,16 @@ title = TXT_Run(prj.getMavenProject().getArtifactId()); } else if (ActionProvider.COMMAND_DEBUG.equals(action)) { title = TXT_Debug(prj.getMavenProject().getArtifactId()); + } else if (ActionProvider.COMMAND_PROFILE.equals(action)) { + title = TXT_Profile(prj.getMavenProject().getArtifactId()); } else if (ActionProvider.COMMAND_TEST.equals(action)) { title = TXT_Test(prj.getMavenProject().getArtifactId()); } else if (action.startsWith(ActionProvider.COMMAND_RUN_SINGLE)) { title = TXT_Run(dobjName); } else if (action.startsWith(ActionProvider.COMMAND_DEBUG_SINGLE) || ActionProvider.COMMAND_DEBUG_TEST_SINGLE.equals(action)) { title = TXT_Debug(dobjName); + } else if (action.startsWith(ActionProvider.COMMAND_PROFILE_SINGLE) || ActionProvider.COMMAND_PROFILE_TEST_SINGLE.equals(action)) { + title = TXT_Profile(dobjName); } else if (ActionProvider.COMMAND_TEST_SINGLE.equals(action)) { title = TXT_Test(dobjName); } else { @@ -289,7 +298,8 @@ COMMAND_MOVE.equals(action)) { return true; } - if (action.equals(SingleMethod.COMMAND_RUN_SINGLE_METHOD) || action.equals(SingleMethod.COMMAND_DEBUG_SINGLE_METHOD)) { + if (action.equals(SingleMethod.COMMAND_RUN_SINGLE_METHOD) || + action.equals(SingleMethod.COMMAND_DEBUG_SINGLE_METHOD)) { return true; } //TODO if order is important, use the lookupmerger --- a/maven/src/org/netbeans/modules/maven/layer.xml +++ a/maven/src/org/netbeans/modules/maven/layer.xml @@ -122,7 +122,7 @@
- + --- a/maven/src/org/netbeans/modules/maven/runjar/RunJarStartupArgs.java +++ a/maven/src/org/netbeans/modules/maven/runjar/RunJarStartupArgs.java @@ -71,8 +71,10 @@ mode = StartupExtender.StartMode.NORMAL; } else if (ActionProvider.COMMAND_DEBUG.equals(actionName) || DEBUG_MAIN.equals(actionName)) { mode = StartupExtender.StartMode.DEBUG; - } else if ("profile".equals(actionName)) { + } else if (ActionProvider.COMMAND_PROFILE.equals(actionName) || ActionProvider.COMMAND_PROFILE_SINGLE.equals(actionName)) { mode = StartupExtender.StartMode.PROFILE; + } else if (ActionProvider.COMMAND_PROFILE_TEST_SINGLE.equals(actionName)) { + mode = StartupExtender.StartMode.TEST_PROFILE; } else { // XXX could also set argLine for COMMAND_TEST and relatives (StartMode.TEST_*); need not be specific to TYPE_JAR return true; --- a/nbbuild/build.xml +++ a/nbbuild/build.xml @@ -914,8 +914,17 @@ - - + + + + + + + + + + + @@ -934,10 +943,11 @@ - - - - + + + + + Must set test.includes + @@ -701,6 +702,8 @@ + + @@ -708,6 +711,8 @@ + + @@ -776,6 +781,7 @@ Must set test.class Must set test.methods + @@ -783,6 +789,7 @@ + @@ -799,16 +806,20 @@ Must set main.class. + + + + @@ -875,7 +886,16 @@ - + + + + + + + + + + @@ -905,6 +925,16 @@ + + + + + + + + + + --- a/profiler.api/src/org/netbeans/modules/profiler/api/project/ProjectProfilingSupport.java +++ a/profiler.api/src/org/netbeans/modules/profiler/api/project/ProjectProfilingSupport.java @@ -41,6 +41,7 @@ */ package org.netbeans.modules.profiler.api.project; +import java.util.Map; import java.util.Properties; import org.netbeans.lib.profiler.common.SessionSettings; import org.netbeans.modules.profiler.api.JavaPlatform; @@ -122,7 +123,7 @@ * @param props properties * @param profiledClassFile profiled file or null for profiling the entire project */ - public void configurePropertiesForProfiling(Properties props, FileObject profiledClassFile) { + public void configurePropertiesForProfiling(Map props, FileObject profiledClassFile) { provider.configurePropertiesForProfiling(props, profiledClassFile); } --- a/profiler.api/src/org/netbeans/modules/profiler/spi/project/ProjectProfilingSupportProvider.java +++ a/profiler.api/src/org/netbeans/modules/profiler/spi/project/ProjectProfilingSupportProvider.java @@ -41,6 +41,7 @@ */ package org.netbeans.modules.profiler.spi.project; +import java.util.Map; import java.util.Properties; import org.netbeans.lib.profiler.common.SessionSettings; import org.netbeans.modules.profiler.api.JavaPlatform; @@ -103,7 +104,7 @@ * @param props properties * @param profiledClassFile profiled file or null for profiling the entire project */ - public abstract void configurePropertiesForProfiling(Properties props, FileObject profiledClassFile); + public abstract void configurePropertiesForProfiling(Map props, FileObject profiledClassFile); /** * Configures project-specific session settings. @@ -175,7 +176,7 @@ } @Override - public void configurePropertiesForProfiling(Properties props, FileObject profiledClassFile) { + public void configurePropertiesForProfiling(Map props, FileObject profiledClassFile) { } @Override --- a/profiler.freeform/nbproject/project.xml +++ a/profiler.freeform/nbproject/project.xml @@ -122,6 +122,15 @@ + org.netbeans.modules.project.ant + + + + 1 + 1.46 + + + org.netbeans.modules.projectapi @@ -154,6 +163,14 @@ 8.0 + + org.openide.util.lookup + + + + 8.12 + + --- a/profiler.freeform/src/org/netbeans/modules/profiler/freeform/FreeFormProjectProfilingSupportProvider.java +++ a/profiler.freeform/src/org/netbeans/modules/profiler/freeform/FreeFormProjectProfilingSupportProvider.java @@ -42,17 +42,20 @@ */ package org.netbeans.modules.profiler.freeform; +import java.util.Map; import org.netbeans.api.project.Project; import org.netbeans.api.project.ProjectUtils; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileUtil; import org.w3c.dom.Element; -import java.util.Properties; +import org.netbeans.modules.ant.freeform.spi.ProjectAccessor; +import org.netbeans.modules.profiler.api.JavaPlatform; import org.netbeans.modules.profiler.api.java.JavaProfilerSource; import org.netbeans.modules.profiler.nbimpl.project.JavaProjectProfilingSupportProvider; import org.netbeans.modules.profiler.nbimpl.project.ProjectUtilities; import org.netbeans.spi.project.LookupProvider.Registration.ProjectType; import org.netbeans.spi.project.ProjectServiceProvider; +import org.netbeans.spi.project.support.ant.EditableProperties; /** * A class providing basic support for profiling free-form projects. @@ -62,6 +65,8 @@ @ProjectServiceProvider(service=org.netbeans.modules.profiler.spi.project.ProjectProfilingSupportProvider.class, projectTypes={@ProjectType(id="org-netbeans-modules-ant-freeform", position=1210)}) // NOI18N public final class FreeFormProjectProfilingSupportProvider extends JavaProjectProfilingSupportProvider { + private static final String NBJDK_PROPERTIES = "nbproject/nbjdk.properties"; // NOI18N + private static final String NBJDK_ACTIVE = "nbjdk.active"; // NOI18N @Override public boolean checkProjectIsModifiedForProfiler() { @@ -85,7 +90,7 @@ } @Override - public void configurePropertiesForProfiling(final Properties props, final FileObject profiledClassFile) { + public void configurePropertiesForProfiling(final Map props, final FileObject profiledClassFile) { if (profiledClassFile != null) { // In case the class to profile is explicitely selected (profile-single) // 1. specify profiled class name @@ -93,19 +98,41 @@ JavaProfilerSource src = JavaProfilerSource.createFrom(profiledClassFile); if (src != null) { final String profiledClass = src.getTopLevelClass().getQualifiedName(); - props.setProperty("profile.class", profiledClass); //NOI18N + props.put("profile.class", profiledClass); //NOI18N // 2. include it in javac.includes so that the compile-single picks it up final String clazz = FileUtil.getRelativePath(ProjectUtilities.getRootOf(ProjectUtilities.getSourceRoots(getProject()), profiledClassFile), profiledClassFile); - props.setProperty("javac.includes", clazz); //NOI18N + props.put("javac.includes", clazz); //NOI18N } } } - + + @Override + public JavaPlatform resolveProjectJavaPlatform() { + ProjectAccessor acc = getProject().getLookup().lookup(ProjectAccessor.class); + EditableProperties ep = acc.getHelper().getProperties(NBJDK_PROPERTIES); + String platformName = ep.getProperty(NBJDK_ACTIVE); + + return getPlatformByName(platformName); + } + + @Override + public boolean isProfilingSupported() { + boolean supported = super.isProfilingSupported(); + if (!supported) return false; + + final String WEB_MODULE_PROVIDER_TYPE = "org.netbeans.modules.web.freeform.WebModules"; + + for(Object x : getProject().getLookup().lookupAll(Object.class)) { + if (WEB_MODULE_PROVIDER_TYPE.equals(x.getClass().getName())) { + return false; // web freeforms are not supported + } + } + return true; + } public FreeFormProjectProfilingSupportProvider(Project project) { super(project); } - } --- a/profiler.j2ee/src/org/netbeans/modules/profiler/j2ee/J2EEProjectProfilingSupportProvider.java +++ a/profiler.j2ee/src/org/netbeans/modules/profiler/j2ee/J2EEProjectProfilingSupportProvider.java @@ -76,6 +76,7 @@ import org.netbeans.modules.profiler.api.JavaPlatform; import org.netbeans.modules.profiler.api.java.JavaProfilerSource; import org.netbeans.modules.profiler.api.ProfilerDialogs; +import org.netbeans.modules.profiler.nbimpl.actions.ProfilerLauncher; import org.netbeans.modules.profiler.nbimpl.project.JavaProjectProfilingSupportProvider; import org.netbeans.modules.profiler.nbimpl.project.ProjectUtilities; import org.netbeans.spi.project.LookupProvider.Registration.ProjectType; @@ -198,7 +199,7 @@ // --- ProjectTypeProfiler implementation ------------------------------------------------------------------------------ @Override - public JavaPlatform getProjectJavaPlatform() { + public JavaPlatform resolveProjectJavaPlatform() { String serverInstanceID = getServerInstanceID(getProject()); if (serverInstanceID == null) { @@ -265,42 +266,42 @@ } @Override - public void configurePropertiesForProfiling(final Properties props, final FileObject profiledClassFile) { + public void configurePropertiesForProfiling(final Map props, final FileObject profiledClassFile) { Project project = getProject(); initAntPlatform(project, props); // set forceRestart - props.setProperty("profiler.j2ee.serverForceRestart", "true"); // NOI18N + props.put("profiler.j2ee.serverForceRestart", "true"); // NOI18N // set timeout - props.setProperty("profiler.j2ee.serverStartupTimeout", "300000"); // NOI18N + props.put("profiler.j2ee.serverStartupTimeout", "300000"); // NOI18N // set agent id - props.setProperty("profiler.j2ee.agentID", "-Dnbprofiler.agentid=" + new Integer(generateAgentID()).toString()); // NOI18N // sets lastAgentID + props.put("profiler.j2ee.agentID", "-Dnbprofiler.agentid=" + new Integer(generateAgentID()).toString()); // NOI18N // sets lastAgentID // redirect profiler.info.jvmargs to profiler.info.jvmargs.extra // NOTE: disabled as a workaround for Issue 102323, needs to be fixed in order to restore the OOME detection functionality! - String jvmArgs = props.getProperty("profiler.info.jvmargs"); // NOI18N + String jvmArgs = props.get("profiler.info.jvmargs"); // NOI18N if ((jvmArgs != null) && (jvmArgs.trim().length() > 0)) { - props.setProperty("profiler.info.jvmargs.extra", jvmArgs); + props.put("profiler.info.jvmargs.extra", jvmArgs); } // fix agent startup arguments JavaPlatform javaPlatform = getJavaPlatformFromAntName(project, props); - props.setProperty("profiler.info.javaPlatform", javaPlatform.getPlatformId()); // set the used platform ant property + props.put("profiler.java.platform", javaPlatform.getPlatformId()); // set the used platform ant property String javaVersion = javaPlatform.getPlatformJDKVersion(); String localPlatform = IntegrationUtils.getLocalPlatform(javaPlatform.getPlatformArchitecture()); if (javaVersion.equals(CommonConstants.JDK_15_STRING)) { // JDK 1.5 used - props.setProperty("profiler.info.jvmargs.agent", // NOI18N + props.put("profiler.info.jvmargs.agent", // NOI18N IntegrationUtils.getProfilerAgentCommandLineArgs(localPlatform, IntegrationUtils.PLATFORM_JAVA_50, false, ProfilerIDESettings.getInstance().getPortNo())); } else { // JDK 1.6 or later used - props.setProperty("profiler.info.jvmargs.agent", // NOI18N + props.put("profiler.info.jvmargs.agent", // NOI18N IntegrationUtils.getProfilerAgentCommandLineArgs(localPlatform, IntegrationUtils.PLATFORM_JAVA_60, false, ProfilerIDESettings.getInstance().getPortNo())); @@ -310,7 +311,7 @@ String loadGenPath = LoadGenPanel.hasInstance() ? LoadGenPanel.instance().getSelectedScript() : null; if (loadGenPath != null) { - props.setProperty("profiler.loadgen.path", loadGenPath); // TODO factor out "profiler.loadgen.path" to a constant + props.put("profiler.loadgen.path", loadGenPath); // TODO factor out "profiler.loadgen.path" to a constant } if (profiledClassFile == null) { @@ -359,12 +360,12 @@ JavaProfilerSource src = JavaProfilerSource.createFrom(profiledClassFile); if (src != null) { String profiledClass = src.getTopLevelClass().getQualifiedName(); - props.setProperty("profile.class", profiledClass); //NOI18N + props.put("profile.class", profiledClass); //NOI18N // include it in javac.includes so that the compile-single picks it up final String clazz = FileUtil.getRelativePath(ProjectUtilities.getRootOf( ProjectUtilities.getSourceRoots(project),profiledClassFile), profiledClassFile); - props.setProperty("javac.includes", clazz); //NOI18N + props.put("javac.includes", clazz); //NOI18N } } @@ -422,6 +423,8 @@ FileUtil.toFile(project.getProjectDirectory()).getAbsolutePath()) : ""); // NOI18N ss.setJVMArgs(""); // NOI18N ss.setWorkingDir(""); // NOI18N + + super.setupProjectSessionSettings(ss); } @Override @@ -453,8 +456,8 @@ return Deployment.getDefault().getJ2eePlatform(serverInstanceID); } - private static JavaPlatform getJavaPlatformFromAntName(Project project, Properties props) { - String javaPlatformAntName = props.getProperty("profiler.info.javaPlatform"); // NOI18N + private static JavaPlatform getJavaPlatformFromAntName(Project project, Map props) { + String javaPlatformAntName = props.get("profiler.info.javaPlatform"); // NOI18N if (javaPlatformAntName.equals("default_platform")) { return JavaPlatform.getDefaultPlatform(); @@ -468,22 +471,20 @@ return (int) (Math.random() * (float) Integer.MAX_VALUE); } - private static void initAntPlatform(Project project, Properties props) { - String javaPlatformAntName = props.getProperty("profiler.info.javaPlatform"); // NOI18N + private void initAntPlatform(Project project, Map props) { + String javaPlatformAntName = props.get("profiler.info.javaPlatform"); // NOI18N if (javaPlatformAntName == null) { - JavaPlatform platform = null; - J2eePlatform j2eepf = getJ2eePlatform(project); // try to get the J2EE Platform + JavaPlatform platform = getProjectJavaPlatform(); String platformId; - if (j2eepf == null) { - platformId = JavaPlatform.getDefaultPlatform().getPlatformId(); // no J2EE Platform sepcified; use the IDE default JVM platform + if (platform == null) { + platformId = JavaPlatform.getDefaultPlatform().getPlatformId(); // no Platform sepcified; use the IDE default JVM platform } else { - Map jpprops = j2eepf.getJavaPlatform().getProperties(); // use the J2EE Platform specified JVM platform - platformId = jpprops.get("platform.ant.name"); + platformId = platform.getPlatformId(); } - props.setProperty("profiler.info.javaPlatform", platformId); // set the used platform ant property + props.put("profiler.info.javaPlatform", platformId); // set the used platform ant property } } --- a/profiler.j2ee/src/org/netbeans/modules/profiler/j2ee/impl/ProfilerArgsProvider.java +++ a/profiler.j2ee/src/org/netbeans/modules/profiler/j2ee/impl/ProfilerArgsProvider.java @@ -45,6 +45,7 @@ import java.util.Collections; import java.util.List; import org.netbeans.api.extexecution.startup.StartupExtender.StartMode; +import org.netbeans.api.project.Project; import org.netbeans.api.server.ServerInstance; import org.netbeans.modules.j2ee.deployment.plugins.api.InstanceProperties; import org.netbeans.modules.j2ee.deployment.profiler.spi.Profiler; @@ -57,19 +58,20 @@ */ @StartupExtenderImplementation.Registration(position=100, displayName="#DESC_Profiler", startMode=StartMode.PROFILE) -public class ProfilerArgsProvider implements StartupExtenderImplementation { +public class ServerProfilerArgsProvider implements StartupExtenderImplementation { @Override public List getArguments(Lookup context, StartMode mode) { - Profiler p = Lookup.getDefault().lookup(Profiler.class); - ServerInstance server = context.lookup(ServerInstance.class); - if (server != null) { - InstanceProperties ip = server.getLookup().lookup(InstanceProperties.class); - if (ip != null) { - return Arrays.asList(p.getSettings(ip.getProperty("url"), false).getJvmArgs()); //NOI18N + if (context.lookup(Project.class) == null) { // project related execution is handled elsewhere + Profiler p = Lookup.getDefault().lookup(Profiler.class); + ServerInstance server = context.lookup(ServerInstance.class); + if (server != null) { + InstanceProperties ip = server.getLookup().lookup(InstanceProperties.class); + if (ip != null) { + return Arrays.asList(p.getSettings(ip.getProperty("url"), false).getJvmArgs()); //NOI18N + } } } - return Collections.EMPTY_LIST; } --- a/profiler.j2se/src/org/netbeans/modules/profiler/j2se/J2SEProjectProfilingSupportProvider.java +++ a/profiler.j2se/src/org/netbeans/modules/profiler/j2se/J2SEProjectProfilingSupportProvider.java @@ -44,20 +44,20 @@ package org.netbeans.modules.profiler.j2se; import org.netbeans.api.project.Project; -import org.netbeans.api.project.ProjectManager; import org.netbeans.lib.profiler.common.SessionSettings; import org.netbeans.modules.profiler.projectsupport.utilities.AppletSupport; import org.netbeans.modules.profiler.nbimpl.project.ProjectUtilities; import org.netbeans.spi.project.support.ant.*; -import org.openide.ErrorManager; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileUtil; -import org.openide.modules.InstalledFileLocator; import java.io.*; import java.net.URL; import java.util.Map; import java.util.Properties; +import java.util.logging.Level; +import java.util.logging.Logger; import javax.swing.event.ChangeListener; +import org.netbeans.api.project.ProjectManager; import org.netbeans.modules.profiler.api.JavaPlatform; import org.netbeans.modules.profiler.api.java.JavaProfilerSource; import org.netbeans.modules.profiler.api.java.ProfilerTypeUtils; @@ -65,6 +65,7 @@ import org.netbeans.modules.profiler.spi.project.ProjectProfilingSupportProvider; import org.netbeans.spi.project.LookupProvider.Registration.ProjectType; import org.netbeans.spi.project.ProjectServiceProvider; +import org.openide.modules.InstalledFileLocator; /** @@ -74,7 +75,7 @@ @ProjectServiceProvider(service=ProjectProfilingSupportProvider.class, projectTypes={@ProjectType(id="org-netbeans-modules-java-j2seproject",position=550)}) // NOI18N public class J2SEProjectProfilingSupportProvider extends JavaProjectProfilingSupportProvider { - //~ Inner Classes ------------------------------------------------------------------------------------------------------------ + final private static Logger LOG = Logger.getLogger(J2SEProjectProfilingSupportProvider.class.getName()); private static class MyPropertyProvider implements PropertyProvider { //~ Instance fields ------------------------------------------------------------------------------------------------------ @@ -100,12 +101,6 @@ } } - //~ Static fields/initializers ----------------------------------------------------------------------------------------------- - - // ----- - // I18N String constants // ----- - public static final ErrorManager err = ErrorManager.getDefault().getInstance("org.netbeans.modules.profiler.j2se"); // NOI18N - //~ Instance fields ---------------------------------------------------------------------------------------------------------- private String mainClassSetManually = null; // used for case when the main class is not set in project and user is prompted for it @@ -120,7 +115,7 @@ } @Override - public JavaPlatform getProjectJavaPlatform() { + public JavaPlatform resolveProjectJavaPlatform() { PropertyEvaluator props = getProjectProperties(getProject()); String platformName = props.getProperty("platform.active"); // NOI18N @@ -128,10 +123,6 @@ return null; // not provided for some reason } - if (platformName.equals("default_platform")) { // NOI18N - return JavaPlatform.getDefaultPlatform(); - } - return JavaPlatform.getJavaPlatformById(platformName); } @@ -167,7 +158,7 @@ } @Override - public void configurePropertiesForProfiling(final Properties props, final FileObject profiledClassFile) { + public void configurePropertiesForProfiling(final Map props, final FileObject profiledClassFile) { if (profiledClassFile == null) { if (mainClassSetManually != null) { props.put("main.class", mainClassSetManually); // NOI18N @@ -182,7 +173,7 @@ if (src != null) { Project project = getProject(); if (src.isApplet()) { - String jvmargs = props.getProperty("run.jvmargs"); // NOI18N + String jvmargs = props.get("run.jvmargs"); // NOI18N URL url = null; @@ -198,11 +189,11 @@ AppletSupport.generateSecurityPolicy(project.getProjectDirectory(), buildFolder); if ((jvmargs == null) || (jvmargs.length() == 0)) { - props.setProperty("run.jvmargs", + props.put("run.jvmargs", "-Djava.security.policy=" + FileUtil.toFile(buildFolder).getPath() + File.separator + "applet.policy"); //NOI18N } else { - props.setProperty("run.jvmargs", + props.put("run.jvmargs", jvmargs + " -Djava.security.policy=" + FileUtil.toFile(buildFolder).getPath() + File.separator + "applet.policy"); //NOI18N } @@ -218,16 +209,16 @@ return; // TODO: fail? } - props.setProperty("applet.url", url.toString()); // NOI18N + props.put("applet.url", url.toString()); // NOI18N } else { final String profiledClass = src.getTopLevelClass().getQualifiedName(); - props.setProperty("profile.class", profiledClass); //NOI18N + props.put("profile.class", profiledClass); //NOI18N } // 2. include it in javac.includes so that the compile-single picks it up final String clazz = FileUtil.getRelativePath(ProjectUtilities.getRootOf(ProjectUtilities.getSourceRoots(project), profiledClassFile), profiledClassFile); - props.setProperty("javac.includes", clazz); //NOI18N + props.put("javac.includes", clazz); //NOI18N } } } @@ -252,6 +243,8 @@ String jvmArgs = pp.getProperty("run.jvmargs"); // NOI18N ss.setJVMArgs((jvmArgs != null) ? jvmArgs : ""); // NOI18N + + super.setupProjectSessionSettings(ss); } @Override @@ -294,7 +287,7 @@ is.close(); } } catch (IOException e) { - err.notify(ErrorManager.INFORMATIONAL, e); + LOG.log(Level.INFO, null, e); } } @@ -308,7 +301,7 @@ is.close(); } } catch (IOException e) { - err.notify(ErrorManager.INFORMATIONAL, e); + LOG.log(Level.INFO, null, e); } } @@ -322,7 +315,7 @@ is.close(); } } catch (IOException e) { - err.notify(ErrorManager.INFORMATIONAL, e); + LOG.log(Level.INFO, null, e); } } @@ -352,7 +345,7 @@ is.close(); } } catch (IOException e) { - err.notify(ErrorManager.INFORMATIONAL, e); + LOG.log(Level.INFO, null, e); } } } --- a/profiler.nbimpl/antsrc/org/netbeans/modules/profiler/ant/NBProfileAttachTask.java +++ a/profiler.nbimpl/antsrc/org/netbeans/modules/profiler/ant/NBProfileAttachTask.java @@ -1,159 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright 1997-2010 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]" - * - * Contributor(s): - * The Original Software is NetBeans. The Initial Developer of the Original - * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun - * Microsystems, Inc. All Rights Reserved. - * - * 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. - */ - -package org.netbeans.modules.profiler.ant; - -import org.apache.tools.ant.BuildException; -import org.apache.tools.ant.Project; -import org.apache.tools.ant.Task; -import org.apache.tools.ant.types.Path; -import org.netbeans.api.project.ProjectManager; -import org.netbeans.lib.profiler.common.AttachSettings; -import org.netbeans.lib.profiler.common.Profiler; -import org.netbeans.lib.profiler.common.ProfilingSettings; -import org.netbeans.modules.profiler.NetBeansProfiler; -import org.openide.filesystems.FileObject; -import org.openide.filesystems.FileUtil; -import java.io.File; -import java.io.IOException; -import java.util.Hashtable; -import javax.swing.*; - - -/** Ant task to start the NetBeans profiler attach action. - * - * @author Tomas Hurka - * @author Ian Formanek - */ -public final class NBProfileAttachTask extends Task { - //~ Instance fields ---------------------------------------------------------------------------------------------------------- - - /** Explicit classpath of the profiled process. */ - private Path classpath = null; - private String port = null; - private boolean direct = true; - private boolean directDefinedExplicitely = false; - - //~ Methods ------------------------------------------------------------------------------------------------------------------ - - public void setDirect(final boolean aos) { - this.direct = aos; - directDefinedExplicitely = true; - } - - public void setPort(final String port) { - this.port = port; - } - - // properties ----------------------------------------------------------------- - - /** "classpath" subelements, only one is allowed - * @param path the classpath - */ - public void addClasspath(final Path path) { - if (classpath != null) { - throw new BuildException("Only one classpath subelement is supported"); //NOI18N - } - - classpath = path; - } - - // main methods --------------------------------------------------------------- - public void execute() throws BuildException { - Project antProject = getProject(); - final Hashtable props = antProject.getProperties(); - final ProfilingSettings ps = new ProfilingSettings(); - - // 1. process parameters passed via Properties - ps.load(props); - - final AttachSettings as = new AttachSettings(); - as.load(antProject.getProperties()); - - // 2. Process those passed as attributes/elements from the buildl script - if (directDefinedExplicitely) { - as.setDirect(Boolean.valueOf(direct).booleanValue()); - } - - if (port != null) { - try { - final int portNo = Integer.parseInt(port); - as.setPort(portNo); - } catch (NumberFormatException e) { - } // ignore, will not be used - } - - // 3. log used properties in verbose level - antProject.log("Attaching to Profiled Application", Project.MSG_VERBOSE); //NOI18N - antProject.log(" classpath: " + classpath, Project.MSG_VERBOSE); //NOI18N - antProject.log(" attach direct: " + as.isDirect(), Project.MSG_VERBOSE); //NOI18N - antProject.log(" remote attach: " + as.isRemote(), Project.MSG_VERBOSE); //NOI18N - antProject.log(" remote host: " + as.getHost(), Project.MSG_VERBOSE); //NOI18N - antProject.log(" profiler port: " + as.getPort(), Project.MSG_VERBOSE); //NOI18N - - // 4. log profiling and session settings in debug level - antProject.log(" profiling settings: " + ps.debug(), Project.MSG_DEBUG); //NOI18N - antProject.log(" attach settings: " + as.debug(), Project.MSG_DEBUG); //NOI18N - - // 5. determine project being profiled - org.netbeans.api.project.Project profiledProject = null; - - String projectDir = (String) props.get("profiler.info.project.dir"); //NOI18N - - if (projectDir != null) { - FileObject projectFO = FileUtil.toFileObject(FileUtil.normalizeFile(new File(projectDir))); - - if (projectFO != null) { - try { - profiledProject = ProjectManager.getDefault().findProject(projectFO); - } catch (IOException e) { - antProject.log("Could not determine project: " + e.getMessage(), Project.MSG_WARN); //NOI18N - } - } - } - - // 6. invoke profiling with constructed profiling and attach settings - ((NetBeansProfiler) Profiler.getDefault()).setProfiledProject(profiledProject, null); - Profiler.getDefault().attachToApp(ps, as); - } -} --- a/profiler.nbimpl/antsrc/org/netbeans/modules/profiler/ant/NBProfileDirectTask.java +++ a/profiler.nbimpl/antsrc/org/netbeans/modules/profiler/ant/NBProfileDirectTask.java @@ -1,543 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright 1997-2010 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]" - * - * Contributor(s): - * The Original Software is NetBeans. The Initial Developer of the Original - * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun - * Microsystems, Inc. All Rights Reserved. - * - * 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. - */ - -package org.netbeans.modules.profiler.ant; - -import org.apache.tools.ant.BuildException; -import org.apache.tools.ant.Project; -import org.apache.tools.ant.Task; -import org.apache.tools.ant.types.EnumeratedAttribute; -import org.apache.tools.ant.types.Path; -import org.netbeans.api.project.ProjectManager; -import org.netbeans.lib.profiler.client.ClientUtils; -import org.netbeans.lib.profiler.common.Profiler; -import org.netbeans.lib.profiler.common.ProfilingSettings; -import org.netbeans.lib.profiler.common.SessionSettings; -import org.netbeans.lib.profiler.global.CalibrationDataFileIO; -import org.netbeans.modules.profiler.NetBeansProfiler; -import org.netbeans.modules.profiler.api.ProfilerIDESettings; -import org.netbeans.modules.profiler.ProfilerModule; -import org.netbeans.modules.profiler.actions.JavaPlatformSelector; -import org.netbeans.modules.profiler.actions.ProfilingSupport; -import org.netbeans.modules.profiler.utils.IDEUtils; -import org.openide.filesystems.FileObject; -import org.openide.filesystems.FileUtil; -import org.openide.util.NbBundle; -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.Hashtable; -import java.util.jar.JarEntry; -import java.util.jar.JarFile; -import org.netbeans.modules.profiler.api.JavaPlatform; -import org.netbeans.modules.profiler.api.ProfilerDialogs; -import org.netbeans.modules.profiler.nbimpl.project.ProjectUtilities; - - -/** - * Ant task to start the NetBeans profiler profile action. - *

- * Will put the profiler into listening mode, placing the port number into the "profiler.port" property. - * The target app then should be started through the profiler agent passing it this port number. - * - * @author Tomas Hurka - * @author Ian Formanek - */ -public final class NBProfileDirectTask extends Task { - //~ Inner Classes ------------------------------------------------------------------------------------------------------------ - - /** - * Enumerated attribute with the values "asis", "add" and "remove". - */ - public static class YesNoAuto extends EnumeratedAttribute { - //~ Methods -------------------------------------------------------------------------------------------------------------- - - public String[] getValues() { - return new String[] { "yes", "true", "no", "false", "auto" }; //NOI18N - } - } - - //~ Static fields/initializers ----------------------------------------------------------------------------------------------- - - // ----- - // I18N String constants - private static final String CALIBRATION_FAILED_MESSAGE = NbBundle.getMessage(ProfilerModule.class, - "ProfilerModule_CalibrationFailedMessage"); //NOI18N - // ----- - private static final int INTERACTIVE_AUTO = 0; - private static final int INTERACTIVE_YES = 1; - private static final int INTERACTIVE_NO = 2; - private static final String DEFAULT_AGENT_JVMARGS_PROPERTY = "profiler.info.jvmargs.agent"; // NOI18N - private static final String DEFAULT_JVM_PROPERTY = "profiler.info.jvm"; // NOI18N - private static final String EXTRA_JVM_ARGS = "profiler.info.jvmargs"; // NOI18N - private static final String EXTRA_RUN_ARGS = "run.args.extra"; // NOI18N - - //~ Instance fields ---------------------------------------------------------------------------------------------------------- - - /** - * Explicit classpath of the profiled process. - */ - private Path classpath = null; - private Path rootsPath = null; - private String jvmArgsPrefix = ""; // NOI18N - private String jvmArgsProperty = DEFAULT_AGENT_JVMARGS_PROPERTY; - private String jvmProperty = DEFAULT_JVM_PROPERTY; - private String mainClass = null; - private int interactive = INTERACTIVE_AUTO; - - //~ Methods ------------------------------------------------------------------------------------------------------------------ - - public void setInteractive(YesNoAuto arg) { - String value = arg.getValue(); - - if (value.equals("auto")) { //NOI18N - interactive = INTERACTIVE_AUTO; - } else if (value.equals("yes") || value.equals("true")) { // NOI18N - interactive = INTERACTIVE_YES; - } else if (value.equals("no") || value.equals("false")) { // NOI18N - interactive = INTERACTIVE_NO; - } - } - - public void setJvmArgsPrefix(String value) { - jvmArgsPrefix = value; - } - - public void setJvmArgsProperty(String value) { - jvmArgsProperty = value; - } - - public void setJvmProperty(String value) { - jvmProperty = value; - } - - // -- Properties ------------------------------------------------------------------------------------------------------- - public void setMainClass(String mainClass) { - this.mainClass = mainClass; - } - - /** - * "classpath" subelements, only one is allowed - * - * @param path the classpath - */ - public void addClasspath(final Path path) { - if (classpath != null) { - throw new BuildException("Only one classpath subelement is supported"); //NOI18N - } - - classpath = path; - } - - /** - * "classpath" subelements, only one is allowed - * - * @param path the classpath - */ - public void addRootspath(final Path path) { - if (rootsPath != null) { - throw new BuildException("Only one classpath subelement is supported"); //NOI18N - } - - rootsPath = path; - } - - // -- Main methods ----------------------------------------------------------------------------------------------------- - public void execute() throws BuildException { - // Settings are created this way: - // 1. project context (stored as properties) - // 2. profiling settings (configuration) - // - possibly override some of the settings from 1. if ps.getOverrideGlobalSettings() is set - // 3. explicitely override anything and everything in the build script - Project antProject = getProject(); - final Hashtable props = antProject.getProperties(); - ProfilingSettings ps = new ProfilingSettings(); - final SessionSettings ss = new SessionSettings(); - String projectDir = (String) props.get("profiler.info.project.dir"); //NOI18N - String singleFile = (String) props.get("profiler.info.single.file"); //NOI18N - - boolean initializedInteractively = false; - - if ((props.get(DEFAULT_AGENT_JVMARGS_PROPERTY) == null) || (interactive == INTERACTIVE_YES)) { - if (interactive != INTERACTIVE_NO) { - projectDir = initializeInteractively(ps, ss); - initializedInteractively = true; - } - } - - if (!initializedInteractively) { - if (props.get(DEFAULT_AGENT_JVMARGS_PROPERTY) == null) { - throw new BuildException("Missing context for nbprofiledirect task.\n" //NOI18N - + "Please set the \"interactive\" attribute to \"true\" or set the required properties." //NOI18N - ); - } - - if (!DEFAULT_AGENT_JVMARGS_PROPERTY.equals(jvmArgsProperty) || !"".equals(jvmArgsPrefix)) { //NOI18N - - String args = " " + (String) props.get(EXTRA_JVM_ARGS); // get the extra JVM args - // reformat the string to the form suitable for starting the NB platform - - args = args.replaceAll("\\s+(\\-)", " -J$1"); // NOI18N - - String origArgs = antProject.getProperty(EXTRA_RUN_ARGS); - origArgs = (origArgs != null) ? (" " + origArgs + " ") : ""; // NOI18N - - antProject.setProperty("run.args.extra", origArgs + args); // merge the profiler extra JVM args with the platform extra JVM args - - String usedAgentJvmArgs = jvmArgsPrefix + props.get(DEFAULT_AGENT_JVMARGS_PROPERTY); - antProject.setProperty(jvmArgsProperty, usedAgentJvmArgs); - antProject.log("Profiler agent JVM arguments: " + usedAgentJvmArgs, Project.MSG_VERBOSE); //NOI18N - antProject.log("Profiler agent JVM arguments stored in property " + jvmArgsProperty, Project.MSG_INFO); //NOI18N - antProject.log("Extra JVM arguments: " + antProject.getProperty("run.args.extra")); // NOI18N - } - - // 2. process parameters passed via Properties - ps.load(props); - try { - ss.load(props); - } catch (IllegalArgumentException e) { - ProfilerDialogs.displayWarning(e.getLocalizedMessage()); - } - - // get correct working directory available only at runtime (not from ProjectTypeProfiler!) - String projectWorkDir = (String) props.get("work.dir"); // NOI18N - ss.setWorkingDir(((projectWorkDir != null) && !"".equals(projectWorkDir.trim())) ? projectWorkDir - : System.getProperty("user.dir")); // NOI18N - } - - // Correctly setup working directory - String profilerInfoDir = (String) props.get("profiler.info.dir"); // NOI18N - - if (!initializedInteractively || (profilerInfoDir == null /* means that WD wasn't set in interactive setup */) - || !"".equals(profilerInfoDir.trim())) { // NOI18N - - String workingDirectory = ss.getWorkingDir(); - - if (ps.getOverrideGlobalSettings()) { - String overridenWorkingDirectory = ps.getWorkingDir(); - - if ((overridenWorkingDirectory != null) && !"".equals(overridenWorkingDirectory.trim())) { - workingDirectory = overridenWorkingDirectory; // NOI18N - } - } - - antProject.setProperty("profiler.info.dir", workingDirectory); // NOI18N - } - - if (classpath != null) { - ss.setMainClassPath(classpath.toString()); - } - - if (ps.getProfilingType() == ProfilingSettings.PROFILE_CPU_ENTIRE) { - antProject.log("Roots path: " + rootsPath, Project.MSG_VERBOSE); //NOI18N - - if (rootsPath != null) { - String[] paths = rootsPath.list(); - ArrayList al = new ArrayList(); - - for (int i = 0; i < paths.length; i++) { - addPackagesList(al, paths[i]); - } - - ClientUtils.SourceCodeSelection[] ret = new ClientUtils.SourceCodeSelection[al.size()]; - - for (int i = 0; i < al.size(); i++) { - if ("".equals(al.get(i))) { //NOI18N - ret[i] = new ClientUtils.SourceCodeSelection("", "", ""); //NOI18N - } else { - ret[i] = new ClientUtils.SourceCodeSelection(((String) al.get(i)) + ".", "", ""); //NOI18N - } - } - - ps.setInstrumentationRootMethods(ret); - } - } - - // 3. log used properties in verbose level - antProject.log("Starting Profiled Application", Project.MSG_VERBOSE); //NOI18N - antProject.log(" mainClass: " + ss.getMainClass(), Project.MSG_VERBOSE); //NOI18N - antProject.log(" classpath: " + ss.getMainClassPath(), Project.MSG_VERBOSE); //NOI18N - antProject.log(" arguments: " + ss.getMainArgs(), Project.MSG_VERBOSE); //NOI18N - - if (ps.getOverrideGlobalSettings()) { - antProject.log(" jvm arguments: " + ps.getJVMArgs(), Project.MSG_VERBOSE); //NOI18N - } else { - antProject.log(" jvm arguments: " + ss.getJVMArgs(), Project.MSG_VERBOSE); //NOI18N - } - - if (ps.getOverrideGlobalSettings()) { - antProject.log(" working dir: " + ps.getWorkingDir(), Project.MSG_VERBOSE); //NOI18N - } else { - antProject.log(" working dir: " + ss.getWorkingDir(), Project.MSG_VERBOSE); //NOI18N - } - - // 4. log profiling and session settings in debug level - antProject.log(" profiling settings: " + ps.debug(), Project.MSG_DEBUG); //NOI18N - antProject.log(" session settings: " + ss.debug(), Project.MSG_DEBUG); //NOI18N - - // 5. determine project being profiled - org.netbeans.api.project.Project profiledProject = null; - FileObject singleFO = null; - - if (projectDir != null) { - String errorMessage = null; - FileObject projectFO = FileUtil.toFileObject(FileUtil.normalizeFile(new File(projectDir))); - - if (projectFO != null) { - try { - profiledProject = ProjectManager.getDefault().findProject(projectFO); - } catch (IOException e) { - errorMessage = "IOException: " + e.getMessage(); //NOI18N - } - } else { - errorMessage = "Could not find project directory: " + projectDir; //NOI18N - } - - if (errorMessage != null) { - antProject.log("Could not determine project: " + errorMessage, Project.MSG_INFO); //NOI18N - antProject.log("Using global (no project) attach context", Project.MSG_INFO); //NOI18N - } - - if (singleFile != null) { - singleFO = FileUtil.toFileObject(FileUtil.normalizeFile(new File(singleFile))); - } - } else { - antProject.log("You can use property profiler.info.project.dir to specify project that is being profiled.", //NOI18N - Project.MSG_VERBOSE); - } - - final org.netbeans.api.project.Project projectToUse = profiledProject; - - if (!CalibrationDataFileIO.validateCalibrationInput(ss.getJavaVersionString(), ss.getJavaExecutable()) - || !Profiler.getDefault() - .runCalibration(true, ss.getJavaExecutable(), ss.getJavaVersionString(), - ss.getSystemArchitecture())) { - ProfilerDialogs.displayError(CALIBRATION_FAILED_MESSAGE); - throw new BuildException(CALIBRATION_FAILED_MESSAGE); // failed, cannot proceed - } - - // 6. invoke profiling with constructed profiling and session settings - final ProfilingSettings ps1 = ps; - final FileObject singleFO1 = singleFO; - - NetBeansProfiler.getDefaultNB().setProfiledProject(projectToUse, singleFO1); - Profiler.getDefault().connectToStartedApp(ps1, ss); - } - - private void addPackagesForArchive(ArrayList list, String s, File f) { - Project antProject = getProject(); - - antProject.log("Add root packages for archive: " + f.getName(), Project.MSG_VERBOSE); //NOI18N - try { - JarFile jf = new JarFile(f); - - for (Enumeration e = jf.entries(); e.hasMoreElements();) { - JarEntry je = (JarEntry) e.nextElement(); - antProject.log("Checking jar entry: " + je.getName(), Project.MSG_VERBOSE); //NOI18N - - if (!je.isDirectory() && je.getName().endsWith(".class")) { //NOI18N - - String name = je.getName(); - int idx = name.lastIndexOf('/'); //NOI18N - String packageName = (idx == -1) ? name : name.substring(0, idx); - packageName = packageName.replace('/', '.'); //NOI18N - - if (!list.contains(packageName)) { - antProject.log("Adding package: " + packageName, Project.MSG_VERBOSE); //NOI18N - list.add(packageName); - } - } - } - } catch (IOException e) { - antProject.log("Failed to scan packages for archive: " + f.getName()); //NOI18N - } - } - - private void addPackagesForDirectory(ArrayList packages, String prefix, File f) { - if (!f.isDirectory()) { // not a folder - - return; - } - - getProject().log("Add root packages for directory: " + f.getName(), Project.MSG_VERBOSE); //NOI18N - - File[] children = f.listFiles(); - - // 1. check if there are java sdources in this folder and if so, add to the list of packages - if (!packages.contains(prefix)) { // already in there, skip this - - for (int i = 0; i < children.length; i++) { - File child = children[i]; - - if (child.getName().endsWith(".class")) { //NOI18N - getProject().log("Addding package: " + prefix, Project.MSG_VERBOSE); //NOI18N - packages.add(prefix); - - break; - } - } - } - - // 2. recurse into subfolders - for (int i = 0; i < children.length; i++) { - File child = children[i]; - - if (child.isDirectory()) { - if ("".equals(prefix)) { //NOI18N - addPackagesForDirectory(packages, child.getName(), child); - } else { - addPackagesForDirectory(packages, prefix + "." + child.getName(), child); //NOI18N - } - } - } - } - - private void addPackagesList(ArrayList list, String path) - throws BuildException { - File f = new File(path); - - if (!f.exists()) { - getProject().log("Cannot find: " + path); //NOI18N - - return; - } - - if (f.isDirectory()) { - addPackagesForDirectory(list, "", f); //NOI18N - } else if (f.getName().endsWith(".jar")) { //NOI18N - addPackagesForArchive(list, "", f); //NOI18N - } - } - - private String initializeInteractively(ProfilingSettings ps, SessionSettings ss) - throws BuildException { - String projectDir = null; - Project antProject = getProject(); - antProject.log("Entering interactive mode of nbprofiledirect task...", Project.MSG_VERBOSE); //NOI18N - - org.netbeans.api.project.Project p = ProjectUtilities.getProjectForBuildScript(getLocation().getFileName()); - - if (p != null) { - antProject.log("Using project: " + ProjectUtilities.getProjectName(p), Project.MSG_INFO); //NOI18N - projectDir = FileUtil.toFile(p.getProjectDirectory()).getAbsolutePath(); - } - - ss.setPortNo(ProfilerIDESettings.getInstance().getPortNo()); - - if (mainClass != null) { - ss.setMainClass(mainClass); - } - - JavaPlatform platform = JavaPlatform.getJavaPlatformById(ProfilerIDESettings.getInstance().getJavaPlatformForProfiling()); - - if (platform == null) { - platform = JavaPlatformSelector.getDefault().selectPlatformToUse(); - - if (platform == null) { - throw new BuildException("Cancelled..."); //NOI18N - } - } - - String javaFile = platform.getPlatformJavaFile(); - - if (javaFile == null) { - throw new BuildException("Cannot determine Java executable for platform: " + platform.getDisplayName()); //NOI18N - } - - String javaVersion = platform.getPlatformJDKVersion(); - - if (javaVersion == null) { - throw new BuildException("Cannot determine Java version for the selected Java platform"); //NOI18N - } - - ss.setJavaExecutable(javaFile); - ss.setJavaVersionString(javaVersion); - ss.setSystemArchitecture(platform.getPlatformArchitecture()); - - ps = ProfilingSupport.getDefault().selectTaskForProfiling(p, ss, null, false); - - if (ps == null) { - throw new BuildException("Cancelled by the user"); //NOI18N - } - - String usedJavaExecutable = null; - String usedJvmArgs = null; - String usedWorkDir = null; - - if (ps.getOverrideGlobalSettings()) { - antProject.log("Global settings are overridden by the profiling configuration", Project.MSG_VERBOSE); //NOI18N - - if (ps.getJavaPlatformName() != null) { - usedJavaExecutable = Profiler.getDefault().getPlatformJavaFile(ps.getJavaPlatformName()); - } - - usedJvmArgs = ps.getJVMArgs(); - usedWorkDir = ps.getWorkingDir(); - - if (usedJavaExecutable != null) { - antProject.log("Overridden Java Executable: " + usedJavaExecutable //NOI18N - + ", stored in property: " + jvmProperty, Project.MSG_VERBOSE //NOI18N - ); - antProject.setProperty(jvmProperty, usedJavaExecutable); - } - - if (usedJvmArgs != null) { - antProject.log("Overridden Working Directory: " + usedWorkDir, Project.MSG_VERBOSE); //NOI18N - antProject.setProperty("profiler.info.jvmargs", usedJvmArgs); // NOI18N - } - - if (usedWorkDir != null) { - antProject.setProperty("profiler.info.dir", usedWorkDir); // NOI18N - } - } - - String usedAgentJvmArgs = jvmArgsPrefix - + IDEUtils.getAntProfilerStartArgument15(ss.getPortNo(), ss.getSystemArchitecture()); - antProject.setProperty(jvmArgsProperty, usedAgentJvmArgs); // NOI18N - antProject.log("Profiler agent JVM arguments: " + usedAgentJvmArgs, Project.MSG_VERBOSE); //NOI18N - antProject.log("Profiler agent JVM arguments stored in property " + jvmArgsProperty, Project.MSG_INFO); //NOI18N - - return projectDir; - } -} --- a/profiler.nbimpl/antsrc/org/netbeans/modules/profiler/nbimpl/StartProfilerTask.java +++ a/profiler.nbimpl/antsrc/org/netbeans/modules/profiler/nbimpl/StartProfilerTask.java @@ -0,0 +1,96 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright 2012 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 2012 Sun Microsystems, Inc. + */ +package org.netbeans.modules.profiler.nbimpl; + +import java.io.File; +import java.util.Map; +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.Task; +import org.netbeans.api.project.FileOwnerQuery; +import org.netbeans.api.project.Project; +import org.netbeans.lib.profiler.common.Profiler; +import org.netbeans.modules.profiler.nbimpl.actions.ProfilerLauncher; +import org.openide.filesystems.FileUtil; + +/** + * + * @author Jaroslav Bachorik + */ +public class StartProfilerTask extends Task { + private String freeformStr = ""; + private boolean isFreeForm = false; + + @Override + public void execute() throws BuildException { + ProfilerLauncher.Session s = ProfilerLauncher.getLastSession(); + if (s == null && isFreeForm) { + File baseDir = getProject().getBaseDir(); + if (baseDir != null) { + Project p = FileOwnerQuery.getOwner(FileUtil.toFileObject(baseDir)); + if (p != null) { + s = ProfilerLauncher.Session.createSession(p); + } + } + + } + if (s != null) { + Map props = s.getProperties(); + if (props != null) { + for(Map.Entry e : props.entrySet()) { + getProject().setProperty(e.getKey(), e.getValue()); + } + NetBeansProfiler.getDefaultNB().setupDispatcher(s.getProfilingSettings()); + Profiler.getDefault().connectToStartedApp(s.getProfilingSettings(), s.getSessionSettings()); + getProject().setProperty("profiler.configured", "true"); // NOI18N + } + } + } + + public void setFreeform(String val) { + freeformStr = val; + isFreeForm = Boolean.parseBoolean(val); + } + + public String getFreeform() { + return freeformStr; + } +} --- a/profiler.nbimpl/antsrc/org/netbeans/modules/profiler/nbimpl/antlib.xml +++ a/profiler.nbimpl/antsrc/org/netbeans/modules/profiler/nbimpl/antlib.xml @@ -2,7 +2,7 @@ - - + --- a/profiler.nbimpl/manifest.mf +++ a/profiler.nbimpl/manifest.mf @@ -3,5 +3,5 @@ OpenIDE-Module: org.netbeans.modules.profiler.nbimpl/1 OpenIDE-Module-Layer: org/netbeans/modules/profiler/nbimpl/layer.xml OpenIDE-Module-Localizing-Bundle: org/netbeans/modules/profiler/nbimpl/Bundle.properties -OpenIDE-Module-Provides: org.netbeans.lib.profiler.common.Profiler +OpenIDE-Module-Provides: org.netbeans.lib.profiler.common.Profiler,org.netbeans.api.profiler OpenIDE-Module-Specification-Version: 1.2 --- a/profiler.nbimpl/nbproject/project.xml +++ a/profiler.nbimpl/nbproject/project.xml @@ -59,6 +59,15 @@ + org.netbeans.api.annotations.common + + + + 1 + 1.13 + + + org.netbeans.api.java.classpath @@ -68,6 +77,15 @@ + org.netbeans.api.progress + + + + 1 + 1.27 + + + org.netbeans.lib.profiler @@ -130,6 +148,15 @@ + org.netbeans.modules.extexecution + + + + 2 + 1.30 + + + org.netbeans.modules.java.platform @@ -426,6 +453,7 @@ org.netbeans.modules.profiler.j2ee org.netbeans.modules.profiler.j2se org.netbeans.modules.profiler.nbmodule + org.netbeans.modules.profiler.nbimpl.actions org.netbeans.modules.profiler.nbimpl.javac org.netbeans.modules.profiler.nbimpl.project --- a/profiler.nbimpl/src/org/netbeans/modules/profiler/nbimpl/NetBeansProfiler.java +++ a/profiler.nbimpl/src/org/netbeans/modules/profiler/nbimpl/NetBeansProfiler.java @@ -50,6 +50,7 @@ import org.netbeans.lib.profiler.common.ProfilingSettings; import org.netbeans.modules.profiler.HeapDumpWatch; import org.netbeans.modules.profiler.ProfilerModule; +import org.netbeans.modules.profiler.nbimpl.actions.ProfilerLauncher; import org.netbeans.modules.profiler.spi.LoadGenPlugin; import org.openide.execution.ExecutorTask; import org.openide.filesystems.FileObject; @@ -72,6 +73,14 @@ doRunTarget(buildScriptFO, target, props); } + + public void notifyRunTarget(FileObject buildXml, String target) { + getActionSupport().setAll(buildXml, target, null); + } + + public void storeProfilingProperties(Properties props) { + getActionSupport().setProperties(props); + } /** * Runs an target in Ant script with properties context. @@ -114,19 +123,19 @@ @Override public boolean rerunAvailable() { int state = getProfilingState(); - return (state == Profiler.PROFILING_INACTIVE || state == Profiler.PROFILING_STOPPED) ? getActionSupport().isActionAvailable() : false; + return (state == Profiler.PROFILING_INACTIVE || state == Profiler.PROFILING_STOPPED) ? ProfilerLauncher.canRelaunch() : false; } @Override public boolean modifyAvailable() { - return getProfilingMode()==MODE_ATTACH || getActionSupport().isActionAvailable(); + return getProfilingState() == Profiler.PROFILING_RUNNING; } @Override public void rerunLastProfiling() { - String target = getActionSupport().getTarget(); - if (target!=null) { - doRunTarget(getActionSupport().getScript(), target, getActionSupport().getProperties()); + ProfilerLauncher.Session s = ProfilerLauncher.getLastSession(); + if (s != null) { + s.run(); } } --- a/profiler.nbimpl/src/org/netbeans/modules/profiler/nbimpl/ProfilerControlPanel2Support.java +++ a/profiler.nbimpl/src/org/netbeans/modules/profiler/nbimpl/ProfilerControlPanel2Support.java @@ -82,6 +82,12 @@ this.properties = properties; registerListener(); } + + void setProperties(Properties p) { + if (this.script != null) { + this.properties = p; + } + } FileObject getScript() { return script; --- a/profiler.nbimpl/src/org/netbeans/modules/profiler/nbimpl/actions/AntActions.java +++ a/profiler.nbimpl/src/org/netbeans/modules/profiler/nbimpl/actions/AntActions.java @@ -1,7 +1,7 @@ /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * - * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved. + * 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. @@ -24,11 +24,6 @@ * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * - * Contributor(s): - * The Original Software is NetBeans. The Initial Developer of the Original - * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun - * Microsystems, Inc. All Rights Reserved. - * * 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 @@ -39,772 +34,148 @@ * 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.profiler.nbimpl.actions; +import javax.swing.Action; import org.netbeans.api.project.Project; -import org.netbeans.api.project.ProjectUtils; -import org.netbeans.api.project.ui.OpenProjects; import org.netbeans.lib.profiler.ProfilerLogger; -import org.netbeans.lib.profiler.common.Profiler; -import org.netbeans.lib.profiler.common.ProfilingSettings; -import org.netbeans.lib.profiler.common.SessionSettings; -import org.netbeans.lib.profiler.global.CommonConstants; -import org.netbeans.lib.profiler.utils.MiscUtils; import org.netbeans.modules.profiler.NetBeansProfiler; -import org.netbeans.modules.profiler.api.ProfilerIDESettings; -import org.netbeans.modules.profiler.utils.IDEUtils; + +import org.netbeans.modules.profiler.api.icons.Icons; +import org.netbeans.modules.profiler.api.icons.ProfilerIcons; +import org.netbeans.modules.profiler.api.project.ProjectProfilingSupport; +import org.netbeans.spi.project.ActionProvider; +import org.netbeans.spi.project.ui.support.FileSensitiveActions; import org.netbeans.spi.project.ui.support.MainProjectSensitiveActions; import org.netbeans.spi.project.ui.support.ProjectActionPerformer; -import org.openide.ErrorManager; -import org.openide.filesystems.FileObject; -import org.openide.filesystems.FileUtil; -import org.openide.util.Lookup; +import org.netbeans.spi.project.ui.support.ProjectSensitiveActions; +import org.openide.awt.ActionID; +import org.openide.awt.ActionReference; +import org.openide.awt.ActionReferences; +import org.openide.awt.ActionRegistration; import org.openide.util.NbBundle; -import org.openide.util.RequestProcessor; -import java.io.IOException; -import java.text.MessageFormat; -import java.util.Properties; -import javax.swing.Action; -import org.netbeans.api.java.source.ui.ScanDialog; -import org.netbeans.lib.profiler.common.CommonUtils; -import org.netbeans.lib.profiler.global.Platform; -import org.netbeans.modules.profiler.HeapDumpWatch; -import org.netbeans.modules.profiler.actions.JavaPlatformSelector; -import org.netbeans.modules.profiler.actions.ProfilingSupport; -import org.netbeans.modules.profiler.api.icons.Icons; -import org.netbeans.modules.profiler.api.JavaPlatform; -import org.netbeans.modules.profiler.api.java.JavaProfilerSource; -import org.netbeans.modules.profiler.api.ProfilerDialogs; -import org.netbeans.modules.profiler.api.icons.ProfilerIcons; -import org.netbeans.modules.profiler.api.project.ProjectStorage; -import org.netbeans.modules.profiler.api.project.AntProjectSupport; -import org.netbeans.modules.profiler.api.project.ProjectProfilingSupport; -import org.netbeans.modules.profiler.projectsupport.utilities.ProjectUtilities; - +import org.openide.util.NbBundle.Messages; /** - * 4.0 Ant-style actions * - * @author Tomas Hurka - * @author Ian Formanek + * @author Jaroslav Bachorik */ -@NbBundle.Messages({ - "AntActions_FileTestNotFoundMsg=Test for the file does not exist.", - "AntActions_FailedDetermineJavaPlatformMsg=Failed to determine version of Java platform: {0}", - "AntActions_FailedDetermineProjectBuildScriptMsg=Cannot determine build script for project {0}", - "AntActions_IncorrectJavaSpecVersionDialogCaption=Warning", - "AntActions_IncorrectJavaSpecVersionDialogMsg=The specification version of project Java Platform is greater than specification version of the\nplatform that will be used for profiling. You may experience problems unless you set the compiler\nparameter to generate bytecode compatible with the platform that will be used.\n\nDo you want to continue with the current settings?", - "AntActions_UnsupportedProjectTypeMsg=Profiling this project type is not supported.", - "AntActions_InvalidJavaplatformMsg=Failed to determine overridden platform: {0}", - "AntActions_InvalidPlatformProjectMsg=The Java platform defined for the project is invalid. Right-click the project\nand choose a different platform using Properties | Libraries | Java Platform.\n\nInvalid platform: {0}", - "AntActions_InvalidPlatformProfilerMsg=The Java platform defined for profiling is invalid. Choose a different platform\nin Tools | Options | Miscellaneous | Profiler | Profiler Java Platform.\n\nInvalid platform: {0}", - "AntActions_LazyEnablementFailure=Unable to start profiling.

Please, make sure the project type is supported

and/or the selected file can be executed.", - "AntActions_LazyEnablementProgressMessage=Validating profiler action" -}) -public final class AntActions { - private static final String LINUX_THREAD_TIMER_KEY = "-XX:+UseLinuxPosixThreadCPUClocks"; // NOI18N - //~ Constructors ------------------------------------------------------------------------------------------------------------- - - /** Default constructor to avoid creating instances */ - private AntActions() { +public class AntActions { + @ActionID(category="Profile", id="org.netbeans.modules.profiler.actions.ProfileMainProject") + @ActionRegistration(displayName="Profile Main Project", lazy=false) + @ActionReferences({ + @ActionReference(path="Menu/Profile", position=100), + @ActionReference(path="Shortcuts", name="A-F2") + }) + public static Action profileMainProjectAction() { + final Action delegate = MainProjectSensitiveActions.mainProjectSensitiveAction( + new ProjectSensitivePerformer(ActionProvider.COMMAND_PROFILE), + NbBundle.getMessage(AntActions.class, "LBL_ProfileMainProjectAction"), // NOI18N + Icons.getIcon(ProfilerIcons.PROFILE) + ); + delegate.putValue(Action.SHORT_DESCRIPTION, NbBundle.getMessage(AntActions.class, "HINT_ProfileMainProjectAction")); // NOI18N + + return delegate; } - - //~ Methods ------------------------------------------------------------------------------------------------------------------ - - /** - * @return An Action to invoke profiling of the main project in the IDE - */ - public static Action profileMainProject() { - final Action a = MainProjectSensitiveActions.mainProjectSensitiveAction(new ProjectActionPerformer() { - public boolean enable(final Project project) { - // Check if the Profiler is initialized correctly - if (!NetBeansProfiler.isInitialized()) { - return false; - } - - // No projects opened => disable action - if (OpenProjects.getDefault().getOpenProjects().length == 0) { - return false; - } - - // No main project set => enable action (see Issue 116619) - if (project == null) { - return true; - } - - // Check if project type is supported, eventually return null - return org.netbeans.modules.profiler.nbimpl.project.ProjectUtilities.isProjectTypeSupported(project); + + @ActionID(category="Profile", id="org.netbeans.modules.profiler.actions.ProfileProjectPopup") + @ActionRegistration(displayName="Profile", lazy=false, asynchronous=true) + @ActionReferences({ + @ActionReference(path="Projects/org-netbeans-modules-java-j2seproject/Actions", position=1000), + @ActionReference(path="Projects/org-netbeans-modules-apisupport-project/Actions", position=900), + @ActionReference(path="Projects/org-netbeans-modules-apisupport-project-suite/Actions", position=1000), + @ActionReference(path="Projects/org-netbeans-modules-web-project/Actions", position=1000) + }) + public static Action profileProjectPopup() { + Action delegate = ProjectSensitiveActions.projectSensitiveAction( + new ProjectSensitivePerformer(ActionProvider.COMMAND_PROFILE), + NbBundle.getMessage(AntActions.class, "LBL_ProfileProject"), // NOI18N + null + ); + + return delegate; + } + + @ActionID(category="Project", id="org.netbeans.modules.apisupport.project.suite.ProfileOsgi") + @ActionRegistration(displayName="#SUITE_ACTION_profile_osgi", asynchronous=true) + @ActionReference(path="Projects/org-netbeans-modules-apisupport-project-suite-osgi/Actions", position=500) + @NbBundle.Messages("SUITE_ACTION_profile_osgi=Profile in Felix") + public static Action profileOsgi() { + Action delegate = ProjectSensitiveActions.projectSensitiveAction( + new ProjectSensitivePerformer("profile-osgi"), + Bundle.SUITE_ACTION_profile_osgi(), + null + ); + + return delegate; + } + + @Messages("LBL_ProfileFile=Profile File") + @ActionID(category="Profile", id="org.netbeans.modules.profiler.actions.ProfileSingle") + @ActionRegistration(displayName="#LBL_ProfileFile", lazy=false) + @ActionReferences({ + @ActionReference(path="Loaders/text/x-java/Actions", position=1200), + @ActionReference(path="Loaders/text/x-jsp/Actions", position=800), + @ActionReference(path="Menu/Profile", position=110) + }) + public static Action profileSingle() { + Action delegate = FileSensitiveActions.fileSensitiveAction( + new FileSensitivePerformer(ActionProvider.COMMAND_PROFILE_SINGLE), + Bundle.LBL_ProfileFile(), + null); + + return delegate; + } + + @Messages("LBL_ProfileTest=Profile Test File") + @ActionID(category = "Profile", id = "org.netbeans.modules.profiler.actions.ProfileTest") + @ActionRegistration(displayName = "#LBL_ProfileTest", lazy=false) + @ActionReferences(value = { + @ActionReference(path = "Loaders/text/x-java/Actions", position = 1280), + @ActionReference(path = "Menu/Profile", position = 120)}) + public static Action profileTest() { + return FileSensitiveActions.fileSensitiveAction( + new FileSensitivePerformer(ActionProvider.COMMAND_PROFILE_TEST_SINGLE), + Bundle.LBL_ProfileTest(), + null); + } + + @ActionID(id = "org.netbeans.modules.profiler.nbimpl.actions.UnintegrateProfilerAction", category = "Profile") + @ActionRegistration(displayName = "#LBL_UnintegrateProfilerAction", lazy=false) + @ActionReference(path = "Menu/Profile/Advanced", position = 500) + public static Action unintegrateProfiler() { + final Action a = ProjectSensitiveActions.projectSensitiveAction(new ProjectActionPerformer() { + @Override + public boolean enable(Project project) { + if (!NetBeansProfiler.isInitialized()) { + return false; } - public void perform(final Project project) { - if (org.netbeans.modules.profiler.nbimpl.project.ProjectUtilities.isProjectTypeSupported(project)) { - doProfileProject(project, null, NbBundle.getMessage(AntActions.class, "LBL_ProfileProject")); - } else { - ProfilerDialogs.displayError(Bundle.AntActions_UnsupportedProjectTypeMsg()); - } - } - }, NbBundle.getMessage(AntActions.class, "LBL_ProfileMainProjectAction"), // NOI18N - null); - a.putValue(Action.SHORT_DESCRIPTION, NbBundle.getMessage(AntActions.class, "HINT_ProfileMainProjectAction" // NOI18N - )); - a.putValue("iconBase", Icons.getResource(ProfilerIcons.PROFILE)); - a.putValue(Action.SMALL_ICON, Icons.getIcon(ProfilerIcons.PROFILE)); - - return a; - } - - /** - * @return An Action to invoke profiling of a selected project in the IDE - */ - public static Action profileProject() { - final Action a = ProjectSensitiveAction.projectSensitiveAction(new ProjectSensitiveAction.ProfilerProjectActionPerformer() { - public boolean enable(final Project project, final Lookup context, final boolean lightweightOnly) { - if (!NetBeansProfiler.isInitialized()) { - return false; - } - - if (project == null) { - return false; - } - - return org.netbeans.modules.profiler.nbimpl.project.ProjectUtilities.isProjectTypeSupported(project); + if (project == null) { + return false; } - public void perform(final Project project, final Lookup context) { - doProfileProject(project, null, NbBundle.getMessage(AntActions.class, "LBL_ProfileProject")); + ProjectProfilingSupport support = ProjectProfilingSupport.get(project); + return support.supportsUnintegrate(); + } + + @Override + public void perform(Project project) { + ProjectProfilingSupport support = ProjectProfilingSupport.get(project); + try { + support.unintegrateProfiler(); + } catch (Exception e) { + ProfilerLogger.log(e); } - }, NbBundle.getMessage(AntActions.class, "LBL_ProfileProjectAction40_General"), // NOI18N - NbBundle.getMessage(AntActions.class, - "LBL_ProfileProjectAction40"), // NOI18N - null); + } + }, NbBundle.getMessage(AntActions.class, "LBL_UnintegrateProfilerAction"), null); // NOI18N a.putValue("noIconInMenu", Boolean.TRUE); //NOI18N return a; } - - /** - * @return An Action to invoke profiling of a selected project in the IDE, does not have project name in display name - */ - public static Action profileProjectPopup() { - final Action a = ProjectSensitiveAction.projectSensitiveAction(new ProjectSensitiveAction.ProfilerProjectActionPerformer() { - public boolean enable(final Project project, final Lookup context, final boolean lightweightOnly) { - if (!NetBeansProfiler.isInitialized()) { - return false; - } - - if (project == null) { - return false; - } - - return org.netbeans.modules.profiler.nbimpl.project.ProjectUtilities.isProjectTypeSupported(project); - } - - public void perform(final Project project, final Lookup context) { - doProfileProject(project, null, NbBundle.getMessage(AntActions.class, "LBL_ProfileProject")); - } - }, NbBundle.getMessage(AntActions.class, "LBL_ProfileProjectActionPopup"), // NOI18N - NbBundle.getMessage(AntActions.class, - "LBL_ProfileProjectActionPopup"), // NOI18N - null); - a.putValue("noIconInMenu", Boolean.TRUE); //NOI18N - - return a; - } - - /** - * @return An Action to invoke profiling of a single class in the IDE - */ - public static Action profileSingle() { - final Action a = FileSensitiveAction.fileSensitiveAction(new ProjectSensitiveAction.ProfilerProjectActionPerformer() { - public boolean enable(final Project project, final Lookup context, final boolean lightweightOnly) { - if (!NetBeansProfiler.isInitialized()) { - return false; - } - - if (project == null) { - return false; - } - - final FileObject[] fos = ProjectSensitiveAction.ActionsUtil.getFilesFromLookup(context, project); - - if (fos.length != 1) { - return false; - } - -// final ProjectTypeProfiler ptp = org.netbeans.modules.profiler.utils.ProjectUtilities.getProjectTypeProfiler(project); -// if (!lightweightOnly) { -// if (!ptp.isFileObjectSupported(project, fos[0])) { -// return ProjectUtilities.hasAction(project, "profile-single"); //NOI18N -// } -// } else { -// return ptp.isProfilingSupported(project) || ProjectUtilities.hasAction(project, "profile-single"); //NOI18N -// } - ProjectProfilingSupport support = ProjectProfilingSupport.get(project); - if (!lightweightOnly) { - if (!support.isFileObjectSupported(fos[0])) { - return ProjectUtilities.hasAction(project, "profile-single"); //NOI18N - } - } else { - return support.isProfilingSupported() || ProjectUtilities.hasAction(project, "profile-single"); //NOI18N - } - - return true; - } - - public void perform(final Project project, final Lookup context) { - final FileObject[] fos = ProjectSensitiveAction.ActionsUtil.getFilesFromLookup(context, project); - - if (fos.length != 1) { - throw new IllegalStateException(); - } - - doProfileProject(project, JavaProfilerSource.createFrom(fos[0]), NbBundle.getMessage(AntActions.class, "LBL_ProfileFile")); - } - }, NbBundle.getMessage(AntActions.class, "LBL_ProfileSingleAction40_General"), // NOI18N - NbBundle.getMessage(AntActions.class, "LBL_ProfileSingleAction40"), // NOI18N - null); - a.putValue("noIconInMenu", Boolean.TRUE); //NOI18N - - return a; - } - - /** - * @return An Action to invoke profiling of a single class in the IDE. Does not have file name in its display name - */ - public static Action profileSinglePopup() { - final Action a = FileSensitiveAction.fileSensitiveAction(new ProjectSensitiveAction.ProfilerProjectActionPerformer() { - public boolean enable(final Project project, final Lookup context, final boolean lightweightOnly) { - if (!NetBeansProfiler.isInitialized()) { - return false; - } - - if (project == null) { - return false; - } - - final FileObject[] fos = ProjectSensitiveAction.ActionsUtil.getFilesFromLookup(context, project); - - if (fos.length != 1) { - return false; - } - -// final ProjectTypeProfiler ptp = org.netbeans.modules.profiler.utils.ProjectUtilities.getProjectTypeProfiler(project); -// if (!lightweightOnly) { -// if (!ptp.isFileObjectSupported(project, fos[0])) { -// return ProjectUtilities.hasAction(project, "profile-single"); //NOI18N -// } -// } else { -// return ptp.isProfilingSupported(project) || ProjectUtilities.hasAction(project, "profile-single"); //NOI18N -// } - ProjectProfilingSupport support = ProjectProfilingSupport.get(project); - if (!lightweightOnly) { - if (!support.isFileObjectSupported( fos[0])) { - return ProjectUtilities.hasAction(project, "profile-single"); //NOI18N - } - } else { - return support.isProfilingSupported() || ProjectUtilities.hasAction(project, "profile-single"); //NOI18N - } - - return true; - } - - public void perform(final Project project, final Lookup context) { - final FileObject[] fos = ProjectSensitiveAction.ActionsUtil.getFilesFromLookup(context, project); - - if (fos.length != 1) { - throw new IllegalStateException(); - } - -// final ProjectTypeProfiler ptp = org.netbeans.modules.profiler.utils.ProjectUtilities.getProjectTypeProfiler(project); -// if (!ptp.isFileObjectSupported(project, fos[0]) && !ProjectUtilities.hasAction(project, "profile-single")) { //NOI18N -// throw new IllegalStateException(); -// } - ProjectProfilingSupport support = ProjectProfilingSupport.get(project); - if (!support.isFileObjectSupported( fos[0]) && !ProjectUtilities.hasAction(project, "profile-single")) { //NOI18N - throw new IllegalStateException(); - } - - doProfileProject(project, JavaProfilerSource.createFrom(fos[0]) ,NbBundle.getMessage(AntActions.class, "LBL_ProfileFile")); - } - }, NbBundle.getMessage(AntActions.class, "LBL_ProfileSingleActionPopup"), // NOI18N - NbBundle.getMessage(AntActions.class, - "LBL_ProfileSingleActionPopup"), // NOI18N - null); - a.putValue("noIconInMenu", Boolean.TRUE); //NOI18N - - return a; - } - - /** - * @return An Action to invoke profiling of a single class in the IDE - */ - public static Action profileTest() { - final Action a = FileSensitiveAction.fileSensitiveAction(new ProjectSensitiveAction.ProfilerProjectActionPerformer() { - public boolean enable(final Project project, final Lookup context, final boolean lightweightOnly) { - if (!NetBeansProfiler.isInitialized()) { - return false; - } - - if (project == null) { - return false; - } - - final FileObject[] fos = ProjectSensitiveAction.ActionsUtil.getFilesFromLookup(context, project); - - if (fos.length != 1) { - return false; - } - - final FileObject fo = ProjectUtilities.findTestForFile(fos[0]); - - if (fo == null) { - return false; // not a test and test for it does not exist - } - -// final ProjectTypeProfiler ptp = org.netbeans.modules.profiler.utils.ProjectUtilities.getProjectTypeProfiler(project); -// if (!lightweightOnly) { -// return (ptp.isFileObjectSupported(project, fo)); -// } else { -// return ptp.isProfilingSupported(project); -// } - ProjectProfilingSupport support = ProjectProfilingSupport.get(project); - if (!lightweightOnly) { - return (support.isFileObjectSupported(fo)); - } else { - return support.isProfilingSupported(); - } - } - - public void perform(final Project project, final Lookup context) { - final FileObject[] fos = ProjectSensitiveAction.ActionsUtil.getFilesFromLookup(context, project); - - if (fos.length != 1) { - throw new IllegalStateException(); - } - - final FileObject fo = ProjectUtilities.findTestForFile(fos[0]); - - if (fo == null) { - throw new IllegalStateException(Bundle.AntActions_FileTestNotFoundMsg()); - } - - if (!ProjectProfilingSupport.get(project).isFileObjectSupported(fo)) { - throw new IllegalStateException(); - } - - doProfileProject(project, JavaProfilerSource.createFrom(fo), NbBundle.getMessage(AntActions.class, "LBL_ProfileTest")); - } - }, NbBundle.getMessage(AntActions.class, "LBL_ProfileTestAction_General"), // NI18N - NbBundle.getMessage(AntActions.class, "LBL_ProfileTestAction"), // NOI18N - null); - a.putValue("noIconInMenu", Boolean.TRUE); //NOI18N - - return a; - } - - public static Action unintegrateProfiler() { - final Action a = ProjectSensitiveAction.projectSensitiveAction(new ProjectSensitiveAction.ProfilerProjectActionPerformer() { - public boolean enable(final Project project, final Lookup context, final boolean lightweightOnly) { - if (!NetBeansProfiler.isInitialized()) { - return false; - } - - if (project == null) { - return false; - } - -// final ProjectTypeProfiler ptp = org.netbeans.modules.profiler.utils.ProjectUtilities.getProjectTypeProfiler(project); -// -// return ptp.supportsUnintegrate(project); - ProjectProfilingSupport support = ProjectProfilingSupport.get(project); - return support.supportsUnintegrate(); - } - - public void perform(final Project project, final Lookup context) { -// final ProjectTypeProfiler ptp = org.netbeans.modules.profiler.utils.ProjectUtilities.getProjectTypeProfiler(project); - ProjectProfilingSupport support = ProjectProfilingSupport.get(project); - try { - support.unintegrateProfiler(); - } catch (Exception e) { - ProfilerLogger.log(e); - } - } - }, NbBundle.getMessage(AntActions.class, "LBL_UnintegrateProfilerAction"), // NOI18N - NbBundle.getMessage(AntActions.class, - "LBL_UnintegrateProfilerAction"), // NOI18N - null); - a.putValue("noIconInMenu", Boolean.TRUE); //NOI18N - - return a; - } - - private static String getHeapDumpPath(ProfilerIDESettings gps, Project project) { - int oomeDetectionMode = gps.getOOMDetectionMode(); - - switch (oomeDetectionMode) { - case ProfilerIDESettings.OOME_DETECTION_TEMPDIR: - return System.getProperty("java.io.tmpdir"); // NOI18N - case ProfilerIDESettings.OOME_DETECTION_PROJECTDIR: - - try { - return FileUtil.toFile(ProjectStorage.getSettingsFolder(project, true)).getAbsolutePath(); - } catch (IOException e) { - ErrorManager.getDefault().annotate(e, "Cannot resolve project settings directory:\n" + e.getMessage()); - ErrorManager.getDefault().notify(ErrorManager.ERROR, e); - - return null; - } - case ProfilerIDESettings.OOME_DETECTION_CUSTOMDIR: - return gps.getCustomHeapdumpPath(); - } - - return null; - } - - private static void activateLinuxPosixThreadTime(ProfilingSettings ps, Properties props, Project project) { - if (ps.getThreadCPUTimerOn()) { - props.setProperty("profiler.info.jvmargs", LINUX_THREAD_TIMER_KEY + " " + props.getProperty("profiler.info.jvmargs")); // NOI18N - ProfilerLogger.log("Profiler.UseLinuxPosixThreadCPUClocks: Enabled"); // NOI18N - } - } - - private static void activateOOMProtection(ProfilerIDESettings gps, Properties props, Project project) { - if (gps.isOOMDetectionEnabled()) { - String oldArgs = props.getProperty("profiler.info.jvmargs"); - oldArgs = (oldArgs != null) ? oldArgs : ""; - - StringBuilder oomArgsBuffer = new StringBuilder(oldArgs); - String heapDumpPath = getHeapDumpPath(gps, project); - - if ((heapDumpPath != null) && (heapDumpPath.length() > 0)) { - // used for filesystem listener - props.setProperty(HeapDumpWatch.OOME_PROTECTION_ENABLED_KEY, "yes"); - props.setProperty(HeapDumpWatch.OOME_PROTECTION_DUMPPATH_KEY, heapDumpPath); - - // used as an argument for starting java process - if (heapDumpPath.contains(" ")) { - heapDumpPath = "\"" + heapDumpPath + "\""; - } - - oomArgsBuffer.append(" -XX:+HeapDumpOnOutOfMemoryError"); // NOI18N - oomArgsBuffer.append(" -XX:HeapDumpPath=").append(heapDumpPath).append(" "); // NOI18N - - ProfilerLogger.log("Profiler.OutOfMemoryDetection: Enabled"); // NOI18N - } - - props.setProperty("profiler.info.jvmargs", oomArgsBuffer.toString()); // NOI18N - } - } - - // -- Private implementation ----------------------------------------------------------------------------------------- - - /** - * Performs profiling of the selected project using either the supplied class (in case of profile single) or the - * project's main class. - * - * @param project The project to profile - * @param profiledClassFile In case profiledClass is not null, this is the FileObject representing the specified class - */ - private static void doProfileProject(final Project project, final JavaProfilerSource profiledClassFile, final String actionName) { - final boolean isTest = profiledClassFile != null ? profiledClassFile.isTest() : false; - final FileObject fo = profiledClassFile != null ? profiledClassFile.getFile() : null; - - if (ProfilingSupport.getDefault().isProfilingActionInvoked()) { - return; - } - - ProfilingSupport.getDefault().setProfilingActionInvoked(true); - - final Runnable actionPerform = new Runnable() { - public void run() { - try { - // 1. if there is profiling in progress, ask the user and possibly cancel - if (ProfilingSupport.getDefault().checkProfilingInProgress()) { - return; - } - -// final ProjectTypeProfiler ptp = org.netbeans.modules.profiler.utils.ProjectUtilities.getProjectTypeProfiler(project); - ProjectProfilingSupport support = ProjectProfilingSupport.get(project); - if (!support.isProfilingSupported()) { - // Branch A: not supported project with profile action in the action provider - - // as of now, the profile-tests will neve be used - ProjectUtilities.invokeAction(project, isTest ? "profile-tests" : "profile"); //NOI18N - } else { - // Branch B: project profiling directly supported via ProjectTypeProfiler - // 2. check if the project has been modified for profiling - if (!support.checkProjectIsModifiedForProfiler()) { - return; // something failed - has already been reported to the user - } - - // 3. determine Java platform to use - final JavaPlatform platform = initPlatform(project, support); - - if (platform == null) { - return; // user already notified - } - - // 3. check if the project is properly setup to be profiled (e.g. main class has a main method) - // FIXME - probably it would be better to pass around JavaProfilerSource instead of FileObject - if (!support.checkProjectCanBeProfiled(fo)) { - return; - } - - // 5. get session settings from the project context - final ProfilerIDESettings gps = ProfilerIDESettings.getInstance(); - - final String javaFile = platform.getPlatformJavaFile(); - - if (javaFile == null) { - if (ProfilerIDESettings.getInstance().getJavaPlatformForProfiling() == null) { - // used platform defined for project - ProfilerDialogs.displayError(Bundle.AntActions_InvalidPlatformProjectMsg(platform.getDisplayName())); - } else { - // used platform defined in Options / Profiler - ProfilerDialogs.displayError(Bundle.AntActions_InvalidPlatformProfilerMsg(platform.getDisplayName())); - } - return; - } - - final String javaVersion = platform.getPlatformJDKVersion(); - - if (javaVersion == null) { - ProfilerDialogs.displayError(Bundle.AntActions_FailedDetermineJavaPlatformMsg(platform.getDisplayName())); - - return; - } - - final SessionSettings ss = new SessionSettings(); - ss.setJavaExecutable(javaFile); - ss.setJavaVersionString(javaVersion); - ss.setSystemArchitecture(platform.getPlatformArchitecture()); - ss.setPortNo(gps.getPortNo()); - support.setupProjectSessionSettings(ss); - - boolean settingsAccepted = false; - ProfilingSettings pSettings = null; - - while (!settingsAccepted) { - // 6. show SelectTaskPanel and let the user choose the profiling type - pSettings = ProfilingSupport.getDefault() - .selectTaskForProfiling(project, ss, fo, - support.supportsSettingsOverride()); - - if (pSettings == null) { - return; // cancelled - } - - // Here was a check for enormous profiling overhead when profiling Web Projects. - // Generally, this is the right place to give ProjectTypeProfiler a chance to - // accept/reject current profiling settings before starting new profiling session. - settingsAccepted = true; - } - - final ProfilingSettings profilingSettings = pSettings; - final Properties props = new Properties(); - - // 7. store things into properties to be passed to Ant - profilingSettings.store(props); // Profiling settings - ss.store(props); // Session settings - - // Auxiliary internal profiler information: - String projectDir = FileUtil.toFile(project.getProjectDirectory()).getAbsolutePath(); - props.setProperty("profiler.info.project.dir", projectDir); // NOI18N // TODO: create constant - - if (fo != null) { - String singleFile = FileUtil.toFile(fo).getAbsolutePath(); - props.setProperty("profiler.info.single.file", singleFile); // NOI18N // TODO: create constant - } - - String usedJavaExecutable = ss.getJavaExecutable(); - String usedJvmArgs = ss.getJVMArgs(); - - if (profilingSettings.getOverrideGlobalSettings()) { - String javaPlatformName = profilingSettings.getJavaPlatformName(); - JavaPlatform jp; - - if (javaPlatformName != null) { - usedJavaExecutable = Profiler.getDefault().getPlatformJavaFile(javaPlatformName); - jp = JavaPlatform.getJavaPlatformById(javaPlatformName); - - if (jp == null) { - // selected platform does not exist, use - String text = Bundle.AntActions_InvalidJavaplatformMsg(javaPlatformName); - ProfilerDialogs.displayWarning(text); - jp = platform; - } - } else { - // javaPlatformName == null -> do not override java platform, use platform from global settings - jp = platform; - } - // added to support nbstartprofiledserver - props.setProperty("profiler.info.javaPlatform", - jp.getPlatformId()); - usedJvmArgs = profilingSettings.getJVMArgs(); - } else { - // added to support nbstartprofiledserver - props.setProperty("profiler.info.javaPlatform", - platform.getPlatformId()); - } - - props.setProperty("profiler.info.jvm", usedJavaExecutable); // NOI18N - props.setProperty("profiler.info.jvmargs", usedJvmArgs); // NOI18N - - if (javaVersion.equals(CommonConstants.JDK_15_STRING)) { - // JDK 1.5 used - props.setProperty("profiler.info.jvmargs.agent", // NOI18N - IDEUtils.getAntProfilerStartArgument15(ss.getPortNo(), - ss.getSystemArchitecture()) - ); - - if (platform.getPlatformJDKMinor() >= 7) { - activateOOMProtection(gps, props, project); - } else { - ProfilerLogger.log("Profiler.OutOfMemoryDetection: Disabled. Not supported JVM. Use at least 1.4.2_12 or 1.5.0_07"); // NOI18N - } - } else if (javaVersion.equals(CommonConstants.JDK_16_STRING)) { - // JDK 1.6 used - props.setProperty("profiler.info.jvmargs.agent", // NOI18N - IDEUtils.getAntProfilerStartArgument16(ss.getPortNo(), - ss.getSystemArchitecture()) - ); - activateOOMProtection(gps, props, project); - } else if (javaVersion.equals(CommonConstants.JDK_17_STRING)) { - props.setProperty("profiler.info.jvmargs.agent", // NOI18N - IDEUtils.getAntProfilerStartArgument17(ss.getPortNo(), - ss.getSystemArchitecture()) - ); - activateOOMProtection(gps, props, project); - } else if (javaVersion.equals(CommonConstants.JDK_18_STRING)) { - props.setProperty("profiler.info.jvmargs.agent", // NOI18N - IDEUtils.getAntProfilerStartArgument18(ss.getPortNo(), - ss.getSystemArchitecture()) - ); - activateOOMProtection(gps, props, project); - } else { - throw new IllegalArgumentException("Unsupported JDK " + javaVersion); // NOI18N - } - - if (Platform.isLinux() && javaVersion.equals(CommonConstants.JDK_16_STRING)) { - activateLinuxPosixThreadTime(pSettings, props, project); - } - - if (!support.startProfilingSession(fo, isTest, props)) { // Used for Maven - ProjectTypeProfiler itself controls starting profiling session - - // 8. determine the build script and target to run - AntProjectSupport antSupport = AntProjectSupport.get(project); - final FileObject buildScriptFO = antSupport.getProjectBuildScript(); - - if (buildScriptFO == null) { - ProfilerDialogs.displayError(Bundle.AntActions_FailedDetermineProjectBuildScriptMsg(ProjectUtils.getInformation(project).getName())); - - return; - } - - // determine which type fo target shoudl be called, and request its name - int type; - - if (isTest) { - type = (fo == null) ? AntProjectSupport.TARGET_PROFILE_TEST - : AntProjectSupport.TARGET_PROFILE_TEST_SINGLE; - } else { - type = (fo == null) ? AntProjectSupport.TARGET_PROFILE - : AntProjectSupport.TARGET_PROFILE_SINGLE; - } - - final String profileTarget = antSupport.getProfilerTargetName(buildScriptFO, type, fo); - - if (profileTarget == null) { - return; // already notified the user or user's choice - } - - // 9. final ability of the ProjectTypeProfiler to influence the properties passed to Ant - support.configurePropertiesForProfiling(props, fo); - - // 10. Run the target - ((org.netbeans.modules.profiler.nbimpl.NetBeansProfiler)Profiler.getDefault()).runTarget(buildScriptFO, profileTarget, props); - - } - - - } - } finally { - ProfilingSupport.getDefault().setProfilingActionInvoked(false); - } - } - }; - - CommonUtils.runInEventDispatchThread(new Runnable() { - @Override - public void run() { - if (ScanDialog.runWhenScanFinished(new Runnable() { - @Override - public void run() { - RequestProcessor.getDefault().post(actionPerform); - } - }, actionName)) { - ProfilingSupport.getDefault().setProfilingActionInvoked(false); - } - } - }); - } - - private static JavaPlatform initPlatform(Project project, ProjectProfilingSupport pps) { - // 1. check if we have a Java platform to use for profiling - final ProfilerIDESettings gps = ProfilerIDESettings.getInstance(); - JavaPlatform platform = JavaPlatform.getJavaPlatformById(gps.getJavaPlatformForProfiling()); - JavaPlatform projectPlatform = pps.getProjectJavaPlatform(); - - if (platform == null) { // should use the one defined in project - platform = projectPlatform; - - if ((platform == null) || !MiscUtils.isSupportedJVM(platform.getSystemProperties())) { - platform = JavaPlatformSelector.getDefault().selectPlatformToUse(); - - if (platform == null) { - return null; - } - } - } - - if (projectPlatform != null) { // check that the project platform is not newer than platform to use - - while (true) { - if (projectPlatform.getVersion().compareTo(platform.getVersion()) > 0) { - Boolean ret = ProfilerDialogs.displayCancellableConfirmation( - Bundle.AntActions_IncorrectJavaSpecVersionDialogMsg(), - Bundle.AntActions_IncorrectJavaSpecVersionDialogCaption()); - - if (Boolean.TRUE.equals(ret)) { - break; - } else if (Boolean.FALSE.equals(ret)) { - platform = JavaPlatformSelector.getDefault().selectPlatformToUse(); - - if (platform == null) { - return null; // cancelled by the user - } - } else { // cancelled - - return null; - } - } else { - break; // version comparison OK. - } - } - } - - return platform; - } - -// private static boolean isProjectTypeSupported(final Project project) { -// ProjectTypeProfiler ptp = org.netbeans.modules.profiler.utils.ProjectUtilities.getProjectTypeProfiler(project); -// -// if (ptp.isProfilingSupported(project)) { -// return true; -// } -// -// return ProjectUtilities.hasAction(project, "profile"); //NOI18N -// } } --- a/profiler.nbimpl/src/org/netbeans/modules/profiler/nbimpl/actions/Bundle.properties +++ a/profiler.nbimpl/src/org/netbeans/modules/profiler/nbimpl/actions/Bundle.properties @@ -67,6 +67,4 @@ LBL_ProfileProjectActionPopup=Profile LBL_UnintegrateProfilerAction=&Unintegrate Profiler from {0,choice,0#Project|1#\"{1}\"|1 0) ? files[0].getNameExt() : "")); // NOI18N - } - } -} --- a/profiler.nbimpl/src/org/netbeans/modules/profiler/nbimpl/actions/FileSensitivePerformer.java +++ a/profiler.nbimpl/src/org/netbeans/modules/profiler/nbimpl/actions/FileSensitivePerformer.java @@ -0,0 +1,115 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright 2012 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 2012 Sun Microsystems, Inc. + */ +package org.netbeans.modules.profiler.nbimpl.actions; + +import org.netbeans.api.project.FileOwnerQuery; +import org.netbeans.api.project.Project; +import org.netbeans.modules.profiler.api.project.ProjectProfilingSupport; +import org.netbeans.spi.project.ActionProvider; +import org.netbeans.spi.project.ui.support.FileActionPerformer; +import org.openide.filesystems.FileObject; +import org.openide.loaders.DataObject; +import org.openide.loaders.DataObjectNotFoundException; +import org.openide.util.Lookup; +import org.openide.util.lookup.Lookups; + +/** + * + * @author Jaroslav Bachorik + */ +public class FileSensitivePerformer implements FileActionPerformer { + + final private String command; + + public FileSensitivePerformer(String command) { + this.command = command; + } + + @Override + public boolean enable(FileObject file) { + if (file == null) { + return false; + } + + Project p = FileOwnerQuery.getOwner(file); + + if (p == null) { + return false; + } + + ActionProvider ap = p.getLookup().lookup(ActionProvider.class); + try { + if (ap != null && ap.isActionEnabled(command, getContext(file))) { + ProjectProfilingSupport ppp = ProjectProfilingSupport.get(p); + if (ppp == null) { + return false; + } + + return ppp.isProfilingSupported(); + } + } catch (IllegalArgumentException e) { + // command not supported + } + return false; + } + + @Override + public void perform(FileObject file) { + Project p = FileOwnerQuery.getOwner(file); + ActionProvider ap = p.getLookup().lookup(ActionProvider.class); + if (ap != null) { + ProfilerLauncher.Session s = ProfilerLauncher.newSession(command, getContext(file)); + if (s != null) { + s.run(); + } + } + } + + private Lookup getContext(FileObject file) { + Project p = FileOwnerQuery.getOwner(file); + try { + return Lookups.fixed(file, p, DataObject.find(file)); + } catch (DataObjectNotFoundException e) { + } + return Lookups.fixed(file, p); + } +} --- a/profiler.nbimpl/src/org/netbeans/modules/profiler/nbimpl/actions/ProfilerLauncher.java +++ a/profiler.nbimpl/src/org/netbeans/modules/profiler/nbimpl/actions/ProfilerLauncher.java @@ -0,0 +1,472 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright 2012 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 2012 Sun Microsystems, Inc. + */ +package org.netbeans.modules.profiler.nbimpl.actions; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.netbeans.api.annotations.common.NonNull; +import org.netbeans.api.project.FileOwnerQuery; +import org.netbeans.api.project.Project; +import org.netbeans.lib.profiler.ProfilerLogger; +import org.netbeans.lib.profiler.common.ProfilingSettings; +import org.netbeans.lib.profiler.common.SessionSettings; +import org.netbeans.lib.profiler.global.CommonConstants; +import org.netbeans.lib.profiler.global.Platform; +import org.netbeans.modules.profiler.HeapDumpWatch; +import org.netbeans.modules.profiler.actions.ProfilingSupport; +import org.netbeans.modules.profiler.api.JavaPlatform; +import org.netbeans.modules.profiler.api.ProfilerDialogs; +import org.netbeans.modules.profiler.api.ProfilerIDESettings; +import org.netbeans.modules.profiler.api.project.ProjectProfilingSupport; +import org.netbeans.modules.profiler.api.project.ProjectStorage; +import org.netbeans.modules.profiler.nbimpl.NetBeansProfiler; +import org.netbeans.modules.profiler.utils.IDEUtils; +import org.netbeans.spi.project.ActionProvider; +import org.netbeans.spi.project.LookupProvider.Registration.ProjectType; +import org.netbeans.spi.project.ProjectServiceProvider; +import org.openide.filesystems.FileObject; +import org.openide.filesystems.FileUtil; +import org.openide.util.Lookup; +import org.openide.util.NbBundle; + +/** + * + * @author Jaroslav Bachorik + */ +public class ProfilerLauncher { + final private static Logger LOG = Logger.getLogger(ProfilerLauncher.class.getName()); + + final private static String AGENT_ARGS = "agent.jvmargs"; // NOI18N + final private static String LINUX_THREAD_TIMER_KEY = "-XX:+UseLinuxPosixThreadCPUClocks"; // NOI18N + + final public static class Session { + private SessionSettings ss; + private ProfilingSettings ps; + private Map props; + private Launcher launcher; + private Project project; + private FileObject fo; + private JavaPlatform platform; + private String command; + private Lookup context; + final private Map customProps = new HashMap(); + + private boolean configured = false; + private boolean rerun; + + public static Session createSession(String command, Lookup context) { + Session s = new Session(command, context); + config(s); + lastSession = s; + + return s; + } + + public static Session createSession(Project p) { + Session s = new Session(p); + config(s); + return s; + } + + private Session(Project p) { + this.props = new HashMap(); + this.launcher = null; + this.project = p; + } + + private Session(String command, Lookup context) { + assert command != null; + assert context != null; + + this.project = context.lookup(Project.class); + this.fo = context.lookup(FileObject.class); + this.command = command; + this.props = new HashMap(); + this.context = context; + + initLauncher(); + } + + public ProfilingSettings getProfilingSettings() { + return ps; + } + + public SessionSettings getSessionSettings() { + return ss; + } + + public void setSessionSettings(SessionSettings ss) { + this.ss = ss; + this.ss.store(props); + } + + public Map getProperties() { + if (!configured) { + if (configure()) { + return props; + } else { + return null; + } + } + return props; + } + + public Project getProject() { + return project; + } + + public JavaPlatform getPlatform() { + return platform; + } + + public Lookup getContext() { + return context; + } + + public FileObject getFile() { + return fo; + } + + public String getCommand() { + return command; + } + + public Object getAttribute(String name) { + return customProps.get(name); + } + + public void setAttribute(String name, Object value) { + customProps.put(name, value); + } + + public boolean hasAttribute(String name) { + return customProps.containsKey(name); + } + + public boolean isConfigured() { + return configured; + } + + public boolean configure() { + final ProjectProfilingSupport pSupport = ProjectProfilingSupport.get(project); + + NetBeansProfiler.getDefaultNB().setProfiledProject(project, fo); + + // ** display select task panel + ProfilingSettings ps = ProfilingSupport.getDefault().selectTaskForProfiling(project, ss, fo, true);; + if (ps != null) { + this.ps = ps; + this.ps.store(props); + + setupAgentEnv(platform, ss, ProfilerIDESettings.getInstance(), ps, project, props); + pSupport.configurePropertiesForProfiling(props, fo); + + rerun = false; + configured = true; + } + return configured; + } + + public void run() { + if (launcher != null) { + launcher.launch(rerun); + rerun = true; + } else { + // LOG + } + } + + private void initLauncher() { + Project p = null; + if (project != null) { + p = project; + + } else if (fo != null) { + p = FileOwnerQuery.getOwner(fo); + } + + if (p != null) { + LauncherFactory f = p.getLookup().lookup(LauncherFactory.class); + if (f != null) { + launcher = f.createLauncher(this); + } + } + } + } + + public interface Launcher { + void launch(boolean rerun); + } + + public interface LauncherFactory { + Launcher createLauncher(Session session); + } + + @ProjectServiceProvider(service=LauncherFactory.class, projectTypes={ + @ProjectType(id="org-netbeans-modules-java-j2seproject"), + @ProjectType(id="org-netbeans-modules-ant-freeform"), + @ProjectType(id="org-netbeans-modules-apisupport-project"), + @ProjectType(id="org-netbeans-modules-apisupport-project-suite"), + @ProjectType(id="org-netbeans-modules-j2ee-earproject"), + @ProjectType(id="org-netbeans-modules-j2ee-ejbjarproject"), + @ProjectType(id="org-netbeans-modules-web-project") + }) + final public static class AntLauncherFactory implements LauncherFactory { + final private Project prj; + public AntLauncherFactory(Project prj) { + this.prj = prj; + } + + @Override + public Launcher createLauncher(Session session) { + ActionProvider ap = prj.getLookup().lookup(ActionProvider.class); + if (ap != null) { + return new AntLauncher(ap, session.command, session.context); + } + + return null; + } + } + + final private static class AntLauncher implements Launcher { + private ActionProvider ap; + private String command; + private Lookup context; + + public AntLauncher(ActionProvider ap, String command, Lookup context) { + this.ap = ap; + this.command = command; + this.context = context; + } + + @Override + public void launch(boolean rerun) { + ap.invokeAction( + command, + context + ); + } + } + + private static Session lastSession; + + public static Session newSession(@NonNull final String command, @NonNull final Lookup context) { + return Session.createSession(command, context); + } + + public static Session getLastSession() { + return lastSession; + } + + public static void clearLastSession() { + lastSession = null; + } + + public static boolean canRelaunch() { + return lastSession != null; + } + + @NbBundle.Messages({ + "InvalidPlatformProjectMsg=The Java platform defined for the project is invalid. Right-click the project\nand choose a different platform using Properties | Libraries | Java Platform.\n\nInvalid platform: {0}", + "InvalidPlatformProfilerMsg=The Java platform defined for profiling is invalid. Choose a different platform\nin Tools | Options | Miscellaneous | Profiler | Profiler Java Platform.\n\nInvalid platform: {0}", + "FailedDetermineJavaPlatformMsg=Failed to determine version of Java platform: {0}" + }) + private static void config(Session session) { + Project project = null; + if (session.project == null) { + if (session.fo != null) { + project = FileOwnerQuery.getOwner(session.fo); + } + } else { + project = session.project; + } + if (project == null) return; // sanity check; we need project here + + if (ProfilingSupport.getDefault().checkProfilingInProgress()) { + return; + } + + final ProjectProfilingSupport pSupport = ProjectProfilingSupport.get(project); + if (pSupport == null) { + return; + } + + final SessionSettings ss = new SessionSettings(); + // *** session settings setup + pSupport.setupProjectSessionSettings(ss); + ProfilerIDESettings gps = ProfilerIDESettings.getInstance(); + + ss.setPortNo(gps.getPortNo()); + // *** + + // *** java platform recheck + JavaPlatform platform = pSupport.getProjectJavaPlatform(); + final String javaFile = platform.getPlatformJavaFile(); + + if (javaFile == null) { + if (ProfilerIDESettings.getInstance().getJavaPlatformForProfiling() == null) { + // used platform defined for project + ProfilerDialogs.displayError(Bundle.InvalidPlatformProjectMsg(platform.getDisplayName())); + } else { + // used platform defined in Options / Profiler + ProfilerDialogs.displayError(Bundle.InvalidPlatformProfilerMsg(platform.getDisplayName())); + } + return; + } + + final String javaVersion = platform.getPlatformJDKVersion(); + + if (javaVersion == null) { + ProfilerDialogs.displayError(Bundle.FailedDetermineJavaPlatformMsg(platform.getDisplayName())); + + return; + } + + session.ss = ss; + session.platform = platform; + } + + private static void setupAgentEnv(JavaPlatform platform, SessionSettings ss, ProfilerIDESettings gps, ProfilingSettings pSettings, Project project, Map props) { + String javaVersion = platform.getPlatformJDKVersion(); + if (javaVersion.equals(CommonConstants.JDK_15_STRING)) { + // JDK 1.5 used + props.put( + AGENT_ARGS, + IDEUtils.getAntProfilerStartArgument15(ss.getPortNo(), ss.getSystemArchitecture()) + ); + + if (platform.getPlatformJDKMinor() >= 7) { + activateOOMProtection(gps, props, project); + } else { + ProfilerLogger.log("Profiler.OutOfMemoryDetection: Disabled. Not supported JVM. Use at least 1.4.2_12 or 1.5.0_07"); // NOI18N + } + } else if (javaVersion.equals(CommonConstants.JDK_16_STRING)) { + // JDK 1.6 used + props.put( + AGENT_ARGS, + IDEUtils.getAntProfilerStartArgument16(ss.getPortNo(), ss.getSystemArchitecture()) + ); + activateOOMProtection(gps, props, project); + } else if (javaVersion.equals(CommonConstants.JDK_17_STRING)) { + props.put( + AGENT_ARGS, + IDEUtils.getAntProfilerStartArgument17(ss.getPortNo(), ss.getSystemArchitecture()) + ); + activateOOMProtection(gps, props, project); + } else if (javaVersion.equals(CommonConstants.JDK_18_STRING)) { + props.put( + AGENT_ARGS, + IDEUtils.getAntProfilerStartArgument18(ss.getPortNo(), ss.getSystemArchitecture()) + ); + activateOOMProtection(gps, props, project); + } else { + throw new IllegalArgumentException("Unsupported JDK " + javaVersion); // NOI18N + } + + if (Platform.isLinux() && javaVersion.equals(CommonConstants.JDK_16_STRING)) { + activateLinuxPosixThreadTime(pSettings, props); + } + + props.put("profiler.java.platform", ss.getJavaExecutable()); + props.put("profiler.info.project.dir", project.getProjectDirectory().getPath()); + } + + private static void activateLinuxPosixThreadTime(ProfilingSettings ps, Map props) { + if (ps.getThreadCPUTimerOn()) { + props.put("profiler.info.jvmargs", LINUX_THREAD_TIMER_KEY + " " + props.get("profiler.info.jvmargs")); // NOI18N + ProfilerLogger.log("Profiler.UseLinuxPosixThreadCPUClocks: Enabled"); // NOI18N + } + } + + private static void activateOOMProtection(ProfilerIDESettings gps, Map props, Project project) { + if (gps.isOOMDetectionEnabled()) { + String oldArgs = props.get("profiler.info.jvmargs"); + oldArgs = (oldArgs != null) ? oldArgs : ""; + + StringBuilder oomArgsBuffer = new StringBuilder(oldArgs); + String heapDumpPath = getHeapDumpPath(gps, project); + + if ((heapDumpPath != null) && (heapDumpPath.length() > 0)) { + // used for filesystem listener + props.put(HeapDumpWatch.OOME_PROTECTION_ENABLED_KEY, "yes"); + props.put(HeapDumpWatch.OOME_PROTECTION_DUMPPATH_KEY, heapDumpPath); + + // used as an argument for starting java process + if (heapDumpPath.contains(" ")) { + heapDumpPath = "\"" + heapDumpPath + "\""; + } + + oomArgsBuffer.append(" -XX:+HeapDumpOnOutOfMemoryError"); // NOI18N + oomArgsBuffer.append(" -XX:HeapDumpPath=").append(heapDumpPath).append(" "); // NOI18N + + ProfilerLogger.log("Profiler.OutOfMemoryDetection: Enabled"); // NOI18N + } + + props.put("profiler.info.jvmargs", oomArgsBuffer.toString()); // NOI18N + } + } + + private static String getHeapDumpPath(ProfilerIDESettings gps, Project project) { + int oomeDetectionMode = gps.getOOMDetectionMode(); + + switch (oomeDetectionMode) { + case ProfilerIDESettings.OOME_DETECTION_TEMPDIR: + return System.getProperty("java.io.tmpdir"); // NOI18N + case ProfilerIDESettings.OOME_DETECTION_PROJECTDIR: + + try { + return FileUtil.toFile(ProjectStorage.getSettingsFolder(project, true)).getAbsolutePath(); + } catch (IOException e) { + LOG.log(Level.WARNING, "Cannot resolve project settings directory:\n" + e.getMessage(), e); + + return null; + } + case ProfilerIDESettings.OOME_DETECTION_CUSTOMDIR: + return gps.getCustomHeapdumpPath(); + } + + return null; + } +} --- a/profiler.nbimpl/src/org/netbeans/modules/profiler/nbimpl/actions/ProfilerToolbarDropdownAction.java +++ a/profiler.nbimpl/src/org/netbeans/modules/profiler/nbimpl/actions/ProfilerToolbarDropdownAction.java @@ -72,7 +72,7 @@ //~ Constructors ------------------------------------------------------------------------------------------------------------- public ProfilerToolbarDropdownAction() { - defaultAction = AntActions.profileMainProject(); + defaultAction = AntActions.profileMainProjectAction(); } //~ Methods ------------------------------------------------------------------------------------------------------------------ --- a/profiler.nbimpl/src/org/netbeans/modules/profiler/nbimpl/actions/ProjectSensitiveAction.java +++ a/profiler.nbimpl/src/org/netbeans/modules/profiler/nbimpl/actions/ProjectSensitiveAction.java @@ -1,436 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright 1997-2010 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]" - * - * Contributor(s): - * The Original Software is NetBeans. The Initial Developer of the Original - * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun - * Microsystems, Inc. All Rights Reserved. - * - * 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. - */ - -package org.netbeans.modules.profiler.nbimpl.actions; - -import org.netbeans.api.project.FileOwnerQuery; -import org.netbeans.api.project.Project; -import org.netbeans.api.project.ProjectUtils; -import org.netbeans.modules.profiler.ui.NBSwingWorker; -import org.netbeans.modules.profiler.ui.ProfilerProgressDisplayer; -import org.netbeans.modules.profiler.utilities.OutputParameter; -import org.netbeans.spi.project.ActionProvider; -import org.openide.filesystems.FileObject; -import org.openide.loaders.DataObject; -import org.openide.util.*; -import java.awt.event.ActionEvent; -import java.text.MessageFormat; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; -import javax.swing.AbstractAction; -import javax.swing.Action; -import javax.swing.Icon; -import org.netbeans.modules.profiler.api.ProfilerDialogs; -import org.netbeans.lib.profiler.common.CommonUtils; -import org.netbeans.modules.profiler.api.ProgressDisplayer; - - -/** - * Action sensitive to current project - * - * @author Ian Formanek - */ -public class ProjectSensitiveAction extends AbstractAction implements ContextAwareAction, LookupListener { - //~ Inner Interfaces --------------------------------------------------------------------------------------------------------- - - public interface ProfilerProjectActionPerformer { - //~ Methods -------------------------------------------------------------------------------------------------------------- - - /** - * Called when the context of the action changes and the action should - * be enabled or disabled within the new context, according to the newly - * selected project. - * - * @param project the currently selected project, or null if no project is selected - * @return true to enable the action, false to disable it - */ - public boolean enable(Project project, Lookup context, boolean lightweightOnly); - - /** - * Called when the user invokes the action. - * - * @param project the project this action was invoked for (XXX can this be null or not?) - * @throws IllegalStateException when trying to perform the action in an illegal context - */ - public void perform(Project project, Lookup context); - } - - //~ Inner Classes ------------------------------------------------------------------------------------------------------------ - - public static final class ActionsUtil { - //~ Methods -------------------------------------------------------------------------------------------------------------- - - /** - * In given lookup will find all FileObjects owned by given project - * with given command supported. - */ - public static FileObject[] getFilesFromLookup(final Lookup lookup, final Project project) { - final HashSet result = new HashSet(); - final Collection dataObjects = lookup.lookup(new Lookup.Template(DataObject.class)).allInstances(); - - for (Iterator it = dataObjects.iterator(); it.hasNext();) { - final DataObject dObj = (DataObject) it.next(); - final FileObject fObj = dObj.getPrimaryFile(); - final Project p = FileOwnerQuery.getOwner(fObj); - - if ((p != null) && p.equals(project)) { - result.add(fObj); - } - } - - final FileObject[] fos = new FileObject[result.size()]; - result.toArray(fos); - - return fos; - } - - /** - * Finds all projects in given lookup. If the command is not null it will check - * whether given command is enabled on all projects. If and only if all projects - * have the command supported it will return array including the project. If there - * is one project with the command disabled it will return empty array. - */ - public static Project[] getProjectsFromLookup(final Lookup lookup, final String command) { - final Set result = new HashSet(); - - // First find out whether there is a project directly in the Lookup - final Collection projects = lookup.lookup(new Lookup.Template(Project.class)).allInstances(); - - for (Iterator it = projects.iterator(); it.hasNext();) { - final Project p = (Project) it.next(); - result.add(p); - } - - // Now try to guess the project from dataobjects - final Collection dataObjects = lookup.lookup(new Lookup.Template(DataObject.class)).allInstances(); - - for (Iterator it = dataObjects.iterator(); it.hasNext();) { - final DataObject dObj = (DataObject) it.next(); - final FileObject fObj = dObj.getPrimaryFile(); - final Project p = FileOwnerQuery.getOwner(fObj); - - if (p != null) { - result.add(p); - } - } - - final Project[] projectsArray = new Project[result.size()]; - result.toArray(projectsArray); - - if (command != null) { - // All projects have to have the command enabled - for (int i = 0; i < projectsArray.length; i++) { - if (!commandSupported(projectsArray[i], command, lookup)) { - return new Project[0]; - } - } - } - - return projectsArray; - } - - /** - * Tests whether given command is available on the project and whether - * the action as to be enabled in current Context - * - * @param project Project to test - * @param command Command for test - * @param context Lookup representing current context or null if context - * does not matter. - */ - public static boolean commandSupported(final Project project, final String command, final Lookup context) { - //We have to look whether the command is supported by the project - final ActionProvider ap = (ActionProvider) project.getLookup().lookup(ActionProvider.class); - - if (ap != null) { - final List commands = Arrays.asList(ap.getSupportedActions()); - - if (commands.contains(command)) { - if ((context == null) || ap.isActionEnabled(command, context)) { - return true; - } - } - } - - return false; - } - - /** - * Good for formating names of actions with some two parameter pattern - * {0} nuber of objects (e.g. Projects or files ) and {1} name of one - * or first object (e.g. Project or file) or null if the number is == 0 - */ - public static String formatName(final String namePattern, final int numberOfObjects, final String firstObjectName) { - return MessageFormat.format(namePattern, - new Object[] { - Integer.valueOf(numberOfObjects), (firstObjectName == null) ? "" : firstObjectName, //NOI18N - }); - } - - public static String formatProjectSensitiveName(final String namePattern, final Project[] projects) { - // Set the action's name - if ((projects == null) || (projects.length == 0)) { - // No project selected - return ActionsUtil.formatName(namePattern, 0, null); - } else { - // Some project selected - return ActionsUtil.formatName(namePattern, projects.length, - ProjectUtils.getInformation(projects[0]).getDisplayName()); - } - } - } - - //~ Instance fields ---------------------------------------------------------------------------------------------------------- - - protected volatile boolean actionEnabled = false; - private final Lookup lookup; - private final Object initLock = new Object(); - private final Object refreshRequestLock = new Object(); - private final ProfilerProjectActionPerformer performer; - private final String namePattern; - private final Lookup.Result[] results; - private final Class[] watch; - - // @GuarderBy initLock - private volatile boolean isCalculated = false; - - // @GuardedBy refreshRequestLock - private int refreshRequested = 0; - - //~ Constructors ------------------------------------------------------------------------------------------------------------- - - /** - * Constructor for global actions. E.g. actions in main menu which - * listen to the global context. - */ - ProjectSensitiveAction(final ProfilerProjectActionPerformer performer, final String name, final String namePattern, - final Icon icon, Lookup lookup) { - super(name); - - if (icon != null) { - putValue(SMALL_ICON, icon); - } - - if (lookup == null) { - lookup = Utilities.actionsGlobalContext(); - } - - this.lookup = lookup; - this.watch = new Class[] { Project.class, DataObject.class }; - this.results = new Lookup.Result[watch.length]; - - // Needs to listen on changes in results - for (int i = 0; i < watch.length; i++) { - final Lookup.Result result = lookup.lookup(new Lookup.Template(watch[i])); - // #147348 - Action instance is probobly only weakly held; we must add the strong reference to lookup listener -// resultListeners[i] = (LookupListener) WeakListeners.create(LookupListener.class, this, result); -// result.addLookupListener(resultListeners[i]); - result.addLookupListener(this); - // MUST hold on the reference to the result; otherwise it will vanish in a puff of smoke - results[i] = result; - } - - this.performer = performer; - this.namePattern = namePattern; - - init(); - } - - //~ Methods ------------------------------------------------------------------------------------------------------------------ - - /** - * Needs to override isEnabled in order to force refresh - */ - public final boolean isEnabled() { - init(); // the action must be initialized - - return super.isEnabled(); - } - - public final void actionPerformed(final ActionEvent e) { - actionPerformed(lookup); - } - - public static ProjectSensitiveAction projectSensitiveAction(final ProfilerProjectActionPerformer performer, - final String name, final String namePattern, final Icon icon) { - return new ProjectSensitiveAction(performer, name, namePattern, icon, null); - } - - // Implementation of ContextAwareAction ------------------------------------ - public Action createContextAwareInstance(final Lookup actionContext) { - return new ProjectSensitiveAction(getPerformer(), getName(), getNamePattern(), (Icon) getValue(SMALL_ICON), actionContext); - } - - // Implementation of LookupListener ---------------------------------------- - public final void resultChanged(final LookupEvent e) { - isCalculated = false; - } - - protected final void setDisplayName(final String name) { - putValue(NAME, name); - } - - protected final String getName() { - return (String) getValue(NAME); - } - - protected final String getNamePattern() { - return namePattern; - } - - protected final ProfilerProjectActionPerformer getPerformer() { - return performer; - } - - protected void actionPerformed(final Lookup context) { - final Project[] projects = ActionsUtil.getProjectsFromLookup(context, null); - - if (projects.length == 1) { - if (performer != null) { - new NBSwingWorker(false) { - private boolean isEnabled = false; - private final OutputParameter isCancelled = new OutputParameter(Boolean.FALSE); - private final OutputParameter progress = new OutputParameter(null); - - protected void doInBackground() { - isEnabled = performer.enable(projects[0], context, false); - } - - protected void done() { - if (progress.isSet()) { - progress.getValue().close(); - } - - if (isEnabled && !isCancelled.getValue()) { - performer.perform(projects[0], context); - } else if (!isCancelled.getValue()) { - ProfilerDialogs.displayInfo(NbBundle.getMessage(ProjectSensitiveAction.class, "AntActions_LazyEnablementFailure")); // NOI18N - } - } - - protected void nonResponding() { - progress.setValue(ProfilerProgressDisplayer.getDefault().showProgress( - java.util.ResourceBundle.getBundle("org/netbeans/modules/profiler/actions/Bundle") // NOI18N - .getString("AntActions_LazyEnablementProgressMessage"), // NOI18N - new ProgressDisplayer.ProgressController() { - public boolean cancel() { - if (progress.isSet()) { - progress.getValue().close(); - } - - progress.setValue(null); - isCancelled.setValue(true); - - return true; - } - })); - } - }.execute(); - } - } - } - - protected void doRefresh(final Lookup context) { - final Project[] projects = ActionsUtil.getProjectsFromLookup(context, null); - - setDisplayName(ActionsUtil.formatProjectSensitiveName(getNamePattern(), projects)); - - if ((projects != null) && (projects.length == 1)) { // must be selected single project - setEnabled(getPerformer().enable(projects[0], context, true)); - } else { - setEnabled(false); - } - } - - /** - * Initializes the action - */ - private void init() { - if (isCalculated) { - return; - } - - synchronized (initLock) { - if (isCalculated) { - return; - } - - refresh(ProjectSensitiveAction.this.lookup); - isCalculated = true; - } - } - - private void refresh(final Lookup context) { - synchronized (refreshRequestLock) { - if (refreshRequested++ > 0) { - return; - } - - CommonUtils.runInEventDispatchThread(new Runnable() { - public void run() { - int oldReqCount = -1; - int currentReqCount = -1; - - synchronized (refreshRequestLock) { - oldReqCount = refreshRequested; - } - - doRefresh(lookup); - - synchronized (refreshRequestLock) { - currentReqCount = refreshRequested; - refreshRequested = 0; - } - - if (oldReqCount != currentReqCount) { - refresh(context); - } - } - }); - } - } -} --- a/profiler.nbimpl/src/org/netbeans/modules/profiler/nbimpl/actions/ProjectSensitivePerformer.java +++ a/profiler.nbimpl/src/org/netbeans/modules/profiler/nbimpl/actions/ProjectSensitivePerformer.java @@ -0,0 +1,97 @@ +/* + * 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.profiler.nbimpl.actions; + +import org.netbeans.api.project.Project; +import org.netbeans.lib.profiler.common.Profiler; +import org.netbeans.modules.profiler.api.project.ProjectProfilingSupport; +import org.netbeans.modules.profiler.nbimpl.NetBeansProfiler; +import org.netbeans.modules.profiler.nbimpl.actions.ProfilerLauncher.Session; +import org.netbeans.spi.project.ActionProvider; +import org.netbeans.spi.project.ui.support.ProjectActionPerformer; +import org.openide.util.Lookup; +import org.openide.util.lookup.Lookups; +import org.openide.util.lookup.ProxyLookup; + +/** + * + * @author Jaroslav Bachorik + */ +public class ProjectSensitivePerformer implements ProjectActionPerformer { + final private String command; + + public ProjectSensitivePerformer(String command) { + this.command = command; + } + + @Override + public boolean enable(Project project) { + if (project == null) return false; + + ActionProvider ap = project.getLookup().lookup(ActionProvider.class); + try { + if (ap != null && ap.isActionEnabled(command, project.getLookup())) { + ProjectProfilingSupport ppp = ProjectProfilingSupport.get(project); + if (ppp == null) { + return false; + } + return ppp.isProfilingSupported(); + } + } catch (IllegalArgumentException e) { + // no provider responds to the command + } + return false; + } + + @Override + public void perform(final Project project) { + final ActionProvider ap = project.getLookup().lookup(ActionProvider.class); + if (ap != null) { + Lookup ctx = new ProxyLookup(project.getLookup(), Lookups.fixed(project)); + + Session s = ProfilerLauncher.newSession(command, ctx); + if (s != null) { + s.run(); + } + } + } +} --- a/profiler.nbimpl/src/org/netbeans/modules/profiler/nbimpl/layer.xml +++ a/profiler.nbimpl/src/org/netbeans/modules/profiler/nbimpl/layer.xml @@ -57,78 +57,6 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -138,38 +66,4 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - --- a/profiler.nbimpl/src/org/netbeans/modules/profiler/nbimpl/project/JavaProjectProfilingSupportProvider.java +++ a/profiler.nbimpl/src/org/netbeans/modules/profiler/nbimpl/project/JavaProjectProfilingSupportProvider.java @@ -42,9 +42,16 @@ package org.netbeans.modules.profiler.nbimpl.project; import org.netbeans.api.project.Project; +import org.netbeans.lib.profiler.common.SessionSettings; +import org.netbeans.lib.profiler.utils.MiscUtils; +import org.netbeans.modules.profiler.actions.JavaPlatformSelector; +import org.netbeans.modules.profiler.api.JavaPlatform; +import org.netbeans.modules.profiler.api.ProfilerDialogs; +import org.netbeans.modules.profiler.api.ProfilerIDESettings; import org.netbeans.modules.profiler.api.java.JavaProfilerSource; import org.netbeans.modules.profiler.spi.project.ProjectProfilingSupportProvider; import org.openide.filesystems.FileObject; +import org.openide.util.NbBundle; /** * @@ -53,7 +60,7 @@ public abstract class JavaProjectProfilingSupportProvider extends ProjectProfilingSupportProvider.Basic { private final Project project; - + private JavaPlatform projectJavaPlatform = null; @Override public boolean isProfilingSupported() { @@ -74,7 +81,80 @@ @Override public boolean checkProjectCanBeProfiled(FileObject profiledClassFile) { - return true; + return getProjectJavaPlatform() != null; + } + + @Override + public void setupProjectSessionSettings(SessionSettings ss) { + JavaPlatform platform = getProjectJavaPlatform(); + + ss.setSystemArchitecture(platform.getPlatformArchitecture()); + ss.setJavaVersionString(platform.getPlatformJDKVersion()); + ss.setJavaExecutable(platform.getPlatformJavaFile()); + } + + @Override + @NbBundle.Messages({ + "IncorrectJavaSpecVersionDialogCaption=Warning", + "IncorrectJavaSpecVersionDialogMsg=The specification version of project Java Platform is greater than specification version of the\nplatform that will be used for profiling. You may experience problems unless you set the compiler\nparameter to generate bytecode compatible with the platform that will be used.\n\nDo you want to continue with the current settings?" + }) + final synchronized public JavaPlatform getProjectJavaPlatform() { + if (projectJavaPlatform == null) { + // 1. check if we have a Java platform to use for profiling + final ProfilerIDESettings gps = ProfilerIDESettings.getInstance(); + JavaPlatform platform = JavaPlatform.getJavaPlatformById(gps.getJavaPlatformForProfiling()); + projectJavaPlatform = resolveProjectJavaPlatform(); + + if (platform == null) { // should use the one defined in project + platform = projectJavaPlatform; + + if ((platform == null) || !MiscUtils.isSupportedJVM(platform.getSystemProperties())) { + platform = JavaPlatformSelector.getDefault().selectPlatformToUse(); + + if (platform == null) { + return null; + } + projectJavaPlatform = platform; + } + } + + if (projectJavaPlatform != null) { // check that the project platform is not newer than platform to use + + while (true) { + if (projectJavaPlatform.getVersion().compareTo(platform.getVersion()) > 0) { + Boolean ret = ProfilerDialogs.displayCancellableConfirmation( + Bundle.IncorrectJavaSpecVersionDialogMsg(), + Bundle.IncorrectJavaSpecVersionDialogCaption()); + + if (Boolean.TRUE.equals(ret)) { + break; + } else if (Boolean.FALSE.equals(ret)) { + platform = JavaPlatformSelector.getDefault().selectPlatformToUse(); + + if (platform == null) { + return null; // cancelled by the user + } + } else { // cancelled + + return null; + } + } else { + break; // version comparison OK. + } + } + } + } + return projectJavaPlatform; + } + + abstract protected JavaPlatform resolveProjectJavaPlatform(); + + protected final JavaPlatform getPlatformByName(String platformName) { + if (platformName == null || platformName.equals("default_platform")) { // NOI18N + return JavaPlatform.getDefaultPlatform(); + } + + return JavaPlatform.getJavaPlatformById(platformName); } protected final Project getProject() { --- a/profiler.nbimpl/src/org/netbeans/modules/profiler/nbimpl/providers/DefaultProfilerArgsProvider.java +++ a/profiler.nbimpl/src/org/netbeans/modules/profiler/nbimpl/providers/DefaultProfilerArgsProvider.java @@ -0,0 +1,92 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright 2012 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 2012 Sun Microsystems, Inc. + */ +package org.netbeans.modules.profiler.nbimpl.providers; + +import java.util.*; +import org.netbeans.api.extexecution.startup.StartupExtender; +import org.netbeans.api.extexecution.startup.StartupExtender.StartMode; +import org.netbeans.api.project.Project; +import org.netbeans.modules.profiler.nbimpl.actions.ProfilerLauncher; +import org.netbeans.spi.extexecution.startup.StartupExtenderImplementation; +import org.openide.util.Lookup; +import org.openide.util.NbBundle; + +/** + * + * @author Jaroslav Bachorik + */ +@NbBundle.Messages({ + "DESC_NBProfiler=NetBeans Profiler" +}) +@StartupExtenderImplementation.Registration(displayName="#DESC_NBProfiler", position=1000, startMode={ + StartupExtender.StartMode.PROFILE, + StartupExtender.StartMode.TEST_PROFILE +}) +public class DefaultProfilerArgsProvider implements StartupExtenderImplementation { + @Override + public List getArguments(Lookup context, StartMode mode) { + Project p = context.lookup(Project.class); + if (p != null) { + ProfilerLauncher.Session s = ProfilerLauncher.getLastSession(); + if (s != null) { + Map m = ProfilerLauncher.getLastSession().getProperties(); + if (m != null) { + String agentArgs = m.get("agent.jvmargs"); + String jvmargs = m.get("profiler.info.jvmargs"); + jvmargs = jvmargs.replace(" -", "^"); + StringTokenizer st = new StringTokenizer(jvmargs, "^"); + + List args = new ArrayList(); + args.add(agentArgs); + while (st.hasMoreTokens()) { + String arg = st.nextToken(); + if (!arg.isEmpty()) { + args.add((arg.startsWith("-") ? "" : "-") + arg); + } + } + return args; + } + } + } + return Collections.EMPTY_LIST; + } +} --- a/profiler.nbmodule/src/org/netbeans/modules/profiler/nbmodule/NbModuleProjectProfilingSupportProvider.java +++ a/profiler.nbmodule/src/org/netbeans/modules/profiler/nbmodule/NbModuleProjectProfilingSupportProvider.java @@ -52,12 +52,13 @@ import org.openide.util.Utilities; import org.w3c.dom.Element; import java.util.List; -import java.util.Properties; +import java.util.Map; import java.util.Set; import org.netbeans.api.java.platform.JavaPlatformManager; import org.netbeans.api.java.platform.Specification; import org.netbeans.api.project.ProjectUtils; import org.netbeans.lib.profiler.common.Profiler; +import org.netbeans.lib.profiler.common.SessionSettings; import org.netbeans.lib.profiler.common.integration.IntegrationUtils; import org.netbeans.modules.profiler.api.JavaPlatform; import org.netbeans.modules.profiler.api.java.JavaProfilerSource; @@ -102,7 +103,7 @@ } @Override - public JavaPlatform getProjectJavaPlatform() { + public JavaPlatform resolveProjectJavaPlatform() { return getProjectJavaPlatform(getProject()); } @@ -173,32 +174,43 @@ } @Override - public void configurePropertiesForProfiling(final Properties props, final FileObject profiledClassFile) { + public void configurePropertiesForProfiling(final Map props, final FileObject profiledClassFile) { // FIXME JavaProfilerSource src = JavaProfilerSource.createFrom(profiledClassFile); if (src != null) { final String profiledClass = src.getTopLevelClass().getQualifiedName(); - props.setProperty("profile.class", profiledClass); //NOI18N + props.put("profile.class", profiledClass); //NOI18N // Set for all cases (incl. Profile Project, Profile File) but should only // be taken into account when profiling single test - props.setProperty("test.type", getTestType(profiledClassFile)); //NOI18N + props.put("test.type", getTestType(profiledClassFile)); //NOI18N } - String agentArg = props.getProperty("profiler.info.jvmargs.agent"); //NOI18N + String agentArg = props.get("agent.jvmargs"); //NOI18N if (agentArg.indexOf(' ') != -1) { //NOI18N if (Utilities.isUnix()) { // Profiler is installed in directory with space on Unix (Linux, Solaris, Mac OS X) // create temporary link in /tmp directory and use it instead of directory with space String libsDir = Profiler.getDefault().getLibsDir(); - props.setProperty("profiler.info.jvmargs.agent", IntegrationUtils.fixLibsDirPath(libsDir, agentArg)); //NOI18N + props.put("agent.jvmargs", IntegrationUtils.fixLibsDirPath(libsDir, agentArg)); //NOI18N } else if (Utilities.isWindows() && isNbSourceModule(getProject())) { // Profiler is installed in directory with space on Windows // surround the whole -agentpath argument with quotes for NB source module agentArg = "\"" + agentArg + "\""; //NOI18N - props.setProperty("profiler.info.jvmargs.agent", agentArg); //NOI18N + props.put("agent.jvmargs", agentArg); //NOI18N } } } + + @Override + public void setupProjectSessionSettings(SessionSettings ss) { + JavaPlatform platform = getProjectJavaPlatform(); + + ss.setSystemArchitecture(platform.getPlatformArchitecture()); + ss.setJavaVersionString(platform.getPlatformJDKVersion()); + ss.setJavaExecutable(platform.getPlatformJavaFile()); + } + + /** * Returns true if the provided Project is a NB source module, false otherwise. --- a/profiler.stp/src/org/netbeans/modules/profiler/stp/SelectProfilingTask.java +++ a/profiler.stp/src/org/netbeans/modules/profiler/stp/SelectProfilingTask.java @@ -78,6 +78,7 @@ import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import javax.swing.event.ChangeListener; +import org.netbeans.api.progress.ProgressUtils; import org.netbeans.lib.profiler.common.CommonUtils; import org.netbeans.lib.profiler.ui.UIUtils; import org.netbeans.modules.profiler.api.ProfilerDialogs; @@ -258,12 +259,17 @@ initClosedProjectHook(); initComponents(); initTasks(); - SwingUtilities.invokeLater(new Runnable() { - public void run() { - initTaskChooserSize(); - initPreferredSize(); - } - }); + Runnable r = new Runnable() { + public void run() { + initTaskChooserSize(); + initPreferredSize(); + } + }; + if (SwingUtilities.isEventDispatchThread()) { + r.run(); + } else { + SwingUtilities.invokeLater(r); + } } private static void initColors() { @@ -383,38 +389,45 @@ } // --- Public interface ------------------------------------------------------ - public static Configuration selectProfileProjectTask(Lookup.Provider project, FileObject profiledFile, boolean enableOverride) { + public static Configuration selectProfileProjectTask(final Lookup.Provider project, final FileObject profiledFile, final boolean enableOverride) { // Running this code in EDT would cause deadlock - assert !SwingUtilities.isEventDispatchThread(); +// assert !SwingUtilities.isEventDispatchThread(); - final SelectProfilingTask spt = getDefault(); - spt.setSubmitButton(spt.runButton); - spt.setupProfileProject(project, profiledFile, enableOverride); - - String targetName = Utils.getProjectName(project) + ((profiledFile == null) ? "" : (": " + profiledFile.getNameExt())); // NOI18N - spt.dd = new DialogDescriptor(spt, Bundle.SelectProfilingTask_ProfileDialogCaption(targetName), true, - new Object[] { spt.runButton, spt.cancelButton }, spt.runButton, 0, null, null); + final SelectProfilingTask[] spt = new SelectProfilingTask[1]; final CountDownLatch latch = new CountDownLatch(1); - SwingUtilities.invokeLater(new Runnable() { + Runnable r = new Runnable() { public void run() { - Dialog d = DialogDisplayer.getDefault().createDialog(spt.dd); + spt[0] = getDefault(); + spt[0].setSubmitButton(spt[0].runButton); + spt[0].setupProfileProject(project, profiledFile, enableOverride); + + String targetName = Utils.getProjectName(project) + ((profiledFile == null) ? "" : (": " + profiledFile.getNameExt())); // NOI18N + spt[0].dd = new DialogDescriptor(spt, Bundle.SelectProfilingTask_ProfileDialogCaption(targetName), true, + new Object[] { spt[0].runButton, spt[0].cancelButton }, spt[0].runButton, 0, null, null); + Dialog d = DialogDisplayer.getDefault().createDialog(spt[0].dd); d.getAccessibleContext().setAccessibleDescription(d.getTitle()); d.pack(); d.setVisible(true); latch.countDown(); } - }); + }; + + if (SwingUtilities.isEventDispatchThread()) { + r.run(); + } else { + SwingUtilities.invokeLater(r); + } try { latch.await(); Configuration result = null; - if (spt.dd.getValue() == spt.runButton) { - ProfilingSettings settings = spt.createFinalSettings(); + if (spt[0].dd.getValue() == spt[0].runButton) { + ProfilingSettings settings = spt[0].createFinalSettings(); if (settings.getOverrideGlobalSettings()) { String workDir = settings.getWorkingDir().trim(); if (workDir.length() != 0 && !new java.io.File(workDir).exists()) { @@ -427,7 +440,7 @@ } - spt.cleanup(result != null); + spt[0].cleanup(result != null); return result; } catch (InterruptedException e) { --- a/profiler/nbproject/project.xml +++ a/profiler/nbproject/project.xml @@ -289,6 +289,7 @@ org.netbeans.modules.profiler.freeform org.netbeans.modules.profiler.heapwalker org.netbeans.modules.profiler.j2ee + org.netbeans.modules.profiler.j2se org.netbeans.modules.profiler.nbimpl org.netbeans.modules.profiler.ppoints org.netbeans.modules.profiler.snaptracer --- a/profiler/src/org/netbeans/modules/profiler/NetBeansProfiler.java +++ a/profiler/src/org/netbeans/modules/profiler/NetBeansProfiler.java @@ -1663,7 +1663,8 @@ controlPanel2.requestActive(); } - private void setupDispatcher(ProfilingSettings profilingSettings) { + public void setupDispatcher(ProfilingSettings profilingSettings) { + lastProfilingSettings = profilingSettings; synchronized (setupLock) { final Lookup.Provider project = getProfiledProject(); @@ -1752,7 +1753,7 @@ } } } - + ProfilingPointsProcessor ppp = getProfilingPointsManager(); if (ppp != null) ppp.init(getProfiledProject()); @@ -1763,6 +1764,8 @@ // Used for killing an agent which could cause a collision on port // Returns true if TERMINATE_TARGET_JVM was invoked on agent (not necessarily killed!), false if the agent is already profiling (port is used) private boolean shutdownAgent(String host, int port) { + if (port == -1) return false; // invalid port + Socket clientSocket = null; ObjectOutputStream socketOut = null; ObjectInputStream socketIn = null; --- a/profiler/src/org/netbeans/modules/profiler/actions/JavaPlatformSelector.java +++ a/profiler/src/org/netbeans/modules/profiler/actions/JavaPlatformSelector.java @@ -51,6 +51,7 @@ import javax.swing.*; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; +import org.netbeans.modules.profiler.api.JavaPlatform; import org.netbeans.modules.profiler.api.ProfilerDialogs; import org.openide.DialogDisplayer; --- a/profiler/src/org/netbeans/modules/profiler/actions/ProfilingSupport.java +++ a/profiler/src/org/netbeans/modules/profiler/actions/ProfilingSupport.java @@ -44,7 +44,6 @@ package org.netbeans.modules.profiler.actions; import org.netbeans.lib.profiler.ProfilerLogger; -import org.netbeans.lib.profiler.TargetAppRunner; import org.netbeans.lib.profiler.common.*; import org.netbeans.modules.profiler.NetBeansProfiler; import org.netbeans.modules.profiler.ui.panels.PIDSelectPanel; @@ -52,7 +51,7 @@ import org.openide.util.NbBundle; import org.openide.util.RequestProcessor; import java.io.IOException; -import java.text.MessageFormat; +import org.netbeans.lib.profiler.TargetAppRunner; import org.netbeans.modules.profiler.api.ProfilerDialogs; import org.netbeans.modules.profiler.api.project.ProjectStorage; import org.netbeans.modules.profiler.api.TaskConfigurator; @@ -76,6 +75,7 @@ "ProfilingSupport_FailedLoadSettingsMsg=Failed to load attach settings: {0}" }) public final class ProfilingSupport { + public static final String RERUN_PROP = "profiler.rerun"; //~ Inner Classes ------------------------------------------------------------------------------------------------------------ public static class AttachSTPData { --- a/profiler/src/org/netbeans/modules/profiler/actions/ResetResultsAction.java +++ a/profiler/src/org/netbeans/modules/profiler/actions/ResetResultsAction.java @@ -119,7 +119,7 @@ @ActionRegistration(displayName="#LBL_ResetResultsAction", lazy=false) @ActionReferences({ @ActionReference(path="Menu/Profile", position=900), - @ActionReference(path = "Shortcuts", name = "AS-F2") + @ActionReference(path = "Shortcuts", name = "CA-F2") }) public static ResetResultsAction getInstance() { return Singleton.INSTANCE; --- a/projectapi/apichanges.xml +++ a/projectapi/apichanges.xml @@ -107,7 +107,24 @@ - + + +

Profiler actions are an integral part of the project infrastructure - just like the debugger actions + + + + + +

+ In order to be able to fully integrate the profiler with the project infrastructure + it is necessary to add three new constants to + ActionProvider SPI for profiling a project, profiling a single file and + profiling a test for single file. +

+
+ + + SourceGroup.contains no longer throws IllegalArgumentException --- a/projectapi/manifest.mf +++ a/projectapi/manifest.mf @@ -1,7 +1,7 @@ Manifest-Version: 1.0 OpenIDE-Module: org.netbeans.modules.projectapi/1 OpenIDE-Module-Install: org/netbeans/modules/projectapi/Installer.class -OpenIDE-Module-Specification-Version: 1.42 +OpenIDE-Module-Specification-Version: 1.43 OpenIDE-Module-Localizing-Bundle: org/netbeans/modules/projectapi/Bundle.properties OpenIDE-Module-Layer: org/netbeans/modules/projectapi/layer.xml --- a/projectapi/src/org/netbeans/spi/project/ActionProvider.java +++ a/projectapi/src/org/netbeans/spi/project/ActionProvider.java @@ -130,6 +130,24 @@ String COMMAND_DEBUG_STEP_INTO = "debug.stepinto"; // NOI18N /** + * Standard command for running the project in profiler + * @since 1.43 + */ + String COMMAND_PROFILE = "profile"; // NOI18N + + /** + * Standard command for running single file in profiler + * @since 1.43 + */ + String COMMAND_PROFILE_SINGLE = "profile.single"; // NOI18N + + /** + * Standard command for running one test in profiler + * @since 1.43 + */ + String COMMAND_PROFILE_TEST_SINGLE = "profile.test.single"; // NOI18N + + /** * Standard command for deleting the project. * * @since 1.6 --- a/projectapi/src/org/netbeans/spi/project/SingleMethod.java +++ a/projectapi/src/org/netbeans/spi/project/SingleMethod.java @@ -110,7 +110,7 @@ * @since 1.19 */ public static final String COMMAND_DEBUG_SINGLE_METHOD = "debug.single.method"; - + @Override public boolean equals(Object obj) { if ((obj == null) || (obj.getClass() != SingleMethod.class)) { --- a/web.project/src/org/netbeans/modules/web/project/WebActionProvider.java +++ a/web.project/src/org/netbeans/modules/web/project/WebActionProvider.java @@ -142,11 +142,14 @@ COMMAND_RUN_SINGLE, COMMAND_DEBUG, COMMAND_DEBUG_SINGLE, + COMMAND_PROFILE, + COMMAND_PROFILE_SINGLE, WebProjectConstants.COMMAND_REDEPLOY, JavaProjectConstants.COMMAND_JAVADOC, COMMAND_TEST, COMMAND_TEST_SINGLE, COMMAND_DEBUG_TEST_SINGLE, + COMMAND_PROFILE_TEST_SINGLE, SingleMethod.COMMAND_RUN_SINGLE_METHOD, SingleMethod.COMMAND_DEBUG_SINGLE_METHOD, JavaProjectConstants.COMMAND_DEBUG_FIX, @@ -163,12 +166,14 @@ COMMAND_COMPILE_SINGLE, COMMAND_RUN_SINGLE, COMMAND_DEBUG_SINGLE, + COMMAND_PROFILE_SINGLE, JavaProjectConstants.COMMAND_JAVADOC, COMMAND_TEST, COMMAND_TEST_SINGLE, COMMAND_DEBUG_TEST_SINGLE, + COMMAND_PROFILE_TEST_SINGLE, SingleMethod.COMMAND_RUN_SINGLE_METHOD, - SingleMethod.COMMAND_DEBUG_SINGLE_METHOD, + SingleMethod.COMMAND_DEBUG_SINGLE_METHOD }; /**Set of commands which are affected by background scanning*/ @@ -201,14 +206,18 @@ commands.put(COMMAND_DEBUG, new String[]{"debug"}); // NOI18N // the target name is debug, except for Java files with main method, where it is debug-single-main commands.put(COMMAND_DEBUG_SINGLE, new String[]{"debug-single-main"}); // NOI18N + commands.put(COMMAND_PROFILE, new String[]{"profile"}); // NOI18N + commands.put(COMMAND_PROFILE_SINGLE, new String[]{"profile-single-main"}); // NOI18N commands.put(JavaProjectConstants.COMMAND_JAVADOC, new String[]{"javadoc"}); // NOI18N commands.put(COMMAND_TEST, new String[]{"test"}); // NOI18N commands.put(COMMAND_TEST_SINGLE, new String[]{"test-single"}); // NOI18N commands.put(COMMAND_DEBUG_TEST_SINGLE, new String[]{"debug-test"}); // NOI18N + commands.put(COMMAND_PROFILE_TEST_SINGLE, new String[]{"profile-test"}); // NOI18N commands.put(JavaProjectConstants.COMMAND_DEBUG_FIX, new String[]{"debug-fix"}); // NOI18N commands.put(COMMAND_VERIFY, new String[]{"verify"}); // NOI18N this.bkgScanSensitiveActions = new HashSet(Arrays.asList( - COMMAND_RUN_SINGLE + COMMAND_RUN_SINGLE, + COMMAND_PROFILE_SINGLE )); this.needJavaModelActions = new HashSet(Arrays.asList( @@ -254,9 +263,9 @@ @Override protected void updateJavaRunnerClasspath(String command, Map execProperties) { - if (COMMAND_TEST_SINGLE.equals(command) || COMMAND_DEBUG_TEST_SINGLE.equals(command) || + if (COMMAND_TEST_SINGLE.equals(command) || COMMAND_DEBUG_TEST_SINGLE.equals(command) || COMMAND_PROFILE_TEST_SINGLE.equals(command) || SingleMethod.COMMAND_DEBUG_SINGLE_METHOD.equals(command) || SingleMethod.COMMAND_RUN_SINGLE_METHOD.equals(command) || - COMMAND_RUN_SINGLE.equals(command) || COMMAND_DEBUG_SINGLE.equals(command)) { + COMMAND_RUN_SINGLE.equals(command) || COMMAND_DEBUG_SINGLE.equals(command) || COMMAND_PROFILE_SINGLE.equals(command)) { FileObject fo = (FileObject)execProperties.get(JavaRunner.PROP_EXECUTE_FILE); ClassPath cp = getCallback().findClassPath(fo, ClassPath.EXECUTE); ClassPath cp2 = ClassPathFactory.createClassPath( @@ -287,7 +296,7 @@ @Override protected boolean handleJavaClass(Properties p, FileObject javaFile, String command, List targetNames) { - return runServlet(p, javaFile, "LBL_RunAction", false, targetNames); + return runServlet(p, javaFile, "LBL_RunAction", COMMAND_DEBUG_SINGLE.equals(command), COMMAND_PROFILE_SINGLE.equals(command), targetNames); } @Override @@ -295,7 +304,8 @@ if (command.equals(COMMAND_RUN_SINGLE) ||command.equals(COMMAND_RUN) || command.equals(WebProjectConstants.COMMAND_REDEPLOY) ||command.equals(COMMAND_DEBUG) || command.equals(COMMAND_DEBUG_SINGLE) || command.equals(JavaProjectConstants.COMMAND_DEBUG_FIX) || - command.equals( COMMAND_TEST_SINGLE) || command.equals(COMMAND_DEBUG_TEST_SINGLE)) { + command.equals(COMMAND_PROFILE) || command.equals(COMMAND_PROFILE_SINGLE) || + command.equals( COMMAND_TEST_SINGLE) || command.equals(COMMAND_DEBUG_TEST_SINGLE) || command.equals(COMMAND_PROFILE_TEST_SINGLE)) { setDirectoryDeploymentProperty(p); } @@ -308,7 +318,7 @@ if (isDebugged()) { p.setProperty("is.debugged", "true"); } - if (command.equals(COMMAND_RUN_SINGLE) || command.equals(COMMAND_DEBUG_SINGLE)) { + if (command.equals(COMMAND_RUN_SINGLE) || command.equals(COMMAND_DEBUG_SINGLE) || command.equals(COMMAND_PROFILE_SINGLE)) { String res[] = super.getTargetNames(command, context, p, doJavaChecks); if (res != null) { return res; @@ -323,6 +333,8 @@ if (!keepDebugging) { return null; } + } else if (command.equals(COMMAND_PROFILE_SINGLE)) { + targetNames = new String[]{"profile"}; } else { targetNames = new String[]{"run"}; } @@ -372,6 +384,11 @@ return null; } return commands.get(command); + } else if (command.equals(COMMAND_PROFILE)) { + if (!isSelectedServer()) { + return null; + } + initWebServiceProperties(p); } else if (command.equals(COMMAND_DEBUG)) { if (!isSelectedServer()) { return null; @@ -486,8 +503,10 @@ // Fix for IZ#170419 - Invoking Run took 29110 ms. private boolean runServlet( Properties p, FileObject javaFile, String - actionName , boolean debug, List targetNames) + actionName , boolean debug, boolean profile, List targetNames) { + assert !(debug && profile); + // run servlet // PENDING - what about servlets with main method? servlet should take // precedence @@ -576,7 +595,13 @@ return runEmptyMapping(javaFile); } p.setProperty(BaseActionProvider.PROPERTY_RUN_SINGLE_ON_SERVER, "yes"); - targetNames.add("run"); // NOI18N + if (profile) { + targetNames.add("profile"); // NOI18N + } else if (debug) { + targetNames.add("debug"); // NOI18N + } else { + targetNames.add("run"); // NOI18N + } return true; } @@ -784,7 +809,8 @@ } if (command.equals(COMMAND_COMPILE_SINGLE) || command.equals(COMMAND_DEBUG_SINGLE) || - command.equals(COMMAND_RUN_SINGLE)) { + command.equals(COMMAND_RUN_SINGLE) || + command.equals(COMMAND_PROFILE_SINGLE)) { if (findJsps(context) != null || findHtml(context) != null ) { return true; } else { --- a/web.project/src/org/netbeans/modules/web/project/resources/build-impl.xsl +++ a/web.project/src/org/netbeans/modules/web/project/resources/build-impl.xsl @@ -719,6 +719,7 @@ + @@ -940,22 +941,33 @@
- + + pre NB7.2 profiling section; consider it deprecated + + + profiler.info.jvmargs.agent + Empty placeholder for easier customization. You can override this target in the ../build.xml file. + profiler.info.jvmargs.agent Empty placeholder for easier customization. You can override this target in the ../build.xml file. + profiler.info.jvmargs.agent -profile-pre-init, init, -profile-post-init + profiler.info.jvmargs.agent Must set JVM to use for profiling in profiler.info.jvm Must set profiler agent JVM arguments in profiler.info.jvmargs.agent + + end of pre NB7.2 profiling section + -pre-init,-init-private,-init-libraries,-init-user,-init-project,-do-init,-post-init,-init-check,-init-macrodef-property,-init-macrodef-javac,-init-macrodef-junit,-init-macrodef-java,-init-macrodef-nbjpda,-init-macrodef-nbjsdebug,-init-macrodef-debug,-init-taskdefs,-init-ap-cmdline @@ -1712,8 +1724,12 @@ ================= - + + pre NB7.2 profiling section; consider it deprecated + + Profile a J2EE project in the IDE. + profiler.info.jvmargs.agent profiler.startserver.target start-profiled-server-extraargs @@ -1729,11 +1745,11 @@ run
- start-loadgen + -profile-start-loadgen - + ${profiler.j2ee.serverForceRestart} ${profiler.j2ee.serverStartupTimeout} @@ -1747,7 +1763,7 @@ - + ${profiler.j2ee.serverForceRestart} ${profiler.j2ee.serverStartupTimeout} @@ -1763,11 +1779,71 @@ + + + profiler.info.jvmargs.agent + This target only works when run from inside the NetBeans IDE. + profile-init,compile-test-single + + + + + + - - - ${profiler.loadgen.path} - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Profile a J2EE project in the IDE. + + + + + + + debug-display-browser + + + -profile-start-loadgen + + + + + + + + + + + + + ${profiler.loadgen.path} + @@ -2051,40 +2127,6 @@ netbeans.home init,-pre-debug-fix,-do-debug-fix-test - - - ========================= - TESTS PROFILING SECTION - ========================= - - - - netbeans.home - profile-init,compile-test-single - - - - - - - - - - - - - - - - - - - - - - - - --- a/web.project/src/org/netbeans/modules/web/project/ui/resources/layer.xml +++ a/web.project/src/org/netbeans/modules/web/project/ui/resources/layer.xml @@ -234,10 +234,6 @@
- - - -