sdedic commented on a change in pull request #3350:
URL: https://github.com/apache/netbeans/pull/3350#discussion_r762927856



##########
File path: 
groovy/groovy.support/src/org/netbeans/modules/groovy/support/actions/singlefilerun/SingleGroovySourceRunActionProvider.java
##########
@@ -0,0 +1,168 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.
+ */
+package org.netbeans.modules.groovy.support.actions.singlefilerun;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.Callable;
+import org.netbeans.api.extexecution.ExecutionDescriptor;
+import org.netbeans.api.extexecution.ExecutionService;
+import org.netbeans.api.java.platform.JavaPlatformManager;
+import org.netbeans.api.project.FileOwnerQuery;
+import org.netbeans.api.project.Project;
+import org.netbeans.spi.project.ActionProgress;
+import org.netbeans.spi.project.ActionProvider;
+import org.openide.filesystems.FileObject;
+import org.openide.filesystems.FileUtil;
+import org.openide.loaders.DataObject;
+import org.openide.modules.InstalledFileLocator;
+import org.openide.util.Lookup;
+import org.openide.util.NbBundle;
+import org.openide.util.lookup.ServiceProvider;
+import org.openide.windows.IOProvider;
+import org.openide.windows.InputOutput;
+
+/**
+ * This implementation provides support to run a single Groovy file without
+ * a parent  project. 
+ * 
+ * @author Petr Pisl
+ */
+@ServiceProvider(service = ActionProvider.class)
+public class SingleGroovySourceRunActionProvider implements ActionProvider {
+
+    private static final String GROOVY_EXTENSION = "groovy";  //NOI18N
+    
+    @Override
+    public String[] getSupportedActions() {
+        return new String[]{
+            ActionProvider.COMMAND_RUN_SINGLE,
+            ActionProvider.COMMAND_DEBUG_SINGLE
+        };
+    }
+
+    @NbBundle.Messages({
+        "CTL_SingleGroovyFile=Running Single Groovy File"
+    })
+    @Override
+    public void invokeAction(String command, Lookup context) throws 
IllegalArgumentException {
+        FileObject fileObject = getGroovyFile(context);
+        if (!isSingleSourceFile(fileObject)) {
+            return;

Review comment:
       Maybe use StatusDisplayer to inform the user that the action has failed 
bcs the file is not single-executable ?

##########
File path: 
groovy/groovy.support/src/org/netbeans/modules/groovy/support/actions/singlefilerun/SingleGroovySourceRunActionProvider.java
##########
@@ -0,0 +1,168 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.
+ */
+package org.netbeans.modules.groovy.support.actions.singlefilerun;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.Callable;
+import org.netbeans.api.extexecution.ExecutionDescriptor;
+import org.netbeans.api.extexecution.ExecutionService;
+import org.netbeans.api.java.platform.JavaPlatformManager;
+import org.netbeans.api.project.FileOwnerQuery;
+import org.netbeans.api.project.Project;
+import org.netbeans.spi.project.ActionProgress;
+import org.netbeans.spi.project.ActionProvider;
+import org.openide.filesystems.FileObject;
+import org.openide.filesystems.FileUtil;
+import org.openide.loaders.DataObject;
+import org.openide.modules.InstalledFileLocator;
+import org.openide.util.Lookup;
+import org.openide.util.NbBundle;
+import org.openide.util.lookup.ServiceProvider;
+import org.openide.windows.IOProvider;
+import org.openide.windows.InputOutput;
+
+/**
+ * This implementation provides support to run a single Groovy file without
+ * a parent  project. 
+ * 
+ * @author Petr Pisl
+ */
+@ServiceProvider(service = ActionProvider.class)
+public class SingleGroovySourceRunActionProvider implements ActionProvider {
+
+    private static final String GROOVY_EXTENSION = "groovy";  //NOI18N
+    
+    @Override
+    public String[] getSupportedActions() {
+        return new String[]{
+            ActionProvider.COMMAND_RUN_SINGLE,
+            ActionProvider.COMMAND_DEBUG_SINGLE
+        };
+    }
+
+    @NbBundle.Messages({
+        "CTL_SingleGroovyFile=Running Single Groovy File"
+    })
+    @Override
+    public void invokeAction(String command, Lookup context) throws 
IllegalArgumentException {
+        FileObject fileObject = getGroovyFile(context);
+        if (!isSingleSourceFile(fileObject)) {
+            return;
+        }
+        InputOutput io = 
IOProvider.getDefault().getIO(Bundle.CTL_SingleGroovyFile(), false);
+        ActionProgress progress = ActionProgress.start(context);
+        ExecutionDescriptor descriptor = new ExecutionDescriptor().
+                controllable(true).
+                frontWindow(true).
+                preExecution(null).
+                inputOutput(io).
+                postExecution((exitCode) -> {
+                    progress.finished(exitCode == 0);
+                });
+        JPDAStart jpdaStart = 
ActionProvider.COMMAND_DEBUG_SINGLE.equals(command) ?
+                new JPDAStart(io, fileObject) : null;
+        LaunchProcess process = new LaunchProcess(fileObject, jpdaStart);
+        ExecutionService exeService = ExecutionService.newService(
+                process,
+                descriptor, Bundle.CTL_SingleGroovyFile());
+        exeService.run();
+    }
+
+    @Override
+    public boolean isActionEnabled(String command, Lookup context) throws 
IllegalArgumentException {
+        return isSingleSourceFile(getGroovyFile(context));
+    }
+
+    static private boolean isSingleSourceFile(FileObject fileObject) {
+        if (fileObject == null) {
+            return false;
+        }
+        Project p = FileOwnerQuery.getOwner(fileObject);
+        return p == null;
+    }
+    
+    static private FileObject getGroovyFile(Lookup lookup) {
+        for (DataObject dObj : lookup.lookupAll(DataObject.class)) {
+            FileObject fObj = dObj.getPrimaryFile();
+            if (GROOVY_EXTENSION.equals(fObj.getExt().toLowerCase())) {
+                return fObj;
+            }
+        }
+        for (FileObject fObj : lookup.lookupAll(FileObject.class)) {
+            if (GROOVY_EXTENSION.equals(fObj.getExt().toLowerCase())) {
+                return fObj;
+            }
+        }
+        return null;
+    }
+
+    private static class LaunchProcess implements Callable<Process> {
+
+        private final FileObject fileObject;
+        private final JPDAStart startDebug;
+
+        public LaunchProcess(FileObject file, JPDAStart startDebug) {
+            this.fileObject = file;
+            this.startDebug = startDebug;
+        }
+
+        @Override
+        public Process call() throws Exception {
+            if (startDebug != null) {
+                return setupProcess(startDebug.execute());
+            }
+            return setupProcess(null);
+        }
+
+        private Process setupProcess(String port) throws InterruptedException {
+            List<String> commandList = new ArrayList<>();
+            FileObject java = 
JavaPlatformManager.getDefault().getDefaultPlatform().findTool("java"); //NOI18N
+            File groovyJar = 
InstalledFileLocator.getDefault().locate("modules/org-netbeans-modules-libs-groovy.jar",
 null, false); //NOI18N
+
+            // the command should be like java -cp .:paht_to_groovy_jars 
groovy.ui.GroovyMain  path_to_script"
+            commandList.add(FileUtil.toFile(java).getAbsolutePath()); // NOI18N
+            
+            if (port != null) {
+                commandList.add("-agentlib:jdwp=transport=dt_socket,address=" 
+ port + ",server=n"); //NOI18N
+            }
+            commandList.add("-cp"); // NOI18N
+            // TODO can we add here some heuristic, from which folder and 
appropriate path the script can be run?
+            // For example we can look for the `src` or `src/groovy` fodler, 
from which the script can be probably run. 
+            commandList.add(".:" + groovyJar.getAbsolutePath());    //NOI18N

Review comment:
       Use OS-specific path separator

##########
File path: 
groovy/groovy.support/src/org/netbeans/modules/groovy/support/actions/singlefilerun/JPDAStart.java
##########
@@ -0,0 +1,145 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.
+ */
+package org.netbeans.modules.groovy.support.actions.singlefilerun;
+
+import com.sun.jdi.Bootstrap;
+import com.sun.jdi.connect.Connector;
+import com.sun.jdi.connect.ListeningConnector;
+import com.sun.jdi.connect.Transport;
+import java.io.File;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+import org.netbeans.api.debugger.jpda.DebuggerStartException;
+import org.netbeans.api.debugger.jpda.JPDADebugger;
+import org.netbeans.api.java.classpath.ClassPath;
+import org.netbeans.spi.java.classpath.support.ClassPathSupport;
+import org.openide.filesystems.FileObject;
+import org.openide.filesystems.FileUtil;
+import org.openide.util.RequestProcessor;
+import org.openide.windows.InputOutput;
+
+// This class is copy of 
org.netbeans.modules.java.api.common.singlesourcefile.JPDAStart
+/**
+ * Start the JPDA debugger.
+ *
+ * @author Arunava Sinha
+ */
+public class JPDAStart implements Runnable {
+
+    static final Logger LOG = 
Logger.getLogger(JPDAStart.class.getPackage().getName());
+    
+    private static final RequestProcessor RP = new 
RequestProcessor(JPDAStart.class);
+    private static final String TRANSPORT = "dt_socket"; //NOI18N
+
+    private final Object[] lock = new Object[2];
+    private final InputOutput io;
+    private final FileObject fileObject;
+
+    JPDAStart(InputOutput inputOutput, FileObject fileObject) {
+        io = inputOutput;
+        this.fileObject = fileObject;
+    }
+
+    /**
+     * returns the port that the debugger listens to..
+     */
+    public String execute() throws Exception {
+        LOG.log(Level.INFO, "JPDA Listening Start"); //NOI18N
+        synchronized (lock) {
+            RP.post(this);
+            lock.wait();
+            if (lock[1] != null) {
+                throw ((Exception) lock[1]); //NOI18N
+            }
+        }
+        return (String) lock[0];
+    }
+
+    @Override
+    public void run() {
+        synchronized (lock) {
+
+            try {
+
+                ListeningConnector lc = null;
+                Iterator i = Bootstrap.virtualMachineManager().
+                        listeningConnectors().iterator();
+                for (; i.hasNext();) {
+                    lc = (ListeningConnector) i.next();
+                    Transport t = lc.transport();
+                    if (t != null && t.name().equals(getTransport())) {
+                        break;
+                    }
+                }
+                if (lc == null) {
+                    throw new RuntimeException("No trasports named " + 
getTransport() + " found!"); //NOI18N
+                }
+
+                final Map args = lc.defaultArguments();
+                String address = lc.startListening(args);
+                try {
+                    int port = 
Integer.parseInt(address.substring(address.indexOf(':') + 1));
+                    Connector.IntegerArgument portArg = 
(Connector.IntegerArgument) args.get("port"); //NOI18N
+                    portArg.setValue(port);
+                    lock[0] = Integer.toString(port);
+                } catch (NumberFormatException e) {
+                    lock[0] = address;
+                }
+                LOG.log(Level.INFO, "Debug Port:{0}", lock[0]);  //NOI18N
+
+                final Map properties = new HashMap();
+
+                ClassPath sourcePath = 
ClassPathSupport.createClassPath(fileObject.getParent());
+                ClassPath jdkPath = 
ClassPathSupport.createClassPath(System.getProperty("java.class.path"));

Review comment:
       .... hm, the `jdkPath` local seems to be unused anyway ?

##########
File path: 
groovy/groovy.support/src/org/netbeans/modules/groovy/support/actions/singlefilerun/SingleGroovySourceRunActionProvider.java
##########
@@ -0,0 +1,168 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.
+ */
+package org.netbeans.modules.groovy.support.actions.singlefilerun;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.Callable;
+import org.netbeans.api.extexecution.ExecutionDescriptor;
+import org.netbeans.api.extexecution.ExecutionService;
+import org.netbeans.api.java.platform.JavaPlatformManager;
+import org.netbeans.api.project.FileOwnerQuery;
+import org.netbeans.api.project.Project;
+import org.netbeans.spi.project.ActionProgress;
+import org.netbeans.spi.project.ActionProvider;
+import org.openide.filesystems.FileObject;
+import org.openide.filesystems.FileUtil;
+import org.openide.loaders.DataObject;
+import org.openide.modules.InstalledFileLocator;
+import org.openide.util.Lookup;
+import org.openide.util.NbBundle;
+import org.openide.util.lookup.ServiceProvider;
+import org.openide.windows.IOProvider;
+import org.openide.windows.InputOutput;
+
+/**
+ * This implementation provides support to run a single Groovy file without
+ * a parent  project. 
+ * 
+ * @author Petr Pisl
+ */
+@ServiceProvider(service = ActionProvider.class)
+public class SingleGroovySourceRunActionProvider implements ActionProvider {
+
+    private static final String GROOVY_EXTENSION = "groovy";  //NOI18N
+    
+    @Override
+    public String[] getSupportedActions() {
+        return new String[]{
+            ActionProvider.COMMAND_RUN_SINGLE,
+            ActionProvider.COMMAND_DEBUG_SINGLE
+        };
+    }
+
+    @NbBundle.Messages({
+        "CTL_SingleGroovyFile=Running Single Groovy File"
+    })
+    @Override
+    public void invokeAction(String command, Lookup context) throws 
IllegalArgumentException {
+        FileObject fileObject = getGroovyFile(context);
+        if (!isSingleSourceFile(fileObject)) {
+            return;
+        }
+        InputOutput io = 
IOProvider.getDefault().getIO(Bundle.CTL_SingleGroovyFile(), false);
+        ActionProgress progress = ActionProgress.start(context);
+        ExecutionDescriptor descriptor = new ExecutionDescriptor().
+                controllable(true).
+                frontWindow(true).
+                preExecution(null).
+                inputOutput(io).
+                postExecution((exitCode) -> {
+                    progress.finished(exitCode == 0);
+                });
+        JPDAStart jpdaStart = 
ActionProvider.COMMAND_DEBUG_SINGLE.equals(command) ?
+                new JPDAStart(io, fileObject) : null;
+        LaunchProcess process = new LaunchProcess(fileObject, jpdaStart);
+        ExecutionService exeService = ExecutionService.newService(
+                process,
+                descriptor, Bundle.CTL_SingleGroovyFile());
+        exeService.run();
+    }
+
+    @Override
+    public boolean isActionEnabled(String command, Lookup context) throws 
IllegalArgumentException {
+        return isSingleSourceFile(getGroovyFile(context));
+    }
+
+    static private boolean isSingleSourceFile(FileObject fileObject) {
+        if (fileObject == null) {
+            return false;
+        }
+        Project p = FileOwnerQuery.getOwner(fileObject);
+        return p == null;
+    }
+    
+    static private FileObject getGroovyFile(Lookup lookup) {
+        for (DataObject dObj : lookup.lookupAll(DataObject.class)) {
+            FileObject fObj = dObj.getPrimaryFile();
+            if (GROOVY_EXTENSION.equals(fObj.getExt().toLowerCase())) {
+                return fObj;
+            }
+        }
+        for (FileObject fObj : lookup.lookupAll(FileObject.class)) {
+            if (GROOVY_EXTENSION.equals(fObj.getExt().toLowerCase())) {
+                return fObj;
+            }
+        }
+        return null;
+    }
+
+    private static class LaunchProcess implements Callable<Process> {
+
+        private final FileObject fileObject;
+        private final JPDAStart startDebug;
+
+        public LaunchProcess(FileObject file, JPDAStart startDebug) {
+            this.fileObject = file;
+            this.startDebug = startDebug;
+        }
+
+        @Override
+        public Process call() throws Exception {
+            if (startDebug != null) {
+                return setupProcess(startDebug.execute());
+            }
+            return setupProcess(null);
+        }
+
+        private Process setupProcess(String port) throws InterruptedException {
+            List<String> commandList = new ArrayList<>();
+            FileObject java = 
JavaPlatformManager.getDefault().getDefaultPlatform().findTool("java"); //NOI18N
+            File groovyJar = 
InstalledFileLocator.getDefault().locate("modules/org-netbeans-modules-libs-groovy.jar",
 null, false); //NOI18N
+
+            // the command should be like java -cp .:paht_to_groovy_jars 
groovy.ui.GroovyMain  path_to_script"
+            commandList.add(FileUtil.toFile(java).getAbsolutePath()); // NOI18N
+            
+            if (port != null) {
+                commandList.add("-agentlib:jdwp=transport=dt_socket,address=" 
+ port + ",server=n"); //NOI18N
+            }
+            commandList.add("-cp"); // NOI18N
+            // TODO can we add here some heuristic, from which folder and 
appropriate path the script can be run?
+            // For example we can look for the `src` or `src/groovy` fodler, 
from which the script can be probably run. 
+            commandList.add(".:" + groovyJar.getAbsolutePath());    //NOI18N
+
+            commandList.add("groovy.ui.GroovyMain");    //NOI18N
+            commandList.add(fileObject.getNameExt());
+            ProcessBuilder pb = new ProcessBuilder(commandList);
+            
pb.directory(FileUtil.toFile(fileObject.getParent())).redirectErrorStream(true)
+                    .redirectOutput();
+            try {
+                return pb.start();
+            } catch (IOException ex) {
+                System.out.println("Could not get InputStream of Run Process");

Review comment:
       Use a logger ?




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]



---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

For further information about the NetBeans mailing lists, visit:
https://cwiki.apache.org/confluence/display/NETBEANS/Mailing+lists

Reply via email to