Example usage for java.lang IllegalArgumentException printStackTrace

List of usage examples for java.lang IllegalArgumentException printStackTrace

Introduction

In this page you can find the example usage for java.lang IllegalArgumentException printStackTrace.

Prototype

public void printStackTrace(PrintStream s) 

Source Link

Document

Prints this throwable and its backtrace to the specified print stream.

Usage

From source file:fr.cs.examples.bodies.Phasing.java

/** Program entry point.
 * @param args program arguments/*from   w  w  w.ja  v  a  2 s .c  om*/
 */
public static void main(String[] args) {
    try {

        if (args.length != 1) {
            System.err.println("usage: java fr.cs.examples.bodies.Phasing filename");
            System.exit(1);
        }

        // configure Orekit
        Autoconfiguration.configureOrekit();

        // input/out
        URL url = Phasing.class.getResource("/" + args[0]);
        if (url == null) {
            System.err.println(args[0] + " not found");
            System.exit(1);
        }
        File input = new File(url.toURI().getPath());

        new Phasing().run(input);

    } catch (URISyntaxException use) {
        System.err.println(use.getLocalizedMessage());
        System.exit(1);
    } catch (IOException ioe) {
        System.err.println(ioe.getLocalizedMessage());
        System.exit(1);
    } catch (IllegalArgumentException iae) {
        iae.printStackTrace(System.err);
        System.err.println(iae.getLocalizedMessage());
        System.exit(1);
    } catch (ParseException pe) {
        System.err.println(pe.getLocalizedMessage());
        System.exit(1);
    } catch (OrekitException oe) {
        oe.printStackTrace(System.err);
        System.err.println(oe.getLocalizedMessage());
        System.exit(1);
    }
}

From source file:de.huberlin.wbi.hiway.common.Client.java

/**
 * The main routine./* www.  j a  v  a  2 s.  c om*/
 * 
 * @param args Command line arguments passed to the Client.
 */
public static void main(String[] args) {
    boolean result = false;
    try {
        Client client = new Client();
        try {
            boolean doRun = client.init(args);
            if (!doRun) {
                System.exit(0);
            }
        } catch (IllegalArgumentException e) {
            client.printUsage();
            e.printStackTrace(System.out);
            System.exit(-1);
        }
        result = client.run();
    } catch (Throwable t) {
        System.out.println("Error running Client");
        t.printStackTrace();
        System.exit(-1);
    }
    if (result) {
        System.out.println("Application completed successfully");
        System.exit(0);
    }
    System.out.println("Application failed");
    System.exit(2);
}

From source file:com.zimbra.cs.service.util.ItemDataFile.java

public static void main(String[] args) {
    String cset = null;//from   w ww . ja v  a 2s.  co  m
    Options opts = new Options();
    CommandLineParser parser = new GnuParser();

    opts.addOption("a", "assemble", false, "assemble backup");
    opts.addOption("c", "charset", true, "path charset");
    opts.addOption("e", "extract", false, "extract backup");
    opts.addOption("h", "help", false, "help");
    opts.addOption("l", "list", false, "list backup");
    opts.addOption("n", "nometa", false, "ignore metadata");
    opts.addOption("p", "path", true, "extracted backup path");
    opts.addOption("t", "types", true, "item types");
    ZimbraLog.toolSetupLog4j("ERROR", null);
    try {
        CommandLine cl = parser.parse(opts, args);
        String path = ".";
        String file = null;
        boolean meta = true;
        Set<MailItem.Type> types = null;

        if (cl.hasOption('c')) {
            cset = cl.getOptionValue('c');
        }
        if (cl.hasOption('n')) {
            meta = false;
        }
        if (cl.hasOption('p')) {
            path = cl.getOptionValue('p');
        }
        if (cl.hasOption('t')) {
            try {
                types = MailItem.Type.setOf(cl.getOptionValue('t'));
            } catch (IllegalArgumentException e) {
                throw MailServiceException.INVALID_TYPE(e.getMessage());
            }
        }
        if (cl.hasOption('h') || cl.getArgs().length != 1) {
            usage(opts);
        }
        file = cl.getArgs()[0];
        if (cl.hasOption('a')) {
            create(path, types, cset, new FileOutputStream(file));
        } else if (cl.hasOption('e')) {
            extract(new FileInputStream(file), meta, types, cset, path);
        } else if (cl.hasOption('l')) {
            list(file.equals("-") ? System.in : new FileInputStream(file), types, cset, System.out);
        } else {
            usage(opts);
        }
    } catch (Exception e) {
        if (e instanceof UnrecognizedOptionException)
            usage(opts);
        else
            e.printStackTrace(System.out);
        System.exit(1);
    }
}

From source file:org.apache.jmeter.junit.JMeterTest.java

private static Test suiteBeanComponents() throws Exception {
    TestSuite suite = new TestSuite("BeanComponents");
    for (Object o : getObjects(TestBean.class)) {
        Class<?> c = o.getClass();
        try {//from  w ww. jav a 2  s .co m
            JMeterGUIComponent item = new TestBeanGUI(c);
            TestSuite ts = new TestSuite(item.getClass().getName());
            ts.addTest(new JMeterTest("GUIComponents2", item));
            ts.addTest(new JMeterTest("runGUITitle", item));
            suite.addTest(ts);
        } catch (IllegalArgumentException e) {
            System.out.println("o.a.j.junit.JMeterTest Cannot create test for " + c.getName() + " " + e);
            e.printStackTrace(System.out);
        }
    }
    return suite;
}

From source file:com.redhat.jenkins.nodesharingfrontend.Api.java

/**
 * Request to utilize reserved computer.
 *
 * Response codes://from   w  w  w  .ja va  2  s  .c o  m
 * - "200 OK" is used when the node was accepted, the node is expected to be correctly added to Jenkins by the time
 *   the request completes with the code. The code is also returned when the node is already helt by this executor.
 * - "410 Gone" when there is no longer the need for such host and orchestrator can reuse it immediately. The node must not be created.
 */
@RequirePOST
public void doUtilizeNode(@Nonnull final StaplerRequest req, @Nonnull final StaplerResponse rsp)
        throws IOException {
    final Jenkins jenkins = Jenkins.getActiveInstance();
    jenkins.checkPermission(RestEndpoint.RESERVE);

    UtilizeNodeRequest request = Entity.fromInputStream(req.getInputStream(), UtilizeNodeRequest.class);
    final NodeDefinition definition = NodeDefinition.create(request.getFileName(), request.getDefinition());
    if (definition == null)
        throw new AssertionError("Unknown node definition: " + request.getFileName());

    final String name = definition.getName();

    // utilizeNode call received even though the node is already being utilized
    Node node = getCollidingNode(jenkins, name);
    if (node != null) {
        new UtilizeNodeResponse(fingerprint).toOutputStream(rsp.getOutputStream());
        rsp.setStatus(HttpServletResponse.SC_OK);
        LOGGER.warning("Skipping node addition as it already exists");
        return;
    }

    // Do not accept the node when there is no load for it
    if (!isThereAWorkloadFor(jenkins, definition)) {
        rsp.setStatus(HttpServletResponse.SC_GONE);
        LOGGER.info("Skipping node addition as there isn't a workload for it");
        return;
    }

    try {
        final SharedNode newNode = cloud.createNode(definition);
        // Prevent replacing existing node due to a race condition in repeated utilizeNode calls
        Queue.withLock(new NotReallyRoleSensitiveCallable<Void, IOException>() {
            @Override
            public Void call() throws IOException {
                Node node = getCollidingNode(jenkins, name);
                if (node == null) {
                    jenkins.addNode(newNode);
                } else {
                    LOGGER.warning("Skipping node addition due to race condition");
                }
                return null;
            }
        });

        new UtilizeNodeResponse(fingerprint).toOutputStream(rsp.getOutputStream());
        rsp.setStatus(HttpServletResponse.SC_OK);
    } catch (IllegalArgumentException e) {
        e.printStackTrace(new PrintStream(rsp.getOutputStream()));
        rsp.setStatus(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
    }
}

From source file:at.univie.sensorium.extinterfaces.HTTPSUploader.java

private String uploadFiles(List<File> files) {
    String result = "";
    try {/*from   w ww  .  j  a  va 2  s . co  m*/

        if (URLUtil.isValidUrl(posturl)) {
            HttpClient httpclient = getNewHttpClient();

            HttpPost httppost = new HttpPost(posturl);
            MultipartEntity mpEntity = new MultipartEntity();
            //            MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

            mpEntity.addPart("username", new StringBody(username));
            mpEntity.addPart("password", new StringBody(password));
            for (File file : files) {
                Log.d(SensorRegistry.TAG, "preparing " + file.getName() + " for upload");
                ContentBody cbFile = new FileBody(file, "application/json");
                mpEntity.addPart(file.toString(), cbFile);
            }
            httppost.addHeader("username", username);
            httppost.addHeader("password", password);
            httppost.setEntity(mpEntity);
            HttpResponse response = httpclient.execute(httppost);

            String reply;
            InputStream in = response.getEntity().getContent();

            StringBuilder sb = new StringBuilder();
            try {
                int chr;
                while ((chr = in.read()) != -1) {
                    sb.append((char) chr);
                }
                reply = sb.toString();
            } finally {
                in.close();
            }
            result = response.getStatusLine().toString();
            Log.d(SensorRegistry.TAG, "Http upload completed with response: " + result + " " + reply);

        } else {
            result = "URL invalid";
            Log.d(SensorRegistry.TAG, "Invalid http upload url, aborting.");
        }
    } catch (IllegalArgumentException e) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        Log.d(SensorRegistry.TAG, sw.toString());
    } catch (FileNotFoundException e) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        Log.d(SensorRegistry.TAG, sw.toString());
    } catch (ClientProtocolException e) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        Log.d(SensorRegistry.TAG, sw.toString());
    } catch (IOException e) {
        result = "upload failed due to timeout";
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        Log.d(SensorRegistry.TAG, sw.toString());
    }
    return result;
}

From source file:org.apache.hadoop.fs.FsShell.java

/**
 * run/* w w  w .ja v a2 s  .c o m*/
 */
@Override
public int run(String argv[]) throws Exception {
    // initialize FsShell
    init();
    int exitCode = -1;
    if (argv.length < 1) {
        printUsage(System.err);
    } else {
        String cmd = argv[0];
        Command instance = null;
        try {
            instance = commandFactory.getInstance(cmd);
            if (instance == null) {
                throw new UnknownCommandException();
            }
            TraceScope scope = tracer.newScope(instance.getCommandName());
            if (scope.getSpan() != null) {
                String args = StringUtils.join(" ", argv);
                if (args.length() > 2048) {
                    args = args.substring(0, 2048);
                }
                scope.getSpan().addKVAnnotation("args", args);
            }
            try {
                exitCode = instance.run(Arrays.copyOfRange(argv, 1, argv.length));
            } finally {
                scope.close();
            }
        } catch (IllegalArgumentException e) {
            if (e.getMessage() == null) {
                displayError(cmd, "Null exception message");
                e.printStackTrace(System.err);
            } else {
                displayError(cmd, e.getLocalizedMessage());
            }
            printUsage(System.err);
            if (instance != null) {
                printInstanceUsage(System.err, instance);
            }
        } catch (Exception e) {
            // instance.run catches IOE, so something is REALLY wrong if here
            LOG.debug("Error", e);
            displayError(cmd, "Fatal internal error");
            e.printStackTrace(System.err);
        }
    }
    tracer.close();
    return exitCode;
}

From source file:com.genentech.chemistry.openEye.apps.QTorsionProfileGenerator.java

/**
 * Create gaussian files and core file for one sdf file with molecules.
 *
 * @param inFile name of input file with molecules
 * @param coreFile name of file into which to store the core, may be null
 * @param nCPU overwrite gaussian %nprocshared parameter, if null no overwriting takes place
 * @param sdfFile if null no sdf file is written
 * @param memStr Memory for Gaussian e.g. "10GB"
 *//*  www.jav a  2 s.  co  m*/
private void run(String inFile, String sdfFile, String coreFile, String nCPU, String memStr)
        throws IOException {
    TorsionScanner torScanner = new TorsionScanner(bondFile, coreFile, FROZEN_ATOM_TAG, nSteps, startTorsion,
            torsionIncrement, sampleNConf, doMinimize, constraintStrength);

    oemolithread ifs = new oemolithread(inFile);
    OEGraphMol mol = new OEGraphMol();
    List<OEGraphMol> inMols = new ArrayList<OEGraphMol>();

    oemolothread ofs = null;
    if (sdfFile != null)
        ofs = new oemolothread(sdfFile);

    int molNum = 0;
    while (oechem.OEReadMolecule(ifs, mol)) {
        try {
            Map<String, Integer> angleCountMap = new HashMap<String, Integer>();

            if (coreFile != null)
                inMols.add(new OEGraphMol(mol));
            OEMCMolBase mcMol = torScanner.run(mol);
            OEConfBaseIter cIt = mcMol.GetConfs();
            while (cIt.hasNext()) {
                OEConfBase conf = cIt.next();
                if (ofs != null)
                    oechem.OEWriteMolecule(ofs, conf);
                String angle = oechem.OEGetSDData(conf, TorsionScanner.ANGLE_TAG);
                int countSameAngle = 0;
                if (angleCountMap.containsKey(angle))
                    countSameAngle = angleCountMap.get(angle);
                angleCountMap.put(angle, ++countSameAngle);

                molNum++;

                String fName;
                double dAngle = Double.parseDouble(angle);
                if (outPrefix != null)
                    fName = String.format("%s_%02d.%04.0f_%03d", outPrefix, molNum, dAngle, countSameAngle);
                else if ("TITLE".equals(outNameTag))
                    fName = String.format("%s.%04.0f_%03d", mol.GetTitle(), dAngle, countSameAngle);
                else
                    fName = String.format("%s.%04.0f_%03d", oechem.OEGetSDData(mol, outNameTag), dAngle,
                            countSameAngle);

                String xMat = getXMat(conf);

                String frozenStmt = getFrozenCoordinate(conf);
                String gCom = qTemplate.replace("#FName#", fName);

                if (qTemplate.contains("#FIX#"))
                    gCom = gCom.replace("#FIX#", frozenStmt);
                else
                    // add statement to freeze torsion
                    xMat += "\n" + getFrozenCoordinate(conf);

                gCom = gCom.replace("#XYZ#", xMat);
                gCom = gCom.replace("#mem#", memStr);
                if (nCPU != null)
                    gCom = gCom.replaceAll("%nprocshared=.*", "%nprocshared=" + nCPU);

                IOUtil.stringToFile(workDir + File.separatorChar + fName + ".g", gCom);
            }
            cIt.delete();
            mcMol.delete();

        } catch (IllegalArgumentException e) {
            System.err.println(e.getMessage() + " compound ignored!\n" + e.getMessage());
            if (debug)
                e.printStackTrace(System.err);
        }
    }
    mol.delete();

    if (ofs != null) {
        ofs.close();
        ofs.delete();
    }

    ifs.close();
    ifs.delete();

    if (coreFile != null && molNum > 0)
        torScanner.computeCore(coreFile);

    torScanner.close();
}

From source file:com.ruizhan.hadoop.hdfs.FsShell.java

/**
 * run//from w  w w.  j a v a2 s  .  com
 */
public int run(String argv[]) throws Exception {
    // initialize FsShell
    init();

    int exitCode = -1;
    if (argv.length < 1) {
        printUsage(System.err);
    } else {
        String cmd = argv[0];
        Command instance = null;
        try {
            instance = commandFactory.getInstance(cmd);
            if (instance == null) {
                throw new UnknownCommandException();
            }
            exitCode = instance.run(Arrays.copyOfRange(argv, 1, argv.length));
        } catch (IllegalArgumentException e) {
            displayError(cmd, e.getLocalizedMessage());
            if (instance != null) {
                printInstanceUsage(System.err, instance);
            }
        } catch (Exception e) {
            // instance.run catches IOE, so something is REALLY wrong if here
            LOG.debug("Error", e);
            displayError(cmd, "Fatal internal error");
            e.printStackTrace(System.err);
        }
    }
    return exitCode;
}

From source file:edu.nyu.tandon.tool.RawHits.java

/**
 * Interpret the given command, changing the static variables.
 * See the help printing code for possible commands.
 *
 * @param line the command line.//from   ww  w.j av a 2s.  c o  m
 * @return false iff we should exit after this command.
 */
public boolean interpretCommand(final String line) {
    String[] part = line.substring(1).split("[ \t\n\r]+");

    final Command command;
    int i;

    if (part[0].length() == 0) {
        System.err.println("$                                                       prints this help.");
        System.err.println("$mode [time|short|long|snippet|trec <topicNo> <runTag>] chooses display mode.");
        System.err.println(
                "$limit <max>                                            output at most <max> results per query.");
        System.err.println(
                "$divert [<filename>]                                    diverts output to <filename> or to stdout.");
        System.err.println(
                "$weight {index:weight}                                  set index weights (unspecified weights are set to 1).");
        System.err.println("$mplex [<on>|<off>]                                     set/unset multiplex mode.");
        System.err.println(
                "$equalize <sample>                                      equalize scores using the given sample size.");
        System.err.println(
                "$score {<scorerClass>(<arg>,...)[:<weight>]}            order documents according to <scorerClass>.");
        System.err.println(
                "$expand {<expanderClass>(<arg>,...)}                    expand terms and prefixes according to <expanderClass>.");
        System.err.println("$quit                                                   quits.");
        return true;
    }

    try {
        command = Command.valueOf(part[0].toUpperCase());
    } catch (IllegalArgumentException e) {
        System.err.println("Invalid command \"" + part[0] + "\"; type $ for help.");
        return true;
    }

    switch (command) {
    case MODE:
        if (part.length >= 2) {
            try {
                final OutputType tempMode = OutputType.valueOf(part[1].toUpperCase());

                if (tempMode != OutputType.TREC && part.length > 2)
                    System.err.println("Extra arguments.");
                else if (tempMode == OutputType.TREC && part.length != 4)
                    System.err.println("Missing or extra arguments.");
                else {
                    displayMode = tempMode;
                    if (displayMode == OutputType.TREC) {
                        trecTopicNumber = Integer.parseInt(part[2]);
                        trecRunTag = part[3];
                    }
                }
            } catch (IllegalArgumentException e) {
                System.err.println("Unknown mode: " + part[1]);
            }
        } else
            System.err.println("Missing mode.");
        break;

    case LIMIT:
        int out = -1;
        if (part.length == 2) {
            try {
                out = Integer.parseInt(part[1]);
            } catch (NumberFormatException e) {
            }
            if (out >= 0)
                maxOutput = out;
        }
        if (out < 0)
            System.err.println("Missing or incorrect limit.");
        break;

    case SCORE:
        final Scorer[] scorer = new Scorer[part.length - 1];
        final double[] weight = new double[part.length - 1];
        for (i = 1; i < part.length; i++)
            try {
                weight[i - 1] = loadClassFromSpec(part[i], scorer, i - 1);
                if (weight[i - 1] < 0)
                    throw new IllegalArgumentException("Weights should be non-negative");
            } catch (Exception e) {
                System.err.print("Error while parsing specification: ");
                e.printStackTrace(System.err);
                break;
            }
        if (i == part.length)
            queryEngine.score(scorer, weight);
        break;

    case EXPAND:
        if (part.length > 2)
            System.err.println("Wrong argument(s) to command");
        else if (part.length == 1) {
            queryEngine.transformer(null);
        } else {
            QueryTransformer[] t = new QueryTransformer[1];
            try {
                loadClassFromSpec(part[1], t, 0);
                queryEngine.transformer(t[0]);
            } catch (Exception e) {
                System.err.print("Error while parsing specification: ");
                e.printStackTrace(System.err);
                break;
            }
        }
        break;

    case MPLEX:
        if (part.length != 2 || (part.length == 2 && !"on".equals(part[1]) && !"off".equals(part[1])))
            System.err.println("Wrong argument(s) to command");
        else {
            if (part.length > 1)
                queryEngine.multiplex = "on".equals(part[1]);
            System.err.println("Multiplex: " + part[1]);
        }
        break;

    case DIVERT:
        if (part.length > 2)
            System.err.println("Wrong argument(s) to command");
        else {
            outputPH.close();
            try {
                outputPH = part.length == 1 ? System.out
                        : new PrintStream(new FastBufferedOutputStream(
                                new FileOutputStream(part[1] + "-" + phBatch++ + ".ph.txt")));
                outputName = part[1];
            } catch (FileNotFoundException e) {
                System.err.println("Cannot create file " + part[1]);
                outputPH = System.out;
            }
        }
        break;

    case EQUALIZE:
        try {
            if (part.length != 2)
                throw new NumberFormatException("Illegal number of arguments");
            queryEngine.equalize(Integer.parseInt(part[1]));
            System.err.println("Equalization sample set to " + Integer.parseInt(part[1]));
        } catch (NumberFormatException e) {
            System.err.println(e.getMessage());
        }
        break;

    case QUIT:
        return false;
    }
    return true;
}