execution-impl

This commit is contained in:
Dmitry Jemerov
2009-08-30 20:45:43 +04:00
parent 786fa6b666
commit b37036acfc
52 changed files with 1 additions and 1 deletions
+27
View File
@@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8"?>
<module relativePaths="true" type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="module" module-name="openapi" />
<orderEntry type="module" module-name="idea" />
<orderEntry type="module" module-name="execution-openapi" />
<orderEntry type="module" module-name="idea_rt" />
<orderEntry type="module" module-name="resources_eng" />
<orderEntry type="module" module-name="refactoring-openapi" />
<orderEntry type="module" module-name="debugger-impl" />
<orderEntry type="library" name="JUnit4" level="project" />
<orderEntry type="library" name="jgoodies-forms" level="project" />
<orderEntry type="module" module-name="testRunner" />
</component>
<component name="copyright">
<Base>
<setting name="state" value="1" />
</Base>
</component>
</module>
@@ -0,0 +1,125 @@
package com.intellij.compiler.options;
import com.intellij.execution.BeforeRunTask;
import com.intellij.execution.BeforeRunTaskProvider;
import com.intellij.execution.ExecutionBundle;
import com.intellij.execution.configurations.RunConfiguration;
import com.intellij.execution.configurations.RunProfileWithCompileBeforeLaunchOption;
import com.intellij.execution.remote.RemoteConfiguration;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.compiler.CompileContext;
import com.intellij.openapi.compiler.CompileScope;
import com.intellij.openapi.compiler.CompileStatusNotification;
import com.intellij.openapi.compiler.CompilerManager;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import com.intellij.util.concurrency.Semaphore;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* @author spleaner
*/
public class CompileStepBeforeRun implements BeforeRunTaskProvider<CompileStepBeforeRun.MakeBeforeRunTask> {
public static final Key<MakeBeforeRunTask> ID = Key.create("Make");
private static final Key<RunConfiguration> RUN_CONFIGURATION = Key.create("RUN_CONFIGURATION");
@NonNls protected static final String MAKE_PROJECT_ON_RUN_KEY = "makeProjectOnRun";
private final Project myProject;
public CompileStepBeforeRun(@NotNull final Project project) {
myProject = project;
}
public Key<MakeBeforeRunTask> getId() {
return ID;
}
public String getDescription(final RunConfiguration runConfiguration, MakeBeforeRunTask task) {
return ExecutionBundle.message("before.launch.compile.step");
}
public MakeBeforeRunTask createTask(RunConfiguration runConfiguration) {
return !(runConfiguration instanceof RemoteConfiguration) && runConfiguration instanceof RunProfileWithCompileBeforeLaunchOption
? new MakeBeforeRunTask()
: null;
}
public void configureTask(RunConfiguration runConfiguration, MakeBeforeRunTask task) {
}
public boolean executeTask(DataContext context, final RunConfiguration configuration, MakeBeforeRunTask task) {
if (!(configuration instanceof RunProfileWithCompileBeforeLaunchOption)) {
return true;
}
final RunProfileWithCompileBeforeLaunchOption runConfiguration = (RunProfileWithCompileBeforeLaunchOption)configuration;
final Semaphore done = new Semaphore();
final boolean[] result = new boolean[1];
try {
final CompileStatusNotification callback = new CompileStatusNotification() {
public void finished(final boolean aborted, final int errors, final int warnings, CompileContext compileContext) {
if (errors == 0 && !aborted) {
result[0] = true;
}
done.up();
}
};
ApplicationManager.getApplication().invokeAndWait(new Runnable() {
public void run() {
CompileScope scope;
final CompilerManager compilerManager = CompilerManager.getInstance(myProject);
if (Boolean.valueOf(System.getProperty(MAKE_PROJECT_ON_RUN_KEY, Boolean.FALSE.toString())).booleanValue()) {
// user explicitly requested whole-project make
scope = compilerManager.createProjectCompileScope(myProject);
}
else {
final Module[] modules = runConfiguration.getModules();
if (modules.length > 0) {
scope = compilerManager.createModulesCompileScope(modules, true);
}
else {
scope = compilerManager.createProjectCompileScope(myProject);
}
}
done.down();
scope.putUserData(RUN_CONFIGURATION, configuration);
compilerManager.make(scope, callback);
}
}, ModalityState.NON_MODAL);
}
catch (Exception e) {
return false;
}
done.waitFor();
return result[0];
}
public boolean hasConfigurationButton() {
return false;
}
@Nullable
public static RunConfiguration getRunConfiguration(final CompileContext context) {
return context.getCompileScope().getUserData(RUN_CONFIGURATION);
}
@Nullable
public static RunConfiguration getRunConfiguration(final CompileScope compileScope) {
return compileScope.getUserData(RUN_CONFIGURATION);
}
public static class MakeBeforeRunTask extends BeforeRunTask {
private MakeBeforeRunTask() {
setEnabled(true);
}
}
}
@@ -0,0 +1,49 @@
package com.intellij.execution;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.JDOMExternalizable;
import com.intellij.openapi.util.WriteExternalException;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFileManager;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import java.io.File;
/**
* @author dyoma
*/
public class ExternalizablePath implements JDOMExternalizable {
@NonNls private static final String VALUE_ATTRIBUTE = "value";
private String myUrl;
public void readExternal(final Element element) throws InvalidDataException {
final String value = element.getAttributeValue(VALUE_ATTRIBUTE);
myUrl = value != null ? value : "";
final String protocol = VirtualFileManager.extractProtocol(myUrl);
if (protocol == null) myUrl = urlValue(myUrl);
}
public void writeExternal(final Element element) throws WriteExternalException {
element.setAttribute(VALUE_ATTRIBUTE, myUrl);
}
public String getLocalPath() {
return localPathValue(myUrl);
}
public static String urlValue(String localPath) {
if (localPath == null) return "";
localPath = localPath.trim();
if (localPath.length() == 0) return "";
return VirtualFileManager.constructUrl(LocalFileSystem.PROTOCOL, localPath.replace(File.separatorChar, '/'));
}
public static String localPathValue(String url) {
if (url == null) return "";
url = url.trim();
if (url.length() == 0) return "";
return VirtualFileManager.extractPath(url).replace('/', File.separatorChar);
}
}
@@ -0,0 +1,73 @@
/*
* Copyright 2000-2007 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Created by IntelliJ IDEA.
* User: yole
* Date: 31.01.2007
* Time: 13:56:12
*/
package com.intellij.execution;
import com.intellij.execution.configurations.JavaParameters;
import com.intellij.execution.configurations.ModuleBasedConfiguration;
import com.intellij.execution.configurations.RunnerSettings;
import com.intellij.execution.process.OSProcessHandler;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.options.SettingsEditor;
import com.intellij.openapi.options.SettingsEditorGroup;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.WriteExternalException;
import com.intellij.ui.LayeredIcon;
import org.jetbrains.annotations.Nullable;
import org.jdom.Element;
import javax.swing.*;
public abstract class RunConfigurationExtension {
public static final ExtensionPointName<RunConfigurationExtension> EP_NAME = new ExtensionPointName<RunConfigurationExtension>("com.intellij.runConfigurationExtension");
public abstract void handleStartProcess(final ModuleBasedConfiguration configuration, final OSProcessHandler handler);
public abstract <T extends ModuleBasedConfiguration & RunJavaConfiguration> SettingsEditor createEditor(T configuration);
public abstract String getEditorTitle();
@Nullable
public abstract <T extends ModuleBasedConfiguration & RunJavaConfiguration> Icon getIcon(T runConfiguration);
public static <T extends ModuleBasedConfiguration & RunJavaConfiguration> void appendEditors(T configuration, SettingsEditorGroup<T> group) {
for (RunConfigurationExtension extension : Extensions.getExtensions(EP_NAME)) {
final SettingsEditor editor = extension.createEditor(configuration);
if (editor != null) {
group.addEditor(extension.getEditorTitle(), editor);
}
}
}
public static <T extends ModuleBasedConfiguration & RunJavaConfiguration> Icon getIcon(T configuration, Icon icon) {
for (RunConfigurationExtension extension : Extensions.getExtensions(EP_NAME)) {
final Icon extIcon = extension.getIcon(configuration);
if (extIcon != null) {
return LayeredIcon.create(icon, extIcon);
}
}
return icon;
}
public abstract <T extends ModuleBasedConfiguration & RunJavaConfiguration> void updateJavaParameters(final T configuration, final JavaParameters params, RunnerSettings runnerSettings);
public abstract void readExternal(ModuleBasedConfiguration runConfiguration, Element element) throws InvalidDataException;
public abstract void writeExternal(ModuleBasedConfiguration runConfiguration, Element element) throws WriteExternalException;
}
@@ -0,0 +1,22 @@
package com.intellij.execution;
import com.intellij.openapi.project.Project;
public interface RunJavaConfiguration {
int VM_PARAMETERS_PROPERTY = 0;
int PROGRAM_PARAMETERS_PROPERTY = 1;
int WORKING_DIRECTORY_PROPERTY = 2;
void setProperty(int property, String value);
String getProperty(int property);
Project getProject();
boolean isAlternativeJrePathEnabled();
void setAlternativeJrePathEnabled(boolean enabled);
String getAlternativeJrePath();
void setAlternativeJrePath(String ALTERNATIVE_JRE_PATH);
}
@@ -0,0 +1,20 @@
/*
* Copyright (c) 2000-2004 by JetBrains s.r.o. All Rights Reserved.
* Use is subject to license terms.
*/
package com.intellij.execution;
import com.intellij.execution.configurations.ConfigurationFactory;
import com.intellij.execution.configurations.ModuleBasedConfiguration;
import com.intellij.execution.configurations.RunConfigurationModule;
import com.intellij.psi.PsiClass;
/**
* @author dyoma
*/
public interface SingleClassConfiguration {
void setMainClass(final PsiClass psiClass);
PsiClass getMainClass();
void setMainClassName(String qualifiedName);
}
@@ -0,0 +1,188 @@
/*
* Copyright 2000-2008 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* User: anna
* Date: 24-Dec-2008
*/
package com.intellij.execution.actions;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.Executor;
import com.intellij.execution.RunnerRegistry;
import com.intellij.execution.configurations.*;
import com.intellij.execution.executors.DefaultDebugExecutor;
import com.intellij.execution.executors.DefaultRunExecutor;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.execution.runners.ProgramRunner;
import com.intellij.execution.testframework.*;
import com.intellij.idea.ActionsBundle;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.options.SettingsEditor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Getter;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.JDOMExternalizable;
import com.intellij.openapi.util.WriteExternalException;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import java.util.List;
public class AbstractRerunFailedTestsAction extends AnAction {
private static final Logger LOG = Logger.getInstance("#com.intellij.execution.junit2.ui.actions.RerunFailedTestsAction");
private TestFrameworkRunningModel myModel;
private Getter<TestFrameworkRunningModel> myModelProvider;
protected TestConsoleProperties myConsoleProperties;
protected RunnerSettings myRunnerSettings;
protected ConfigurationPerRunnerSettings myConfigurationPerRunnerSettings;
public void init(final TestConsoleProperties consoleProperties,
final RunnerSettings runnerSettings,
final ConfigurationPerRunnerSettings configurationSettings) {
myConfigurationPerRunnerSettings = configurationSettings;
myRunnerSettings = runnerSettings;
myConsoleProperties = consoleProperties;
}
public void setModel(TestFrameworkRunningModel model) {
myModel = model;
}
public void setModelProvider(Getter<TestFrameworkRunningModel> modelProvider) {
myModelProvider = modelProvider;
}
public void update(AnActionEvent e) {
e.getPresentation().setEnabled(isActive(e));
}
private boolean isActive(AnActionEvent e) {
DataContext dataContext = e.getDataContext();
Project project = PlatformDataKeys.PROJECT.getData(dataContext);
if (project == null) return false;
TestFrameworkRunningModel model = getModel();
if (model == null || model.getRoot() == null) return false;
List<AbstractTestProxy> failed = getFailedTests(project);
return !failed.isEmpty();
}
@NotNull
protected List<AbstractTestProxy> getFailedTests(Project project) {
List<? extends AbstractTestProxy> myAllTests = getModel().getRoot().getAllTests();
return Filter.DEFECTIVE_LEAF.and(JavaAwareFilter.METHOD(project)).select(myAllTests);
}
public void actionPerformed(AnActionEvent e) {
final DataContext dataContext = e.getDataContext();
boolean isDebug = myConsoleProperties.isDebug();
final MyRunProfile profile = getRunProfile();
try {
final Executor executor = isDebug ? DefaultDebugExecutor.getDebugExecutorInstance() : DefaultRunExecutor.getRunExecutorInstance();
final ProgramRunner runner = RunnerRegistry.getInstance().getRunner(executor.getId(), profile);
assert runner != null;
runner.execute(executor, new ExecutionEnvironment(profile, myRunnerSettings, myConfigurationPerRunnerSettings, dataContext));
}
catch (ExecutionException e1) {
LOG.error(e1);
}
finally {
profile.clear();
}
}
public MyRunProfile getRunProfile() {
return null;
}
public TestFrameworkRunningModel getModel() {
if (myModel != null) {
return myModel;
}
if (myModelProvider != null) {
return myModelProvider.get();
}
return null;
}
protected static abstract class MyRunProfile implements ModuleRunProfile, RunConfiguration {
private final RunConfiguration myConfiguration;
public MyRunProfile(RunConfiguration configuration) {
myConfiguration = configuration;
}
public void clear() { }
public String getName() {
return ActionsBundle.message("action.RerunFailedTests.text");
}
public void checkConfiguration() throws RuntimeConfigurationException {}
///////////////////////////////////Delegates
public void readExternal(final Element element) throws InvalidDataException {
myConfiguration.readExternal(element);
}
public void writeExternal(final Element element) throws WriteExternalException {
myConfiguration.writeExternal(element);
}
public ConfigurationFactory getFactory() {
return myConfiguration.getFactory();
}
public void setName(final String name) {
myConfiguration.setName(name);
}
public SettingsEditor<? extends RunConfiguration> getConfigurationEditor() {
return myConfiguration.getConfigurationEditor();
}
public Project getProject() {
return myConfiguration.getProject();
}
@NotNull
public ConfigurationType getType() {
return myConfiguration.getType();
}
public JDOMExternalizable createRunnerSettings(final ConfigurationInfoProvider provider) {
return myConfiguration.createRunnerSettings(provider);
}
public SettingsEditor<JDOMExternalizable> getRunnerSettingsEditor(final ProgramRunner runner) {
return myConfiguration.getRunnerSettingsEditor(runner);
}
public RunConfiguration clone() {
return myConfiguration.clone();
}
public int getUniqueID() {
return myConfiguration.getUniqueID();
}
}
}
@@ -0,0 +1,316 @@
<?xml version="1.0" encoding="UTF-8"?>
<form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="com.intellij.execution.applet.AppletConfigurable">
<grid id="e5f4d" binding="myWholePanel" row-count="7" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<xy x="133" y="39" width="454" height="596"/>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<grid id="ccef6" row-count="1" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<xy x="0" y="0" width="454" height="22"/>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="1" hsize-policy="0" anchor="0" fill="1"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<component id="fa258" class="javax.swing.JRadioButton" binding="myMainClass">
<constraints>
<xy x="0" y="0" width="84" height="22"/>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0"/>
</constraints>
<properties>
<selected value="true"/>
<text resource-bundle="messages/ExecutionBundle" key="applet.configuration.applet.class.label"/>
</properties>
</component>
<component id="74d77" class="javax.swing.JRadioButton" binding="myURL">
<constraints>
<xy x="94" y="0" width="46" height="22"/>
<grid row="0" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="8" fill="0"/>
</constraints>
<properties>
<text resource-bundle="messages/ExecutionBundle" key="applet.configuration.url.label"/>
</properties>
</component>
</children>
</grid>
<component id="5dbf7" class="com.intellij.openapi.ui.LabeledComponent" binding="myPolicyFile">
<constraints>
<xy x="0" y="407" width="454" height="39"/>
<grid row="2" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="1" fill="1"/>
</constraints>
<properties>
<componentClass value="com.intellij.openapi.ui.TextFieldWithBrowseButton"/>
<labelInsets top="0" left="0" bottom="5" right="0"/>
<text resource-bundle="messages/ExecutionBundle" key="applet.configuration.policy.file.label"/>
</properties>
</component>
<component id="67632" class="com.intellij.openapi.ui.LabeledComponent" binding="myVMParameters">
<constraints>
<xy x="0" y="451" width="454" height="21"/>
<grid row="3" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="1" fill="1">
<preferred-size width="400" height="-1"/>
</grid>
</constraints>
<properties>
<componentClass value="com.intellij.ui.RawCommandLineEditor"/>
<labelInsets top="5" left="0" bottom="2" right="0"/>
<text resource-bundle="messages/ExecutionBundle" key="applet.configuration.vm.parameters.for.appletviewer.label"/>
</properties>
</component>
<component id="eac49" class="com.intellij.openapi.ui.LabeledComponent" binding="myModule">
<constraints>
<xy x="0" y="477" width="454" height="46"/>
<grid row="4" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="1" fill="1"/>
</constraints>
<properties>
<componentClass value="javax.swing.JComboBox"/>
<labelInsets top="5" left="0" bottom="5" right="0"/>
<text resource-bundle="messages/ExecutionBundle" key="applet.configuration.use.classpath.and.jdk.of.module.label"/>
</properties>
</component>
<grid id="c178e" row-count="2" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<xy x="0" y="27" width="454" height="375"/>
<grid row="1" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<grid id="dbe39" binding="myHTMLOptions" row-count="1" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="5" vgap="-1">
<margin top="5" left="5" bottom="5" right="5"/>
<constraints>
<xy x="0" y="0" width="454" height="56"/>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="7" hsize-policy="3" anchor="1" fill="1"/>
</constraints>
<properties/>
<border type="etched" title-resource-bundle="messages/ExecutionBundle" title-key="applet.configuration.url.border"/>
<children>
<component id="a2b70" class="javax.swing.JLabel" binding="myHtmlFileLabel">
<constraints>
<xy x="11" y="28" width="74" height="14"/>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0"/>
</constraints>
<properties>
<text resource-bundle="messages/ExecutionBundle" key="applet.configuration.url.html.file.label"/>
</properties>
</component>
<component id="9aa99" class="com.intellij.openapi.ui.TextFieldWithBrowseButton" binding="myHtmlFile">
<constraints>
<xy x="90" y="25" width="353" height="20"/>
<grid row="0" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="8" fill="3"/>
</constraints>
<properties>
<text value=""/>
</properties>
</component>
</children>
</grid>
<grid id="71bb1" binding="myClassOptions" row-count="4" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="7">
<margin top="5" left="5" bottom="5" right="5"/>
<constraints>
<xy x="0" y="61" width="454" height="314"/>
<grid row="1" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="1" fill="1"/>
</constraints>
<properties>
<enabled value="true"/>
</properties>
<border type="etched" title-resource-bundle="messages/ExecutionBundle" title-key="applet.configuration.applet.class.border"/>
<children>
<grid id="9c777" row-count="1" column-count="4" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<xy x="11" y="52" width="432" height="20"/>
<grid row="1" column="0" row-span="1" col-span="1" vsize-policy="1" hsize-policy="3" anchor="0" fill="3"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<component id="575e9" class="javax.swing.JTextField" binding="myWidth">
<constraints>
<xy x="62" y="0" width="50" height="20"/>
<grid row="0" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0">
<minimum-size width="50" height="-1"/>
</grid>
</constraints>
<properties>
<text value=""/>
</properties>
</component>
<component id="60aa" class="javax.swing.JLabel" binding="myWidthLabel">
<constraints>
<xy x="0" y="3" width="52" height="14"/>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="4" fill="0">
<minimum-size width="52" height="-1"/>
</grid>
</constraints>
<properties>
<text resource-bundle="messages/ExecutionBundle" key="applet.configuration.width.label"/>
</properties>
</component>
<component id="3cd8" class="javax.swing.JLabel" binding="myHeightLabel">
<constraints>
<xy x="122" y="3" width="39" height="14"/>
<grid row="0" column="2" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="4" fill="0"/>
</constraints>
<properties>
<text resource-bundle="messages/ExecutionBundle" key="applet.configuration.height.label"/>
</properties>
</component>
<component id="16d37" class="javax.swing.JTextField" binding="myHeight">
<constraints>
<xy x="171" y="0" width="50" height="20"/>
<grid row="0" column="3" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="8" fill="0">
<minimum-size width="50" height="-1"/>
</grid>
</constraints>
<properties>
<text value=""/>
</properties>
</component>
</children>
</grid>
<grid id="32908" row-count="1" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<xy x="11" y="106" width="432" height="197"/>
<grid row="3" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="1" fill="1"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<grid id="f7d4e" row-count="3" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<xy x="357" y="0" width="75" height="197"/>
<grid row="0" column="1" row-span="1" col-span="1" vsize-policy="3" hsize-policy="1" anchor="0" fill="3"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<component id="e3f93" class="javax.swing.JButton" binding="myAddButton">
<constraints>
<xy x="0" y="0" width="75" height="25"/>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1"/>
</constraints>
<properties>
<text resource-bundle="messages/ExecutionBundle" key="button.add"/>
</properties>
</component>
<component id="1e21d" class="javax.swing.JButton" binding="myRemoveButton">
<constraints>
<xy x="0" y="32" width="75" height="25"/>
<grid row="1" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1"/>
</constraints>
<properties>
<text resource-bundle="messages/ExecutionBundle" key="button.remove"/>
</properties>
</component>
<vspacer id="b7052">
<constraints>
<xy x="32" y="57" width="11" height="140"/>
<grid row="2" column="0" row-span="1" col-span="1" vsize-policy="6" hsize-policy="1" anchor="0" fill="2"/>
</constraints>
</vspacer>
</children>
</grid>
<xy id="814cb" binding="myTablePlace" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<xy x="0" y="0" width="347" height="197"/>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="-1" height="100"/>
</grid>
</constraints>
<properties/>
<border type="none"/>
<children/>
</xy>
</children>
</grid>
<grid id="d9c99" row-count="1" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="5">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<xy x="11" y="25" width="432" height="20"/>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="1" fill="1"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<component id="36125" class="javax.swing.JLabel" binding="myClassNameLabel">
<constraints>
<xy x="0" y="3" width="65" height="14"/>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="4" fill="0"/>
</constraints>
<properties>
<text resource-bundle="messages/ExecutionBundle" key="applet.configuration.applet.class.label"/>
</properties>
</component>
<component id="70a46" class="com.intellij.openapi.ui.TextFieldWithBrowseButton" binding="myClassName">
<constraints>
<xy x="75" y="0" width="357" height="20"/>
<grid row="0" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="8" fill="3"/>
</constraints>
<properties>
<text value=""/>
</properties>
</component>
</children>
</grid>
<grid id="fcccf" row-count="1" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<xy x="11" y="79" width="432" height="20"/>
<grid row="2" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<component id="de175" class="javax.swing.JLabel">
<constraints>
<xy x="0" y="3" width="93" height="14"/>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0"/>
</constraints>
<properties>
<text resource-bundle="messages/ExecutionBundle" key="applet.configuration.applet.parameters.label"/>
</properties>
</component>
<xy id="c0444" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<xy x="103" y="9" width="329" height="1"/>
<grid row="0" column="1" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<maximum-size width="-1" height="1"/>
</grid>
</constraints>
<properties/>
<border type="bevel-raised"/>
<children/>
</xy>
</children>
</grid>
</children>
</grid>
</children>
</grid>
<vspacer id="8b063">
<constraints>
<xy x="221" y="548" width="11" height="48"/>
<grid row="6" column="0" row-span="1" col-span="1" vsize-policy="6" hsize-policy="1" anchor="0" fill="2"/>
</constraints>
</vspacer>
<component id="b2d36" class="com.intellij.execution.ui.AlternativeJREPanel" binding="myAlternativeJREPanel">
<constraints>
<xy x="0" y="528" width="454" height="20"/>
<grid row="5" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="1"/>
</constraints>
</component>
</children>
</grid>
</form>
@@ -0,0 +1,288 @@
package com.intellij.execution.applet;
import com.intellij.execution.ExecutionBundle;
import com.intellij.execution.impl.CheckableRunConfigurationEditor;
import com.intellij.execution.junit2.configuration.ClassBrowser;
import com.intellij.execution.junit2.configuration.ConfigurationModuleSelector;
import com.intellij.execution.ui.AlternativeJREPanel;
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory;
import com.intellij.openapi.options.SettingsEditor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.LabeledComponent;
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.ui.RawCommandLineEditor;
import com.intellij.ui.ScrollPaneFactory;
import com.intellij.ui.table.TableView;
import com.intellij.util.ui.ColumnInfo;
import com.intellij.util.ui.ListTableModel;
import org.jetbrains.annotations.NonNls;
import javax.swing.*;
import javax.swing.table.TableCellEditor;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.*;
import java.util.List;
public class AppletConfigurable extends SettingsEditor<AppletConfiguration> implements CheckableRunConfigurationEditor<AppletConfiguration>{
private JPanel myWholePanel;
private JRadioButton myMainClass;
private JRadioButton myURL;
private JPanel myClassOptions;
private JPanel myHTMLOptions;
private LabeledComponent<TextFieldWithBrowseButton> myPolicyFile;
private LabeledComponent<RawCommandLineEditor> myVMParameters;
private TextFieldWithBrowseButton myClassName;
private TextFieldWithBrowseButton myHtmlFile;
private JTextField myWidth;
private JTextField myHeight;
private LabeledComponent<JComboBox> myModule;
private JPanel myTablePlace;
private JButton myAddButton;
private JButton myRemoveButton;
private JLabel myHtmlFileLabel;
private JLabel myClassNameLabel;
private JLabel myWidthLabel;
private JLabel myHeightLabel;
private AlternativeJREPanel myAlternativeJREPanel;
private final ButtonGroup myAppletRadioButtonGroup = new ButtonGroup();
private final Project myProject;
private final ConfigurationModuleSelector myModuleSelector;
private static final ColumnInfo[] PARAMETER_COLUMNS = new ColumnInfo[]{
new MyColumnInfo(ExecutionBundle.message("applet.configuration.parameter.name.column")){
public String valueOf(final AppletConfiguration.AppletParameter appletParameter) {
return appletParameter.getName();
}
public void setValue(final AppletConfiguration.AppletParameter appletParameter, final String name) {
appletParameter.setName(name);
}
},
new MyColumnInfo(ExecutionBundle.message("applet.configuration.parameter.value.column")) {
public String valueOf(final AppletConfiguration.AppletParameter appletParameter) {
return appletParameter.getValue();
}
public void setValue(final AppletConfiguration.AppletParameter appletParameter, final String value) {
appletParameter.setValue(value);
}
}
};
private final ListTableModel<AppletConfiguration.AppletParameter> myParameters = new ListTableModel<AppletConfiguration.AppletParameter>(PARAMETER_COLUMNS);
private final TableView myTable;
@NonNls
protected static final String HTTP_PREFIX = "http:/";
private void changePanel () {
if (myMainClass.isSelected()) {
myClassOptions.setVisible(true);
myHTMLOptions.setVisible(false);
}
else {
myHTMLOptions.setVisible(true);
myClassOptions.setVisible(false);
}
}
public AppletConfigurable(final Project project) {
myClassNameLabel.setLabelFor(myClassName.getTextField());
myHtmlFileLabel.setLabelFor(myHtmlFile.getTextField());
myWidthLabel.setLabelFor(myWidth);
myHeightLabel.setLabelFor(myHeight);
myProject = project;
myModuleSelector = new ConfigurationModuleSelector(project, getModuleComponent());
myTablePlace.setLayout(new BorderLayout());
myTable = new TableView(myParameters);
myTablePlace.add(ScrollPaneFactory.createScrollPane(myTable), BorderLayout.CENTER);
myAppletRadioButtonGroup.add(myMainClass);
myAppletRadioButtonGroup.add(myURL);
getVMParametersComponent().setDialogCaption(myVMParameters.getRawText());
myMainClass.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
changePanel();
}
});
myURL.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
changePanel();
}
});
getPolicyFileComponent().addBrowseFolderListener(ExecutionBundle.message("select.applet.policy.file.dialog.title"), null, myProject,
FileChooserDescriptorFactory.createSingleFileNoJarsDescriptor());
getHtmlPathComponent().addBrowseFolderListener(ExecutionBundle.message("choose.html.file.dialog.title"), null, myProject,
FileChooserDescriptorFactory.createSingleFileNoJarsDescriptor());
ClassBrowser.createAppletClassBrowser(myProject, myModuleSelector).setField(getClassNameComponent());
myHTMLOptions.setVisible(false);
myAddButton.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
addParameter();
}
});
myRemoveButton.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
removeParameter();
}
});
}
private void removeParameter() {
final int selectedRow = myTable.getSelectedRow();
if (selectedRow < 0 || selectedRow >= myTable.getRowCount()) return;
final ArrayList<AppletConfiguration.AppletParameter> newItems =
new ArrayList<AppletConfiguration.AppletParameter>(myParameters.getItems());
newItems.remove(selectedRow);
myParameters.setItems(newItems);
}
private void addParameter() {
final ArrayList<AppletConfiguration.AppletParameter> newItems =
new ArrayList<AppletConfiguration.AppletParameter>(myParameters.getItems());
newItems.add(new AppletConfiguration.AppletParameter("newParameter", ""));
myParameters.setItems(newItems);
}
private JComboBox getModuleComponent() {
return myModule.getComponent();
}
private TextFieldWithBrowseButton getPolicyFileComponent() {
return myPolicyFile.getComponent();
}
private void getConfigurationTo(final AppletConfiguration configuration) {
}
private List<AppletConfiguration.AppletParameter> cloneParameters(final List<AppletConfiguration.AppletParameter> items) {
final List<AppletConfiguration.AppletParameter> params = new ArrayList<AppletConfiguration.AppletParameter>();
for (Iterator<AppletConfiguration.AppletParameter> iterator = items.iterator(); iterator.hasNext();) {
AppletConfiguration.AppletParameter appletParameter = iterator.next();
params.add(new AppletConfiguration.AppletParameter(appletParameter.getName(), appletParameter.getValue()));
}
return params;
}
private JTextField getWidthComponent() {
return myWidth;
}
private TextFieldWithBrowseButton getClassNameComponent() {
return myClassName;
}
private TextFieldWithBrowseButton getHtmlPathComponent() {
return myHtmlFile;
}
private String toNull(String s) {
s = s.trim();
return s.length() == 0 ? null : s;
}
private String toSystemFormat(String s) {
s = s.trim();
return s.length() == 0 ? null : s.replace(File.separatorChar, '/');
}
public void applyEditorTo(final AppletConfiguration configuration) {
checkEditorData(configuration);
myTable.stopEditing();
final List<AppletConfiguration.AppletParameter> params = cloneParameters(myParameters.getItems());
configuration.setAppletParameters(params);
}
public void resetEditorFrom(final AppletConfiguration configuration) {
getClassNameComponent().setText(configuration.MAIN_CLASS_NAME);
String presentableHtmlName = configuration.HTML_FILE_NAME;
if (presentableHtmlName != null && !StringUtil.startsWithIgnoreCase(presentableHtmlName, HTTP_PREFIX)) {
presentableHtmlName = presentableHtmlName.replace('/', File.separatorChar);
}
getHtmlPathComponent().setText(presentableHtmlName);
getPolicyFileComponent().setText(configuration.getPolicyFile());
getVMParametersComponent().setText(configuration.VM_PARAMETERS);
getWidthComponent().setText(Integer.toString(configuration.WIDTH));
getHeightComponent().setText(Integer.toString(configuration.HEIGHT));
(configuration.HTML_USED ? myURL : myMainClass).setSelected(true);
changePanel();
final AppletConfiguration.AppletParameter[] appletParameters = configuration.getAppletParameters();
if (appletParameters != null) {
myParameters.setItems(cloneParameters(Arrays.asList(appletParameters)));
}
myModuleSelector.reset(configuration);
myAlternativeJREPanel.init(configuration.ALTERNATIVE_JRE_PATH, configuration.ALTERNATIVE_JRE_PATH_ENABLED);
}
private RawCommandLineEditor getVMParametersComponent() {
return myVMParameters.getComponent();
}
private JTextField getHeightComponent() {
return myHeight;
}
public JComponent createEditor() {
return myWholePanel;
}
public void disposeEditor() {
}
public void checkEditorData(final AppletConfiguration configuration) {
configuration.MAIN_CLASS_NAME = toNull(getClassNameComponent().getText());
configuration.HTML_FILE_NAME = toSystemFormat(getHtmlPathComponent().getText());
configuration.VM_PARAMETERS = toNull(getVMParametersComponent().getText());
configuration.setPolicyFile(getPolicyFileComponent().getText());
myModuleSelector.applyTo(configuration);
try {
configuration.WIDTH = Integer.parseInt(getWidthComponent().getText());
}
catch (NumberFormatException e) {
}
try {
configuration.HEIGHT = Integer.parseInt(getHeightComponent().getText());
}
catch (NumberFormatException e) {
}
configuration.HTML_USED = myURL.isSelected();
configuration.ALTERNATIVE_JRE_PATH = myAlternativeJREPanel.getPath();
configuration.ALTERNATIVE_JRE_PATH_ENABLED = myAlternativeJREPanel.isPathEnabled();
}
private static abstract class MyColumnInfo extends ColumnInfo<AppletConfiguration.AppletParameter, String> {
public MyColumnInfo(final String name) {
super(name);
}
public Comparator<AppletConfiguration.AppletParameter> getComparator() {
return new Comparator<AppletConfiguration.AppletParameter>() {
public int compare(final AppletConfiguration.AppletParameter parameter1,
final AppletConfiguration.AppletParameter parameter2) {
return valueOf(parameter1).compareTo(valueOf(parameter2));
}
};
}
public TableCellEditor getEditor(final AppletConfiguration.AppletParameter item) {
final JTextField textField = new JTextField();
textField.setBorder(BorderFactory.createLineBorder(Color.BLACK));
return new DefaultCellEditor(textField);
}
public boolean isCellEditable(final AppletConfiguration.AppletParameter appletParameter) {
return true;
}
}
}
@@ -0,0 +1,346 @@
package com.intellij.execution.applet;
import com.intellij.execution.*;
import com.intellij.execution.configurations.*;
import com.intellij.execution.filters.TextConsoleBuilderFactory;
import com.intellij.execution.junit.RefactoringListeners;
import com.intellij.execution.process.OSProcessHandler;
import com.intellij.execution.process.ProcessAdapter;
import com.intellij.execution.process.ProcessEvent;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.execution.util.JavaParametersUtil;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.options.SettingsEditor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.impl.JavaSdkImpl;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.DefaultJDOMExternalizer;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.WriteExternalException;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.refactoring.listeners.RefactoringElementListener;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
public class AppletConfiguration extends ModuleBasedConfiguration<JavaRunConfigurationModule> implements SingleClassConfiguration, RefactoringListenerProvider {
public String MAIN_CLASS_NAME;
public String HTML_FILE_NAME;
public boolean HTML_USED;
public int WIDTH;
public int HEIGHT;
public String POLICY_FILE;
public String VM_PARAMETERS;
private AppletParameter[] myAppletParameters;
public boolean ALTERNATIVE_JRE_PATH_ENABLED;
public String ALTERNATIVE_JRE_PATH;
@NonNls
protected static final String NAME_ATTR = "name";
@NonNls
protected static final String VALUE_ATTR = "value";
@NonNls
protected static final String PARAMETER_ELEMENT_NAME = "parameter";
public AppletConfiguration(final String name, final Project project, ConfigurationFactory factory) {
super(name, new JavaRunConfigurationModule(project, false), factory);
}
public void setMainClass(final PsiClass psiClass) {
final Module originalModule = getConfigurationModule().getModule();
setMainClassName(JavaExecutionUtil.getRuntimeQualifiedName(psiClass));
setModule(JavaExecutionUtil.findModule(psiClass));
restoreOriginalModule(originalModule);
}
public RunProfileState getState(@NotNull final Executor executor, @NotNull final ExecutionEnvironment env) throws ExecutionException {
final JavaCommandLineState state = new JavaCommandLineState(env) {
private AppletHtmlFile myHtmlURL = null;
protected JavaParameters createJavaParameters() throws ExecutionException {
final JavaParameters params = new JavaParameters();
myHtmlURL = getHtmlURL();
if (myHtmlURL != null) {
final int classPathType = myHtmlURL.isHttp() ? JavaParameters.JDK_ONLY : JavaParameters.JDK_AND_CLASSES;
final RunConfigurationModule runConfigurationModule = getConfigurationModule();
JavaParametersUtil.configureModule(runConfigurationModule, params, classPathType, ALTERNATIVE_JRE_PATH_ENABLED ? ALTERNATIVE_JRE_PATH : null);
final String policyFileParameter = getPolicyFileParameter();
if (policyFileParameter != null) {
params.getVMParametersList().add(policyFileParameter);
}
params.getVMParametersList().addParametersString(VM_PARAMETERS);
params.setMainClass("sun.applet.AppletViewer");
params.getProgramParametersList().add(myHtmlURL.getUrl());
}
return params;
}
protected OSProcessHandler startProcess() throws ExecutionException {
final OSProcessHandler handler = super.startProcess();
final AppletHtmlFile htmlUrl = myHtmlURL;
if (htmlUrl != null) {
handler.addProcessListener(new ProcessAdapter() {
public void processTerminated(ProcessEvent event) {
htmlUrl.deleteFile();
}
});
}
return handler;
}
};
state.setConsoleBuilder(TextConsoleBuilderFactory.getInstance().createBuilder(getProject()));
return state;
}
public SettingsEditor<? extends RunConfiguration> getConfigurationEditor() {
return new AppletConfigurable(getProject());
}
@NonNls private String getPolicyFileParameter() {
if (POLICY_FILE != null && POLICY_FILE.length() > 0) {
return "-Djava.security.policy=" + getPolicyFile();
}
return null;
}
public void setPolicyFile(final String localPath) {
POLICY_FILE = ExternalizablePath.urlValue(localPath);
}
public String getPolicyFile() {
return ExternalizablePath.localPathValue(POLICY_FILE);
}
public static class AppletParameter {
public String myName;
public String myValue;
public AppletParameter(@NonNls final String name, final String value) {
myName = name;
myValue = value;
}
public String getName() {
return myName;
}
public void setName(final String name) {
myName = name;
}
public String getValue() {
return myValue;
}
public void setValue(final String value) {
myValue = value;
}
public boolean equals(final Object obj) {
if (!(obj instanceof AppletParameter)) return false;
final AppletParameter second = (AppletParameter)obj;
return Comparing.equal(myName, second.myName) && Comparing.equal(myValue, second.myValue);
}
public int hashCode() {
return Comparing.hashcode(myName, myValue);
}
}
public Collection<Module> getValidModules() {
return JavaRunConfigurationModule.getModulesForClass(getProject(), MAIN_CLASS_NAME);
}
public void readExternal(final Element parentNode) throws InvalidDataException {
DefaultJDOMExternalizer.readExternal(this, parentNode);
readModule(parentNode);
final ArrayList<AppletParameter> parameters = new ArrayList<AppletParameter>();
for (
Iterator iterator = parentNode.getChildren(PARAMETER_ELEMENT_NAME).iterator(); iterator.hasNext();) {
final Element element = (Element)iterator.next();
final String name = element.getAttributeValue(NAME_ATTR);
final String value = element.getAttributeValue(VALUE_ATTR);
parameters.add(new AppletParameter(name, value));
}
myAppletParameters = parameters.toArray(new AppletParameter[parameters.size()]);
}
public void writeExternal(final Element parentNode) throws WriteExternalException {
writeModule(parentNode);
DefaultJDOMExternalizer.writeExternal(this, parentNode);
if (myAppletParameters != null) {
for (int i = 0; i < myAppletParameters.length; i++) {
final Element element = new Element(PARAMETER_ELEMENT_NAME);
parentNode.addContent(element);
element.setAttribute(NAME_ATTR, myAppletParameters[i].getName());
element.setAttribute(VALUE_ATTR, myAppletParameters[i].getValue());
}
}
}
protected ModuleBasedConfiguration createInstance() {
return new AppletConfiguration(getName(), getProject(), AppletConfigurationType.getInstance().getConfigurationFactories()[0]);
}
public String getGeneratedName() {
if (MAIN_CLASS_NAME == null) return null;
return JavaExecutionUtil.getPresentableClassName(MAIN_CLASS_NAME, getConfigurationModule());
}
public RefactoringElementListener getRefactoringElementListener(final PsiElement element) {
if (HTML_USED) return null;
return RefactoringListeners.getClassOrPackageListener(element, new RefactoringListeners.SingleClassConfigurationAccessor(this));
}
public PsiClass getMainClass() {
return getConfigurationModule().findClass(MAIN_CLASS_NAME);
}
public void setGeneratedName() {
setName(getGeneratedName());
}
public boolean isGeneratedName() {
return Comparing.equal(getName(), getGeneratedName());
}
public String suggestedName() {
return ExecutionUtil.shortenName(JavaExecutionUtil.getShortClassName(MAIN_CLASS_NAME), 0);
}
public void setMainClassName(final String qualifiedName) {
final boolean generatedName = isGeneratedName();
MAIN_CLASS_NAME = qualifiedName;
if (generatedName) setGeneratedName();
}
public void checkConfiguration() throws RuntimeConfigurationException {
if (ALTERNATIVE_JRE_PATH_ENABLED){
if (ALTERNATIVE_JRE_PATH == null ||
ALTERNATIVE_JRE_PATH.length() == 0 ||
!JavaSdkImpl.checkForJre(ALTERNATIVE_JRE_PATH)){
throw new RuntimeConfigurationWarning(ExecutionBundle.message("jre.not.valid.error.message", ALTERNATIVE_JRE_PATH));
}
}
getConfigurationModule().checkForWarning();
if (HTML_USED) {
if (HTML_FILE_NAME == null || HTML_FILE_NAME.length() == 0) {
throw new RuntimeConfigurationWarning(ExecutionBundle.message("html.file.not.specified.error.message"));
}
}
else {
getConfigurationModule().checkClassName(MAIN_CLASS_NAME, ExecutionBundle.message("no.applet.class.specified.error.message"));
}
}
public AppletParameter[] getAppletParameters() {
return myAppletParameters;
}
public void setAppletParameters(final AppletParameter[] appletParameters) {
myAppletParameters = appletParameters;
}
public void setAppletParameters(final List<AppletParameter> parameters) {
setAppletParameters(parameters.toArray(new AppletParameter[parameters.size()]));
}
private AppletHtmlFile getHtmlURL() throws CantRunException {
if (HTML_USED) {
if (HTML_FILE_NAME == null || HTML_FILE_NAME.length() == 0) {
throw new CantRunException(ExecutionBundle.message("html.file.not.specified.error.message"));
}
return new AppletHtmlFile(HTML_FILE_NAME, null);
}
else {
if (MAIN_CLASS_NAME == null || MAIN_CLASS_NAME.length() == 0) {
throw new CantRunException(ExecutionBundle.message("class.not.specified.error.message"));
}
// generate html
try {
return generateAppletTempPage();
}
catch (IOException e) {
throw new CantRunException(ExecutionBundle.message("failed.to.generate.wrapper.error.message"));
}
}
}
private AppletHtmlFile generateAppletTempPage() throws IOException {
final File tempFile = File.createTempFile("AppletPage", ".html");
@NonNls final FileWriter writer = new FileWriter(tempFile);
try {
writer.write("<html>\n" +
"<head>\n" +
"<title>" + MAIN_CLASS_NAME + "</title>\n" +
"</head>\n" +
"<applet codebase=\".\"\n" +
"code=\"" + MAIN_CLASS_NAME + "\"\n" +
"name=\"" + MAIN_CLASS_NAME + "\"\n" +
"width=" + WIDTH + "\n" +
"height=" + HEIGHT + "\n" +
"align=top>\n");
final AppletParameter[] appletParameters = getAppletParameters();
if (appletParameters != null) {
for (final AppletParameter parameter : appletParameters) {
writer.write("<param name=\"" + parameter.getName() + "\" value=\"" + parameter.getValue() + "\">\n");
}
}
writer.write("</applet>\n</body>\n</html>\n");
}
finally {
writer.close();
}
final String htmlFile = tempFile.getAbsolutePath();
return new AppletHtmlFile(htmlFile, tempFile);
}
private static class AppletHtmlFile {
private final String myHtmlFile;
private final File myFileToDelete;
@NonNls
protected static final String FILE_PREFIX = "file:/";
@NonNls
protected static final String HTTP_PREFIX = "http:/";
@NonNls
protected static final String HTTPS_PREFIX = "https:/";
protected AppletHtmlFile(final String htmlFile, final File fileToDelete) {
myHtmlFile = htmlFile;
myFileToDelete = fileToDelete;
}
public String getUrl() {
if (!StringUtil.startsWithIgnoreCase(myHtmlFile, FILE_PREFIX) && !isHttp()) {
try {
return new File(myHtmlFile).toURL().toString();
}
catch (MalformedURLException ex) {
}
}
return myHtmlFile;
}
public boolean isHttp() {
return StringUtil.startsWithIgnoreCase(myHtmlFile, HTTP_PREFIX) || StringUtil.startsWithIgnoreCase(myHtmlFile, HTTPS_PREFIX);
}
public void deleteFile() {
if (myFileToDelete != null) {
myFileToDelete.delete();
}
}
}
}
@@ -0,0 +1,113 @@
package com.intellij.execution.applet;
import com.intellij.execution.*;
import com.intellij.execution.configurations.ConfigurationFactory;
import com.intellij.execution.configurations.RunConfiguration;
import com.intellij.execution.junit.JUnitUtil;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.IconLoader;
import com.intellij.psi.JavaPsiFacade;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiManager;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.util.PsiClassUtil;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
public class AppletConfigurationType implements LocatableConfigurationType {
private final ConfigurationFactory myFactory;
private static final Icon ICON = IconLoader.getIcon("/runConfigurations/applet.png");
/**reflection*/
AppletConfigurationType() {
myFactory = new ConfigurationFactory(this) {
public RunConfiguration createTemplateConfiguration(Project project) {
return new AppletConfiguration("", project, this);
}
};
}
public String getDisplayName() {
return ExecutionBundle.message("applet.configuration.name");
}
public String getConfigurationTypeDescription() {
return ExecutionBundle.message("applet.configuration.description");
}
public Icon getIcon() {
return ICON;
}
public ConfigurationFactory[] getConfigurationFactories() {
return new ConfigurationFactory[]{myFactory};
}
public RunnerAndConfigurationSettings createConfigurationByLocation(Location location) {
location = JavaExecutionUtil.stepIntoSingleClass(location);
final Project project = location.getProject();
final PsiElement element = location.getPsiElement();
final PsiClass aClass = getAppletClass(element, PsiManager.getInstance(project));
if (aClass == null) return null;
RunnerAndConfigurationSettings settings = RunManagerEx.getInstanceEx(project).createConfiguration("", getConfigurationFactories()[0]);
final AppletConfiguration configuration = (AppletConfiguration)settings.getConfiguration();
configuration.MAIN_CLASS_NAME = JavaExecutionUtil.getRuntimeQualifiedName(aClass);
configuration.setModule(new JUnitUtil.ModuleOfClass().convert(aClass));
configuration.setName(configuration.getGeneratedName());
return settings;
}
public boolean isConfigurationByLocation(final RunConfiguration configuration, Location location) {
final PsiClass aClass = getAppletClass(location.getPsiElement(), PsiManager.getInstance(location.getProject()));
return aClass != null &&
Comparing.equal(JavaExecutionUtil.getRuntimeQualifiedName(aClass), ((AppletConfiguration)configuration).MAIN_CLASS_NAME);
}
private static PsiClass getAppletClass(PsiElement element, final PsiManager manager) {
while (element != null) {
if (element instanceof PsiClass) {
final PsiClass aClass = (PsiClass)element;
if (isAppletClass(aClass, manager)){
return aClass;
}
}
element = element.getParent();
}
return null;
}
private static boolean isAppletClass(final PsiClass aClass, final PsiManager manager) {
if (!PsiClassUtil.isRunnableClass(aClass, true)) return false;
final Module module = JavaExecutionUtil.findModule(aClass);
final GlobalSearchScope scope = module != null
? GlobalSearchScope.moduleWithLibrariesScope(module)
: GlobalSearchScope.projectScope(manager.getProject());
PsiClass appletClass = JavaPsiFacade.getInstance(manager.getProject()).findClass("java.applet.Applet", scope);
if (appletClass != null) {
if (aClass.isInheritor(appletClass, true)) return true;
}
appletClass = JavaPsiFacade.getInstance(manager.getProject()).findClass("javax.swing.JApplet", scope);
if (appletClass != null) {
if (aClass.isInheritor(appletClass, true)) return true;
}
return false;
}
@NotNull
public String getId() {
return "Applet";
}
public static AppletConfigurationType getInstance() {
return ContainerUtil.findInstance(Extensions.getExtensions(CONFIGURATION_TYPE_EP), AppletConfigurationType.class);
}
}
@@ -0,0 +1,62 @@
<?xml version="1.0" encoding="UTF-8"?>
<form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="com.intellij.execution.application.ApplicationConfigurable2">
<grid id="93687" binding="myWholePanel" layout-manager="GridLayoutManager" row-count="7" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="10">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<xy x="53" y="36" width="470" height="424"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<vspacer id="eeb03">
<constraints>
<grid row="6" column="0" row-span="1" col-span="1" vsize-policy="6" hsize-policy="1" anchor="0" fill="2" indent="0" use-parent-layout="false"/>
</constraints>
</vspacer>
<component id="50b09" class="com.intellij.execution.junit2.configuration.CommonJavaParameters" binding="myCommonJavaParameters">
<constraints>
<grid row="1" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<programParametersText resource-bundle="messages/ExecutionBundle" key="run.configuration.program.parameters"/>
</properties>
</component>
<component id="50d08" class="com.intellij.openapi.ui.LabeledComponent" binding="myMainClass">
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<componentClass value="com.intellij.openapi.ui.TextFieldWithBrowseButton"/>
<text resource-bundle="messages/ExecutionBundle" key="application.configuration.main.class.label"/>
</properties>
</component>
<component id="c45d2" class="com.intellij.openapi.ui.LabeledComponent" binding="myModule">
<constraints>
<grid row="3" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<componentClass value="javax.swing.JComboBox"/>
<text resource-bundle="messages/ExecutionBundle" key="application.configuration.use.classpath.and.jdk.of.module.label"/>
</properties>
</component>
<component id="e88bd" class="com.intellij.execution.ui.AlternativeJREPanel" binding="myAlternativeJREPanel">
<constraints>
<grid row="4" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
</component>
<component id="b45cf" class="javax.swing.JCheckBox" binding="myShowSwingInspectorCheckbox">
<constraints>
<grid row="5" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text resource-bundle="messages/ExecutionBundle" key="show.swing.inspector"/>
</properties>
</component>
<component id="2e57d" class="com.intellij.execution.configuration.EnvironmentVariablesComponent" binding="myEnvVariablesComponent">
<constraints>
<grid row="2" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
</component>
</children>
</grid>
</form>
@@ -0,0 +1,97 @@
package com.intellij.execution.application;
import com.intellij.execution.ExecutionBundle;
import com.intellij.execution.configuration.EnvironmentVariablesComponent;
import com.intellij.execution.junit2.configuration.ClassBrowser;
import com.intellij.execution.junit2.configuration.CommonJavaParameters;
import com.intellij.execution.junit2.configuration.ConfigurationModuleSelector;
import com.intellij.execution.ui.AlternativeJREPanel;
import com.intellij.execution.util.JreVersionDetector;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.options.SettingsEditor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.LabeledComponent;
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ApplicationConfigurable2 extends SettingsEditor<ApplicationConfiguration> {
private CommonJavaParameters myCommonJavaParameters;
private LabeledComponent<TextFieldWithBrowseButton> myMainClass;
private LabeledComponent<JComboBox> myModule;
private JPanel myWholePanel;
private final ConfigurationModuleSelector myModuleSelector;
private AlternativeJREPanel myAlternativeJREPanel;
private JCheckBox myShowSwingInspectorCheckbox;
private EnvironmentVariablesComponent myEnvVariablesComponent;
private final JreVersionDetector myVersionDetector = new JreVersionDetector();
public ApplicationConfigurable2(final Project project) {
myModuleSelector = new ConfigurationModuleSelector(project, myModule.getComponent());
myModule.getComponent().addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
myCommonJavaParameters.setModuleContext(myModuleSelector.getModule());
}
});
ClassBrowser.createApplicationClassBrowser(project, myModuleSelector).setField(getMainClassField());
}
public void applyEditorTo(final ApplicationConfiguration configuration) throws ConfigurationException {
myCommonJavaParameters.applyTo(configuration);
myModuleSelector.applyTo(configuration);
configuration.MAIN_CLASS_NAME = getMainClassField().getText();
configuration.ALTERNATIVE_JRE_PATH = myAlternativeJREPanel.getPath();
configuration.ALTERNATIVE_JRE_PATH_ENABLED = myAlternativeJREPanel.isPathEnabled();
configuration.ENABLE_SWING_INSPECTOR = myVersionDetector.isJre50Configured(configuration) && myShowSwingInspectorCheckbox.isSelected();
configuration.setEnvs(myEnvVariablesComponent.getEnvs());
configuration.PASS_PARENT_ENVS = myEnvVariablesComponent.isPassParentEnvs();
updateShowSwingInspector(configuration);
}
public void resetEditorFrom(final ApplicationConfiguration configuration) {
myCommonJavaParameters.reset(configuration);
myModuleSelector.reset(configuration);
getMainClassField().setText(configuration.MAIN_CLASS_NAME);
myAlternativeJREPanel.init(configuration.ALTERNATIVE_JRE_PATH, configuration.ALTERNATIVE_JRE_PATH_ENABLED);
myEnvVariablesComponent.setEnvs(configuration.getEnvs());
myEnvVariablesComponent.setPassParentEnvs(configuration.PASS_PARENT_ENVS);
updateShowSwingInspector(configuration);
}
private void updateShowSwingInspector(final ApplicationConfiguration configuration) {
if (myVersionDetector.isJre50Configured(configuration)) {
myShowSwingInspectorCheckbox.setEnabled(true);
myShowSwingInspectorCheckbox.setSelected(configuration.ENABLE_SWING_INSPECTOR);
myShowSwingInspectorCheckbox.setText(ExecutionBundle.message("show.swing.inspector"));
}
else {
myShowSwingInspectorCheckbox.setEnabled(false);
myShowSwingInspectorCheckbox.setSelected(false);
myShowSwingInspectorCheckbox.setText(ExecutionBundle.message("show.swing.inspector.disabled"));
}
}
public TextFieldWithBrowseButton getMainClassField() {
return myMainClass.getComponent();
}
public CommonJavaParameters getCommonJavaParameters() {
return myCommonJavaParameters;
}
@NotNull
public JComponent createEditor() {
return myWholePanel;
}
public void disposeEditor() {
}
}
@@ -0,0 +1,248 @@
package com.intellij.execution.application;
import com.intellij.diagnostic.logging.LogConfigurationPanel;
import com.intellij.execution.*;
import com.intellij.execution.configuration.EnvironmentVariablesComponent;
import com.intellij.execution.configurations.*;
import com.intellij.execution.filters.TextConsoleBuilderFactory;
import com.intellij.execution.junit.RefactoringListeners;
import com.intellij.execution.process.OSProcessHandler;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.execution.util.JavaParametersUtil;
import com.intellij.openapi.components.PathMacroManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.options.SettingsEditor;
import com.intellij.openapi.options.SettingsEditorGroup;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.impl.JavaSdkImpl;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.DefaultJDOMExternalizer;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.WriteExternalException;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.util.PsiMethodUtil;
import com.intellij.refactoring.listeners.RefactoringElementListener;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
public class ApplicationConfiguration extends ModuleBasedConfiguration<JavaRunConfigurationModule> implements RunJavaConfiguration, SingleClassConfiguration, RefactoringListenerProvider {
private static final Logger LOG = Logger.getInstance("com.intellij.execution.application.ApplicationConfiguration");
public String MAIN_CLASS_NAME;
public String VM_PARAMETERS;
public String PROGRAM_PARAMETERS;
public String WORKING_DIRECTORY;
public boolean ALTERNATIVE_JRE_PATH_ENABLED;
public String ALTERNATIVE_JRE_PATH;
public boolean ENABLE_SWING_INSPECTOR;
public String ENV_VARIABLES;
private Map<String,String> myEnvs = new LinkedHashMap<String, String>();
public boolean PASS_PARENT_ENVS = true;
public ApplicationConfiguration(final String name, final Project project, ApplicationConfigurationType applicationConfigurationType) {
super(name, new JavaRunConfigurationModule(project, true), applicationConfigurationType.getConfigurationFactories()[0]);
}
public void setMainClass(final PsiClass psiClass) {
final Module originalModule = getConfigurationModule().getModule();
setMainClassName(JavaExecutionUtil.getRuntimeQualifiedName(psiClass));
setModule(JavaExecutionUtil.findModule(psiClass));
restoreOriginalModule(originalModule);
}
public RunProfileState getState(@NotNull final Executor executor, @NotNull final ExecutionEnvironment env) throws ExecutionException {
final JavaCommandLineState state = new MyJavaCommandLineState(env);
state.setConsoleBuilder(TextConsoleBuilderFactory.getInstance().createBuilder(getProject()));
return state;
}
public SettingsEditor<? extends RunConfiguration> getConfigurationEditor() {
SettingsEditorGroup<ApplicationConfiguration> group = new SettingsEditorGroup<ApplicationConfiguration>();
group.addEditor(ExecutionBundle.message("run.configuration.configuration.tab.title"), new ApplicationConfigurable2(getProject()));
RunConfigurationExtension.appendEditors(this, group);
group.addEditor(ExecutionBundle.message("logs.tab.title"), new LogConfigurationPanel());
return group;
}
@Nullable
public String getGeneratedName() {
if (MAIN_CLASS_NAME == null) {
return null;
}
return JavaExecutionUtil.getPresentableClassName(MAIN_CLASS_NAME, getConfigurationModule());
}
public void setGeneratedName() {
setName(getGeneratedName());
}
public RefactoringElementListener getRefactoringElementListener(final PsiElement element) {
return RefactoringListeners.
getClassOrPackageListener(element, new RefactoringListeners.SingleClassConfigurationAccessor(this));
}
@Nullable
public PsiClass getMainClass() {
return getConfigurationModule().findClass(MAIN_CLASS_NAME);
}
public boolean isGeneratedName() {
if (MAIN_CLASS_NAME == null || MAIN_CLASS_NAME.length() == 0) {
return JavaExecutionUtil.isNewName(getName());
}
return Comparing.equal(getName(), getGeneratedName());
}
public String suggestedName() {
return ExecutionUtil.shortenName(JavaExecutionUtil.getShortClassName(MAIN_CLASS_NAME), 6) + ".main()";
}
public void setMainClassName(final String qualifiedName) {
final boolean generatedName = isGeneratedName();
MAIN_CLASS_NAME = qualifiedName;
if (generatedName) setGeneratedName();
}
public void checkConfiguration() throws RuntimeConfigurationException {
if (ALTERNATIVE_JRE_PATH_ENABLED){
if (ALTERNATIVE_JRE_PATH == null ||
ALTERNATIVE_JRE_PATH.length() == 0 ||
!JavaSdkImpl.checkForJre(ALTERNATIVE_JRE_PATH)){
throw new RuntimeConfigurationWarning(ExecutionBundle.message("jre.path.is.not.valid.jre.home.error.mesage", ALTERNATIVE_JRE_PATH));
}
}
final JavaRunConfigurationModule configurationModule = getConfigurationModule();
final PsiClass psiClass = configurationModule.checkModuleAndClassName(MAIN_CLASS_NAME, ExecutionBundle.message("no.main.class.specified.error.text"));
if (!PsiMethodUtil.hasMainMethod(psiClass)) {
throw new RuntimeConfigurationWarning(ExecutionBundle.message("main.method.not.found.in.class.error.message", MAIN_CLASS_NAME));
}
}
public void setProperty(final int property, final String value) {
switch (property) {
case PROGRAM_PARAMETERS_PROPERTY:
PROGRAM_PARAMETERS = value;
break;
case VM_PARAMETERS_PROPERTY:
VM_PARAMETERS = value;
break;
case WORKING_DIRECTORY_PROPERTY:
WORKING_DIRECTORY = ExternalizablePath.urlValue(value);
break;
default:
throw new RuntimeException("Unknown property: " + property);
}
}
public String getProperty(final int property) {
switch (property) {
case PROGRAM_PARAMETERS_PROPERTY:
return PROGRAM_PARAMETERS;
case VM_PARAMETERS_PROPERTY:
return VM_PARAMETERS;
case WORKING_DIRECTORY_PROPERTY:
return getWorkingDirectory();
default:
throw new RuntimeException("Unknown property: " + property);
}
}
public boolean isAlternativeJrePathEnabled() {
return ALTERNATIVE_JRE_PATH_ENABLED;
}
public void setAlternativeJrePathEnabled(boolean enabled) {
this.ALTERNATIVE_JRE_PATH_ENABLED = enabled;
}
public String getAlternativeJrePath() {
return ALTERNATIVE_JRE_PATH;
}
public void setAlternativeJrePath(String ALTERNATIVE_JRE_PATH) {
this.ALTERNATIVE_JRE_PATH = ALTERNATIVE_JRE_PATH;
}
private String getWorkingDirectory() {
return ExternalizablePath.localPathValue(WORKING_DIRECTORY);
}
public Collection<Module> getValidModules() {
return JavaRunConfigurationModule.getModulesForClass(getProject(), MAIN_CLASS_NAME);
}
protected ModuleBasedConfiguration createInstance() {
return new ApplicationConfiguration(getName(), getProject(), ApplicationConfigurationType.getInstance());
}
public void readExternal(final Element element) throws InvalidDataException {
PathMacroManager.getInstance(getProject()).expandPaths(element);
super.readExternal(element);
for (RunConfigurationExtension extension : Extensions.getExtensions(RunConfigurationExtension.EP_NAME)) {
extension.readExternal(this, element);
}
DefaultJDOMExternalizer.readExternal(this, element);
readModule(element);
EnvironmentVariablesComponent.readExternal(element, getEnvs());
}
public void writeExternal(final Element element) throws WriteExternalException {
super.writeExternal(element);
for (RunConfigurationExtension extension : Extensions.getExtensions(RunConfigurationExtension.EP_NAME)) {
extension.writeExternal(this, element);
}
DefaultJDOMExternalizer.writeExternal(this, element);
writeModule(element);
EnvironmentVariablesComponent.writeExternal(element, getEnvs());
PathMacroManager.getInstance(getProject()).collapsePathsRecursively(element);
}
public Map<String, String> getEnvs() {
return myEnvs;
}
public void setEnvs(final Map<String, String> envs) {
this.myEnvs = envs;
}
private class MyJavaCommandLineState extends JavaCommandLineState {
public MyJavaCommandLineState(final ExecutionEnvironment environment) {
super(environment);
}
protected JavaParameters createJavaParameters() throws ExecutionException {
final JavaParameters params = new JavaParameters();
params.setupEnvs(getEnvs(), PASS_PARENT_ENVS);
final int classPathType = JavaParametersUtil.getClasspathType(getConfigurationModule(), MAIN_CLASS_NAME, false);
JavaParametersUtil.configureModule(getConfigurationModule(), params, classPathType, ALTERNATIVE_JRE_PATH_ENABLED ? ALTERNATIVE_JRE_PATH : null);
JavaParametersUtil.configureConfiguration(params, ApplicationConfiguration.this);
params.setMainClass(MAIN_CLASS_NAME);
for(RunConfigurationExtension ext: Extensions.getExtensions(RunConfigurationExtension.EP_NAME)) {
ext.updateJavaParameters(ApplicationConfiguration.this, params, getRunnerSettings());
}
return params;
}
@Override
protected OSProcessHandler startProcess() throws ExecutionException {
final OSProcessHandler handler = super.startProcess();
for(RunConfigurationExtension ext: Extensions.getExtensions(RunConfigurationExtension.EP_NAME)) {
ext.handleStartProcess(ApplicationConfiguration.this, handler);
}
return handler;
}
}
}
@@ -0,0 +1,72 @@
package com.intellij.execution.application;
import com.intellij.execution.JavaExecutionUtil;
import com.intellij.execution.Location;
import com.intellij.execution.actions.ConfigurationContext;
import com.intellij.execution.configurations.ConfigurationUtil;
import com.intellij.execution.impl.RunnerAndConfigurationSettingsImpl;
import com.intellij.execution.junit.JavaRuntimeConfigurationProducerBase;
import com.intellij.execution.junit.RuntimeConfigurationProducer;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiMethod;
import com.intellij.psi.util.PsiMethodUtil;
import org.jetbrains.annotations.Nullable;
public class ApplicationConfigurationProducer extends JavaRuntimeConfigurationProducerBase implements Cloneable {
private PsiElement myPsiElement = null;
public static final RuntimeConfigurationProducer PROTOTYPE = new ApplicationConfigurationProducer();
public ApplicationConfigurationProducer() {
super(ApplicationConfigurationType.getInstance());
}
public PsiElement getSourceElement() {
return myPsiElement;
}
protected RunnerAndConfigurationSettingsImpl createConfigurationByElement(Location location, final ConfigurationContext context) {
location = JavaExecutionUtil.stepIntoSingleClass(location);
final PsiElement element = location.getPsiElement();
PsiElement currentElement = element;
PsiMethod method;
while ((method = findMain(currentElement)) != null) {
final PsiClass aClass = method.getContainingClass();
if (ConfigurationUtil.MAIN_CLASS.value(aClass)) {
myPsiElement = method;
return createConfiguration(aClass, context);
}
currentElement = method.getParent();
}
final PsiClass aClass = ApplicationConfigurationType.getMainClass(element);
if (aClass == null) return null;
myPsiElement = aClass;
return createConfiguration(aClass, context);
}
private RunnerAndConfigurationSettingsImpl createConfiguration(final PsiClass aClass, final ConfigurationContext context) {
final Project project = aClass.getProject();
RunnerAndConfigurationSettingsImpl settings = cloneTemplateConfiguration(project, context);
final ApplicationConfiguration configuration = (ApplicationConfiguration)settings.getConfiguration();
configuration.MAIN_CLASS_NAME = JavaExecutionUtil.getRuntimeQualifiedName(aClass);
configuration.setName(configuration.getGeneratedName());
setupConfigurationModule(context, configuration);
copyStepsBeforeRun(project, configuration);
return settings;
}
@Nullable
private static PsiMethod findMain(PsiElement element) {
PsiMethod method;
while ((method = getContainingMethod(element)) != null)
if (PsiMethodUtil.isMainMethod(method)) return method;
else element = method.getParent();
return null;
}
public int compareTo(final Object o) {
return PREFERED;
}
}
@@ -0,0 +1,102 @@
package com.intellij.execution.application;
import com.intellij.execution.*;
import com.intellij.execution.configurations.ConfigurationFactory;
import com.intellij.execution.configurations.RunConfiguration;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.IconLoader;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiJavaFile;
import com.intellij.psi.util.PsiMethodUtil;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
public class ApplicationConfigurationType implements LocatableConfigurationType {
private final ConfigurationFactory myFactory;
private static final Icon ICON = IconLoader.getIcon("/runConfigurations/application.png");
/**reflection*/
public ApplicationConfigurationType() {
myFactory = new ConfigurationFactory(this) {
public RunConfiguration createTemplateConfiguration(Project project) {
return new ApplicationConfiguration("", project, ApplicationConfigurationType.this);
}
@Override
public Icon getIcon(@NotNull final RunConfiguration configuration) {
return RunConfigurationExtension.getIcon((ApplicationConfiguration)configuration, getIcon());
}
};
}
public String getDisplayName() {
return ExecutionBundle.message("application.configuration.name");
}
public String getConfigurationTypeDescription() {
return ExecutionBundle.message("application.configuration.description");
}
public Icon getIcon() {
return ICON;
}
public ConfigurationFactory[] getConfigurationFactories() {
return new ConfigurationFactory[]{myFactory};
}
public RunnerAndConfigurationSettings createConfigurationByLocation(final Location location) {
return null;
}
public boolean isConfigurationByLocation(final RunConfiguration configuration, final Location location) {
final PsiClass aClass = getMainClass(location.getPsiElement());
if (aClass == null) {
return false;
}
return Comparing.equal(JavaExecutionUtil.getRuntimeQualifiedName(aClass), ((ApplicationConfiguration)configuration).MAIN_CLASS_NAME)
&& Comparing.equal(JavaExecutionUtil.findModule(aClass), ((ApplicationConfiguration)configuration).getConfigurationModule().getModule());
}
public static PsiClass getMainClass(PsiElement element) {
while (element != null) {
if (element instanceof PsiClass) {
final PsiClass aClass = (PsiClass)element;
if (PsiMethodUtil.findMainInClass(aClass) != null){
return aClass;
}
} else if (element instanceof PsiJavaFile) {
final PsiJavaFile javaFile = (PsiJavaFile)element;
final PsiClass[] classes = javaFile.getClasses();
for (PsiClass aClass : classes) {
if (PsiMethodUtil.findMainInClass(aClass) != null) {
return aClass;
}
}
}
element = element.getParent();
}
return null;
}
@NotNull
@NonNls
public String getId() {
return "Application";
}
@Nullable
public static ApplicationConfigurationType getInstance() {
return ContainerUtil.findInstance(Extensions.getExtensions(CONFIGURATION_TYPE_EP), ApplicationConfigurationType.class);
}
}
@@ -0,0 +1,14 @@
/*
* User: anna
* Date: 20-Aug-2007
*/
package com.intellij.execution.filters;
import com.intellij.openapi.project.Project;
import org.jetbrains.annotations.NotNull;
public class DefaultConsoleFiltersProvider implements ConsoleFilterProvider{
public Filter[] getDefaultFilters(@NotNull Project project) {
return new Filter[]{new ExceptionFilter(project), new YourkitFilter(project)};
}
}
@@ -0,0 +1,174 @@
package com.intellij.execution.impl;
import com.intellij.execution.ExecutionBundle;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.ExecutionResult;
import com.intellij.execution.Executor;
import com.intellij.execution.configurations.*;
import com.intellij.execution.executors.DefaultRunExecutor;
import com.intellij.execution.process.ProcessAdapter;
import com.intellij.execution.process.ProcessEvent;
import com.intellij.execution.process.ProcessHandler;
import com.intellij.execution.remote.RemoteConfiguration;
import com.intellij.execution.runners.*;
import com.intellij.execution.ui.ExecutionConsole;
import com.intellij.execution.ui.RunContentDescriptor;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CustomShortcutSet;
import com.intellij.openapi.actionSystem.Presentation;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.options.SettingsEditor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.util.JDOMExternalizable;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
/**
* @author spleaner
*/
public class DefaultJavaProgramRunner extends JavaPatchableProgramRunner {
public boolean canRun(@NotNull final String executorId, @NotNull final RunProfile profile) {
return executorId.equals(DefaultRunExecutor.EXECUTOR_ID) &&
profile instanceof ModuleRunProfile &&
!(profile instanceof RemoteConfiguration);
}
public JDOMExternalizable createConfigurationData(ConfigurationInfoProvider settingsProvider) {
return null;
}
public SettingsEditor<JDOMExternalizable> getSettingsEditor(final Executor executor, RunConfiguration configuration) {
return null;
}
public void patch(JavaParameters javaParameters, RunnerSettings settings, final boolean beforeExecution) throws ExecutionException {
}
public void checkConfiguration(final RunnerSettings settings, final ConfigurationPerRunnerSettings configurationPerRunnerSettings)
throws RuntimeConfigurationException {
}
public void onProcessStarted(final RunnerSettings settings, final ExecutionResult executionResult) {
}
public AnAction[] createActions(ExecutionResult executionResult) {
return AnAction.EMPTY_ARRAY;
}
protected RunContentDescriptor doExecute(final Project project, final Executor executor, final RunProfileState state, final RunContentDescriptor contentToReuse,
final ExecutionEnvironment env) throws ExecutionException {
FileDocumentManager.getInstance().saveAllDocuments();
ExecutionResult executionResult;
boolean shouldAddDefaultActions = true;
if (state instanceof JavaCommandLine) {
patch(((JavaCommandLine)state).getJavaParameters(), state.getRunnerSettings(), true);
final ProcessProxy proxy = ProcessProxyFactory.getInstance().createCommandLineProxy((JavaCommandLine)state);
executionResult = state.execute(executor, this);
if (proxy != null && executionResult != null) {
proxy.attach(executionResult.getProcessHandler());
}
if (state instanceof JavaCommandLineState && !((JavaCommandLineState)state).shouldAddJavaProgramRunnerActions()) {
shouldAddDefaultActions = false;
}
}
else {
executionResult = state.execute(executor, this);
}
if (executionResult == null) {
return null;
}
onProcessStarted(env.getRunnerSettings(), executionResult);
final RunContentBuilder contentBuilder = new RunContentBuilder(project, this, executor);
contentBuilder.setExecutionResult(executionResult);
contentBuilder.setEnvironment(env);
if (shouldAddDefaultActions) {
addDefaultActions(contentBuilder);
}
RunContentDescriptor runContent = contentBuilder.showRunContent(contentToReuse);
AnAction[] actions = createActions(contentBuilder.getExecutionResult());
for (AnAction action : actions) {
contentBuilder.addAction(action);
}
return runContent;
}
protected static void addDefaultActions(final RunContentBuilder contentBuilder) {
final ExecutionResult executionResult = contentBuilder.getExecutionResult();
final ExecutionConsole executionConsole = executionResult.getExecutionConsole();
final JComponent consoleComponent = executionConsole != null ? executionConsole.getComponent() : null;
final ControlBreakAction controlBreakAction = new ControlBreakAction(contentBuilder.getProcessHandler());
if (consoleComponent != null) {
controlBreakAction.registerCustomShortcutSet(controlBreakAction.getShortcutSet(), consoleComponent);
final ProcessHandler processHandler = executionResult.getProcessHandler();
processHandler.addProcessListener(new ProcessAdapter() {
public void processTerminated(final ProcessEvent event) {
processHandler.removeProcessListener(this);
controlBreakAction.unregisterCustomShortcutSet(consoleComponent);
}
});
}
contentBuilder.addAction(controlBreakAction);
contentBuilder.addAction(new SoftExitAction(contentBuilder.getProcessHandler()));
}
private abstract static class LauncherBasedAction extends AnAction {
protected final ProcessHandler myProcessHandler;
protected LauncherBasedAction(String text, String description, Icon icon, ProcessHandler processHandler) {
super(text, description, icon);
myProcessHandler = processHandler;
}
public void update(final AnActionEvent event) {
final Presentation presentation = event.getPresentation();
if (ProcessProxyFactory.getInstance().getAttachedProxy(myProcessHandler) == null) {
presentation.setVisible(false);
presentation.setEnabled(false);
return;
}
presentation.setVisible(true);
presentation.setEnabled(!myProcessHandler.isProcessTerminated());
}
}
protected static class ControlBreakAction extends LauncherBasedAction {
public ControlBreakAction(final ProcessHandler processHandler) {
super(ExecutionBundle.message("run.configuration.dump.threads.action.name"), null, IconLoader.getIcon("/actions/dump.png"),
processHandler);
setShortcutSet(new CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_CANCEL, InputEvent.CTRL_DOWN_MASK)));
}
public void actionPerformed(final AnActionEvent e) {
ProcessProxyFactory.getInstance().getAttachedProxy(myProcessHandler).sendBreak();
}
}
protected static class SoftExitAction extends LauncherBasedAction {
public SoftExitAction(final ProcessHandler processHandler) {
super(ExecutionBundle.message("run.configuration.exit.action.name"), null, IconLoader.getIcon("/actions/exit.png"), processHandler);
}
public void actionPerformed(final AnActionEvent e) {
ProcessProxyFactory.getInstance().getAttachedProxy(myProcessHandler).sendStop();
}
}
@NotNull
public String getRunnerId() {
return "Run";
}
}
@@ -0,0 +1,32 @@
package com.intellij.execution.impl;
import com.intellij.execution.RunManager;
import com.intellij.execution.configurations.RefactoringListenerProvider;
import com.intellij.execution.configurations.RunConfiguration;
import com.intellij.psi.PsiElement;
import com.intellij.refactoring.listeners.RefactoringElementListener;
import com.intellij.refactoring.listeners.RefactoringElementListenerComposite;
import com.intellij.refactoring.listeners.RefactoringElementListenerProvider;
/**
* @author spleaner
*/
public class RunConfigurationRefactoringElementListenerProvider implements RefactoringElementListenerProvider {
public RefactoringElementListener getListener(final PsiElement element) {
RefactoringElementListenerComposite composite = null;
final RunConfiguration[] configurations = RunManager.getInstance(element.getProject()).getAllConfigurations();
for (RunConfiguration configuration : configurations) {
if (configuration instanceof RefactoringListenerProvider) { // todo: perhaps better way to handle listeners?
final RefactoringElementListener listener = ((RefactoringListenerProvider)configuration).getRefactoringElementListener(element);
if (listener != null) {
if (composite == null) {
composite = new RefactoringElementListenerComposite();
}
composite.addListener(listener);
}
}
}
return composite;
}
}
@@ -0,0 +1,113 @@
package com.intellij.execution.junit;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.configurations.CommandLineBuilder;
import com.intellij.execution.configurations.GeneralCommandLine;
import com.intellij.execution.configurations.JavaParameters;
import com.intellij.execution.junit2.SegmentedInputStream;
import com.intellij.execution.junit2.segments.DeferedActionsQueue;
import com.intellij.execution.junit2.segments.DispatchListener;
import com.intellij.execution.junit2.segments.PacketExtractorBase;
import com.intellij.execution.process.OSProcessHandler;
import com.intellij.execution.process.ProcessTerminatedListener;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.project.Project;
import com.intellij.rt.execution.junit.segments.PacketProcessor;
import java.io.InputStream;
import java.io.Reader;
import java.nio.charset.Charset;
/**
* @author dyoma
*/
public class JUnitProcessHandler extends OSProcessHandler {
private final Extractor myOut;
private final Extractor myErr;
private final Charset myCharset;
public JUnitProcessHandler(final Process process, final String commandLine, final Charset charset) {
super(process, commandLine);
myOut = new Extractor(getProcess().getInputStream(), charset);
myErr = new Extractor(getProcess().getErrorStream(), charset);
myCharset = charset;
}
protected Reader createProcessOutReader() {
return myOut.getReader();
}
protected Reader createProcessErrReader() {
return myErr.getReader();
}
public PacketExtractorBase getErr() {
return myErr;
}
public PacketExtractorBase getOut() {
return myOut;
}
public Charset getCharset() {
return myCharset;
}
public static JUnitProcessHandler runJava(final JavaParameters javaParameters) throws ExecutionException {
return runJava(javaParameters, null);
}
public static JUnitProcessHandler runJava(final JavaParameters javaParameters, final Project project) throws ExecutionException {
return runCommandLine(CommandLineBuilder.createFromJavaParameters(javaParameters, project, true));
}
public static JUnitProcessHandler runCommandLine(final GeneralCommandLine commandLine) throws ExecutionException {
final JUnitProcessHandler processHandler = new JUnitProcessHandler(commandLine.createProcess(), commandLine.getCommandLineString(),
commandLine.getCharset());
ProcessTerminatedListener.attach(processHandler);
return processHandler;
}
private class Extractor extends PacketExtractorBase {
private final SegmentedInputStream myStream;
public Extractor(final InputStream stream, final Charset charset) {
myStream = new SegmentedInputStream(stream, charset);
}
public void setPacketProcessor(final PacketProcessor packetProcessor) {
myStream.setEventsDispatcher(new PacketProcessor() {
public void processPacket(final String packet) {
perform(new Runnable() {
public void run() {
packetProcessor.processPacket(packet);
}
});
}
});
}
public void setFulfilledWorkGate(final DeferedActionsQueue fulfilledWorkGate) {
super.setFulfilledWorkGate(new DeferedActionsQueue() {
public void addLast(final Runnable runnable) {
ApplicationManager.getApplication().invokeLater(new Runnable() {
public void run() {
fulfilledWorkGate.addLast(runnable);
}
}, ModalityState.NON_MODAL);
}
public void setDispactchListener(final DispatchListener listener) {
fulfilledWorkGate.setDispactchListener(listener);
}
});
}
public Reader getReader() {
return new SegmentedInputStreamReader(myStream);
//return new InputStreamReader(myStream, myCharset);
}
}
}
@@ -0,0 +1,287 @@
package com.intellij.execution.junit;
import com.intellij.codeInsight.AnnotationUtil;
import com.intellij.execution.*;
import com.intellij.execution.junit2.info.MethodLocation;
import com.intellij.execution.testframework.SourceScope;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleUtil;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Condition;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.util.PsiClassUtil;
import com.intellij.psi.util.TypeConversionUtil;
import com.intellij.util.containers.Convertor;
import gnu.trove.THashSet;
import junit.runner.BaseTestRunner;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.Nullable;
import org.junit.runners.Parameterized;
import java.util.*;
public class JUnitUtil {
@NonNls private static final String TESTCASE_CLASS = "junit.framework.TestCase";
@NonNls private static final String TEST_INTERFACE = "junit.framework.Test";
@NonNls private static final String TESTSUITE_CLASS = "junit.framework.TestSuite";
@NonNls public static final String RUN_WITH = "org.junit.runner.RunWith";
public static boolean isSuiteMethod(final PsiMethod psiMethod) {
if (psiMethod == null) return false;
if (!psiMethod.hasModifierProperty(PsiModifier.PUBLIC)) return false;
if (!psiMethod.hasModifierProperty(PsiModifier.STATIC)) return false;
if (psiMethod.isConstructor()) return false;
final PsiType returnType = psiMethod.getReturnType();
if (returnType != null) {
if (!returnType.equalsToText(TEST_INTERFACE) && !returnType.equalsToText(TESTSUITE_CLASS)) {
final PsiType testType =
JavaPsiFacade.getInstance(psiMethod.getProject()).getElementFactory().createTypeFromText(TEST_INTERFACE, null);
if (!TypeConversionUtil.isAssignable(testType, returnType)) {
return false;
}
}
}
final PsiParameter[] parameters = psiMethod.getParameterList().getParameters();
return parameters.length == 0;
}
public static boolean isTestMethod(final Location<? extends PsiMethod> location) {
final PsiMethod psiMethod = location.getPsiElement();
final PsiClass aClass = location instanceof MethodLocation ? ((MethodLocation)location).getContainingClass() : psiMethod.getContainingClass();
if (aClass == null || !isTestClass(aClass)) return false;
if (isTestAnnotated(psiMethod)) return true;
if (psiMethod.isConstructor()) return false;
if (!psiMethod.hasModifierProperty(PsiModifier.PUBLIC)) return false;
if (psiMethod.hasModifierProperty(PsiModifier.ABSTRACT)) return false;
if (AnnotationUtil.isAnnotated(aClass, RUN_WITH, true)) return true;
if (psiMethod.getParameterList().getParametersCount() > 0) return false;
if (psiMethod.hasModifierProperty(PsiModifier.STATIC) && BaseTestRunner.SUITE_METHODNAME.equals(psiMethod.getName())) return false;
if (!psiMethod.getName().startsWith("test")) return false;
PsiClass testCaseClass = getTestCaseClassOrNull(location);
return testCaseClass != null && psiMethod.getContainingClass().isInheritor(testCaseClass, true);
}
private static boolean isTestCaseInheritor(final PsiClass aClass) {
if (!aClass.isValid()) return false;
Location<PsiClass> location = PsiLocation.fromPsiElement(aClass);
PsiClass testCaseClass = getTestCaseClassOrNull(location);
return testCaseClass != null && aClass.isInheritor(testCaseClass, true);
}
/**
*
* @param aClassLocation
* @return true iff aClassLocation can be used as JUnit test class.
*/
private static boolean isTestClass(final Location<? extends PsiClass> aClassLocation) {
return isTestClass(aClassLocation.getPsiElement());
}
public static boolean isTestClass(final PsiClass psiClass) {
return isTestClass(psiClass, true, null, true);
}
private static boolean isTestClass(final PsiClass psiClass, boolean checkAbstract, @Nullable Set<PsiClass> visited, boolean checkForTestCaseInheritance) {
if (!PsiClassUtil.isRunnableClass(psiClass, true, checkAbstract)) return false;
if (checkForTestCaseInheritance && isTestCaseInheritor(psiClass)) return true;
final PsiModifierList modifierList = psiClass.getModifierList();
if (modifierList == null) return false;
if (AnnotationUtil.isAnnotated(psiClass, RUN_WITH, true)) return true;
for (final PsiMethod method : psiClass.getMethods()) {
if (isSuiteMethod(method)) return true;
if (isTestAnnotated(method)) return true;
}
PsiClass superClass = psiClass.getSuperClass();
if (superClass != null && !"java.lang.Object".equals(superClass.getQualifiedName()) && !superClass.isInterface()) {
if (visited != null && visited.contains(psiClass)) return false;
if (visited == null) visited = new THashSet<PsiClass>();
visited.add(psiClass);
return isTestClass(superClass, false, visited, false);
}
return false;
}
public static boolean isJUnit3TestClass(final PsiClass clazz) {
return isTestCaseInheritor(clazz);
}
public static boolean isJUnit4TestClass(final PsiClass psiClass) {
return isJUnit4TestClass(psiClass, true,null);
}
private static boolean isJUnit4TestClass(final PsiClass psiClass, boolean checkAbstract, @Nullable Set<PsiClass> visited) {
if (!PsiClassUtil.isRunnableClass(psiClass, true, checkAbstract)) return false;
final PsiModifierList modifierList = psiClass.getModifierList();
if (modifierList == null) return false;
if (AnnotationUtil.isAnnotated(psiClass, RUN_WITH, true)) return true;
for (final PsiMethod method : psiClass.getMethods()) {
if (isTestAnnotated(method)) return true;
}
PsiClass superClass = psiClass.getSuperClass();
if (superClass != null && !"java.lang.Object".equals(superClass.getQualifiedName()) && !superClass.isInterface()) {
if (visited != null && visited.contains(psiClass)) return false;
if (visited == null) visited = new THashSet<PsiClass>();
visited.add(psiClass);
return isJUnit4TestClass(superClass, false, visited);
}
return false;
}
public static boolean isTestAnnotated(final PsiMethod method) {
if (AnnotationUtil.isAnnotated(method, "org.junit.Test", false)) {
final PsiAnnotation annotation = AnnotationUtil.findAnnotationInHierarchy(method.getContainingClass(), Collections.singleton(RUN_WITH));
if (annotation != null) {
final PsiNameValuePair[] attributes = annotation.getParameterList().getAttributes();
for (PsiNameValuePair attribute : attributes) {
final PsiAnnotationMemberValue value = attribute.getValue();
if (value instanceof PsiClassObjectAccessExpression ) {
final PsiTypeElement typeElement = ((PsiClassObjectAccessExpression)value).getOperand();
if (typeElement.getType().getCanonicalText().equals(Parameterized.class.getName())) {
return false;
}
}
}
}
return true;
}
return false;
}
private static PsiClass getTestCaseClassOrNull(final Location<?> location) {
final Location<PsiClass> ancestorOrSelf = location.getAncestorOrSelf(PsiClass.class);
final PsiClass aClass = ancestorOrSelf.getPsiElement();
Module module = JavaExecutionUtil.findModule(aClass);
if (module == null) return null;
GlobalSearchScope scope = GlobalSearchScope.moduleRuntimeScope(module, true);
return getTestCaseClassOrNull(scope, module.getProject());
}
public static PsiClass getTestCaseClass(final Module module) throws NoJUnitException {
if (module == null) throw new NoJUnitException();
final GlobalSearchScope scope = GlobalSearchScope.moduleRuntimeScope(module, true);
return getTestCaseClass(scope, module.getProject());
}
public static PsiClass getTestCaseClass(final SourceScope scope) throws NoJUnitException {
if (scope == null) throw new NoJUnitException();
return getTestCaseClass(scope.getLibrariesScope(), scope.getProject());
}
private static PsiClass getTestCaseClass(final GlobalSearchScope scope, final Project project) throws NoJUnitException {
PsiClass testCaseClass = getTestCaseClassOrNull(scope, project);
if (testCaseClass == null) throw new NoJUnitException(scope.getDisplayName());
return testCaseClass;
}
private static PsiClass getTestCaseClassOrNull(final GlobalSearchScope scope, final Project project) {
return JavaPsiFacade.getInstance(project).findClass(TESTCASE_CLASS, scope);
}
public static class TestMethodFilter implements Condition<PsiMethod> {
private final PsiClass myClass;
public TestMethodFilter(final PsiClass aClass) {
myClass = aClass;
}
public boolean value(final PsiMethod method) {
return isTestMethod(MethodLocation.elementInClass(method, myClass));
}
}
public static PsiClass findPsiClass(final String qualifiedName, final Module module, final Project project) {
final GlobalSearchScope scope = module == null ? GlobalSearchScope.projectScope(project) : GlobalSearchScope.moduleWithDependenciesScope(module);
return JavaPsiFacade.getInstance(project).findClass(qualifiedName, scope);
}
public static PsiPackage getContainingPackage(final PsiClass psiClass) {
return JavaDirectoryService.getInstance().getPackage(psiClass.getContainingFile().getContainingDirectory());
}
public static PsiClass getTestClass(final PsiElement element) {
return getTestClass(PsiLocation.fromPsiElement(element));
}
public static PsiClass getTestClass(final Location<?> location) {
for (Iterator<Location<PsiClass>> iterator = location.getAncestors(PsiClass.class, false); iterator.hasNext();) {
final Location<PsiClass> classLocation = iterator.next();
if (isTestClass(classLocation)) return classLocation.getPsiElement();
}
PsiElement element = location.getPsiElement();
if (element instanceof PsiJavaFile) {
PsiClass[] classes = ((PsiJavaFile)element).getClasses();
if (classes.length == 1) return classes[0];
}
return null;
}
public static PsiMethod getTestMethod(final PsiElement element) {
final PsiManager manager = element.getManager();
final Location<PsiElement> location = PsiLocation.fromPsiElement(manager.getProject(), element);
for (Iterator<Location<PsiMethod>> iterator = location.getAncestors(PsiMethod.class, false); iterator.hasNext();) {
final Location<? extends PsiMethod> methodLocation = iterator.next();
if (isTestMethod(methodLocation)) return methodLocation.getPsiElement();
}
return null;
}
/**
* @param collection
* @param comparator returns 0 iff elemets are incomparable.
* @return maximum elements
*/
public static <T> Collection<T> findMaximums(final Collection<T> collection, final Comparator<T> comparator) {
final ArrayList<T> maximums = new ArrayList<T>();
loop:
for (final T candidate : collection) {
for (final T element : collection) {
if (comparator.compare(element, candidate) > 0) continue loop;
}
maximums.add(candidate);
}
return maximums;
}
/*public static Map<Module, Collection<Module>> buildAllDependencies(final Project project) {
final Module[] modules = ModuleManager.getInstance(project).getSortedModules();
final HashMap<Module, Collection<Module>> lessers = new HashMap<Module, Collection<Module>>();
int prevProcessedCount = 0;
while (modules.length > lessers.size()) {
for (int i = 0; i < modules.length; i++) {
final Module module = modules[i];
if (lessers.containsKey(module)) continue;
final Module[] dependencies = ModuleRootManager.getInstance(module).getDependencies();
if (lessers.keySet().containsAll(Arrays.asList(dependencies))) {
final HashSet<Module> allDependencies = new HashSet<Module>();
for (int j = 0; j < dependencies.length; j++) {
final Module dependency = dependencies[j];
allDependencies.add(dependency);
allDependencies.addAll(lessers.get(dependency));
}
lessers.put(module, allDependencies);
}
}
if (lessers.size() == prevProcessedCount) return null;
prevProcessedCount = lessers.size();
}
return lessers;
}*/
public static class ModuleOfClass implements Convertor<PsiClass, Module> {
public Module convert(final PsiClass psiClass) {
if (psiClass == null || !psiClass.isValid()) return null;
return ModuleUtil.findModuleForPsiElement(psiClass);
}
}
public static class NoJUnitException extends CantRunException {
public NoJUnitException() {
super(ExecutionBundle.message("no.junit.error.message"));
}
public NoJUnitException(final String message) {
super(ExecutionBundle.message("no.junit.in.scope.error.message", message));
}
}
}
@@ -0,0 +1,88 @@
package com.intellij.execution.junit;
import com.intellij.execution.actions.ConfigurationContext;
import com.intellij.execution.configurations.ConfigurationType;
import com.intellij.execution.configurations.ModuleBasedConfiguration;
import com.intellij.execution.impl.RunManagerImpl;
import com.intellij.execution.impl.RunnerAndConfigurationSettingsImpl;
import com.intellij.execution.testframework.TestSearchScope;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ProjectFileIndex;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import org.jetbrains.annotations.Nullable;
/**
* @author spleaner
*/
public abstract class JavaRuntimeConfigurationProducerBase extends RuntimeConfigurationProducer {
protected JavaRuntimeConfigurationProducerBase(final ConfigurationType configurationType) {
super(configurationType);
}
protected static PsiMethod getContainingMethod(PsiElement element) {
while (element != null)
if (element instanceof PsiMethod) break;
else element = element.getParent();
return (PsiMethod) element;
}
@Nullable
protected static PsiPackage checkPackage(final PsiElement element) {
if (element == null || !element.isValid()) return null;
final Project project = element.getProject();
final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex();
if (element instanceof PsiPackage) {
final PsiPackage aPackage = (PsiPackage)element;
final PsiDirectory[] directories = aPackage.getDirectories(GlobalSearchScope.projectScope(project));
for (final PsiDirectory directory : directories) {
if (isSource(directory, fileIndex)) return aPackage;
}
return null;
}
else if (element instanceof PsiDirectory) {
final PsiDirectory directory = (PsiDirectory)element;
return isSource(directory, fileIndex) ? JavaDirectoryService.getInstance().getPackage(directory) : null;
}
else {
return null;
}
}
private static boolean isSource(final PsiDirectory directory, final ProjectFileIndex fileIndex) {
final VirtualFile virtualFile = directory.getVirtualFile();
return fileIndex.getSourceRootForFile(virtualFile) != null;
}
protected TestSearchScope setupPackageConfiguration(ConfigurationContext context, Project project, ModuleBasedConfiguration configuration, TestSearchScope scope) {
copyStepsBeforeRun(project, configuration);
if (scope != TestSearchScope.WHOLE_PROJECT) {
if (!setupConfigurationModule(context, configuration)) {
return TestSearchScope.WHOLE_PROJECT;
}
}
return scope;
}
protected boolean setupConfigurationModule(@Nullable ConfigurationContext context, ModuleBasedConfiguration configuration) {
if (context != null) {
final RunnerAndConfigurationSettingsImpl template =
((RunManagerImpl)context.getRunManager()).getConfigurationTemplate(getConfigurationFactory());
final Module contextModule = context.getModule();
final Module predefinedModule = ((ModuleBasedConfiguration)template.getConfiguration()).getConfigurationModule().getModule();
if (predefinedModule != null) {
configuration.setModule(predefinedModule);
return true;
}
else if (configuration.getConfigurationModule().getModule() == null && contextModule != null) {
configuration.setModule(contextModule);
return true;
}
}
return false;
}
}
@@ -0,0 +1,195 @@
package com.intellij.execution.junit;
import com.intellij.execution.JavaExecutionUtil;
import com.intellij.execution.SingleClassConfiguration;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.refactoring.listeners.RefactoringElementListener;
import org.jetbrains.annotations.NotNull;
public class RefactoringListeners {
public static RefactoringElementListener getListener(final PsiPackage psiPackage, final Accessor<PsiPackage> accessor) {
final StringBuilder path = new StringBuilder();
for (PsiPackage parent = accessor.getPsiElement(); parent != null; parent = parent.getParentPackage()) {
if (parent.equals(psiPackage)) return new RefactorPackage(accessor, path.toString());
if (path.length() > 0) path.insert(0, '.');
path.insert(0, parent.getName());
}
return null;
}
public static RefactoringElementListener getListeners(final PsiClass psiClass, final Accessor<PsiClass> accessor) {
final PsiClass aClass = accessor.getPsiElement();
if (aClass == null) return null;
final StringBuilder path = new StringBuilder();
for (PsiClass parent = aClass; parent != null; parent = PsiTreeUtil.getParentOfType(parent, PsiClass.class, true)) {
if (parent.equals(psiClass)) return new RefactorClass(accessor, path.toString());
if (path.length() > 0) path.insert(0, '$');
path.insert(0, parent.getName());
}
return null;
}
public static RefactoringElementListener getClassOrPackageListener(final PsiElement element, final Accessor<PsiClass> accessor) {
if (element instanceof PsiClass) return getListeners((PsiClass)element, accessor);
if (element instanceof PsiPackage) {
final PsiClass aClass = accessor.getPsiElement();
if (aClass == null) return null;
return getListener((PsiPackage)element, new ClassPackageAccessor(accessor));
}
return null;
}
public interface Accessor<T extends PsiElement> {
void setName(String qualifiedName);
T getPsiElement();
void setPsiElement(T psiElement);
}
public static class SingleClassConfigurationAccessor implements Accessor<PsiClass> {
private final SingleClassConfiguration myConfiguration;
public SingleClassConfigurationAccessor(final SingleClassConfiguration configuration) {
myConfiguration = configuration;
}
public PsiClass getPsiElement() {
return myConfiguration.getMainClass();
}
public void setPsiElement(final PsiClass psiClass) {
myConfiguration.setMainClass(psiClass);
}
public void setName(final String qualifiedName) {
myConfiguration.setMainClassName(qualifiedName);
}
}
private static abstract class RenameElement<T extends PsiElement> implements RefactoringElementListener {
private final Accessor<T> myAccessor;
private final String myPath;
public RenameElement(final Accessor<T> accessor, final String path) {
myAccessor = accessor;
myPath = path;
}
public void elementMoved(@NotNull final PsiElement newElement) {
setName((T)newElement);
}
public void elementRenamed(@NotNull final PsiElement newElement) {
setName((T)newElement);
}
private void setName(@NotNull T newElement) {
String qualifiedName = getQualifiedName(newElement);
if (myPath.length() > 0) {
qualifiedName = qualifiedName + "." + myPath;
newElement = findNewElement(newElement, qualifiedName);
}
if (newElement != null) {
myAccessor.setPsiElement(newElement);
}
else {
myAccessor.setName(qualifiedName);
}
}
protected abstract T findNewElement(T newParent, String qualifiedName);
protected abstract String getQualifiedName(T element);
}
private static class RefactorPackage extends RenameElement<PsiPackage> {
public RefactorPackage(final Accessor<PsiPackage> accessor, final String path) {
super(accessor, path);
}
public PsiPackage findNewElement(final PsiPackage psiPackage, final String qualifiedName) {
return JavaPsiFacade.getInstance(psiPackage.getProject()).findPackage(qualifiedName);
}
public String getQualifiedName(final PsiPackage psiPackage) {
return psiPackage.getQualifiedName();
}
}
private static class RefactorClass extends RenameElement<PsiClass> {
public RefactorClass(final Accessor<PsiClass> accessor, final String path) {
super(accessor, path);
}
public PsiClass findNewElement(final PsiClass psiClass, final String qualifiedName) {
return JavaPsiFacade.getInstance(psiClass.getProject())
.findClass(qualifiedName.replace('$', '.'), GlobalSearchScope.moduleScope(JavaExecutionUtil.findModule(psiClass)));
}
public String getQualifiedName(final PsiClass psiClass) {
return psiClass.getQualifiedName();
}
}
private static class ClassPackageAccessor implements RefactoringListeners.Accessor<PsiPackage> {
private final PsiPackage myContainingPackage;
private final Module myModule;
private final RefactoringListeners.Accessor<PsiClass> myAccessor;
private final String myInpackageName;
public ClassPackageAccessor(final RefactoringListeners.Accessor<PsiClass> accessor) {
myAccessor = accessor;
PsiClass aClass = myAccessor.getPsiElement();
aClass = (PsiClass)aClass.getOriginalElement();
myContainingPackage = JavaDirectoryService.getInstance().getPackage(aClass.getContainingFile().getContainingDirectory());
myModule = JavaExecutionUtil.findModule(aClass);
final String classQName = aClass.getQualifiedName();
final String classPackageQName = myContainingPackage.getQualifiedName();
if (classQName.startsWith(classPackageQName)) {
final String inpackageName = classQName.substring(classPackageQName.length());
if (StringUtil.startsWithChar(inpackageName, '.')) {
myInpackageName = inpackageName.substring(1);
}
else {
myInpackageName = inpackageName;
}
}
else {
myInpackageName = null;
}
}
public PsiPackage getPsiElement() {
return myContainingPackage;
}
public void setPsiElement(final PsiPackage psiPackage) {
if (myInpackageName == null) return; //we can do nothing
final String classQName = getClassQName(psiPackage.getQualifiedName());
final PsiClass newClass = JUnitUtil.findPsiClass(classQName, myModule, psiPackage.getProject());
if (newClass != null) {
myAccessor.setPsiElement(newClass);
}
else {
myAccessor.setName(classQName);
}
}
public void setName(final String qualifiedName) {
myAccessor.setName(getClassQName(qualifiedName));
}
private String getClassQName(final String packageQName) {
if (packageQName.length() > 0) {
return packageQName + '.' + myInpackageName;
}
else {
return myInpackageName;
}
}
}
}
@@ -0,0 +1,39 @@
/*
* Copyright (c) 2000-2004 by JetBrains s.r.o. All Rights Reserved.
* Use is subject to license terms.
*/
package com.intellij.execution.junit;
import com.intellij.execution.junit2.SegmentedInputStream;
import java.io.IOException;
import java.io.Reader;
/**
* @author Eugene Zhuravlev
* Date: Apr 25, 2007
*/
public class SegmentedInputStreamReader extends Reader {
private final SegmentedInputStream myStream;
public SegmentedInputStreamReader(SegmentedInputStream stream) {
myStream = stream;
}
public void close() throws IOException {
myStream.close();
}
public boolean ready() throws IOException {
return myStream.available() > 0;
}
public int read(final char[] cbuf, final int off, final int len) throws IOException {
for (int i = 0; i < len; i++) {
final int aChar = myStream.read();
if (aChar == -1) return i == 0 ? -1 : i;
cbuf[off + i] = (char)aChar;
}
return len;
}
}
@@ -0,0 +1,61 @@
package com.intellij.execution.junit2;
import gnu.trove.TIntArrayList;
import java.io.IOException;
import java.io.Reader;
import org.jetbrains.annotations.NonNls;
/**
* @author dyoma
*/
public class PushReader {
private final Reader mySource;
private final TIntArrayList myReadAhead = new TIntArrayList();
@NonNls
protected static final String INTERNAL_ERROR_UNEXPECTED_END_OF_PIPE = "Unexpected end of pipe";
public PushReader(final Reader source) {
mySource = source;
}
public int next() throws IOException {
return myReadAhead.isEmpty() ? mySource.read() : myReadAhead.remove(myReadAhead.size() - 1);
}
public void pushBack(final char[] chars) {
for (int i = chars.length - 1; i >= 0; i--) {
final char aChar = chars[i];
myReadAhead.add(aChar);
}
}
public void close() throws IOException {
mySource.close();
}
public boolean ready() throws IOException {
return !myReadAhead.isEmpty() || mySource.ready();
}
public void pushBack(final int aChar) {
myReadAhead.add(aChar);
}
public char[] next(final int charCount) throws IOException {
final char[] chars = new char[charCount];
int offset = 0;
for (; offset < chars.length && offset < myReadAhead.size(); offset++)
chars[offset] = (char)myReadAhead.remove(myReadAhead.size() - 1);
while (offset < chars.length) {
int bytesRead = mySource.read(chars, offset, chars.length - offset);
if (bytesRead == -1)
throw new IOException (INTERNAL_ERROR_UNEXPECTED_END_OF_PIPE);
offset += bytesRead;
}
return chars;
}
}
@@ -0,0 +1,157 @@
package com.intellij.execution.junit2;
import com.intellij.rt.execution.junit.segments.Packet;
import com.intellij.rt.execution.junit.segments.PacketProcessor;
import com.intellij.rt.execution.junit.segments.SegmentedStream;
import com.intellij.util.StringBuilderSpinAllocator;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
public class SegmentedInputStream extends InputStream {
private final PushReader mySourceStream;
private PacketProcessor myEventsDispatcher;
private int myStartupPassed = 0;
public SegmentedInputStream(final InputStream sourceStream, final Charset charset) {
mySourceStream = new PushReader(new BufferedReader(new InputStreamReader(sourceStream, charset)));
}
public int read() throws IOException {
if (myStartupPassed < SegmentedStream.STARTUP_MESSAGE.length()) {
return rawRead();
} else {
return findNextSymbol();
}
}
private int rawRead() throws IOException {
while(myStartupPassed < SegmentedStream.STARTUP_MESSAGE.length()) {
final int aChar = readNext();
if (aChar != SegmentedStream.STARTUP_MESSAGE.charAt(myStartupPassed)) {
mySourceStream.pushBack(aChar);
mySourceStream.pushBack(SegmentedStream.STARTUP_MESSAGE.substring(0, myStartupPassed).toCharArray());
myStartupPassed = 0;
return readNext();
}
myStartupPassed++;
}
return read();
}
private int findNextSymbol() throws IOException {
int nextByte;
while (true) {
nextByte = readNext();
if (nextByte != SegmentedStream.SPECIAL_SYMBOL) break;
final boolean packetRead = readControlSequence();
if (!packetRead) break;
}
return nextByte;
}
private boolean readControlSequence() throws IOException {
for (int idx = 1; idx < SegmentedStream.MARKER_PREFIX.length(); idx++) {
if (readNext() != SegmentedStream.MARKER_PREFIX.charAt(idx)) {
return false;
}
}
final char[] marker = readMarker();
if(myEventsDispatcher != null) myEventsDispatcher.processPacket(decode(marker));
return true;
}
public void setEventsDispatcher(final PacketProcessor eventsDispatcher) {
myEventsDispatcher = eventsDispatcher;
}
private char[] readMarker() throws IOException {
int nextRead = '0';
final StringBuilder buffer = StringBuilderSpinAllocator.alloc();
try {
while (nextRead != ' ' && nextRead != SegmentedStream.SPECIAL_SYMBOL) {
buffer.append((char)nextRead);
nextRead = readNext();
}
return readNext(Integer.valueOf(buffer.toString()).intValue());
}
finally {
StringBuilderSpinAllocator.dispose(buffer);
}
}
private char[] readNext(final int charCount) throws IOException {
return mySourceStream.next(charCount);
}
private int readNext() throws IOException {
return mySourceStream.next();
}
public int available() throws IOException {
while (mySourceStream.ready()) {
while(myStartupPassed < SegmentedStream.STARTUP_MESSAGE.length()) {
final int aChar = readNext();
if (aChar != SegmentedStream.STARTUP_MESSAGE.charAt(myStartupPassed)) {
mySourceStream.pushBack(aChar);
final char[] charsRead = SegmentedStream.STARTUP_MESSAGE.substring(0, myStartupPassed).toCharArray();
mySourceStream.pushBack(charsRead);
myStartupPassed = 0;
return charsRead.length + 1;
}
myStartupPassed++;
}
final int b = mySourceStream.next();
if (b != SegmentedStream.SPECIAL_SYMBOL) {
mySourceStream.pushBack(b);
return 1;
}
final boolean packetRead = readControlSequence();
if (!packetRead) {
// push back quoted slash
mySourceStream.pushBack(b);
mySourceStream.pushBack(b);
return 1;
}
}
return 0;
}
public void close() throws IOException {
mySourceStream.close();
}
public static String decode(final char[] chars) {
final StringBuilder buffer = StringBuilderSpinAllocator.alloc();
try {
for (int i = 0; i < chars.length; i++) {
char chr = chars[i];
final char decodedChar;
if (chr == Packet.ourSpecialSymbol) {
i++;
chr = chars[i];
if (chr != Packet.ourSpecialSymbol) {
final StringBuffer codeBuffer = new StringBuffer(Packet.CODE_LENGTH);
codeBuffer.append(chr);
for (int j = 1; j < Packet.CODE_LENGTH; j++)
codeBuffer.append(chars[i+j]);
i += Packet.CODE_LENGTH - 1;
decodedChar = (char)Integer.parseInt(codeBuffer.toString());
}
else decodedChar = chr;
} else decodedChar = chr;
buffer.append(decodedChar);
}
return buffer.toString();
}
finally {
StringBuilderSpinAllocator.dispose(buffer);
}
}
}
@@ -0,0 +1,152 @@
package com.intellij.execution.junit2.configuration;
import com.intellij.execution.ExecutionBundle;
import com.intellij.execution.JavaExecutionUtil;
import com.intellij.execution.configuration.BrowseModuleValueActionListener;
import com.intellij.execution.configurations.ConfigurationUtil;
import com.intellij.ide.util.TreeClassChooser;
import com.intellij.ide.util.TreeClassChooserDialog;
import com.intellij.ide.util.TreeClassChooserFactory;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.ex.MessagesEx;
import com.intellij.psi.JavaPsiFacade;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.util.PsiMethodUtil;
import org.jetbrains.annotations.Nullable;
public abstract class ClassBrowser extends BrowseModuleValueActionListener {
private final String myTitle;
public ClassBrowser(final Project project, final String title) {
super(project);
myTitle = title;
}
@Nullable
protected String showDialog() {
final TreeClassChooser.ClassFilterWithScope classFilter;
try {
classFilter = getFilter();
}
catch (NoFilterException e) {
final MessagesEx.MessageInfo info = e.getMessageInfo();
info.showNow();
return null;
}
final TreeClassChooser dialog = TreeClassChooserFactory.getInstance(getProject()).createWithInnerClassesScopeChooser(myTitle, classFilter.getScope(), classFilter, null);
configureDialog(dialog);
dialog.showDialog();
final PsiClass psiClass = dialog.getSelectedClass();
if (psiClass == null) return null;
onClassChoosen(psiClass);
return JavaExecutionUtil.getRuntimeQualifiedName(psiClass);
}
protected abstract TreeClassChooser.ClassFilterWithScope getFilter() throws NoFilterException;
protected void onClassChoosen(final PsiClass psiClass) { }
private void configureDialog(final TreeClassChooser dialog) {
final String className = getText();
final PsiClass psiClass = findClass(className);
if (psiClass == null) return;
final PsiDirectory directory = psiClass.getContainingFile().getContainingDirectory();
if (directory != null) dialog.selectDirectory(directory);
dialog.selectClass(psiClass);
}
protected abstract PsiClass findClass(String className);
public static ClassBrowser createApplicationClassBrowser(final Project project,
final ConfigurationModuleSelector moduleSelector) {
final TreeClassChooser.ClassFilter applicationClass = new TreeClassChooser.ClassFilter() {
public boolean isAccepted(final PsiClass aClass) {
return ConfigurationUtil.MAIN_CLASS.value(aClass) && PsiMethodUtil.findMainMethod(aClass) != null;
}
};
return new MainClassBrowser(project, moduleSelector, ExecutionBundle.message("choose.main.class.dialog.title")){
protected TreeClassChooser.ClassFilter createFilter(final Module module) {
return applicationClass;
}
};
}
public static ClassBrowser createAppletClassBrowser(final Project project,
final ConfigurationModuleSelector moduleSelector) {
return new MainClassBrowser(project, moduleSelector, ExecutionBundle.message("choose.applet.class.dialog.title")) {
protected TreeClassChooser.ClassFilter createFilter(final Module module) {
final GlobalSearchScope scope =
module == null ? GlobalSearchScope.allScope(myProject) : GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module);
final PsiClass appletClass = JavaPsiFacade.getInstance(project).findClass("java.applet.Applet", scope);
return new TreeClassChooserDialog.InheritanceClassFilterImpl(appletClass, false, false, ConfigurationUtil.PUBLIC_INSTANTIATABLE_CLASS);
}
};
}
private abstract static class MainClassBrowser extends ClassBrowser {
protected final Project myProject;
private final ConfigurationModuleSelector myModuleSelector;
public MainClassBrowser(final Project project,
final ConfigurationModuleSelector moduleSelector,
final String title) {
super(project, title);
myProject = project;
myModuleSelector = moduleSelector;
}
protected PsiClass findClass(final String className) {
return myModuleSelector.findClass(className);
}
protected TreeClassChooser.ClassFilterWithScope getFilter() throws NoFilterException {
final Module module = myModuleSelector.getModule();
final GlobalSearchScope scope;
if (module == null) scope = GlobalSearchScope.allScope(myProject);
else scope = GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module);
final TreeClassChooser.ClassFilter filter = createFilter(module);
return new TreeClassChooser.ClassFilterWithScope() {
public GlobalSearchScope getScope() {
return scope;
}
public boolean isAccepted(final PsiClass aClass) {
return filter == null || filter.isAccepted(aClass);
}
};
}
protected TreeClassChooser.ClassFilter createFilter(final Module module) { return null; }
}
public static class NoFilterException extends Exception {
private final MessagesEx.MessageInfo myMessageInfo;
public NoFilterException(final MessagesEx.MessageInfo messageInfo) {
super(messageInfo.getMessage());
myMessageInfo = messageInfo;
}
public MessagesEx.MessageInfo getMessageInfo() {
return myMessageInfo;
}
public static NoFilterException noJUnitInModule(final Module module) {
return new NoFilterException(new MessagesEx.MessageInfo(
module.getProject(),
ExecutionBundle.message("junit.not.found.in.module.error.message", module.getName()),
ExecutionBundle.message("cannot.browse.test.inheritors.dialog.title")));
}
public static NoFilterException moduleDoesntExist(final ConfigurationModuleSelector moduleSelector) {
final Project project = moduleSelector.getProject();
return new NoFilterException(new MessagesEx.MessageInfo(
project,
ExecutionBundle.message("module.does.not.exists", moduleSelector.getModuleName(), project.getName()),
ExecutionBundle.message("cannot.browse.test.inheritors.dialog.title")));
}
}
}
@@ -0,0 +1,53 @@
<?xml version="1.0" encoding="UTF-8"?>
<form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="com.intellij.execution.junit2.configuration.CommonJavaParameters">
<grid id="d88e6" binding="myWholePanel" row-count="3" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="10">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<xy x="64" y="62" width="431" height="137"/>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<component id="6e486" class="com.intellij.openapi.ui.LabeledComponent" binding="myVMParameters">
<constraints>
<xy x="0" y="9" width="431" height="16"/>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1">
<minimum-size width="0" height="-1"/>
<preferred-size width="400" height="-1"/>
</grid>
</constraints>
<properties>
<componentClass value="com.intellij.ui.RawCommandLineEditor"/>
<text resource-bundle="messages/ExecutionBundle" key="junit.configuration.vm.parameters.label"/>
</properties>
</component>
<component id="acecf" class="com.intellij.openapi.ui.LabeledComponent" binding="myProgramParameters">
<constraints>
<xy x="0" y="53" width="431" height="16"/>
<grid row="1" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1">
<minimum-size width="0" height="-1"/>
<preferred-size width="400" height="-1"/>
</grid>
</constraints>
<properties>
<componentClass value="com.intellij.ui.RawCommandLineEditor"/>
<text resource-bundle="messages/ExecutionBundle" key="junit.configuration.test.runner.parameters.label"/>
</properties>
</component>
<component id="8c18f" class="com.intellij.openapi.ui.LabeledComponent" binding="myWorkingDirectory">
<constraints>
<xy x="0" y="94" width="431" height="36"/>
<grid row="2" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1">
<minimum-size width="0" height="-1"/>
</grid>
</constraints>
<properties>
<componentClass value="com.intellij.openapi.ui.TextFieldWithBrowseButton"/>
<opaque value="true"/>
<text resource-bundle="messages/ExecutionBundle" key="junit.configuration.working.directory.label"/>
</properties>
</component>
</children>
</grid>
</form>
@@ -0,0 +1,112 @@
package com.intellij.execution.junit2.configuration;
import com.intellij.execution.ExecutionBundle;
import com.intellij.execution.RunJavaConfiguration;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.fileChooser.FileChooser;
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.ui.LabeledComponent;
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.RawCommandLineEditor;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class CommonJavaParameters extends JPanel {
private static final Logger LOG = Logger.getInstance("#com.intellij.execution.junit2.configuration.CommonJavaParameters");
private static final int[] ourProperties = new int[]{
RunJavaConfiguration.PROGRAM_PARAMETERS_PROPERTY,
RunJavaConfiguration.VM_PARAMETERS_PROPERTY,
RunJavaConfiguration.WORKING_DIRECTORY_PROPERTY
};
private JPanel myWholePanel;
private LabeledComponent<TextFieldWithBrowseButton> myWorkingDirectory;
private LabeledComponent<RawCommandLineEditor> myProgramParameters;
private LabeledComponent<RawCommandLineEditor> myVMParameters;
private final LabeledComponent[] myFields = new LabeledComponent[3];
private Module myModule = null;
public CommonJavaParameters() {
super(new BorderLayout());
add(myWholePanel, BorderLayout.CENTER);
copyDialogCaption(myProgramParameters);
copyDialogCaption(myVMParameters);
myWorkingDirectory.getComponent()
.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
FileChooserDescriptor fileChooserDescriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor();
fileChooserDescriptor.setTitle(ExecutionBundle.message("select.working.directory.message"));
fileChooserDescriptor.putUserData(LangDataKeys.MODULE_CONTEXT, myModule);
VirtualFile[] files = FileChooser.chooseFiles(myWorkingDirectory, fileChooserDescriptor);
if (files.length != 0) {
setText(RunJavaConfiguration.WORKING_DIRECTORY_PROPERTY, files[0].getPresentableUrl());
}
}
});
myFields[RunJavaConfiguration.PROGRAM_PARAMETERS_PROPERTY] = myProgramParameters;
myFields[RunJavaConfiguration.VM_PARAMETERS_PROPERTY] = myVMParameters;
myFields[RunJavaConfiguration.WORKING_DIRECTORY_PROPERTY] = myWorkingDirectory;
}
private static void copyDialogCaption(final LabeledComponent<RawCommandLineEditor> component) {
final RawCommandLineEditor rawCommandLineEditor = component.getComponent();
rawCommandLineEditor.setDialogCaption(component.getRawText());
component.getLabel().setLabelFor(rawCommandLineEditor.getTextField());
}
public String getProgramParametersText() {
return getLabeledComponent(RunJavaConfiguration.PROGRAM_PARAMETERS_PROPERTY).getText();
}
public void setProgramParametersText(String textWithMnemonic) {
getLabeledComponent(RunJavaConfiguration.PROGRAM_PARAMETERS_PROPERTY).setText(textWithMnemonic);
copyDialogCaption(myProgramParameters);
}
public void applyTo(final RunJavaConfiguration configuration) {
for (final int property : ourProperties) {
configuration.setProperty(property, getText(property));
}
}
public void reset(final RunJavaConfiguration configuration) {
for (final int property : ourProperties) {
setText(property, configuration.getProperty(property));
}
}
public void setText(final int property, final String value) {
final JComponent component = getLabeledComponent(property).getComponent();
if (component instanceof TextFieldWithBrowseButton)
((TextFieldWithBrowseButton)component).setText(value);
else if (component instanceof RawCommandLineEditor)
((RawCommandLineEditor)component).setText(value);
else LOG.error(component.getClass().getName());
}
public String getText(final int property) {
final JComponent component = getLabeledComponent(property).getComponent();
if (component instanceof TextFieldWithBrowseButton)
return ((TextFieldWithBrowseButton)component).getText();
else if (component instanceof RawCommandLineEditor)
return ((RawCommandLineEditor)component).getText();
else LOG.error(component.getClass().getName());
return "";
}
private LabeledComponent getLabeledComponent(final int index) {
return myFields[index];
}
public void setModuleContext(final Module module) {
myModule = module;
}
}
@@ -0,0 +1,112 @@
package com.intellij.execution.junit2.configuration;
import com.intellij.execution.configurations.JavaRunConfigurationModule;
import com.intellij.execution.configurations.ModuleBasedConfiguration;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.module.ModuleTypeManager;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiClass;
import com.intellij.ui.ComboboxSpeedSearch;
import com.intellij.ui.SortedComboBoxModel;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
public class ConfigurationModuleSelector {
private final Project myProject;
private final JComboBox myModulesList;
private final SortedComboBoxModel<Object> myModules = new SortedComboBoxModel<Object>(new Comparator<Object>() {
public int compare(final Object module, final Object module1) {
if (module instanceof Module && module1 instanceof Module){
return ((Module)module).getName().compareToIgnoreCase(((Module)module1).getName());
}
return -1;
}
});
private static final String NO_MODULE = "<no module>";
public ConfigurationModuleSelector(final Project project, final JComboBox modulesList) {
myProject = project;
myModulesList = modulesList;
new ComboboxSpeedSearch(modulesList){
protected String getElementText(Object element) {
if (element instanceof Module){
return ((Module)element).getName();
} else if (element == null) {
return NO_MODULE;
}
return super.getElementText(element);
}
};
myModulesList.setModel(myModules);
myModulesList.setRenderer(new DefaultListCellRenderer(){
public Component getListCellRendererComponent(final JList list, final Object value, final int index, final boolean isSelected, final boolean cellHasFocus) {
final Component component = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if (value instanceof Module) {
final Module module = (Module)value;
setIcon(module.getModuleType().getNodeIcon(true));
setText(module.getName());
} else if (value == null) {
setText(NO_MODULE);
}
return component;
}
});
}
public void applyTo(final ModuleBasedConfiguration configurationModule) {
configurationModule.setModule((Module)myModulesList.getSelectedItem());
}
public void reset(final ModuleBasedConfiguration configuration) {
final Module[] modules = ModuleManager.getInstance(getProject()).getModules();
final List<Module> list = new ArrayList<Module>();
for (final Module module : modules) {
if (isModuleAccepted(module)) list.add(module);
}
setModules(list);
myModules.setSelectedItem(configuration.getConfigurationModule().getModule());
}
public static boolean isModuleAccepted(final Module module) {
return ModuleTypeManager.getInstance().isClasspathProvider(module.getModuleType());
}
public Project getProject() {
return myProject;
}
public JavaRunConfigurationModule getConfigurationModule() {
final JavaRunConfigurationModule configurationModule = new JavaRunConfigurationModule(getProject(), false);
configurationModule.setModule((Module)myModules.getSelectedItem());
return configurationModule;
}
private void setModules(final Collection<Module> modules) {
myModules.clear();
myModules.add(null);
for (Module module : modules) {
myModules.add(module);
}
}
public Module getModule() {
return (Module)myModules.getSelectedItem();
}
@Nullable
public PsiClass findClass(final String className) {
return getConfigurationModule().findClass(className);
}
public String getModuleName() {
final Module module = (Module)myModules.getSelectedItem();
return module == null ? "" : module.getName();
}
}
@@ -0,0 +1,68 @@
package com.intellij.execution.junit2.info;
import com.intellij.execution.Location;
import com.intellij.execution.PsiLocation;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiMethod;
import org.jetbrains.annotations.NotNull;
import java.util.Iterator;
// Author: dyoma
public class MethodLocation extends Location<PsiMethod> {
private static final Logger LOG = Logger.getInstance("#com.intellij.execution.junit2.info.MethodLocation");
private final Project myProject;
@NotNull private final PsiMethod myMethod;
private final Location<PsiClass> myClassLocation;
public MethodLocation(@NotNull final Project project, @NotNull final PsiMethod method, @NotNull final Location<PsiClass> classLocation) {
myProject = project;
myMethod = method;
myClassLocation = classLocation;
}
public static MethodLocation elementInClass(final PsiMethod psiElement, final PsiClass psiClass) {
final Location<PsiClass> classLocation = PsiLocation.fromPsiElement(psiClass);
return new MethodLocation(classLocation.getProject(), psiElement, classLocation);
}
@NotNull
public PsiMethod getPsiElement() {
return myMethod;
}
@NotNull
public Project getProject() {
return myProject;
}
public PsiClass getContainingClass() {
return myClassLocation.getPsiElement();
}
@NotNull
public <T extends PsiElement> Iterator<Location<T>> getAncestors(final Class<T> ancestorClass, final boolean strict) {
final Iterator<Location<T>> fromClass = myClassLocation.getAncestors(ancestorClass, false);
if (strict) return fromClass;
return new Iterator<Location<T>>() {
private boolean myFirstStep = ancestorClass.isInstance(myMethod);
public boolean hasNext() {
return myFirstStep || fromClass.hasNext();
}
public Location<T> next() {
final Location<T> location = myFirstStep ? (Location<T>)(Location)MethodLocation.this : fromClass.next();
myFirstStep = false;
return location;
}
public void remove() {
LOG.assertTrue(false);
}
};
}
}
@@ -0,0 +1,7 @@
package com.intellij.execution.junit2.segments;
public interface DeferedActionsQueue {
void addLast(Runnable runnable);
void setDispactchListener(DispatchListener listener);
}
@@ -0,0 +1,33 @@
package com.intellij.execution.junit2.segments;
import com.intellij.openapi.diagnostic.Logger;
import java.awt.*;
public class DeferedActionsQueueImpl implements DeferedActionsQueue {
private static final Logger LOG = Logger.getInstance("#com.intellij.execution.junit2.segments.DeferedActionsQueueImpl");
private DispatchListener myListener = DispatchListener.DEAF;
private int myCounter = 0;
public void addLast(final Runnable runnable) {
checkIsDispatchThread();
myListener.onStarted();
try {
runnable.run();
} finally{
myListener.onFinished();
}
}
private void checkIsDispatchThread() {
myCounter++;
if (myCounter > 127) {
myCounter = 0;
LOG.assertTrue(EventQueue.isDispatchThread());
}
}
public void setDispactchListener(final DispatchListener listener) {
myListener = listener;
}
}
@@ -0,0 +1,14 @@
package com.intellij.execution.junit2.segments;
public interface DispatchListener {
void onStarted();
void onFinished();
DispatchListener DEAF = new DispatchListener() {
public void onStarted() {
}
public void onFinished() {
}
};
}
@@ -0,0 +1,12 @@
package com.intellij.execution.junit2.segments;
import com.intellij.execution.ui.ConsoleViewContentType;
public interface InputConsumer {
class DeafInputConsumer implements InputConsumer {
public void onOutput(final String text, final ConsoleViewContentType contentType) {
}
}
DeafInputConsumer DEAF = new DeafInputConsumer();
void onOutput(String text, ConsoleViewContentType contentType);
}
@@ -0,0 +1,24 @@
package com.intellij.execution.junit2.segments;
import com.intellij.rt.execution.junit.segments.PacketProcessor;
/**
* @author dyoma
*/
public abstract class PacketExtractorBase {
private DeferedActionsQueue myFulfilledWorkGate = null;
public void setFulfilledWorkGate(final DeferedActionsQueue fulfilledWorkGate) {
myFulfilledWorkGate = fulfilledWorkGate;
}
public abstract void setPacketProcessor(PacketProcessor packetProcessor);
public void setDispatchListener(final DispatchListener listener) {
myFulfilledWorkGate.setDispactchListener(listener);
}
protected void perform(final Runnable runnable) {
myFulfilledWorkGate.addLast(runnable);
}
}
@@ -0,0 +1,68 @@
package com.intellij.execution.junit2.segments;
import com.intellij.rt.execution.junit.segments.PoolOfDelimiters;
import com.intellij.util.ArrayUtil;
import java.util.ArrayList;
public class SegmentReader {
private final String myString;
private final char[] myChars;
private int myPosition = 0;
public SegmentReader(final String packet) {
myString = packet;
myChars = packet.toCharArray();
}
public String upTo(final char symbol) {
int position = myPosition;
while (position < myChars.length && myChars[position] != symbol) position++;
final String result = advanceTo(position);
skip(1);
return result;
}
public void skip(final int count) {
myPosition = Math.min(myChars.length, myPosition + count);
}
public String upToEnd() {
return advanceTo(myChars.length);
}
private String advanceTo(final int position) {
final String result = myString.substring(myPosition, position);
myPosition = position;
return result;
}
public String readLimitedString() {
final int symbolCount = readInt();
return advanceTo(myPosition + symbolCount);
}
public int readInt() {
final String intString = upTo(PoolOfDelimiters.INTEGER_DELIMITER);
return Integer.parseInt(intString);
}
public char readChar() {
myPosition++;
return myChars[myPosition - 1];
}
public boolean isAtEnd() {
return myPosition == myChars.length;
}
public String[] readStringArray() {
final int count = readInt();
if (count == 0) return ArrayUtil.EMPTY_STRING_ARRAY;
final ArrayList<String> strings = new ArrayList<String>(count);
for (int i = 0; i < count; i++) {
strings.add(readLimitedString());
}
return strings.toArray(new String[count]);
}
}
@@ -0,0 +1,183 @@
<?xml version="1.0" encoding="UTF-8"?>
<form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="com.intellij.execution.remote.RemoteConfigurable">
<grid id="715ea" binding="myPanel" layout-manager="GridLayoutManager" row-count="5" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<xy x="64" y="1" width="482" height="367"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<component id="49c58" class="javax.swing.JLabel">
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text resource-bundle="messages/ExecutionBundle" key="remote.configuration.remote.debugging.allows.you.to.connect.idea.to.a.running.jvm.label"/>
</properties>
</component>
<vspacer id="3ca11">
<constraints>
<grid row="4" column="0" row-span="1" col-span="1" vsize-policy="6" hsize-policy="1" anchor="0" fill="2" indent="0" use-parent-layout="false"/>
</constraints>
</vspacer>
<grid id="e37d3" layout-manager="GridLayoutManager" row-count="3" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="5" vgap="8">
<margin top="3" left="5" bottom="5" right="5"/>
<constraints>
<grid row="3" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="1" fill="1" indent="0" use-parent-layout="false">
<minimum-size width="-1" height="170"/>
<maximum-size width="-1" height="170"/>
</grid>
</constraints>
<properties/>
<border type="etched" title-resource-bundle="messages/ExecutionBundle" title-key="remote.configuration.settings.border"/>
<children>
<grid id="d0319" binding="mySocketPanel" layout-manager="GridLayoutManager" row-count="2" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="1" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="1" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<component id="11a97" class="javax.swing.JTextField" binding="myPortField">
<constraints>
<grid row="1" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="8" fill="1" indent="0" use-parent-layout="false">
<preferred-size width="150" height="-1"/>
</grid>
</constraints>
<properties/>
</component>
<component id="76d9b" class="javax.swing.JTextField" binding="myHostField">
<constraints>
<grid row="0" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="8" fill="1" indent="0" use-parent-layout="false">
<preferred-size width="150" height="-1"/>
</grid>
</constraints>
<properties/>
</component>
<component id="66348" class="javax.swing.JLabel">
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="4" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text resource-bundle="messages/ExecutionBundle" key="remote.configuration.host.label"/>
</properties>
</component>
<component id="24ab6" class="javax.swing.JLabel">
<constraints>
<grid row="1" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="4" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text resource-bundle="messages/ExecutionBundle" key="remote.configuration.port.label"/>
</properties>
</component>
</children>
</grid>
<grid id="446e3" binding="myShmemPanel" layout-manager="GridLayoutManager" row-count="1" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="2" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="1" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<component id="9623e" class="javax.swing.JLabel">
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="4" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text resource-bundle="messages/ExecutionBundle" key="remote.configuration.shared.memory.address.label"/>
</properties>
</component>
<component id="d75e1" class="javax.swing.JTextField" binding="myAddressField">
<constraints>
<grid row="0" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="8" fill="1" indent="0" use-parent-layout="false">
<preferred-size width="150" height="-1"/>
</grid>
</constraints>
<properties>
<text value=""/>
</properties>
</component>
</children>
</grid>
<grid id="353eb" layout-manager="GridLayoutManager" row-count="2" column-count="3" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="1" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<component id="9ca9f" class="javax.swing.JRadioButton" binding="myRbSocket">
<constraints>
<grid row="0" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text resource-bundle="messages/ExecutionBundle" key="remote.configuration.socket.radio"/>
</properties>
</component>
<component id="43956" class="javax.swing.JRadioButton" binding="myRbShmem">
<constraints>
<grid row="0" column="2" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text resource-bundle="messages/ExecutionBundle" key="remote.configuration.shared.memory.radio"/>
</properties>
</component>
<component id="360fe" class="javax.swing.JLabel">
<constraints>
<grid row="1" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="4" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text resource-bundle="messages/ExecutionBundle" key="remote.configuration.debugger.mode.label"/>
</properties>
</component>
<component id="130cc" class="javax.swing.JRadioButton" binding="myRbAttach">
<constraints>
<grid row="1" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text resource-bundle="messages/ExecutionBundle" key="remote.configuration.attach.radio"/>
</properties>
</component>
<component id="886d9" class="javax.swing.JRadioButton" binding="myRbListen">
<constraints>
<grid row="1" column="2" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text resource-bundle="messages/ExecutionBundle" key="remote.configuration.listen.radio"/>
</properties>
</component>
<component id="a481c" class="javax.swing.JLabel">
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="4" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text resource-bundle="messages/ExecutionBundle" key="remote.configuration.transport.label"/>
</properties>
</component>
</children>
</grid>
</children>
</grid>
<component id="aa30e" class="com.intellij.execution.ui.ConfigurationArgumentsHelpArea" binding="myHelpArea">
<constraints>
<grid row="1" column="0" row-span="1" col-span="1" vsize-policy="7" hsize-policy="6" anchor="8" fill="3" indent="0" use-parent-layout="false">
<preferred-size width="150" height="100"/>
</grid>
</constraints>
<properties/>
</component>
<component id="77c23" class="com.intellij.execution.ui.ConfigurationArgumentsHelpArea" binding="myJDK13HelpArea">
<constraints>
<grid row="2" column="0" row-span="1" col-span="1" vsize-policy="7" hsize-policy="6" anchor="8" fill="3" indent="0" use-parent-layout="false">
<preferred-size width="150" height="100"/>
</grid>
</constraints>
<properties/>
</component>
</children>
</grid>
</form>
@@ -0,0 +1,170 @@
/*
* Class RemoteConfigurable
* @author Jeka
*/
package com.intellij.execution.remote;
import com.intellij.execution.ExecutionBundle;
import com.intellij.execution.configurations.RemoteConnection;
import com.intellij.execution.ui.ConfigurationArgumentsHelpArea;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.options.SettingsEditor;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.ui.DocumentAdapter;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.event.*;
public class RemoteConfigurable extends SettingsEditor<RemoteConfiguration> {
JPanel myPanel;
private JRadioButton myRbSocket;
private JRadioButton myRbShmem;
private JRadioButton myRbListen;
private JRadioButton myRbAttach;
private JTextField myAddressField;
private JTextField myHostField;
private JTextField myPortField;
private JPanel myShmemPanel;
private JPanel mySocketPanel;
private ConfigurationArgumentsHelpArea myHelpArea;
@NonNls private ConfigurationArgumentsHelpArea myJDK13HelpArea;
private String myHostName = "";
@NonNls
protected static final String LOCALHOST = "localhost";
public RemoteConfigurable() {
myJDK13HelpArea.setLabelText(ExecutionBundle.message("environment.variables.helper.use.arguments.jdk13.label"));
final ButtonGroup transportGroup = new ButtonGroup();
transportGroup.add(myRbSocket);
transportGroup.add(myRbShmem);
final ButtonGroup connectionGroup = new ButtonGroup();
connectionGroup.add(myRbListen);
connectionGroup.add(myRbAttach);
final DocumentListener helpTextUpdater = new DocumentAdapter() {
public void textChanged(DocumentEvent event) {
updateHelpText();
}
};
myAddressField.getDocument().addDocumentListener(helpTextUpdater);
myHostField.getDocument().addDocumentListener(helpTextUpdater);
myPortField.getDocument().addDocumentListener(helpTextUpdater);
myRbSocket.setSelected(true);
final ActionListener listener = new ActionListener() {
public void actionPerformed(final ActionEvent e) {
final Object source = e.getSource();
if (source.equals(myRbSocket)) {
myShmemPanel.setVisible(false);
mySocketPanel.setVisible(true);
}
else if (source.equals(myRbShmem)) {
myShmemPanel.setVisible(true);
mySocketPanel.setVisible(false);
}
myPanel.repaint();
updateHelpText();
}
};
myRbShmem.addActionListener(listener);
myRbSocket.addActionListener(listener);
final ItemListener updateListener = new ItemListener() {
public void itemStateChanged(final ItemEvent e) {
final boolean isAttach = myRbAttach.isSelected();
if(!isAttach && myHostField.isEditable()) {
myHostName = myHostField.getText();
}
myHostField.setEditable(isAttach);
myHostField.setEnabled(isAttach);
myHostField.setText(isAttach ? myHostName : LOCALHOST);
updateHelpText();
}
};
myRbAttach.addItemListener(updateListener);
myRbListen.addItemListener(updateListener);
final FocusListener fieldFocusListener = new FocusAdapter() {
public void focusLost(final FocusEvent e) {
updateHelpText();
}
};
myAddressField.addFocusListener(fieldFocusListener);
myPortField.addFocusListener(fieldFocusListener);
}
public void applyEditorTo(@NotNull final RemoteConfiguration configuration) throws ConfigurationException {
configuration.HOST = (myHostField.isEditable() ? myHostField.getText() : myHostName).trim();
if ("".equals(configuration.HOST)) {
configuration.HOST = null;
}
configuration.PORT = myPortField.getText().trim();
if ("".equals(configuration.PORT)) {
configuration.PORT = null;
}
configuration.SHMEM_ADDRESS = myAddressField.getText().trim();
if ("".equals(configuration.SHMEM_ADDRESS)) {
configuration.SHMEM_ADDRESS = null;
}
configuration.USE_SOCKET_TRANSPORT = myRbSocket.isSelected();
configuration.SERVER_MODE = myRbListen.isSelected();
}
public void resetEditorFrom(final RemoteConfiguration configuration) {
if (!SystemInfo.isWindows) {
configuration.USE_SOCKET_TRANSPORT = true;
myRbShmem.setEnabled(false);
myAddressField.setEditable(false);
}
myAddressField.setText(configuration.SHMEM_ADDRESS);
myHostName = configuration.HOST;
myHostField.setText(configuration.HOST);
myPortField.setText(configuration.PORT);
if (configuration.USE_SOCKET_TRANSPORT) {
myRbSocket.doClick();
}
else {
myRbShmem.doClick();
}
if (configuration.SERVER_MODE) {
myRbListen.doClick();
}
else {
myRbAttach.doClick();
}
myRbShmem.setEnabled(SystemInfo.isWindows);
}
@NotNull
public JComponent createEditor() {
return myPanel;
}
public void disposeEditor() {
}
private void updateHelpText() {
boolean useSockets = !myRbShmem.isSelected();
final RemoteConnection connection = new RemoteConnection(
useSockets,
myHostName,
useSockets ? myPortField.getText().trim() : myAddressField.getText().trim(),
myRbListen.isSelected()
);
final String cmdLine = connection.getLaunchCommandLine();
myHelpArea.updateText(cmdLine);
myJDK13HelpArea.updateText("-Xnoagent -Djava.compiler=NONE " + cmdLine);
}
}
@@ -0,0 +1,77 @@
/*
* @author Jeka
*/
package com.intellij.execution.remote;
import com.intellij.debugger.engine.RemoteStateState;
import com.intellij.debugger.impl.GenericDebuggerRunnerSettings;
import com.intellij.debugger.settings.DebuggerSettings;
import com.intellij.diagnostic.logging.LogConfigurationPanel;
import com.intellij.execution.ExecutionBundle;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.Executor;
import com.intellij.execution.configurations.*;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.options.SettingsEditor;
import com.intellij.openapi.options.SettingsEditorGroup;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.DefaultJDOMExternalizer;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.WriteExternalException;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import java.util.Collection;
public class RemoteConfiguration extends ModuleBasedConfiguration<JavaRunConfigurationModule> {
public void writeExternal(final Element element) throws WriteExternalException {
super.writeExternal(element);
DefaultJDOMExternalizer.writeExternal(this, element);
}
public void readExternal(final Element element) throws InvalidDataException {
super.readExternal(element);
DefaultJDOMExternalizer.readExternal(this, element);
}
public boolean USE_SOCKET_TRANSPORT;
public boolean SERVER_MODE;
public String SHMEM_ADDRESS;
public String HOST;
public String PORT;
public RemoteConfiguration(final String name, final Project project, ConfigurationFactory configurationFactory) {
super(name, new JavaRunConfigurationModule(project, true), configurationFactory);
}
public RemoteConnection createRemoteConnection() {
return new RemoteConnection(USE_SOCKET_TRANSPORT, HOST, USE_SOCKET_TRANSPORT ? PORT : SHMEM_ADDRESS, SERVER_MODE);
}
public RunProfileState getState(@NotNull final Executor executor, @NotNull final ExecutionEnvironment env) throws ExecutionException {
GenericDebuggerRunnerSettings debuggerSettings = ((GenericDebuggerRunnerSettings)env.getRunnerSettings().getData());
debuggerSettings.LOCAL = false;
debuggerSettings.setDebugPort(USE_SOCKET_TRANSPORT ? PORT : SHMEM_ADDRESS);
debuggerSettings.setTransport(USE_SOCKET_TRANSPORT ? DebuggerSettings.SOCKET_TRANSPORT : DebuggerSettings.SHMEM_TRANSPORT);
return new RemoteStateState(getProject(), createRemoteConnection(), env.getRunnerSettings(), env.getConfigurationSettings());
}
public SettingsEditor<? extends RunConfiguration> getConfigurationEditor() {
SettingsEditorGroup<RemoteConfiguration> group = new SettingsEditorGroup<RemoteConfiguration>();
group.addEditor(ExecutionBundle.message("run.configuration.configuration.tab.title"), new RemoteConfigurable());
group.addEditor(ExecutionBundle.message("logs.tab.title"), new LogConfigurationPanel());
return group;
}
protected ModuleBasedConfiguration createInstance() {
return new RemoteConfiguration(getName(), getProject(), RemoteConfigurationType.getInstance().getConfigurationFactories()[0]);
}
public Collection<Module> getValidModules() {
return getAllModules();
}
}
@@ -0,0 +1,60 @@
/*
* Class RemoteConfigurationFactory
* @author Jeka
*/
package com.intellij.execution.remote;
import com.intellij.execution.ExecutionBundle;
import com.intellij.execution.configurations.ConfigurationFactory;
import com.intellij.execution.configurations.ConfigurationType;
import com.intellij.execution.configurations.RunConfiguration;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.IconLoader;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
public class RemoteConfigurationType implements ConfigurationType {
private final ConfigurationFactory myFactory;
private static final Icon ICON = IconLoader.getIcon("/runConfigurations/remote.png");
/**reflection*/
public RemoteConfigurationType() {
myFactory = new ConfigurationFactory(this) {
public RunConfiguration createTemplateConfiguration(Project project) {
return new RemoteConfiguration("", project, this);
}
};
}
public String getDisplayName() {
return ExecutionBundle.message("remote.debug.configuration.display.name");
}
public String getConfigurationTypeDescription() {
return ExecutionBundle.message("remote.debug.configuration.description");
}
public Icon getIcon() {
return ICON;
}
public ConfigurationFactory[] getConfigurationFactories() {
return new ConfigurationFactory[]{myFactory};
}
@NotNull
public String getId() {
return "Remote";
}
@Nullable
public static RemoteConfigurationType getInstance() {
return ContainerUtil.findInstance(Extensions.getExtensions(CONFIGURATION_TYPE_EP), RemoteConfigurationType.class);
}
}
@@ -0,0 +1,39 @@
/*
* Copyright (c) 2000-2004 by JetBrains s.r.o. All Rights Reserved.
* Use is subject to license terms.
*/
package com.intellij.execution.runners;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.configurations.JavaCommandLine;
import com.intellij.execution.configurations.JavaParameters;
import com.intellij.execution.configurations.ParametersList;
import com.intellij.execution.process.ProcessHandler;
import com.intellij.openapi.projectRoots.ex.JavaSdkUtil;
import com.intellij.openapi.application.PathManager;
public class ProcessProxyFactoryImpl extends ProcessProxyFactory {
public ProcessProxy createCommandLineProxy(final JavaCommandLine javaCmdLine) throws ExecutionException {
ProcessProxyImpl proxy = null;
if (ProcessProxyImpl.useLauncher()) {
try {
proxy = new ProcessProxyImpl();
final JavaParameters javaParameters = javaCmdLine.getJavaParameters();
JavaSdkUtil.addRtJar(javaParameters.getClassPath());
final ParametersList vmParametersList = javaParameters.getVMParametersList();
vmParametersList.defineProperty(ProcessProxyImpl.PROPERTY_PORT_NUMBER, "" + proxy.getPortNumber());
vmParametersList.defineProperty(ProcessProxyImpl.PROPERTY_BINPATH, PathManager.getBinPath());
javaParameters.getProgramParametersList().prepend(javaParameters.getMainClass());
javaParameters.setMainClass(ProcessProxyImpl.LAUNCH_MAIN_CLASS);
}
catch (ProcessProxyImpl.NoMoreSocketsException e) {
proxy = null;
}
}
return proxy;
}
public ProcessProxy getAttachedProxy(final ProcessHandler processHandler) {
return processHandler != null ? processHandler.getUserData(ProcessProxyImpl.KEY) : null;
}
}
@@ -0,0 +1,114 @@
package com.intellij.execution.runners;
import com.intellij.execution.process.ProcessHandler;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.SystemInfo;
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import org.jetbrains.annotations.NonNls;
/**
* @author ven
*/
class ProcessProxyImpl implements ProcessProxy {
public static final Key<ProcessProxyImpl> KEY = Key.create("ProcessProxyImpl");
private final int myPortNumber;
private static final int SOCKET_NUMBER_START = 7532;
private static final int SOCKET_NUMBER = 100;
private static final boolean[] ourUsedSockets = new boolean[SOCKET_NUMBER];
private PrintWriter myWriter;
private Socket mySocket;
@NonNls private static final String DONT_USE_LAUNCHER_PROPERTY = "idea.no.launcher";
@NonNls public static final String PROPERTY_BINPATH = "idea.launcher.bin.path";
@NonNls public static final String PROPERTY_PORT_NUMBER = "idea.launcher.port";
@NonNls public static final String LAUNCH_MAIN_CLASS = "com.intellij.rt.execution.application.AppMain";
@NonNls
protected static final String LOCALHOST = "localhost";
public int getPortNumber() {
return myPortNumber;
}
public static class NoMoreSocketsException extends Exception {
}
public ProcessProxyImpl () throws NoMoreSocketsException {
myPortNumber = getPortNumer();
if (myPortNumber == -1) throw new NoMoreSocketsException();
}
private static int getPortNumer() {
synchronized (ourUsedSockets) {
for (int j = 0; j < SOCKET_NUMBER; j++) {
if (ourUsedSockets[j]) continue;
try {
ServerSocket s = new ServerSocket(j + SOCKET_NUMBER_START);
s.close();
ourUsedSockets[j] = true;
return j + SOCKET_NUMBER_START;
} catch (IOException e) {
continue;
}
}
}
return -1;
}
public void finalize () throws Throwable {
if (myWriter != null) {
myWriter.close();
}
ourUsedSockets[myPortNumber - SOCKET_NUMBER_START] = false;
super.finalize();
}
public void attach(final ProcessHandler processHandler) {
processHandler.putUserData(KEY, this);
}
private synchronized void writeLine (@NonNls final String s) {
if (myWriter == null) {
try {
if (mySocket == null)
mySocket = new Socket(InetAddress.getByName(LOCALHOST), myPortNumber);
myWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(mySocket.getOutputStream())));
} catch (IOException e) {
return;
}
}
myWriter.println(s);
myWriter.flush();
}
public void sendBreak () {
writeLine("BREAK");
}
public void sendStop () {
writeLine("STOP");
}
public static boolean useLauncher() {
if (Boolean.valueOf(System.getProperty(DONT_USE_LAUNCHER_PROPERTY))) {
return false;
}
if (!SystemInfo.isWindows && !SystemInfo.isLinux) {
return false;
}
return new File(getLaunchertLibName()).exists();
}
public static String getLaunchertLibName() {
@NonNls final String libName = SystemInfo.isWindows ? "breakgen.dll" : "libbreakgen.so";
return PathManager.getBinPath() + File.separator + libName;
}
}
@@ -0,0 +1,23 @@
package com.intellij.execution.stacktrace;
import com.intellij.execution.Location;
import com.intellij.execution.junit2.info.MethodLocation;
import com.intellij.openapi.fileEditor.OpenFileDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiMethod;
public class MethodLineLocation extends MethodLocation {
private final int myLineNumber;
public MethodLineLocation(final Project project, final PsiMethod method, final Location<PsiClass> classLocation, final int lineNumber) {
super(project, method, classLocation);
myLineNumber = lineNumber;
}
public OpenFileDescriptor getOpenFileDescriptor() {
final VirtualFile virtualFile = getContainingClass().getContainingFile().getVirtualFile();
return new OpenFileDescriptor(getProject(), virtualFile, myLineNumber, 0);
}
}
@@ -0,0 +1,143 @@
package com.intellij.execution.stacktrace;
import com.intellij.execution.Location;
import com.intellij.execution.PsiLocation;
import com.intellij.openapi.fileEditor.OpenFileDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.text.LineTokenizer;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.util.PsiTreeUtil;
import org.jetbrains.annotations.NonNls;
public class StackTraceLine {
private final Project myProject;
private final String myLine;
@NonNls
protected static final String AT_STR = "at";
protected static final String AT__STR = AT_STR + " ";
@NonNls protected static final String INIT_MESSAGE = "<init>";
public StackTraceLine(Project project, final String line) {
myProject = project;
myLine = line;
}
public String getClassName() {
int index = myLine.indexOf(AT_STR);
if (index < 0) return null;
index += AT__STR.length();
final int lastDot = getLastDot();
if (lastDot < 0) return null;
if (lastDot <= index) return null;
return myLine.substring(index, lastDot);
}
private int getLastDot() {
return myLine.lastIndexOf('.', getOpenBracket());
}
private int getOpenBracket() {
return myLine.indexOf('(');
}
private int getCloseBracket() {
return myLine.indexOf(')');
}
public int getLineNumber() throws NumberFormatException {
final int close = getCloseBracket();
final int lineNumberStart = myLine.lastIndexOf(':') + 1;
if (close < 0 || lineNumberStart < 1) throw new NumberFormatException(myLine);
return Integer.parseInt(myLine.substring(lineNumberStart, close)) - 1;
}
public OpenFileDescriptor getOpenFileDescriptor(final VirtualFile file) {
final int lineNumber;
try {
lineNumber = getLineNumber();
} catch(NumberFormatException e) {
return new OpenFileDescriptor(myProject, file);
}
return new OpenFileDescriptor(myProject, file, lineNumber, 0);
}
public OpenFileDescriptor getOpenFileDescriptor(final Project project) {
final Location<PsiMethod> location = getMethodLocation(project);
if (location == null) return null;
return getOpenFileDescriptor(location.getPsiElement().getContainingFile().getVirtualFile());
}
public String getMethodName() {
final int lastDot = getLastDot();
if (lastDot == -1) return null;
return myLine.substring(getLastDot() + 1, getOpenBracket());
}
public Location<PsiMethod> getMethodLocation(final Project project) {
String className = getClassName();
final String methodName = getMethodName();
if (className == null || methodName == null) return null;
final int lineNumber;
try {
lineNumber = getLineNumber();
} catch(NumberFormatException e) {
return null;
}
final int dollarIndex = className.indexOf('$');
if (dollarIndex != -1) className = className.substring(0, dollarIndex);
PsiClass psiClass = findClass(project, className, lineNumber);
if (psiClass == null || (psiClass.getNavigationElement() instanceof PsiCompiledElement)) return null;
psiClass = (PsiClass)psiClass.getNavigationElement();
final PsiMethod psiMethod = getMethodAtLine(psiClass, methodName, lineNumber);
if (psiMethod != null) {
return new MethodLineLocation(project, psiMethod, PsiLocation.fromPsiElement(psiClass), lineNumber);
}
else {
return null;
}
}
private PsiClass findClass(final Project project, final String className, final int lineNumber) {
if (project == null) return null;
final PsiManager psiManager = PsiManager.getInstance(project);
if (psiManager == null) return null;
PsiClass psiClass = JavaPsiFacade.getInstance(psiManager.getProject()).findClass(className, GlobalSearchScope.allScope(project));
if (psiClass == null || (psiClass.getNavigationElement() instanceof PsiCompiledElement)) return null;
psiClass = (PsiClass)psiClass.getNavigationElement();
final PsiFile psiFile = psiClass.getContainingFile();
return PsiTreeUtil.getParentOfType(psiFile.findElementAt(offsetOfLine(psiFile, lineNumber)), PsiClass.class, false);
}
private static PsiMethod getMethodAtLine(final PsiClass psiClass, final String methodName, final int lineNumber) {
final PsiMethod[] methods;
if (INIT_MESSAGE.equals(methodName)) methods = psiClass.getConstructors();
else methods = psiClass.findMethodsByName(methodName, true);
if (methods.length == 0) return null;
final PsiFile psiFile = methods[0].getContainingFile();
final int offset = offsetOfLine(psiFile, lineNumber);
for (int i = 0; i < methods.length; i++) {
final PsiMethod method = methods[i];
if (method.getTextRange().contains(offset)) return method;
}
//if (!methods.hasNext() || location == null) return null;
//return location.getPsiElement();
//if ("<init>".equals(methodName)) methods = psiClass.getConstructors();
//else methods = psiClass.findMethodsByName(methodName, true);
//if (methods.length == 0) return null;
//for (int i = 0; i < methods.length; i++) {
// PsiMethod method = methods[i];
// if (method.getTextRange().contains(offset)) return method;
//}
return null;
}
private static int offsetOfLine(final PsiFile psiFile, final int lineNumber) {
final LineTokenizer lineTokenizer = new LineTokenizer(psiFile.getViewProvider().getContents());
for (int i = 0; i < lineNumber; i++) lineTokenizer.advance();
final int offset = lineTokenizer.getOffset();
return offset;
}
}
@@ -0,0 +1,27 @@
/*
* User: anna
* Date: 20-Feb-2008
*/
package com.intellij.execution.testframework;
import com.intellij.execution.Location;
import com.intellij.execution.PsiLocation;
import com.intellij.execution.junit2.info.MethodLocation;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiMethod;
public class JavaAwareFilter {
private JavaAwareFilter() {
}
public static Filter METHOD(final Project project) {
return new Filter() {
public boolean shouldAccept(final AbstractTestProxy test) {
final Location location = test.getLocation(project);
if (location instanceof MethodLocation) return true;
if (location instanceof PsiLocation && location.getPsiElement() instanceof PsiMethod) return true;
return false;
}
};
}
}
@@ -0,0 +1,42 @@
/*
* User: anna
* Date: 20-Feb-2008
*/
package com.intellij.execution.testframework;
import com.intellij.debugger.DebuggerManagerEx;
import com.intellij.debugger.impl.DebuggerSession;
import com.intellij.openapi.project.Project;
import com.intellij.util.config.Storage;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
public abstract class JavaAwareTestConsoleProperties extends TestConsoleProperties {
public JavaAwareTestConsoleProperties(final Storage storage, Project project) {
super(storage, project);
}
@Override
public boolean isDebug() {
return getDebugSession() != null;
}
@Override
public boolean isPaused() {
final DebuggerSession debuggerSession = getDebugSession();
return debuggerSession != null && debuggerSession.isPaused();
}
@Nullable
public DebuggerSession getDebugSession() {
final DebuggerManagerEx debuggerManager = DebuggerManagerEx.getInstanceEx(getProject());
if (debuggerManager == null) return null;
final Collection<DebuggerSession> sessions = debuggerManager.getSessions();
for (final DebuggerSession debuggerSession : sessions) {
if (getConsole() == debuggerSession.getProcess().getExecutionResult().getExecutionConsole()) return debuggerSession;
}
return null;
}
}
@@ -0,0 +1,91 @@
package com.intellij.execution.ui;
import com.intellij.execution.ExecutionBundle;
import com.intellij.ide.util.BrowseFilesListener;
import com.intellij.openapi.projectRoots.ProjectJdkTable;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.ui.ComponentWithBrowseButton;
import com.intellij.openapi.ui.TextComponentAccessor;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.ui.GuiUtils;
import com.intellij.ui.InsertPathAction;
import com.intellij.ui.TextFieldWithHistory;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
/**
* User: anna
* Date: Jun 21, 2005
*/
public class AlternativeJREPanel extends JPanel{
private final ComponentWithBrowseButton<TextFieldWithHistory> myPathField;
private final JCheckBox myCbEnabled;
final TextFieldWithHistory myFieldWithHistory;
public AlternativeJREPanel() {
super(new GridBagLayout());
myCbEnabled = new JCheckBox(ExecutionBundle.message("run.configuration.use.alternate.jre.checkbox"));
final GridBagConstraints gc = new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 1.0, 0, GridBagConstraints.NORTHWEST,
GridBagConstraints.HORIZONTAL, new Insets(2, -2, 2, 2), 0, 0);
add(myCbEnabled, gc);
myFieldWithHistory = new TextFieldWithHistory();
myFieldWithHistory.setBorder(BorderFactory.createEtchedBorder());
final ArrayList<String> foundJdks = new ArrayList<String>();
final Sdk[] allJdks = ProjectJdkTable.getInstance().getAllJdks();
for (Sdk jdk : allJdks) {
foundJdks.add(jdk.getHomePath());
}
myFieldWithHistory.setHistory(foundJdks);
myPathField = new ComponentWithBrowseButton<TextFieldWithHistory>(myFieldWithHistory, null);
myPathField.addBrowseFolderListener(ExecutionBundle.message("run.configuration.select.alternate.jre.label"),
ExecutionBundle.message("run.configuration.select.jre.dir.label"),
null, BrowseFilesListener.SINGLE_DIRECTORY_DESCRIPTOR, TextComponentAccessor.TEXT_FIELD_WITH_HISTORY_WHOLE_TEXT);
gc.insets.left = 20;
add(myPathField, gc);
InsertPathAction.addTo(myFieldWithHistory.getTextEditor());
gc.weighty = 1;
add(Box.createVerticalBox(), gc);
myCbEnabled.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
enabledChanged();
}
});
enabledChanged();
}
private void enabledChanged() {
final boolean pathEnabled = isPathEnabled();
GuiUtils.enableChildren(myPathField, pathEnabled);
myFieldWithHistory.invalidate(); //need to revalidate inner component
}
public String getPath() {
return FileUtil.toSystemIndependentName(myPathField.getChildComponent().getText().trim());
}
private void setPath(final String path) {
myPathField.getChildComponent().setText(FileUtil.toSystemDependentName(path == null ? "" : path));
}
public boolean isPathEnabled() {
return myCbEnabled.isSelected();
}
private void setPathEnabled(boolean b) {
myCbEnabled.setSelected(b);
enabledChanged();
}
public void init(String path, boolean isEnabled){
setPathEnabled(isEnabled);
setPath(path);
}
}
@@ -0,0 +1,40 @@
<?xml version="1.0" encoding="UTF-8"?>
<form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="com.intellij.execution.ui.ConfigurationArgumentsHelpArea">
<grid id="f0e0b" binding="myPanel" layout-manager="GridBagLayout">
<constraints>
<xy x="47" y="46" width="482" height="239"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<component id="25a8e" class="javax.swing.JLabel" binding="myLabel">
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
<gridbag weightx="1.0" weighty="0.0"/>
</constraints>
<properties>
<labelFor value="9e177"/>
<text resource-bundle="messages/ExecutionBundle" key="environment.variables.helper.use.arguments.label"/>
</properties>
</component>
<scrollpane id="f35c0">
<constraints>
<grid row="1" column="0" row-span="1" col-span="1" vsize-policy="7" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
<gridbag weightx="1.0" weighty="1.0"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<component id="9e177" class="javax.swing.JTextArea" binding="myHelpArea">
<constraints/>
<properties>
<editable value="false"/>
<lineWrap value="true"/>
<wrapStyleWord value="true"/>
</properties>
</component>
</children>
</scrollpane>
</children>
</grid>
</form>
@@ -0,0 +1,75 @@
/*
* Copyright (c) 2000-2004 by JetBrains s.r.o. All Rights Reserved.
* Use is subject to license terms.
*/
package com.intellij.execution.ui;
import com.intellij.execution.ExecutionBundle;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.ide.CopyPasteManager;
import com.intellij.openapi.project.Project;
import com.intellij.ui.PopupHandler;
import com.intellij.util.ui.EmptyClipboardOwner;
import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
public class ConfigurationArgumentsHelpArea extends JPanel {
private JTextArea myHelpArea;
private JPanel myPanel;
private JLabel myLabel;
public ConfigurationArgumentsHelpArea() {
super(new BorderLayout());
myHelpArea.addMouseListener(
new PopupHandler(){
public void invokePopup(final Component comp,final int x,final int y){
createPopupMenu().getComponent().show(comp,x,y);
}
}
);
add(myPanel);
}
private ActionPopupMenu createPopupMenu() {
final DefaultActionGroup group = new DefaultActionGroup();
group.add(new MyCopyAction());
return ActionManager.getInstance().createActionPopupMenu(ActionPlaces.UNKNOWN,group);
}
public void updateText(final String text) {
myHelpArea.setText(text);
}
public void setLabelText(final String text) {
myLabel.setText(text);
}
public String getLabelText() {
return myLabel.getText();
}
private class MyCopyAction extends AnAction {
public MyCopyAction() {
super(ExecutionBundle.message("run.configuration.arguments.help.panel.copy.action.name"));
}
public void actionPerformed(final AnActionEvent e) {
try {
final StringSelection contents = new StringSelection(myHelpArea.getText().trim());
final Project project = PlatformDataKeys.PROJECT.getData(e.getDataContext());
if (project == null) {
final Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(contents, EmptyClipboardOwner.INSTANCE);
} else {
CopyPasteManager.getInstance().setContents(contents);
}
} catch(Exception ex) {
}
}
}
}
@@ -0,0 +1,126 @@
package com.intellij.execution.util;
import com.intellij.execution.CantRunException;
import com.intellij.execution.JavaExecutionUtil;
import com.intellij.execution.RunJavaConfiguration;
import com.intellij.execution.configurations.JavaParameters;
import com.intellij.execution.configurations.ModuleBasedConfiguration;
import com.intellij.execution.configurations.RunConfigurationModule;
import com.intellij.execution.junit.JUnitUtil;
import com.intellij.openapi.components.PathMacroManager;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.JavaSdk;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.projectRoots.ex.PathUtilEx;
import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiFile;
import com.intellij.util.PathUtil;
import java.util.HashMap;
import java.util.Map;
/**
* User: lex
* Date: Nov 26, 2003
* Time: 10:38:01 PM
*/
public class JavaParametersUtil {
public static void configureConfiguration(final JavaParameters parameters, final RunJavaConfiguration configuration) {
final Project project = configuration.getProject();
parameters.getProgramParametersList().addParametersString(configuration.getProperty(RunJavaConfiguration.PROGRAM_PARAMETERS_PROPERTY));
Module module = null;
if (configuration instanceof ModuleBasedConfiguration) {
module = ((ModuleBasedConfiguration)configuration).getConfigurationModule().getModule();
}
String vmParameters = configuration.getProperty(RunJavaConfiguration.VM_PARAMETERS_PROPERTY);
if (vmParameters != null) {
vmParameters = expandPath(vmParameters, module, project);
}
if (parameters.getEnv() != null) {
final Map<String, String> envs = new HashMap<String, String>();
for (String env : parameters.getEnv().keySet()) {
final String value = expandPath(parameters.getEnv().get(env), module, project);
envs.put(env, value);
if (vmParameters != null) {
vmParameters = StringUtil.replace(vmParameters, "$" + env + "$", value, false); //replace env usages
}
}
parameters.setEnv(envs);
}
parameters.getVMParametersList().addParametersString(vmParameters);
String workingDirectory = configuration.getProperty(RunJavaConfiguration.WORKING_DIRECTORY_PROPERTY);
if (workingDirectory == null || workingDirectory.trim().length() == 0) {
workingDirectory = PathUtil.getLocalPath(project.getBaseDir());
}
parameters.setWorkingDirectory(expandPath(workingDirectory, module, project));
}
private static String expandPath(String path, Module module, Project project) {
path = PathMacroManager.getInstance(project).expandPath(path);
if (module != null) {
path = PathMacroManager.getInstance(module).expandPath(path);
}
return path;
}
public static int getClasspathType(final RunConfigurationModule configurationModule, final String mainClassName,
final boolean classMustHaveSource) throws CantRunException {
final Module module = configurationModule.getModule();
if (module == null) throw CantRunException.noModuleConfigured(configurationModule.getModuleName());
final PsiClass psiClass = JavaExecutionUtil.findMainClass(module, mainClassName);
if (psiClass == null) {
if ( ! classMustHaveSource ) return JavaParameters.JDK_AND_CLASSES_AND_TESTS;
throw CantRunException.classNotFound(mainClassName, module);
}
final PsiFile psiFile = psiClass.getContainingFile();
if (psiFile == null) throw CantRunException.classNotFound(mainClassName, module);
final VirtualFile virtualFile = psiFile.getVirtualFile();
if (virtualFile == null) throw CantRunException.classNotFound(mainClassName, module);
Module classModule = new JUnitUtil.ModuleOfClass().convert(psiClass);
if (classModule == null) classModule = module;
return ModuleRootManager.getInstance(classModule).getFileIndex().
isInTestSourceContent(virtualFile) ? JavaParameters.JDK_AND_CLASSES_AND_TESTS : JavaParameters.JDK_AND_CLASSES;
}
public static void configureModule(final RunConfigurationModule runConfigurationModule,
final JavaParameters parameters,
final int classPathType,
final String jreHome) throws CantRunException {
Module module = runConfigurationModule.getModule();
if (module == null) {
throw CantRunException.noModuleConfigured(runConfigurationModule.getModuleName());
}
parameters.configureByModule(module, classPathType, createModuleJdk(module, jreHome));
}
public static void configureProject(Project project, final JavaParameters parameters, final int classPathType, final String jreHome) throws CantRunException {
parameters.configureByProject(project, classPathType, createProjectJdk(project, jreHome));
}
private static Sdk createModuleJdk(final Module module, final String jreHome) throws CantRunException {
return jreHome == null ? JavaParameters.getModuleJdk(module) : createAlternativeJdk(jreHome);
}
private static Sdk createProjectJdk(final Project project, final String jreHome) throws CantRunException {
return jreHome == null ? createProjectJdk(project) : createAlternativeJdk(jreHome);
}
private static Sdk createProjectJdk(final Project project) throws CantRunException {
final Sdk jdk = PathUtilEx.getAnyJdk(project);
if (jdk == null) {
throw CantRunException.noJdkConfigured();
}
return jdk;
}
private static Sdk createAlternativeJdk(final String jreHome) throws CantRunException {
final Sdk jdk = JavaSdk.getInstance().createJdk("", jreHome);
if (jdk == null) throw CantRunException.noJdkConfigured();
return jdk;
}
}
@@ -0,0 +1,50 @@
/*
* Created by IntelliJ IDEA.
* User: yole
* Date: 03.08.2006
* Time: 14:01:20
*/
package com.intellij.execution.util;
import com.intellij.execution.RunJavaConfiguration;
import com.intellij.execution.configurations.ModuleBasedConfiguration;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.projectRoots.impl.JavaSdkImpl;
import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.roots.ProjectRootManager;
public class JreVersionDetector {
private String myLastAlternativeJrePath = null; //awful hack
private boolean myLastIsJre50;
public <T extends ModuleBasedConfiguration & RunJavaConfiguration> boolean isJre50Configured(final T configuration) {
if (configuration.isAlternativeJrePathEnabled()) {
if (configuration.getAlternativeJrePath().equals(myLastAlternativeJrePath)) return myLastIsJre50;
myLastAlternativeJrePath = configuration.getAlternativeJrePath();
final String versionString = JavaSdkImpl.getJdkVersion(myLastAlternativeJrePath);
myLastIsJre50 = versionString != null && isJre50(versionString);
return myLastIsJre50;
} else {
final Module module = configuration.getConfigurationModule().getModule();
if (module != null && !module.isDisposed()) {
final ModuleRootManager rootManager = ModuleRootManager.getInstance(module);
final Sdk jdk = rootManager.getSdk();
return isJre50(jdk);
}
final Sdk projectJdk = ProjectRootManager.getInstance(configuration.getProject()).getProjectJdk();
return isJre50(projectJdk);
}
}
private static boolean isJre50(final Sdk jdk) {
if (jdk == null) return false;
final String versionString = jdk.getVersionString();
return versionString != null && isJre50(versionString);
}
private static boolean isJre50(final String versionString) {
return versionString.contains("5.0") || versionString.contains("1.5") || versionString.contains("1.6");
}
}