Example usage for java.lang Exception getMessage

List of usage examples for java.lang Exception getMessage

Introduction

In this page you can find the example usage for java.lang Exception getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:MainClass.java

public static void main(String argv[]) {
    int start = 1;
    int end = -1;
    int optind;// w ww.  j  a  v  a 2s.c om

    for (optind = 0; optind < argv.length; optind++) {
        if (argv[optind].equals("-T")) { // protocol
            protocol = argv[++optind];
        } else if (argv[optind].equals("-H")) { // host
            host = argv[++optind];
        } else if (argv[optind].equals("-U")) { // user
            user = argv[++optind];
        } else if (argv[optind].equals("-P")) { // password
            password = argv[++optind];
        } else if (argv[optind].equals("-L")) {
            url = argv[++optind];
        } else if (argv[optind].equals("-s")) { // Source mbox
            src = argv[++optind];
        } else if (argv[optind].equals("-d")) { // Destination mbox
            dest = argv[++optind];
        } else if (argv[optind].equals("-x")) { // Expunge ?
            expunge = true;
        } else if (argv[optind].equals("--")) {
            optind++;
            break;
        } else if (argv[optind].startsWith("-")) {
            System.out.println("Usage: mover [-T protocol] [-H host] [-U user] [-P password] [-L url] [-v]");
            System.out.println("\t[-s source mbox] [-d destination mbox] [-x] [msgnum1] [msgnum2]");
            System.out.println("\t The -x option => EXPUNGE deleted messages");
            System.out.println("\t msgnum1 => start of message-range; msgnum2 => end of message-range");
            System.exit(1);
        } else {
            break;
        }
    }

    if (optind < argv.length)
        start = Integer.parseInt(argv[optind++]); // start msg

    if (optind < argv.length)
        end = Integer.parseInt(argv[optind++]); // end msg

    try {
        // Get a Properties object
        Properties props = System.getProperties();

        // Get a Session object
        Session session = Session.getInstance(props, null);

        // Get a Store object
        Store store = null;
        if (url != null) {
            URLName urln = new URLName(url);
            store = session.getStore(urln);
            store.connect();
        } else {
            if (protocol != null)
                store = session.getStore(protocol);
            else
                store = session.getStore();

            // Connect
            if (host != null || user != null || password != null)
                store.connect(host, user, password);
            else
                store.connect();
        }

        // Open source Folder
        Folder folder = store.getFolder(src);
        if (folder == null || !folder.exists()) {
            System.out.println("Invalid folder: " + folder.getName());
            System.exit(1);
        }

        folder.open(Folder.READ_WRITE);

        int count = folder.getMessageCount();
        if (count == 0) { // No messages in the source folder
            System.out.println(folder.getName() + " is empty");
            // Close folder, store and return
            folder.close(false);
            store.close();
            return;
        }

        // Open destination folder, create if reqd
        Folder dfolder = store.getFolder(dest);
        if (!dfolder.exists())
            dfolder.create(Folder.HOLDS_MESSAGES);

        if (end == -1)
            end = count;

        // Get the message objects to copy
        Message[] msgs = folder.getMessages(start, end);
        System.out.println("Moving " + msgs.length + " messages");

        if (msgs.length != 0) {
            folder.copyMessages(msgs, dfolder);
            folder.setFlags(msgs, new Flags(Flags.Flag.DELETED), true);

            // Dump out the Flags of the moved messages, to insure that
            // all got deleted
            for (int i = 0; i < msgs.length; i++) {
                if (!msgs[i].isSet(Flags.Flag.DELETED))
                    System.out.println("Message # " + msgs[i] + " not deleted");
            }
        }

        // Close folders and store
        folder.close(expunge);
        store.close();

    } catch (MessagingException mex) {
        Exception ex = mex;
        do {
            System.out.println(ex.getMessage());
            if (ex instanceof MessagingException)
                ex = ((MessagingException) ex).getNextException();
            else
                ex = null;
        } while (ex != null);
    }
}

From source file:org.dspace.app.cris.batch.ScriptDeleteRP.java

/**
 * Batch script to delete a RP. See the technical documentation for further
 * details./*from ww  w.  jav  a  2s. c om*/
 */
public static void main(String[] args) {
    log.info("#### START DELETE: -----" + new Date() + " ----- ####");
    Context dspaceContext = null;
    ApplicationContext context = null;
    try {
        dspaceContext = new Context();
        dspaceContext.turnOffAuthorisationSystem();

        DSpace dspace = new DSpace();
        ApplicationService applicationService = dspace.getServiceManager()
                .getServiceByName("applicationService", ApplicationService.class);

        CommandLineParser parser = new PosixParser();

        Options options = new Options();
        options.addOption("h", "help", false, "help");

        options.addOption("r", "researcher", true, "RP id to delete");

        options.addOption("s", "silent", false, "no interactive mode");

        CommandLine line = parser.parse(options, args);

        if (line.hasOption('h')) {
            HelpFormatter myhelp = new HelpFormatter();
            myhelp.printHelp("ScriptHKURPDelete \n", options);
            System.out.println("\n\nUSAGE:\n ScriptHKURPDelete -r <id> \n");
            System.out.println("Please note: add -s for no interactive mode");
            System.exit(0);
        }

        Integer rpId = null;
        boolean delete = false;
        boolean silent = line.hasOption('s');
        Item[] items = null;
        if (line.hasOption('r')) {
            rpId = ResearcherPageUtils.getRealPersistentIdentifier(line.getOptionValue("r"),
                    ResearcherPage.class);
            ResearcherPage rp = applicationService.get(ResearcherPage.class, rpId);

            if (rp == null) {
                if (!silent) {
                    System.out.println("RP not exist...exit");
                }
                log.info("RP not exist...exit");
                System.exit(0);
            }

            log.info("Use browse indexing");

            BrowseIndex bi = BrowseIndex.getBrowseIndex(plugInBrowserIndex);
            // now start up a browse engine and get it to do the work for us
            BrowseEngine be = new BrowseEngine(dspaceContext);

            String authKey = ResearcherPageUtils.getPersistentIdentifier(rp);

            // set up a BrowseScope and start loading the values into it
            BrowserScope scope = new BrowserScope(dspaceContext);
            scope.setBrowseIndex(bi);
            // scope.setOrder(order);
            scope.setFilterValue(authKey);
            scope.setAuthorityValue(authKey);
            scope.setResultsPerPage(Integer.MAX_VALUE);
            scope.setBrowseLevel(1);

            BrowseInfo binfo = be.browse(scope);
            log.debug("Find " + binfo.getResultCount() + "item(s) for the reseracher " + authKey);
            items = binfo.getItemResults(dspaceContext);

            if (!silent && rp != null) {
                System.out.println(MESSAGE_ONE);

                // interactive mode
                System.out.println("Attempting to remove Researcher Page:");
                System.out.println("StaffNo:" + rp.getSourceID());
                System.out.println("FullName:" + rp.getFullName());
                System.out
                        .println("the researcher has " + items.length + " relation(s) with item(s) in the HUB");
                System.out.println();

                System.out.println(QUESTION_ONE);
                InputStreamReader isr = new InputStreamReader(System.in);
                BufferedReader reader = new BufferedReader(isr);
                String answer = reader.readLine();
                if (answer.equals("yes")) {
                    delete = true;
                } else {
                    System.out.println("Exit without delete");
                    log.info("Exit without delete");
                    System.exit(0);
                }

            } else {
                delete = true;
            }
        } else {
            System.out.println("\n\nUSAGE:\n ScriptHKURPDelete <-v> -r <RPid> \n");
            System.out.println("-r option is mandatory");
            log.error("-r option is mandatory");
            System.exit(1);
        }

        if (delete) {
            if (!silent) {
                System.out.println("Deleting...");
            }
            log.info("Deleting...");
            cleanAuthority(dspaceContext, items, rpId);
            applicationService.delete(ResearcherPage.class, rpId);
            dspaceContext.complete();
        }

        if (!silent) {
            System.out.println("Ok...Bye");
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new RuntimeException(e.getMessage(), e);
    } finally {
        if (dspaceContext != null && dspaceContext.isValid()) {
            dspaceContext.abort();
        }
        if (context != null) {
            context.publishEvent(new ContextClosedEvent(context));
        }
    }
    log.info("#### END: -----" + new Date() + " ----- ####");
    System.exit(0);
}

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

/**
 * @param args/*from w  ww .  j a  v  a 2s  . c  o  m*/
 */
public static void main(String... args) throws IOException {
    // create command line Options object
    Options options = new Options();
    Option opt = new Option(OPT_INFILE, true,
            "input file oe-supported Use .sdf|.smi to specify the file type.");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_OUTFILE, true, "Output filename.");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_STARTTorsion, true,
            "The torsion in your inMol will be rotated by this value for the first job");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_TORSIONIncrement, true, "Incremnt each subsequent conformation by this step size");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_NSTEPS, true, "Number of conformations to create");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_BONDFILE, true, "The file containing the bond atoms that define the torsion.");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_MINIMIZE, false,
            "Minimize conformer at each step using MMFFs.  If maxConfsPerStep is > 1, "
                    + "all confs will be mimimized and the lowest E will be output.");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_CONSTRIANT, true,
            "One of strong (90), medium (45), weak(20), none or a floating point number"
                    + " to specify the tethered constraint strength for -minimize (def=strong)");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_MAXCONFS_PER_STEP, true,
            "While holding the torsion fixed, maximum number of conformations of free atoms to generat.  default=1");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_COREFILE, true, "Outputfile to store guessed core.");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_TORSIONS_ATOM_TAG, true,
            "Name of sdf tag which will contain the indices of atoms that define the torsion.");
    opt.setRequired(true);
    options.addOption(opt);

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        System.err.println(e.getMessage());
        exitWithHelp(options);
    }
    args = cmd.getArgs();

    if (args.length != 0) {
        System.err.println("Unknown arguments" + args);
        exitWithHelp(options);
    }

    if (cmd.hasOption("d")) {
        System.err.println("Start debugger and press return:");
        new BufferedReader(new InputStreamReader(System.in)).readLine();
    }

    String inFile = cmd.getOptionValue(OPT_INFILE);
    String outFile = cmd.getOptionValue(OPT_OUTFILE);

    String bondFile = cmd.getOptionValue(OPT_BONDFILE);
    String coreFilename = cmd.getOptionValue(OPT_COREFILE);
    String torsionAtomsTag = cmd.getOptionValue(OPT_TORSIONS_ATOM_TAG);

    int nSteps = Integer.parseInt(cmd.getOptionValue(OPT_NSTEPS));
    int nStartTor = Integer.parseInt(cmd.getOptionValue(OPT_STARTTorsion));
    int nTorIncr = Integer.parseInt(cmd.getOptionValue(OPT_TORSIONIncrement));

    int nMaxConfsPerStep = 1;
    if (cmd.hasOption(OPT_MAXCONFS_PER_STEP)) {
        nMaxConfsPerStep = Integer.parseInt(cmd.getOptionValue(OPT_MAXCONFS_PER_STEP));
    }

    String constraintStrength = cmd.getOptionValue(OPT_CONSTRIANT);

    boolean doMinimize = cmd.hasOption(OPT_MINIMIZE);

    SDFTorsionScanner torGenerator = new SDFTorsionScanner(bondFile, coreFilename, torsionAtomsTag, nSteps,
            nStartTor, nTorIncr, nMaxConfsPerStep, doMinimize, constraintStrength);

    torGenerator.run(inFile, outFile, coreFilename);
}

From source file:it.sardegnaricerche.voiceid.sr.Voiceid.java

public static void main(String[] args) {
    logger.info("Voiceid main method");
    logger.info("First argument: '" + args[0] + "'");
    long startTime = System.currentTimeMillis();
    Voiceid voiceid = null;//from   w  w w  . ja v  a 2 s  . c om
    GMMVoiceDB db = null;
    try {
        db = new GMMVoiceDB(args[1], new UBMModel(args[0]));
        File f = new File(args[2]);
        voiceid = new Voiceid(db, f, new LIUMStandardDiarizator());
        voiceid.extractClusters();
        voiceid.matchClusters();
        // voiceid.toWav();
        // voiceid.printClusters();
        JSONObject obj = voiceid.toJson();

        for (VCluster c : voiceid.getClusters()) {
            logger.info("" + c.getSample().getResource().getAbsolutePath());
        }

        // FileWriter fstream = new
        // FileWriter(f.getAbsolutePath().replaceFirst("[.][^.]+$", "") +
        // ".json");
        String filename = Utils.getBasename(f) + ".json";
        FileWriter fstream = new FileWriter(filename);
        BufferedWriter out = new BufferedWriter(fstream);
        out.write(obj.toString());
        // Close the output stream
        out.close();

        // voiceid.makeAllModels();
    } catch (IOException e) {
        logger.severe(e.getMessage());
    } catch (Exception ex) {
        logger.severe(ex.getMessage());
    }
    long endTime = System.currentTimeMillis();
    long duration = endTime - startTime;
    logger.info("Exit (" + ((float) duration / 1000) + " s)");
    // logger.info("Max Threads: " + (int) db.maxThreads);
}

From source file:GetAppInfo.java

/**
 * @param args// w w  w  .ja v  a  2s.co  m
 */
public static void main(String[] args) {
    if (args.length != 4) {
        System.out.println("Usage :\n" + "java -jar this_jar_name confpath query_str startIndex numbers");
        System.exit(1);
    }
    String confpath = args[0];
    GetAppConfig conf = new GetAppConfig(confpath);
    String email = conf.getUserID();
    String password = conf.getPassword();
    String query = args[1];
    final int startIndex = Integer.parseInt(args[2]);
    final int numbers = Integer.parseInt(args[3]);
    String androidid = conf.getDeviceID();

    if (email.equals("")) {
        System.out.println("Error: Failed to get UserID.");
        System.exit(2);
    } else if (password.equals("")) {
        System.out.println("Error: Failed to get Password.");
        System.exit(3);
    } else if (androidid.equals("")) {
        System.out.println("Error: Failed to get DeviceID.");
        System.exit(4);
    }

    System.out.println("query: " + query);
    MarketSession session = new MarketSession();
    session.getContext().setAndroidId(androidid);

    Locale locale = new Locale("ja", "JP");
    session.setLocale(locale);
    session.setOperator("NTT DOCOMO", "44010");
    session.getContext().setDeviceAndSdkVersion("passion:8");

    try {
        session.login(email, password, androidid);
    } catch (Exception e) {
        System.out.println("Error: failed to login.: " + e.getMessage());
        System.exit(1);
    }

    AppsRequest appsRequest = AppsRequest.newBuilder().setQuery(query).setStartIndex(startIndex)
            .setEntriesCount(numbers).setWithExtendedInfo(true).build();

    Callback<AppsResponse> callback = new Callback<AppsResponse>() {
        @Override
        public void onResult(ResponseContext context, AppsResponse response) {
            int totalcnt, cnt;
            JsonFactory factory = new JsonFactory();
            try {
                JsonGenerator generator = factory.createGenerator(new FileWriter(new File("pkginfo.json")));
                generator.writeStartObject();
                //generator.setRootValueSeparator(new SerializedString("\n"));

                if (response != null) {
                    totalcnt = response.getEntriesCount();
                    cnt = response.getAppCount();
                    System.out.println("startIndex = " + startIndex);
                    System.out.println("entriesCount = " + numbers);
                    System.out.println("totalcount = " + totalcnt);
                    System.out.println("count = " + cnt);
                    generator.writeNumberField("startIndex", startIndex);
                    generator.writeNumberField("entriesCount", numbers);
                    generator.writeNumberField("total", totalcnt);
                    generator.writeNumberField("count", cnt);
                    generator.writeRaw("\n");
                } else {
                    cnt = -1;
                }
                generator.writeFieldName("dataset");
                generator.writeStartArray();

                if (cnt > 0) {
                    for (int i = 0; ((i < cnt) && (i < numbers)); i++) {
                        generator.writeStartObject();
                        generator.writeNumberField("num", i + startIndex);
                        System.out.println(
                                "------------------------------------------------------------------------------------");
                        int counter = i + startIndex;
                        System.out.println(counter + ":");
                        System.out.println(
                                "------------------------------------------------------------------------------------");
                        generator.writeStringField("title", response.getApp(i).getTitle());
                        generator.writeStringField("appType", "" + response.getApp(i).getAppType());
                        generator.writeStringField("category",
                                response.getApp(i).getExtendedInfo().getCategory());
                        generator.writeStringField("rating", response.getApp(i).getRating());
                        generator.writeNumberField("ratingCount", response.getApp(i).getRatingsCount());
                        generator.writeStringField("countText",
                                response.getApp(i).getExtendedInfo().getDownloadsCountText());
                        generator.writeStringField("creatorId", response.getApp(i).getCreatorId());
                        generator.writeStringField("id", response.getApp(i).getId());
                        generator.writeStringField("packageName", response.getApp(i).getPackageName());
                        generator.writeStringField("version", response.getApp(i).getVersion());
                        generator.writeNumberField("versionCode", response.getApp(i).getVersionCode());
                        generator.writeStringField("price", response.getApp(i).getPrice());
                        generator.writeNumberField("priceMicros", response.getApp(i).getPriceMicros());
                        generator.writeStringField("priceCurrency", response.getApp(i).getPriceCurrency());
                        generator.writeStringField("contactWebsite",
                                response.getApp(i).getExtendedInfo().getContactWebsite());
                        generator.writeNumberField("screenshotsCount",
                                response.getApp(i).getExtendedInfo().getScreenshotsCount());
                        generator.writeNumberField("installSize",
                                response.getApp(i).getExtendedInfo().getInstallSize());
                        generator.writeStringField("permissionIdList",
                                "" + response.getApp(i).getExtendedInfo().getPermissionIdList());
                        generator.writeStringField("promotoText",
                                response.getApp(i).getExtendedInfo().getPromoText());
                        generator.writeStringField("description",
                                response.getApp(i).getExtendedInfo().getDescription());

                        System.out.println("title: " + response.getApp(i).getTitle());
                        System.out.println("appType: " + response.getApp(i).getAppType());
                        System.out.println("category: " + response.getApp(i).getExtendedInfo().getCategory());
                        System.out.println("rating: " + response.getApp(i).getRating());
                        System.out.println("ratingsCount: " + response.getApp(i).getRatingsCount());
                        System.out
                                .println("count: " + response.getApp(i).getExtendedInfo().getDownloadsCount());
                        System.out.println(
                                "countText: " + response.getApp(i).getExtendedInfo().getDownloadsCountText());
                        System.out.println("creator: " + response.getApp(i).getCreator());
                        System.out.println("creatorId: " + response.getApp(i).getCreatorId());
                        System.out.println("id: " + response.getApp(i).getId());
                        System.out.println("packageName: " + response.getApp(i).getPackageName());
                        System.out.println("version: " + response.getApp(i).getVersion());
                        //System.out.println("contactEmail: " + response.getApp(i).getExtendedInfo().getContactEmail());
                        //System.out.println("contactPhone: " + response.getApp(i).getExtendedInfo().getContactPhone());
                        System.out.println(
                                "installSize: " + response.getApp(i).getExtendedInfo().getInstallSize());
                        generator.writeEndObject();
                        generator.writeRaw("\n");
                    }
                } else if (cnt == 0) {
                    System.out.println("no hit");
                } else {
                    System.out.println("Bad Reqeust");
                }

                generator.writeEndArray();
                generator.writeEndObject();
                generator.close();

            } catch (Exception e) {
                System.out.println("Error: pkginfo(): " + e.getMessage());
            }

        } // onResult()
    };
    session.append(appsRequest, callback);
    session.flush();
}

From source file:edu.msu.cme.rdp.readseq.utils.ResampleSeqFile.java

public static void main(String[] args) throws IOException {
    int numOfSelection = 0;
    int subregion_length = 0;

    try {// w ww  . j a  va2  s  .  c om
        CommandLine line = new PosixParser().parse(options, args);
        if (line.hasOption("num-selection")) {
            numOfSelection = Integer.parseInt(line.getOptionValue("num-selection"));
            if (numOfSelection < 1) {
                throw new Exception("num-selection should be at least 1");
            }
        }
        if (line.hasOption("subregion_length")) {
            subregion_length = Integer.parseInt(line.getOptionValue("subregion_length"));
            if (subregion_length < 1) {
                throw new Exception("subregion_length should be at least 1");
            }
        }

        args = line.getArgs();
        if (args.length != 2) {
            throw new Exception("Incorrect number of command line arguments");
        }
        ResampleSeqFile.select(args[0], args[1], numOfSelection, subregion_length);
    } catch (Exception e) {
        new HelpFormatter().printHelp(120, "ResampleSeqFile [options] <infile(dir)> <outdir>", "", options, "");
        System.out.println("ERROR: " + e.getMessage());
        return;
    }
}

From source file:com.moss.appsnap.server.AppSnapServer.java

public static void main(String[] args) throws Exception {
    System.setProperty("org.mortbay.log.class", Slf4jLog.class.getName());

    File log4jConfigFile = new File("log4j.xml");

    if (log4jConfigFile.exists()) {
        DOMConfigurator.configureAndWatch(log4jConfigFile.getAbsolutePath(), 1000);
    } else {//  ww  w .  j a v a  2  s.com
        BasicConfigurator.configure();
        Logger.getRootLogger().setLevel(Level.INFO);
    }

    ServerConfiguration config;

    JAXBContext context = JAXBContext.newInstance(ServerConfiguration.class, VeracityId.class);
    JAXBHelper helper = new JAXBHelper(context);

    Logger log = Logger.getLogger(AppSnapServer.class);

    File[] configPaths = new File[] { new File("settings.xml"),
            new File(new File(System.getProperty("user.home")), ".appsnap-server.xml"),
            new File("/etc/appsnap-server.xml") };

    File configFile = null;

    for (File next : configPaths) {
        if (next.exists()) {
            configFile = next;
        }
    }

    if (configFile == null) {

        log.warn("No config file found.");

        for (int x = configPaths.length - 1; x >= 0; x--) {
            File next = configPaths[x];
            log.warn("Attempting to create default config file at " + next.getAbsolutePath());
            ServerConfiguration defaults = new ServerConfiguration();
            defaults.idProofRecipie(
                    new PasswordProofRecipie(new SimpleId("mr-admin-dude"), "my-super-secret-password"));
            try {
                helper.writeToFile(helper.writeToXmlString(defaults), next);
                log.warn("done");
                break;
            } catch (Exception e) {
                log.warn("Error writing file: " + e.getMessage(), e);
            }
        }
        System.exit(1);
        return;
    } else {
        log.info("Reading configuration from " + configFile.getAbsolutePath());
        config = helper.readFromFile(configFile);
    }

    ProxyFactory proxyFactory = new ProxyFactory(new HessianProxyProvider());
    try {
        new AppSnapServer(config, proxyFactory);
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("Unexpected Error.  Shutting Down.");
        System.exit(1);
    }
}

From source file:importer.handler.post.stages.SAXSplitter.java

public static void main(String[] args) {
    if (args.length == 1) {
        File f = new File(args[0]);
        byte[] data = new byte[(int) f.length()];
        try {/*from w  w  w  . ja v a2  s .c  o m*/
            FileInputStream fis = new FileInputStream(f);
            fis.read(data);
            SAXSplitter ss = new SAXSplitter();
            JSONArray jArr = ss.scan(new String(data, "UTF-8"));
            String jStr = jArr.toJSONString();
            System.out.println(jStr.replaceAll("\\\\/", "/"));
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}

From source file:org.eclipse.lyo.client.oslc.samples.RTCFormSample.java

/**
 * Login to the RTC server and perform some OSLC actions
 * @param args/*from   w  ww  .j  a va2s  .c om*/
 * @throws ParseException 
 */
public static void main(String[] args) throws ParseException {

    Options options = new Options();

    options.addOption("url", true, "url");
    options.addOption("user", true, "user ID");
    options.addOption("password", true, "password");
    options.addOption("project", true, "project area");

    CommandLineParser cliParser = new GnuParser();

    //Parse the command line
    CommandLine cmd = cliParser.parse(options, args);

    if (!validateOptions(cmd)) {
        logger.severe(
                "Syntax:  java <class_name> -url https://<server>:port/<context>/ -user <user> -password <password> -project \"<project_area>\"");
        logger.severe(
                "Example: java RTCFormSample -url https://exmple.com:9443/ccm -user ADMIN -password ADMIN -project \"JKE Banking (Change Management)\"");
        return;
    }

    String webContextUrl = cmd.getOptionValue("url");
    String user = cmd.getOptionValue("user");
    String passwd = cmd.getOptionValue("password");
    String projectArea = cmd.getOptionValue("project");

    try {

        //STEP 1: Initialize a Jazz rootservices helper and indicate we're looking for the ChangeManagement catalog
        //RTC contains a service provider for CM and SCM, so we need to indicate our interest in CM
        JazzRootServicesHelper helper = new JazzRootServicesHelper(webContextUrl, OSLCConstants.OSLC_CM_V2);

        //STEP 2: Create a new Form Auth client with the supplied user/password
        JazzFormAuthClient client = helper.initFormClient(user, passwd);

        //STEP 3: Login in to Jazz Server
        if (client.formLogin() == HttpStatus.SC_OK) {

            //STEP 4: Get the URL of the OSLC ChangeManagement catalog
            String catalogUrl = helper.getCatalogUrl();

            //STEP 5: Find the OSLC Service Provider for the project area we want to work with
            String serviceProviderUrl = client.lookupServiceProviderUrl(catalogUrl, projectArea);

            //STEP 6: Get the Query Capabilities URL so that we can run some OSLC queries
            String queryCapability = client.lookupQueryCapability(serviceProviderUrl, OSLCConstants.OSLC_CM_V2,
                    OSLCConstants.CM_CHANGE_REQUEST_TYPE);

            //SCENARIO A: Run a query for all open ChangeRequests with OSLC paging of 10 items per
            //page turned on and list the members of the result
            OslcQueryParameters queryParams = new OslcQueryParameters();
            queryParams.setWhere("oslc_cm:closed=false");
            queryParams.setSelect("dcterms:identifier,dcterms:title,oslc_cm:status");
            OslcQuery query = new OslcQuery(client, queryCapability, 10, queryParams);

            OslcQueryResult result = query.submit();

            boolean processAsJavaObjects = true;
            processPagedQueryResults(result, client, processAsJavaObjects);

            System.out.println("\n------------------------------\n");

            //SCENARIO B:  Run a query for a specific ChangeRequest selecting only certain 
            //attributes and then print it as raw XML.  Change the dcterms:identifier below to match a 
            //real workitem in your RTC project area
            OslcQueryParameters queryParams2 = new OslcQueryParameters();
            queryParams2.setWhere("dcterms:identifier=\"10\"");
            queryParams2.setSelect(
                    "dcterms:identifier,dcterms:title,dcterms:creator,dcterms:created,oslc_cm:status");
            OslcQuery query2 = new OslcQuery(client, queryCapability, queryParams2);

            OslcQueryResult result2 = query2.submit();
            ClientResponse rawResponse = result2.getRawResponse();
            processRawResponse(rawResponse);
            rawResponse.consumeContent();

            //SCENARIO C:  RTC Workitem creation and update
            ChangeRequest changeRequest = new ChangeRequest();
            changeRequest.setTitle("Implement accessibility in Pet Store application");
            changeRequest.setDescription(
                    "Image elements must provide a description in the 'alt' attribute for consumption by screen readers.");
            changeRequest.addTestedByTestCase(new Link(new URI("http://qmprovider/testcase/1"),
                    "Accessibility verification using a screen reader"));
            changeRequest.addDctermsType("task");

            //Get the Creation Factory URL for change requests so that we can create one
            String changeRequestCreation = client.lookupCreationFactory(serviceProviderUrl,
                    OSLCConstants.OSLC_CM_V2, changeRequest.getRdfTypes()[0].toString());

            //Create the change request
            ClientResponse creationResponse = client.createResource(changeRequestCreation, changeRequest,
                    OslcMediaType.APPLICATION_RDF_XML, OslcMediaType.APPLICATION_RDF_XML);
            String changeRequestLocation = creationResponse.getHeaders().getFirst(HttpHeaders.LOCATION);
            creationResponse.consumeContent();
            System.out.println("Change Request created a location " + changeRequestLocation);

            //Get the change request from the service provider and update its title property 
            changeRequest = client.getResource(changeRequestLocation, OslcMediaType.APPLICATION_RDF_XML)
                    .getEntity(ChangeRequest.class);
            changeRequest.setTitle(changeRequest.getTitle() + " (updated)");

            //Create a partial update URL so that only the title will be updated.
            //Assuming (for readability) that the change request URL does not already contain a '?'
            String updateUrl = changeRequest.getAbout() + "?oslc.properties=dcterms:title";

            //Update the change request at the service provider
            ClientResponse updateResponse = client.updateResource(updateUrl, changeRequest,
                    OslcMediaType.APPLICATION_RDF_XML, OslcMediaType.APPLICATION_RDF_XML);

            updateResponse.consumeContent();

        }
    } catch (RootServicesException re) {
        logger.log(Level.SEVERE,
                "Unable to access the Jazz rootservices document at: " + webContextUrl + "/rootservices", re);
    } catch (Exception e) {
        logger.log(Level.SEVERE, e.getMessage(), e);
    }

}

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

/**
 * @param args// w  w  w  .j  av  a 2s.c  om
 */
public static void main(String... args) throws IOException { // create command line Options object
    Options options = new Options();
    Option opt = new Option(OPT_INFILE, true,
            "input file oe-supported Use .sdf|.smi to specify the file type.");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_OUTFILE, true, "output file oe-supported. Use .sdf|.smi to specify the file type.");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_ESTATE_COUNT, false, "Output the the counts (occurrence) for each E-state atom group."
            + " E-state counts will be output if no output option is specified");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_ESTATE_SUM, false, "Output the sum of the E-state indices for each E-state atom group"
            + " in addition to the output of the" + " E-state atom groups.");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_ESTATE_SYMBOL, false, "Output the E-state atom group symbol");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_UNASSIGNED_ATOMS, false,
            "Output atoms in the given molecules that" + " could not be assigned to an E-state atom group");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_UNASSIGNED_COUNT, false, "Output the number of atoms in the given molecules that"
            + " could not be assigned to an E-state atom group");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_ESTATE_INDICE, false,
            "Output the E-state indice of all atoms in the given molecule" + " in one field.");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_SMARTS, true, "Description of the group of interest. If specified, the"
            + " E-state indice of atoms matching the SMARTS are output" + " in separated fields.");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_PRINT_DETAILS, false, "Output the details of the calculation to stderr");
    opt.setRequired(false);
    options.addOption(opt);

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        System.err.println(e.getMessage());
        exitWithHelp(options);
    }
    args = cmd.getArgs();

    if (cmd.hasOption("d")) {
        System.err.println("Start debugger and press return:");
        new BufferedReader(new InputStreamReader(System.in)).readLine();
    }

    String inFile = cmd.getOptionValue(OPT_INFILE);
    String outFile = cmd.getOptionValue(OPT_OUTFILE);
    String smarts = cmd.getOptionValue(OPT_SMARTS);
    boolean outputESIndex = cmd.hasOption(OPT_ESTATE_INDICE);
    boolean outputESCount = cmd.hasOption(OPT_ESTATE_COUNT);
    boolean outputESSum = cmd.hasOption(OPT_ESTATE_SUM);
    boolean outputESSymbol = cmd.hasOption(OPT_ESTATE_SYMBOL);
    boolean outputUnkCount = cmd.hasOption(OPT_UNASSIGNED_COUNT);
    boolean outputUnkAtoms = cmd.hasOption(OPT_UNASSIGNED_ATOMS);
    boolean printDetails = cmd.hasOption(OPT_PRINT_DETAILS);
    SDFEStateCalculator calculator = new SDFEStateCalculator(outFile);

    if (!outputESCount && !outputESSum && !outputUnkCount && !outputESSymbol && !outputESIndex
            && (smarts == null || smarts.length() == 0))
        outputESCount = true;

    try {
        calculator.prepare(outputESCount, outputESSum, outputESSymbol, outputUnkCount, outputUnkAtoms,
                outputESIndex, smarts, printDetails);
        calculator.run(inFile);
    } finally {
        calculator.close();
    }
}