org.netbeans.api.sendopts.CommandException Java Examples

The following examples show how to use org.netbeans.api.sendopts.CommandException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SnapArgsProcessor.java    From snap-desktop with GNU General Public License v3.0 6 votes vote down vote up
private static void processOpen(String[] args) throws CommandException {
    int errorExitCode = 100;

    Path sessionFile = null;
    List<Path> fileList = new ArrayList<>();

    for (String arg : args) {
        Path file = Paths.get(arg);
        if (Files.exists(file)) {
            if (file.toFile() != null && SessionManager.getDefault().getSessionFileFilter().accept(file.toFile())) {
                if (sessionFile != null) {
                    throw new CommandException(errorExitCode, "Only a single SNAP session file can be given.");
                }
                sessionFile = file;
            } else {
                fileList.add(file);
            }
        } else {
            System.err.println("File not found: " + file);
        }
    }

    SnapArgs.getDefault().setSessionFile(sessionFile);
    SnapArgs.getDefault().setFileList(fileList);
}
 
Example #2
Source File: Handler.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Messages("EXC_MissingArgOpen=Missing arguments to --open")
@Override
public void process(Env env) throws CommandException {
    String[] argv = files;
    if (argv == null || argv.length == 0) {
        throw new CommandException(2, EXC_MissingArgOpen());
    }
    
    File curDir = env.getCurrentDirectory ();

    StringBuffer failures = new StringBuffer();
    String sep = "";
    for (int i = 0; i < argv.length; i++) {
        String error = openFile (curDir, env, argv[i]);
        if (error != null) {
            failures.append(sep);
            failures.append(error);
            sep = "\n";
        }
    }
    if (failures.length() > 0) {
        DialogDisplayer.getDefault().notifyLater(new NotifyDescriptor.Message(failures.toString()));
        throw new CommandException(1, failures.toString());
    }
}
 
Example #3
Source File: HandlerImpl.java    From netbeans with Apache License 2.0 6 votes vote down vote up
static int execute(String[] arr, InputStream is, OutputStream os, OutputStream err, File pwd) {
    try {
        CommandLine.getDefault().process(
            arr, is, os, err, pwd
            );
        for (int i = 0; i < arr.length; i++) {
            arr[i] = null;
        }
        return 0;
    } catch (CommandException ex) {
        PrintStream ps = new PrintStream(err);
        ps.println(ex.getLocalizedMessage());
        // XXX pst is not useful, only in verbose mode
        // the question is how to turn that mode on
        // ex.printStackTrace(ps);
        int ret = ex.getExitCode();
        if (ret == 0) {
            ret = Integer.MIN_VALUE;
        }
        return ret;
    }
}
 
Example #4
Source File: ModuleOptions.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@NbBundle.Messages({
    "MSG_NoURL=None extra Update Center (URL) specified."
})
private void extraUC(Env env, String... urls) throws CommandException {
    List<URL> url2UC = new ArrayList<URL> (urls.length);
    for (String spec : urls) {
        try {
            url2UC.add(new URL(spec));
        } catch (MalformedURLException ex) {
            throw initCause(new CommandException(4), ex);
        }
    }
    for (URL url : url2UC) {
        ownUUP.add(UpdateUnitProviderFactory.getDefault().create(Long.toString(System.currentTimeMillis()), url.toExternalForm(), url));
    }
    refresh(env);        
}
 
Example #5
Source File: ModuleOptions.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void changeModuleState(String[] cnbs, boolean enable) throws IOException, CommandException, InterruptedException, OperationException {
    for (String cnb : cnbs) {
        int slash = cnb.indexOf('/');
        if (slash >= 0) {
            cnb = cnb.substring(0, slash);
        }
    }
    
    Set<String> all = new HashSet<String>(Arrays.asList(cnbs));

    List<UpdateUnit> units = UpdateManager.getDefault().getUpdateUnits();
    OperationContainer<OperationSupport> operate = enable ? OperationContainer.createForEnable() : OperationContainer.createForDisable();
    for (UpdateUnit updateUnit : units) {
        if (all.contains(updateUnit.getCodeName())) {
            if (enable) {
                operate.add(updateUnit, updateUnit.getInstalled());
            } else {
                operate.add(updateUnit, updateUnit.getInstalled());
            }
        }
    }
    OperationSupport support = operate.getSupport();
    support.doOperation(null);
}
 
Example #6
Source File: ModuleOptions.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void refresh(Env env) throws CommandException {
    for (UpdateUnitProvider p : UpdateUnitProviderFactory.getDefault().getUpdateUnitProviders(true)) {
        try {
            env.getOutputStream().println("Refreshing " + p.getDisplayName());
            p.refresh(null, true);
        } catch (IOException ex) {
            throw (CommandException)new CommandException(31, ex.getMessage()).initCause(ex);
        }
    }
}
 
Example #7
Source File: ForClassTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testParseAdditionalParam() throws CommandException {
    cmd.process("no", "-m", "Param");
    assertNotNull("Called", methodCalled);
    assertFalse("enabled not set", methodCalled.enabled);
    assertNotNull("additionalParams set", methodCalled.additionalParams);
    assertEquals("two", 2, methodCalled.additionalParams.length);
    assertEquals("no", methodCalled.additionalParams[0]);
    assertEquals("Param", methodCalled.additionalParams[1]);
}
 
Example #8
Source File: ForClassTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testParseLongAdditional() throws CommandException {
    cmd.process("no", "--more", "Param");
    assertNotNull("Called", methodCalled);
    assertFalse("enabled not set", methodCalled.enabled);
    assertNotNull("additionalParams set", methodCalled.additionalParams);
    assertEquals("two", 2, methodCalled.additionalParams.length);
    assertEquals("no", methodCalled.additionalParams[0]);
    assertEquals("Param", methodCalled.additionalParams[1]);
    assertNotNull("environment provided", methodEnv);
}
 
Example #9
Source File: ForClassTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testHelpOnEnv() throws CommandException, UnsupportedEncodingException {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    cmd.process(new String[] { "--tellmehow" }, System.in, os, System.err, null);
    String out = new String(os.toByteArray(), "UTF-8");
    assertTrue("contains additionalParams:\n" + out, out.contains(("MyParams")));
    assertTrue("contains short help:\n" + out, out.contains(("ShorterHelp")));
}
 
Example #10
Source File: OptionTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testParseEnabledWithParamFails() {
    try {
        cmd.process("-e", "Param");
        fail("Parse shall not succeed");
    } catch (CommandException ex) {
        // oK
    }
    assertNull("parse not finished, enabled not set", methodCalled);
}
 
Example #11
Source File: OptionTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testParseWithoutParamFails() throws CommandException {
    try {
        cmd.process("-p");
        fail("Missing param for -p");
    } catch (CommandException ex) {
        // OK
        assertNull("No method called", methodCalled);
    }
}
 
Example #12
Source File: OptionTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testParseAdditionalParam() throws CommandException {
    cmd.process("no", "-a", "Param");
    assertNotNull("Called", methodCalled);
    assertFalse("enabled not set", methodCalled.enabled);
    assertNotNull("additionalParams set", methodCalled.additionalParams);
    assertEquals("two", 2, methodCalled.additionalParams.length);
    assertEquals("no", methodCalled.additionalParams[0]);
    assertEquals("Param", methodCalled.additionalParams[1]);
}
 
Example #13
Source File: OptionTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testParseLongAdditional() throws CommandException {
    cmd.process("no", "--additional", "Param");
    assertNotNull("Called", methodCalled);
    assertFalse("enabled not set", methodCalled.enabled);
    assertNotNull("additionalParams set", methodCalled.additionalParams);
    assertEquals("two", 2, methodCalled.additionalParams.length);
    assertEquals("no", methodCalled.additionalParams[0]);
    assertEquals("Param", methodCalled.additionalParams[1]);
    assertNotNull("environment provided", methodEnv);
}
 
Example #14
Source File: OptionTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testParseImplicit() throws CommandException {
    cmd.process("no", "Param");
    assertNotNull("Called", methodCalled);
    assertFalse("enabled not set", methodCalled.enabled);
    assertNotNull("additionalParams set", methodCalled.additionalParams);
    assertEquals("two", 2, methodCalled.additionalParams.length);
    assertEquals("no", methodCalled.additionalParams[0]);
    assertEquals("Param", methodCalled.additionalParams[1]);
    assertNotNull("environment provided", methodEnv);
}
 
Example #15
Source File: OptionTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testHelp() throws CommandException {
    CharSequence log = Log.enable("org.netbeans.modules.sendopts", Level.WARNING);
    StringWriter w = new StringWriter();
    cmd.usage(new PrintWriter(w));
    assertTrue("contains additionalParams:\n" + w, w.toString().contains(("AddOnParams")));
    assertTrue("contains short help:\n" + w, w.toString().contains(("ShortHelp")));
    assertTrue("contains description for p\n" + w, w.toString().contains("Short description for p"));
    assertEquals("No warnings:\n" + log, 0, log.length());
}
 
Example #16
Source File: Server.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected void process(Env env, Map<Option, String[]> optionValues) throws CommandException {
    try {
        run(env.getInputStream(), env.getOutputStream());
    } catch (Exception ex) {
        throw (CommandException) new CommandException(1).initCause(ex);
    }
}
 
Example #17
Source File: OpenProjectCLITest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testOpenBrokenAndProjectFolder() throws Exception {
    File nonExist = new File(dir, "IDoNotExist");
    assertFalse(nonExist.exists());
    File nonExist2 = new File(dir, "IDoNotExistEither");
    assertFalse(nonExist2.exists());
    
    try {
        CommandLine.getDefault().process(new String[] { "--open", nonExist2.getPath(), nonExist.getPath(), dir.getPath() });
        fail("One project does not exists, should fail");
    } catch (CommandException ex) {
        if (ex.getLocalizedMessage().indexOf(nonExist.getName()) == -1) {
            fail("Messages shall contain " + nonExist + "\n" + ex.getMessage());
        }
    }
    assertNull("No explorer called", MockNodeOperation.explored);

    Project p = OpenProjects.getDefault().getMainProject();
    assertNotNull("There is a main project", p);
    if (!(p instanceof MockProject)) {
        fail("Wrong project: " + p);
    }
    MockProject mp = (MockProject)p;
    
    assertEquals("It is our dir", fo, mp.p);
    
    SwingUtilities.invokeAndWait(new Runnable() { public void run() { } });
    
    assertNotNull("Failure notified", DD.prev);
    assertEquals("Just once", 1, DD.cnt);
}
 
Example #18
Source File: SnapArgsProcessor.java    From snap-desktop with GNU General Public License v3.0 5 votes vote down vote up
public void process(Env env) throws CommandException {

        if (openArgs != null) {
            processOpen(openArgs);
        }

        if (pythonArgs != null) {
            processPython(pythonArgs);
        }
    }
 
Example #19
Source File: SnapArgsProcessor.java    From snap-desktop with GNU General Public License v3.0 5 votes vote down vote up
private static void processPython(String[] args) throws CommandException {
    int errorExitCode = 200;

    Path pythonExecutable = null;
    Path pythonModuleInstallDir = null;

    if (args.length >= 1) {
        pythonExecutable = Paths.get(args[0]);
    }
    if (args.length >= 2) {
        pythonModuleInstallDir = Paths.get(args[1]);
    }

    if (pythonExecutable == null) {
        throw new CommandException(errorExitCode, "Python interpreter executable must be given");
    }

    if (!Files.exists(pythonExecutable)) {
        throw new CommandException(errorExitCode, "Python interpreter executable not found: " + pythonExecutable);
    }

    try {
        System.out.flush();
        System.out.println("Configuring SNAP-Python interface...");
        Path snappyDir = PyBridge.installPythonModule(pythonExecutable, pythonModuleInstallDir, true);
        System.out.flush();
        System.out.printf("Done. The SNAP-Python interface is located in '%s'%n", snappyDir);
        System.out.printf("When using SNAP from Python, either do: sys.path.append('%s')%n", snappyDir.getParent().toString().replace("\\", "\\\\"));
        System.out.printf("or copy the '%s' module into your Python's 'site-packages' directory.%n", snappyDir.getFileName());
        System.out.flush();
    } catch (IOException e) {
        e.printStackTrace(System.out);
        System.out.flush();
        throw new CommandException(errorExitCode, "Python configuration error: " + e.getMessage());
    } catch (Throwable t) {
        t.printStackTrace(System.out);
        System.out.flush();
        throw new CommandException(errorExitCode, "Python configuration internal error: " + t.getMessage());
    }
}
 
Example #20
Source File: Server.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void process(Env env) throws CommandException {
    try {
        run(env.getInputStream(), env.getOutputStream());
    } catch (Exception ex) {
        throw (CommandException) new CommandException(1).initCause(ex);
    }
}
 
Example #21
Source File: ForClassTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testParseEnabledWithParamFails() {
    try {
        cmd.process("--enabled", "Param");
        fail("Parse shall not succeed");
    } catch (CommandException ex) {
        // oK
    }
    assertNull("parse not finished, enabled not set", methodCalled);
}
 
Example #22
Source File: CaptureUsageTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void process(Env env) throws CommandException {
    assertTrue(use);
    final ByteArrayOutputStream os = new ByteArrayOutputStream();
    env.usage(os);
    try {
        usage = os.toString("UTF-8");
    } catch (UnsupportedEncodingException ex) {
        throw new CommandException(1, ex.getMessage());
    }
}
 
Example #23
Source File: CaptureUsageTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Test
public void captureUsage() throws CommandException {
    CommandLine cmd = CommandLine.create(CaptureUsageTest.class);
    usage = null;
    cmd.process("-u");
    assertNotNull("Usage set", usage);
    assertNotEquals("Expecting 'Use me!'", -1, usage.indexOf("Use me!"));
}
 
Example #24
Source File: HandlerImplTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
protected void process(Env env, Map<Option, String[]> optionValues) throws CommandException {
    values = optionValues;
    assertNotNull("each test needs to assign a key", key);
    if (key instanceof Throwable) {
        CommandException ex = new CommandException(221);
        ex.initCause((Throwable)key);
        throw ex;
    }

    String locMsg = MessageFormat.format(bundle.getString((String) key), args);
    throw new CommandException(337, locMsg);
}
 
Example #25
Source File: ForClassTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testParseWithoutParamFails() throws CommandException {
    try {
        cmd.process("-q");
        fail("Missing param for -q");
    } catch (CommandException ex) {
        // OK
        assertNull("No method called", methodCalled);
    }
}
 
Example #26
Source File: OptionTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testDefaultValueProvided() throws CommandException {
    cmd.process("--default=value");
    assertNotNull("Options created", methodCalled);
    assertEquals("Set to value string", "value", methodCalled.defaultValue);
}
 
Example #27
Source File: DefaultProcessor.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
protected void process(Env env, Map<Option, String[]> optionValues) throws CommandException {
    try {
        ClassLoader l = findClassLoader();
        Class<?> realClazz;
        Object inst;
        if (instance == null) {
            realClazz = Class.forName(clazz, true, l);
            inst = realClazz.newInstance();
        } else {
            realClazz = instance.getClass();
            inst = instance;
        }
        Map<Option,Field> map = processFields(realClazz, options);
        for (Map.Entry<Option, String[]> entry : optionValues.entrySet()) {
            final Option option = entry.getKey();
            Type type = Type.valueOf(option);
            Field f = map.get(option);
            assert f != null : "No field for option: " + option;
            switch (type) {
                case withoutArgument:
                    f.setBoolean(inst, true); break;
                case requiredArgument:
                    f.set(inst, entry.getValue()[0]); break;
                case optionalArgument:
                    if (entry.getValue().length == 1) {
                        f.set(inst, entry.getValue()[0]);
                    } else {
                        f.set(inst, f.getAnnotation(Arg.class).defaultValue());
                    }
                    break;
                case additionalArguments:
                    f.set(inst, entry.getValue()); break;
                case defaultArguments:
                    f.set(inst, entry.getValue()); break;
            }
        }
        if (inst instanceof Runnable) {
            ((Runnable)inst).run();
        }
        if (inst instanceof ArgsProcessor) {
            ((ArgsProcessor)inst).process(env);
        }
    } catch (Exception exception) {
        throw (CommandException)new CommandException(10, exception.getLocalizedMessage()).initCause(exception);
    }
}
 
Example #28
Source File: SourceRootsArgument.java    From visualvm with GNU General Public License v2.0 4 votes vote down vote up
@Override
protected void process(Env env, Map<Option, String[]> maps) throws CommandException {
    String[] values = maps.get(argument);
    if (values.length == 1) setValue(values[0]);
    else throw new CommandException(0, "--" + ARGUMENT_LONG_NAME + " requires exactly one value"); // NOI18N
}
 
Example #29
Source File: SourceViewerArgument.java    From visualvm with GNU General Public License v2.0 4 votes vote down vote up
@Override
protected void process(Env env, Map<Option, String[]> maps) throws CommandException {
    String[] values = maps.get(argument);
    if (values.length == 1) setValue(values[0]);
    else throw new CommandException(0, "--" + ARGUMENT_LONG_NAME + " requires exactly one value"); // NOI18N
}
 
Example #30
Source File: OpenJmxApplication.java    From visualvm with GNU General Public License v2.0 4 votes vote down vote up
protected void process(Env env, Map<Option, String[]> optionValues) throws CommandException {
    String[] connectionStrings = optionValues.get(openjmx);
    if (connectionStrings != null && connectionStrings.length > 0)
        openJmxApplication(connectionStrings[0]);
}