Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
   *
   * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
   *
   * The contents of this file are subject to the terms of either the GNU
   * General Public License Version 2 only ("GPL") or the Common
   * Development and Distribution License("CDDL") (collectively, the
   * "License"). You may not use this file except in compliance with the
  * License. You can obtain a copy of the License at
  * http://www.netbeans.org/cddl-gplv2.html
  * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
  * specific language governing permissions and limitations under the
  * License.  When distributing the software, include this License Header
  * Notice in each file and include the License file at
  * nbbuild/licenses/CDDL-GPL-2-CP.  Sun designates this
  * particular file as subject to the "Classpath" exception as provided
  * by Sun in the GPL Version 2 section of the License file that
  * accompanied this code. If applicable, add the following below the
  * License Header, with the fields enclosed by brackets [] replaced by
  * your own identifying information:
  * "Portions Copyrighted [year] [name of copyright owner]"
  *
  * Contributor(s):
  *
  * The Original Software is NetBeans. The Initial Developer of the Original
  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun
  * Microsystems, Inc. All Rights Reserved.
  *
  * If you wish your version of this file to be governed by only the CDDL
  * or only the GPL Version 2, indicate your decision by adding
  * "[Contributor] elects to include this software in this distribution
  * under the [CDDL or GPL Version 2] license." If you do not indicate a
  * single choice of license, a recipient has the option to distribute
  * your version of this file under either the CDDL, the GPL Version 2 or
  * to extend the choice of license to its licensees as provided above.
  * However, if you add GPL Version 2 code and therefore, elected the GPL
  * Version 2 license, then the option applies only if the new code is
  * made subject to such option by the copyright holder.
  */
 package org.netbeans.modules.cnd.makeproject.api;
 
 import java.io.File;
 import java.util.List;
Most of the code here came from DefaultProjectActionHandler as result of refactoring.
 
 public class ProjectActionSupport {
 
     private static ProjectActionSupport instance;
 
     private ProjectActionSupport() {
                 Lookup.getDefault().lookupAll(ProjectActionHandlerFactory.class));
     }

    
Singleton pattern: instance getter.

Returns:
singleton instance
    public static synchronized ProjectActionSupport getInstance() {
        if ( == null) {
             = new ProjectActionSupport();
        }
        return ;
    }

    
Checks if given action type can be handled. All registered handler factories are asked.

Parameters:
conf
type
Returns:
    public boolean canHandle(MakeConfiguration confProjectActionEvent.Type type) {
        if (conf != null) {
            DebuggerChooserConfiguration chooser = conf.getDebuggerChooserConfiguration();
            CustomizerNode node = chooser.getNode();
            if (node instanceof ProjectActionHandlerFactory) {
                if (((ProjectActionHandlerFactorynode).canHandle(typeconf)) {
                    return true;
                }
            }
        }
        for (ProjectActionHandlerFactory factory : ) {
            if (factory.canHandle(typeconf)) {
                return true;
            }
        }
        return false;
    }

    
Executes an array of project actions asynchronously.

Parameters:
paes project actions
    public void fireActionPerformed(ProjectActionEvent[] paes) {
        new HandleEvents(paesnull).go();
    }
    public void fireActionPerformed(ProjectActionEvent[] paesProjectActionHandler preferredHandler) {
        new HandleEvents(paespreferredHandler).go();
    }
////////////////////////////////////////////////////////////////////////////////
    private InputOutput mainTab = null;
    private HandleEvents mainTabHandler = null;
    private ArrayList<StringtabNames = new ArrayList<String>();
    private class HandleEvents implements ExecutionListener {
        private InputOutput ioTab = null;
        private ProjectActionEvent[] paes;
        private String tabName;
        private String tabNameSeq;
        int currentAction = 0;
        private StopAction sa = null;
        private RerunAction ra = null;
        List<BuildActionadditional;
        private ProgressHandle progressHandle = null;
        private final Object lock = new Object();
        private ProjectActionHandler customHandler = null;
        private ProjectActionHandler currentHandler = null;
        public HandleEvents(ProjectActionEvent[] paesProjectActionHandler customHandler) {
            this. = paes;
            this. = customHandler;
             = 0;
            if (MakeOptions.getInstance().getReuse()) {
                synchronized () {
                    if ( == null &&  != null /*&& !mainTab.isClosed()*/) {
                        .closeInputOutput();
                         = null;
                    }
                     = getTabName(paes);
                     = ;
                    if (.contains()) {
                        int seq = 2;
                        while (true) {
                             =  + " #" + seq// NOI18N
                            if (!.contains()) {
                                break;
                            }
                            seq++;
                        }
                    }
                    .add();
                     = getIOTab(true);
                    if ( == null) {
                         = ;
                         = this;
                    }
                }
            } else {
                 = getTabName(paes);
                 = ;
                 = getIOTab(false);
            }
        }
        private String getTabName(ProjectActionEvent[] paes) {
            String projectName = ProjectUtils.getInformation(paes[0].getProject()).getDisplayName();
            StringBuilder name = new StringBuilder(projectName);
            name.append(" ("); // NOI18N
            for (int i = 0; i < paes.lengthi++) {
                if (i >= 2) {
                    name.append("..."); // NOI18N
                    break;
                }
                name.append(paes[i].getActionName());
                if (i < paes.length - 1) {
                    name.append(", "); // NOI18N
                }
            }
            name.append(")"); // NOI18N
            if (paes.length > 0) {
                MakeConfiguration conf = paes[0].getConfiguration();
                if (!conf.getDevelopmentHost().isLocalhost()) {
                    String hkey = conf.getDevelopmentHost().getHostKey();
                    name.append(" - ").append(hkey); //NOI18N
                }
            }
            return name.toString();
        }
        private InputOutput getTab() {
            return ;
        }
        private ProgressHandle createProgressHandle() {
            ProgressHandle handle = ProgressHandleFactory.createHandle(new Cancellable() {
                public boolean cancel() {
                    .actionPerformed(null);
                    return true;
                }
            }, new AbstractAction() {
                public void actionPerformed(ActionEvent e) {
                    getTab().select();
                }
            });
            handle.setInitialDelay(0);
            return handle;
        }
        private ProgressHandle createProgressHandleNoCancel() {
            ProgressHandle handle = ProgressHandleFactory.createHandle(,
                    new AbstractAction() {
                        public void actionPerformed(ActionEvent e) {
                            getTab().select();
                        }
                    });
            handle.setInitialDelay(0);
            return handle;
        }
        private InputOutput getIOTab(String nameboolean reuse) {
             = new StopAction(this);
             = new RerunAction(this);
            List<Actionlist = new ArrayList<Action>();
            list.add();
            list.add();
             = BuildActionsProvider.getDefault().getActions(name);
            list.addAll();
            InputOutput tab;
            if (reuse) {
                tab = IOProvider.getDefault().getIO(namefalse); // This will (sometimes!) find an existing one.
                tab.closeInputOutput(); // Close it...
            }
            tab = IOProvider.getDefault().getIO(namelist.toArray(new Action[list.size()])); // Create a new ...
            try {
                tab.getOut().reset();
            } catch (IOException ioe) {
            }
             = createProgressHandle();
            .start();
            return tab;
        }
        private void reRun() {
             = 0;
            getTab().closeInputOutput();
            synchronized () {
                .add();
            }
            try {
                getTab().getOut().reset();
            } catch (IOException ioe) {
            }
             = createProgressHandle();
            .start();
            go();
        }
        private void go() {
             = null;
            .setEnabled(false);
            .setEnabled(false);
            if ( >= .) {
                return;
            }
            final ProjectActionEvent pae = [];
            // Validate executable
            switch (pae.getType()) {
                case :
                case :
                case :
                case :
                case :
                case :
                if (!checkExecutable(pae) || pae.getType() == ..) {
                    .finish();
                    return;
                }
            }
            if (pae.getType() == .. &&  != null) {
                initHandler(pae);
                .execute();
            } else {
                if ( == 0 && !checkRemotePath(pae)) {
                    .finish();
                    return;
                }
                for (ProjectActionHandlerFactory factory : ) {
                    if (factory.canHandle(pae.getType(), pae.getConfiguration())) {
                        ProjectActionHandler handler =  = factory.createHandler();
                        initHandler(handlerpae);
                        handler.execute();
                        break;
                    }
                }
            }
        }
        // moved from DefaultProjectActionHandler.execute
        private boolean checkRemotePath(ProjectActionEvent pae) {
            boolean success = true;
            MakeConfiguration conf = pae.getConfiguration();
            if (!conf.getDevelopmentHost().isLocalhost()) {
                // Make sure the project and 1st level subprojects are visible remotely
                String baseDir = pae.getProfile().getBaseDir();
                ExecutionEnvironment env = conf.getDevelopmentHost().getExecutionEnvironment();
                for (String subprojectDir : conf.getSubProjectLocations()) {
                    subprojectDir = IpeUtils.toAbsolutePath(baseDirsubprojectDir);
                    RemoteSyncWorker syncWorker = ServerList.get(env).getSyncFactory().createNew(new File(subprojectDir), envnullnull);
                    success &= syncWorker.synchronize();
                    if (!success) {
                        break;
                    }
                }
                if (success) {
                    PrintWriter err = null;
                    PrintWriter out = null;
                    InputOutput tab = getTab();
                    if (tab != null) {
                        out = this..getOut();
                        err = this..getErr();
                    }
                    RemoteSyncWorker syncWorker = ServerList.get(env).getSyncFactory().createNew(
                            new File(baseDir), envouterr);
                    success &= syncWorker.synchronize();
                }
            }
            return success;
        }
        private void initHandler(ProjectActionHandler handlerProjectActionEvent pae) {
            handler.init(pae);
            .finish();
             = handler.canCancel()? createProgressHandle() : createProgressHandleNoCancel();
            .start();
            .setEnabled(handler.canCancel());
            handler.addExecutionListener(this);
        }
        public ProjectActionHandler getCurrentHandler() {
            return ;
        }
        public void executionStarted() {
            if ( != null) {
                for (BuildAction action : ) {
                    action.setStep();
                    action.executionStarted();
                }
            }
        }
        public void executionFinished(int rc) {
            if ( != null) {
                for (Action action : ) {
                    ((ExecutionListeneraction).executionFinished(rc);
                }
            }
                // Refresh all files
                try {
                    FileObject projectFileObject = [].getProject().getProjectDirectory();
                    projectFileObject.getFileSystem().refresh(false);
                    MakeLogicalViewProvider.refreshBrokenItems([].getProject());
                } catch (Exception e) {
                }
            }
            if ( >= . - 1 || rc != 0) {
                synchronized () {
                    if ( == this) {
                         = null;
                    }
                    .remove();
                }
                .setEnabled(false);
                .setEnabled(true);
                .finish();
                return;
            }
            // This code is executed in finishing ProjectActionHandler's thread.
            // Starting next handler in this thread may lead to problems, such as
            // new threads being created in old handler's thread group, and NetBeans
            // thinking that old handler has not completed.
            // So the call to go() is posted to RequestProcessor.
            if (rc == 0) {
                ++;
                RequestProcessor.getDefault().post(new Runnable() {
                    public void run() {
                        go();
                    }
                });
            }
        }
        private boolean checkExecutable(ProjectActionEvent pae) {
            // Check if something is specified
            String executable = pae.getExecutable();
            if (executable.length() == 0) {
                SelectExecutablePanel panel = new SelectExecutablePanel(pae.getConfiguration());
                DialogDescriptor descriptor = new DialogDescriptor(panelgetString("SELECT_EXECUTABLE"));
                panel.setDialogDescriptor(descriptor);
                DialogDisplayer.getDefault().notify(descriptor);
                if (descriptor.getValue() == .) {
                    // Set executable in configuration
                    MakeConfiguration makeConfiguration = pae.getConfiguration();
                    executable = panel.getExecutable();
                    executable = FilePathAdaptor.naturalize(executable);
                    executable = IpeUtils.toRelativePath(makeConfiguration.getBaseDir(), executable);
                    executable = FilePathAdaptor.normalize(executable);
                    makeConfiguration.getMakefileConfiguration().getOutput().setValue(executable);
                    // Mark the project 'modified'
                    ConfigurationDescriptorProvider pdp = pae.getProject().getLookup().lookup(ConfigurationDescriptorProvider.class);
                    if (pdp != null) {
                        pdp.getConfigurationDescriptor().setModified();
                    }
                    // Set executable in pae
                    if (pae.getType() == ..) {
                        // Next block is commented out due to IZ120794
                        /*CompilerSet compilerSet = CompilerSetManager.getDefault(makeConfiguration.getDevelopmentHost().getName()).getCompilerSet(makeConfiguration.getCompilerSet().getValue());
                        if (compilerSet != null && compilerSet.getCompilerFlavor() != CompilerFlavor.MinGW) {
                        // IZ 120352
                        executable = FilePathAdaptor.naturalize(executable);
                        }*/
                        pae.setExecutable(executable);
                    } else {
                        pae.setExecutable(makeConfiguration.getMakefileConfiguration().getAbsOutput());
                    }
                } else {
                    return false;
                }
            }
            // Check existence of executable
            if (!IpeUtils.isPathAbsolute(executable) && (executable.startsWith(".") || executable.indexOf(.) > 0)) { // NOI18N
                //executable is relative to run directory - convert to absolute and check. Should be safe (?).
                String runDir = pae.getProfile().getRunDir();
                if (runDir == null || runDir.length() == 0) {
                    executable = IpeUtils.toAbsolutePath(pae.getConfiguration().getBaseDir(), executable);
                } else {
                    runDir = IpeUtils.toAbsolutePath(pae.getConfiguration().getBaseDir(), runDir);
                    executable = IpeUtils.toAbsolutePath(runDirexecutable);
                }
                executable = FilePathAdaptor.normalize(executable);
            }
            if (IpeUtils.isPathAbsolute(executable)) {
                Configuration conf = pae.getConfiguration();
                boolean ok = true;
                if (conf instanceof MakeConfiguration && !((MakeConfigurationconf).getDevelopmentHost().isLocalhost()) {
                    final ExecutionEnvironment execEnv = ((MakeConfigurationconf).getDevelopmentHost().getExecutionEnvironment();
                    PathMap mapper = HostInfoProvider.getMapper(execEnv);
                    executable = mapper.getRemotePath(executable,true);
                    CommandProvider cmd = Lookup.getDefault().lookup(CommandProvider.class);
                    if (cmd != null) {
                        ok = cmd.run(execEnv"test"null"-x"executable"-a""-f"executable) == 0; // NOI18N
                    }
                } else {
                    // FIXUP: getExecutable should really return fully qualified name to executable including .exe
                    // but it is too late to change now. For now try both with and without.
                    File file = new File(executable);
                    if (!file.exists()) {
                        file = new File(executable + ".exe"); // NOI18N
                    }
                    if (!file.exists() || file.isDirectory()) {
                        ok = false;
                    }
                }
                if (!ok) {
                    String errormsg = getString("EXECUTABLE_DOESNT_EXISTS"executable); // NOI18N
                    DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message(errormsg.));
                    return false;
                }
            }
            // Finally set pae.executable to a real, verified file with an absolute
            // path that reflects file location on a target host (local or remote)
            pae.setExecutable(executable);
            
            return true;
        }
    }
// VK: inlined since it's used once; and caller should know not only return status,
// but mapped name as well => it's easier to inline
//    /**
//     * Verify a remote executable exists, is executable, and is not a directory.
//     *
//     * @param execEnv The remote host
//     * @param executable The file to remotely check
//     * @return true if executable exists and is an executable, otherwise false
//     */
//    private static boolean verifyRemoteExecutable(ExecutionEnvironment execEnv, String executable) {
//        PathMap mapper = HostInfoProvider.getMapper(execEnv);
//        String remoteExecutable = mapper.getRemotePath(executable);
//        CommandProvider cmd = Lookup.getDefault().lookup(CommandProvider.class);
//        if (cmd != null) {
//            return cmd.run(execEnv, "test -x " + remoteExecutable + " -a -f " + remoteExecutable, null) == 0; // NOI18N
//        }
//        return false;
//    }
    private static final class StopAction extends AbstractAction {
        HandleEvents handleEvents;
        public StopAction(HandleEvents handleEvents) {
            this. = handleEvents;
        //System.out.println("handleEvents 1 " + handleEvents);
        //setEnabled(false); // initially, until ready
        }
        @Override
        public Object getValue(String key) {
            if (key.equals(.)) {
                return new ImageIcon(DefaultProjectActionHandler.class.getResource("/org/netbeans/modules/cnd/makeproject/ui/resources/stop.png"));
            } else if (key.equals(.)) {
                return getString("TargetExecutor.StopAction.stop");
            } else {
                return super.getValue(key);
            }
        }
        public void actionPerformed(ActionEvent e) {
            if (!isEnabled()) {
                return;
            }
            setEnabled(false);
            if (.getCurrentHandler() != null) {
                .getCurrentHandler().cancel();
            }
        }
    }
    private static final class RerunAction extends AbstractAction {
        HandleEvents handleEvents;
        public RerunAction(HandleEvents handleEvents) {
            this. = handleEvents;
        }
        @Override
        public Object getValue(String key) {
            if (key.equals(.)) {
                return new ImageIcon(DefaultProjectActionHandler.class.getResource("/org/netbeans/modules/cnd/makeproject/ui/resources/rerun.png"));
            } else if (key.equals(.)) {
                return getString("TargetExecutor.RerunAction.rerun");
            } else {
                return super.getValue(key);
            }
        }
        public void actionPerformed(ActionEvent e) {
            setEnabled(false);
            .reRun();
        }
    }

    
Look up i18n strings here
    private static String getString(String s) {
        return NbBundle.getBundle(ProjectActionSupport.class).getString(s);
    }
    private static String getString(String sString arg) {
        return NbBundle.getMessage(ProjectActionSupport.classsarg);
    }
New to GrepCode? Check out our FAQ X