Example usage for java.io BufferedReader readLine

List of usage examples for java.io BufferedReader readLine

Introduction

In this page you can find the example usage for java.io BufferedReader readLine.

Prototype

public String readLine() throws IOException 

Source Link

Document

Reads a line of text.

Usage

From source file:GenericClient.java

public static void main(String[] args) throws IOException {
    try {/* w  w w  .  j  a  v a 2s  .  c  o  m*/
        // Check the number of arguments
        if (args.length != 2)
            throw new IllegalArgumentException("Wrong number of args");

        // Parse the host and port specifications
        String host = args[0];
        int port = Integer.parseInt(args[1]);

        // Connect to the specified host and port
        Socket s = new Socket(host, port);

        // Set up streams for reading from and writing to the server.
        // The from_server stream is final for use in the inner class below
        final Reader from_server = new InputStreamReader(s.getInputStream());
        PrintWriter to_server = new PrintWriter(s.getOutputStream());

        // Set up streams for reading from and writing to the console
        // The to_user stream is final for use in the anonymous class below
        BufferedReader from_user = new BufferedReader(new InputStreamReader(System.in));
        // Pass true for auto-flush on println()
        final PrintWriter to_user = new PrintWriter(System.out, true);

        // Tell the user that we've connected
        to_user.println("Connected to " + s.getInetAddress() + ":" + s.getPort());

        // Create a thread that gets output from the server and displays
        // it to the user. We use a separate thread for this so that we
        // can receive asynchronous output
        Thread t = new Thread() {
            public void run() {
                char[] buffer = new char[1024];
                int chars_read;
                try {
                    // Read characters from the server until the
                    // stream closes, and write them to the console
                    while ((chars_read = from_server.read(buffer)) != -1) {
                        to_user.write(buffer, 0, chars_read);
                        to_user.flush();
                    }
                } catch (IOException e) {
                    to_user.println(e);
                }

                // When the server closes the connection, the loop above
                // will end. Tell the user what happened, and call
                // System.exit(), causing the main thread to exit along
                // with this one.
                to_user.println("Connection closed by server.");
                System.exit(0);
            }
        };

        // Now start the server-to-user thread
        t.start();

        // In parallel, read the user's input and pass it on to the server.
        String line;
        while ((line = from_user.readLine()) != null) {
            to_server.print(line + "\r\n");
            to_server.flush();
        }

        // If the user types a Ctrl-D (Unix) or Ctrl-Z (Windows) to end
        // their input, we'll get an EOF, and the loop above will exit.
        // When this happens, we stop the server-to-user thread and close
        // the socket.

        s.close();
        to_user.println("Connection closed by client.");
        System.exit(0);
    }
    // If anything goes wrong, print an error message
    catch (Exception e) {
        System.err.println(e);
        System.err.println("Usage: java GenericClient <hostname> <port>");
    }
}

From source file:edu.nyu.vida.data_polygamy.feature_identification.IndexCreation.java

/**
 * @param args//w  w w  . j  av a  2s .co  m
 */
@SuppressWarnings({ "deprecation" })
public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {

    Options options = new Options();

    Option forceOption = new Option("f", "force", false,
            "force the computation of the index and events " + "even if files already exist");
    forceOption.setRequired(false);
    options.addOption(forceOption);

    Option thresholdOption = new Option("t", "use-custom-thresholds", false,
            "use custom thresholds for regular and rare events, defined in HDFS_HOME/"
                    + FrameworkUtils.thresholdDir + " file");
    thresholdOption.setRequired(false);
    options.addOption(thresholdOption);

    Option gOption = new Option("g", "group", true,
            "set group of datasets for which the indices and events" + " will be computed");
    gOption.setRequired(true);
    gOption.setArgName("GROUP");
    gOption.setArgs(Option.UNLIMITED_VALUES);
    options.addOption(gOption);

    Option machineOption = new Option("m", "machine", true, "machine identifier");
    machineOption.setRequired(true);
    machineOption.setArgName("MACHINE");
    machineOption.setArgs(1);
    options.addOption(machineOption);

    Option nodesOption = new Option("n", "nodes", true, "number of nodes");
    nodesOption.setRequired(true);
    nodesOption.setArgName("NODES");
    nodesOption.setArgs(1);
    options.addOption(nodesOption);

    Option s3Option = new Option("s3", "s3", false, "data on Amazon S3");
    s3Option.setRequired(false);
    options.addOption(s3Option);

    Option awsAccessKeyIdOption = new Option("aws_id", "aws-id", true,
            "aws access key id; " + "this is required if the execution is on aws");
    awsAccessKeyIdOption.setRequired(false);
    awsAccessKeyIdOption.setArgName("AWS-ACCESS-KEY-ID");
    awsAccessKeyIdOption.setArgs(1);
    options.addOption(awsAccessKeyIdOption);

    Option awsSecretAccessKeyOption = new Option("aws_key", "aws-id", true,
            "aws secrect access key; " + "this is required if the execution is on aws");
    awsSecretAccessKeyOption.setRequired(false);
    awsSecretAccessKeyOption.setArgName("AWS-SECRET-ACCESS-KEY");
    awsSecretAccessKeyOption.setArgs(1);
    options.addOption(awsSecretAccessKeyOption);

    Option bucketOption = new Option("b", "s3-bucket", true,
            "bucket on s3; " + "this is required if the execution is on aws");
    bucketOption.setRequired(false);
    bucketOption.setArgName("S3-BUCKET");
    bucketOption.setArgs(1);
    options.addOption(bucketOption);

    Option helpOption = new Option("h", "help", false, "display this message");
    helpOption.setRequired(false);
    options.addOption(helpOption);

    HelpFormatter formatter = new HelpFormatter();
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;

    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        formatter.printHelp("hadoop jar data-polygamy.jar "
                + "edu.nyu.vida.data_polygamy.feature_identification.IndexCreation", options, true);
        System.exit(0);
    }

    if (cmd.hasOption("h")) {
        formatter.printHelp("hadoop jar data-polygamy.jar "
                + "edu.nyu.vida.data_polygamy.feature_identification.IndexCreation", options, true);
        System.exit(0);
    }

    boolean s3 = cmd.hasOption("s3");
    String s3bucket = "";
    String awsAccessKeyId = "";
    String awsSecretAccessKey = "";

    if (s3) {
        if ((!cmd.hasOption("aws_id")) || (!cmd.hasOption("aws_key")) || (!cmd.hasOption("b"))) {
            System.out.println(
                    "Arguments 'aws_id', 'aws_key', and 'b'" + " are mandatory if execution is on AWS.");
            formatter.printHelp("hadoop jar data-polygamy.jar "
                    + "edu.nyu.vida.data_polygamy.feature_identification.IndexCreation", options, true);
            System.exit(0);
        }
        s3bucket = cmd.getOptionValue("b");
        awsAccessKeyId = cmd.getOptionValue("aws_id");
        awsSecretAccessKey = cmd.getOptionValue("aws_key");
    }

    boolean snappyCompression = false;
    boolean bzip2Compression = false;
    String machine = cmd.getOptionValue("m");
    int nbNodes = Integer.parseInt(cmd.getOptionValue("n"));

    Configuration s3conf = new Configuration();
    if (s3) {
        s3conf.set("fs.s3.awsAccessKeyId", awsAccessKeyId);
        s3conf.set("fs.s3.awsSecretAccessKey", awsSecretAccessKey);
        s3conf.set("bucket", s3bucket);
    }

    String datasetNames = "";
    String datasetIds = "";

    ArrayList<String> shortDataset = new ArrayList<String>();
    ArrayList<String> shortDatasetIndex = new ArrayList<String>();
    HashMap<String, String> datasetAgg = new HashMap<String, String>();
    HashMap<String, String> datasetId = new HashMap<String, String>();
    HashMap<String, HashMap<Integer, Double>> datasetRegThreshold = new HashMap<String, HashMap<Integer, Double>>();
    HashMap<String, HashMap<Integer, Double>> datasetRareThreshold = new HashMap<String, HashMap<Integer, Double>>();

    Path path = null;
    FileSystem fs = FileSystem.get(new Configuration());
    BufferedReader br;

    boolean removeExistingFiles = cmd.hasOption("f");
    boolean isThresholdUserDefined = cmd.hasOption("t");

    for (String dataset : cmd.getOptionValues("g")) {

        // getting aggregates
        String[] aggregate = FrameworkUtils.searchAggregates(dataset, s3conf, s3);
        if (aggregate.length == 0) {
            System.out.println("No aggregates found for " + dataset + ".");
            continue;
        }

        // getting aggregates header
        String aggregatesHeaderFileName = FrameworkUtils.searchAggregatesHeader(dataset, s3conf, s3);
        if (aggregatesHeaderFileName == null) {
            System.out.println("No aggregate header for " + dataset);
            continue;
        }

        String aggregatesHeader = s3bucket + FrameworkUtils.preProcessingDir + "/" + aggregatesHeaderFileName;

        shortDataset.add(dataset);
        datasetId.put(dataset, null);

        if (s3) {
            path = new Path(aggregatesHeader);
            fs = FileSystem.get(path.toUri(), s3conf);
        } else {
            path = new Path(fs.getHomeDirectory() + "/" + aggregatesHeader);
        }

        br = new BufferedReader(new InputStreamReader(fs.open(path)));
        datasetAgg.put(dataset, br.readLine().split("\t")[1]);
        br.close();
        if (s3)
            fs.close();
    }

    if (shortDataset.size() == 0) {
        System.out.println("No datasets to process.");
        System.exit(0);
    }

    // getting dataset id

    if (s3) {
        path = new Path(s3bucket + FrameworkUtils.datasetsIndexDir);
        fs = FileSystem.get(path.toUri(), s3conf);
    } else {
        path = new Path(fs.getHomeDirectory() + "/" + FrameworkUtils.datasetsIndexDir);
    }
    br = new BufferedReader(new InputStreamReader(fs.open(path)));
    String line = br.readLine();
    while (line != null) {
        String[] dt = line.split("\t");
        if (datasetId.containsKey(dt[0])) {
            datasetId.put(dt[0], dt[1]);
            datasetNames += dt[0] + ",";
            datasetIds += dt[1] + ",";
        }
        line = br.readLine();
    }
    br.close();

    datasetNames = datasetNames.substring(0, datasetNames.length() - 1);
    datasetIds = datasetIds.substring(0, datasetIds.length() - 1);
    Iterator<String> it = shortDataset.iterator();
    while (it.hasNext()) {
        String dataset = it.next();
        if (datasetId.get(dataset) == null) {
            System.out.println("No dataset id for " + dataset);
            System.exit(0);
        }
    }

    // getting user defined thresholds

    if (isThresholdUserDefined) {
        if (s3) {
            path = new Path(s3bucket + FrameworkUtils.thresholdDir);
            fs = FileSystem.get(path.toUri(), s3conf);
        } else {
            path = new Path(fs.getHomeDirectory() + "/" + FrameworkUtils.thresholdDir);
        }
        br = new BufferedReader(new InputStreamReader(fs.open(path)));
        line = br.readLine();
        while (line != null) {
            // getting dataset name
            String dataset = line.trim();
            HashMap<Integer, Double> regThresholds = new HashMap<Integer, Double>();
            HashMap<Integer, Double> rareThresholds = new HashMap<Integer, Double>();
            line = br.readLine();
            while ((line != null) && (line.split("\t").length > 1)) {
                // getting attribute ids and thresholds
                String[] keyVals = line.trim().split("\t");
                int att = Integer.parseInt(keyVals[0].trim());
                regThresholds.put(att, Double.parseDouble(keyVals[1].trim()));
                rareThresholds.put(att, Double.parseDouble(keyVals[2].trim()));
                line = br.readLine();
            }
            datasetRegThreshold.put(dataset, regThresholds);
            datasetRareThreshold.put(dataset, rareThresholds);
        }
        br.close();
    }
    if (s3)
        fs.close();

    // datasets that will use existing merge tree
    ArrayList<String> useMergeTree = new ArrayList<String>();

    // creating index for each spatio-temporal resolution

    FrameworkUtils.createDir(s3bucket + FrameworkUtils.indexDir, s3conf, s3);

    HashSet<String> input = new HashSet<String>();

    for (String dataset : shortDataset) {

        String indexCreationOutputFileName = s3bucket + FrameworkUtils.indexDir + "/" + dataset + "/";
        String mergeTreeFileName = s3bucket + FrameworkUtils.mergeTreeDir + "/" + dataset + "/";

        if (removeExistingFiles) {
            FrameworkUtils.removeFile(indexCreationOutputFileName, s3conf, s3);
            FrameworkUtils.removeFile(mergeTreeFileName, s3conf, s3);
            FrameworkUtils.createDir(mergeTreeFileName, s3conf, s3);
        } else if (datasetRegThreshold.containsKey(dataset)) {
            FrameworkUtils.removeFile(indexCreationOutputFileName, s3conf, s3);
            if (FrameworkUtils.fileExists(mergeTreeFileName, s3conf, s3)) {
                useMergeTree.add(dataset);
            }
        }

        if (!FrameworkUtils.fileExists(indexCreationOutputFileName, s3conf, s3)) {
            input.add(s3bucket + FrameworkUtils.aggregatesDir + "/" + dataset);
            shortDatasetIndex.add(dataset);
        }

    }

    if (input.isEmpty()) {
        System.out.println("All the input datasets have indices.");
        System.out.println("Use -f in the beginning of the command line to force the computation.");
        System.exit(0);
    }

    String aggregateDatasets = "";
    it = input.iterator();
    while (it.hasNext()) {
        aggregateDatasets += it.next() + ",";
    }

    Job icJob = null;
    Configuration icConf = new Configuration();
    Machine machineConf = new Machine(machine, nbNodes);

    String jobName = "index";
    String indexOutputDir = s3bucket + FrameworkUtils.indexDir + "/tmp/";

    FrameworkUtils.removeFile(indexOutputDir, s3conf, s3);

    icConf.set("dataset-name", datasetNames);
    icConf.set("dataset-id", datasetIds);

    if (!useMergeTree.isEmpty()) {
        String useMergeTreeStr = "";
        for (String dt : useMergeTree) {
            useMergeTreeStr += dt + ",";
        }
        icConf.set("use-merge-tree", useMergeTreeStr.substring(0, useMergeTreeStr.length() - 1));
    }

    for (int i = 0; i < shortDataset.size(); i++) {
        String dataset = shortDataset.get(i);
        String id = datasetId.get(dataset);
        icConf.set("dataset-" + id + "-aggregates", datasetAgg.get(dataset));
        if (datasetRegThreshold.containsKey(dataset)) {
            HashMap<Integer, Double> regThresholds = datasetRegThreshold.get(dataset);
            String thresholds = "";
            for (int att : regThresholds.keySet()) {
                thresholds += String.valueOf(att) + "-" + String.valueOf(regThresholds.get(att)) + ",";
            }
            icConf.set("regular-" + id, thresholds.substring(0, thresholds.length() - 1));
        }

        if (datasetRareThreshold.containsKey(dataset)) {
            HashMap<Integer, Double> rareThresholds = datasetRareThreshold.get(dataset);
            String thresholds = "";
            for (int att : rareThresholds.keySet()) {
                thresholds += String.valueOf(att) + "-" + String.valueOf(rareThresholds.get(att)) + ",";
            }
            icConf.set("rare-" + id, thresholds.substring(0, thresholds.length() - 1));
        }
    }

    icConf.set("mapreduce.tasktracker.map.tasks.maximum", String.valueOf(machineConf.getMaximumTasks()));
    icConf.set("mapreduce.tasktracker.reduce.tasks.maximum", String.valueOf(machineConf.getMaximumTasks()));
    icConf.set("mapreduce.jobtracker.maxtasks.perjob", "-1");
    icConf.set("mapreduce.reduce.shuffle.parallelcopies", "20");
    icConf.set("mapreduce.input.fileinputformat.split.minsize", "0");
    icConf.set("mapreduce.task.io.sort.mb", "200");
    icConf.set("mapreduce.task.io.sort.factor", "100");
    //icConf.set("mapreduce.task.timeout", "1800000");
    machineConf.setMachineConfiguration(icConf);

    if (s3) {
        machineConf.setMachineConfiguration(icConf);
        icConf.set("fs.s3.awsAccessKeyId", awsAccessKeyId);
        icConf.set("fs.s3.awsSecretAccessKey", awsSecretAccessKey);
        icConf.set("bucket", s3bucket);
    }

    if (snappyCompression) {
        icConf.set("mapreduce.map.output.compress", "true");
        icConf.set("mapreduce.map.output.compress.codec", "org.apache.hadoop.io.compress.SnappyCodec");
        //icConf.set("mapreduce.output.fileoutputformat.compress.codec", "org.apache.hadoop.io.compress.SnappyCodec");
    }
    if (bzip2Compression) {
        icConf.set("mapreduce.map.output.compress", "true");
        icConf.set("mapreduce.map.output.compress.codec", "org.apache.hadoop.io.compress.BZip2Codec");
        //icConf.set("mapreduce.output.fileoutputformat.compress.codec", "org.apache.hadoop.io.compress.BZip2Codec");
    }

    icJob = new Job(icConf);
    icJob.setJobName(jobName);

    icJob.setMapOutputKeyClass(AttributeResolutionWritable.class);
    icJob.setMapOutputValueClass(SpatioTemporalFloatWritable.class);
    icJob.setOutputKeyClass(AttributeResolutionWritable.class);
    icJob.setOutputValueClass(TopologyTimeSeriesWritable.class);
    //icJob.setOutputKeyClass(Text.class);
    //icJob.setOutputValueClass(Text.class);

    icJob.setMapperClass(IndexCreationMapper.class);
    icJob.setReducerClass(IndexCreationReducer.class);
    icJob.setNumReduceTasks(machineConf.getNumberReduces());

    icJob.setInputFormatClass(SequenceFileInputFormat.class);
    //icJob.setOutputFormatClass(SequenceFileOutputFormat.class);
    LazyOutputFormat.setOutputFormatClass(icJob, SequenceFileOutputFormat.class);
    //LazyOutputFormat.setOutputFormatClass(icJob, TextOutputFormat.class);
    SequenceFileOutputFormat.setCompressOutput(icJob, true);
    SequenceFileOutputFormat.setOutputCompressionType(icJob, CompressionType.BLOCK);

    FileInputFormat.setInputDirRecursive(icJob, true);
    FileInputFormat.setInputPaths(icJob, aggregateDatasets.substring(0, aggregateDatasets.length() - 1));
    FileOutputFormat.setOutputPath(icJob, new Path(indexOutputDir));

    icJob.setJarByClass(IndexCreation.class);

    long start = System.currentTimeMillis();
    icJob.submit();
    icJob.waitForCompletion(true);
    System.out.println(jobName + "\t" + (System.currentTimeMillis() - start));

    // moving files to right place
    for (String dataset : shortDatasetIndex) {
        String from = s3bucket + FrameworkUtils.indexDir + "/tmp/" + dataset + "/";
        String to = s3bucket + FrameworkUtils.indexDir + "/" + dataset + "/";
        FrameworkUtils.renameFile(from, to, s3conf, s3);
    }

}

From source file:cz.cesnet.shongo.connector.device.CiscoMCUConnector.java

/**
 * An example of interaction with the device.
 * <p/>// ww w . ja v  a  2s .  c  o  m
 * Just for debugging purposes.
 *
 * @param args
 * @throws IOException
 */
public static void main(String[] args) throws IOException, CommandException, CommandUnsupportedException {
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

    final String address;
    final String username;
    final String password;

    if (args.length > 0) {
        address = args[0];
    } else {
        System.out.print("address: ");
        address = in.readLine();
    }

    if (args.length > 1) {
        username = args[1];
    } else {
        System.out.print("username: ");
        username = in.readLine();
    }

    if (args.length > 2) {
        password = args[2];
    } else {
        System.out.print("password: ");
        password = in.readLine();
    }

    CiscoMCUConnector connector = new CiscoMCUConnector();
    connector.connect(DeviceAddress.parseAddress(address), username, password);

    // Participant snapshot
    //MediaData mediaData = connector.getRoomParticipantSnapshots("YY-shongo-local-qgotdi", "4");
    //System.out.println(mediaData.getType() + " " + mediaData.getData());

    // Room status by multiple threads
    /*List<Thread> threads = new LinkedList<Thread>();
    for (int i = 0; i < 2; i++ ) {
    Thread thread = new Thread() {
        @Override
        public void run()
        {
            try {
                Room shongoTestRoom = conn.getRoom("shongo-test");
                System.out.println("shongo-test room:");
                System.out.println(shongoTestRoom);
            }
            catch (CommandException exception) {
                exception.printStackTrace();
            }
            super.run();
        }
    };
    thread.start();
    threads.add(thread);
    }
    for (Thread thread : threads) {
    try {
        thread.join();
    }
    catch (InterruptedException exception) {
        exception.printStackTrace();
    }
    }*/

    // gatekeeper status
    //        Map<String, Object> gkInfo = conn.execApi(new Command("gatekeeper.query"));
    //        System.out.println("Gatekeeper status: " + gkInfo.get("gatekeeperUsage"));

    // test of listRooms() command
    //        Collection<RoomInfo> roomList = conn.listRooms();
    //        System.out.println("Existing rooms:");
    //        for (RoomInfo room : roomList) {
    //            System.out.printf("  - %s (%s, started at %s, owned by %s)\n", room.getCode(), room.getType(),
    //                    room.getStartDateTime(), room.getOwner());
    //        }

    // test that the second enumeration query fills data that has not changed and therefore were not transferred
    //        Command enumParticipantsCmd = new Command("participant.enumerate");
    //        enumParticipantsCmd.setParameter("operationScope", new String[]{"currentState"});
    //        enumParticipantsCmd.setParameter("enumerateFilter", "connected");
    //        List<Map<String, Object>> participants = conn.execApiEnumerate(enumParticipantsCmd, "participants");
    //        List<Map<String, Object>> participants2 = conn.execApiEnumerate(enumParticipantsCmd, "participants");

    // test that the second enumeration query fills data that has not changed and therefore were not transferred
    //        Command enumConfCmd = new Command("conference.enumerate");
    //        enumConfCmd.setParameter("moreThanFour", Boolean.TRUE);
    //        enumConfCmd.setParameter("enumerateFilter", "completed");
    //        List<Map<String, Object>> confs = conn.execApiEnumerate(enumConfCmd, "conferences");
    //        List<Map<String, Object>> confs2 = conn.execApiEnumerate(enumConfCmd, "conferences");

    // test of getRoom() command
    //        Room shongoTestRoom = conn.getRoom("shongo-test");
    //        System.out.println("shongo-test room:");
    //        System.out.println(shongoTestRoom);

    // test of deleteRoom() command
    //        Collection<RoomInfo> roomList = conn.listRooms();
    //        System.out.println("Existing rooms:");
    //        for (RoomInfo room : roomList) {
    //            System.out.println(room);
    //        }
    //        System.out.println("Deleting 'shongo-test'");
    //        conn.deleteRoom("shongo-test");
    //        roomList = conn.listRooms();
    //        System.out.println("Existing rooms:");
    //        for (RoomInfo room : roomList) {
    //            System.out.println(room);
    //        }

    // test of createRoom() method
    //        Room newRoom = new Room("shongo-test9", 5);
    //        newRoom.addAlias(new Alias(Technology.H323, AliasType.E164, "950087209"));
    //        newRoom.setOption(Room.OPT_DESCRIPTION, "Shongo testing room");
    //        newRoom.setOption(Room.OPT_LISTED_PUBLICLY, true);
    //        String newRoomId = conn.createRoom(newRoom);
    //        System.out.println("Created room " + newRoomId);
    //        Collection<RoomInfo> roomList = conn.listRooms();
    //        System.out.println("Existing rooms:");
    //        for (RoomInfo room : roomList) {
    //            System.out.println(room);
    //        }

    // test of bad caching
    //        Room newRoom = new Room("shongo-testX", 5);
    //        String newRoomId = conn.createRoom(newRoom);
    //        System.out.println("Created room " + newRoomId);
    //        Collection<RoomSummary> roomList = conn.listRooms();
    //        System.out.println("Existing rooms:");
    //        for (RoomSummary roomSummary : roomList) {
    //            System.out.println(roomSummary);
    //        }
    //        conn.deleteRoom(newRoomId);
    //        System.out.println("Deleted room " + newRoomId);
    //        Map<String, Object> atts = new HashMap<String, Object>();
    //        atts.put(Room.NAME, "shongo-testing");
    //        String changedRoomId = conn.modifyRoom("shongo-test", atts, null);
    //        Collection<RoomSummary> newRoomList = conn.listRooms();
    //        System.out.println("Existing rooms:");
    //        for (RoomSummary roomSummary : newRoomList) {
    //            System.out.println(roomSummary);
    //        }
    //        atts = new HashMap<String, Object>();
    //        atts.put(Room.NAME, "shongo-test");
    //        conn.modifyRoom(changedRoomId, atts, null);

    // test of modifyRoom() method
    //        System.out.println("Modifying shongo-test");
    //        Map<String, Object> atts = new HashMap<String, Object>();
    //        atts.put(Room.NAME, "shongo-testing");
    //        Map<Room.Option, Object> opts = new EnumMap<Room.Option, Object>(Room.Option.class);
    //        opts.put(Room.Option.LISTED_PUBLICLY, false);
    //        opts.put(Room.Option.PIN, "1234");
    //        conn.modifyRoom("shongo-test", atts, opts);
    //        Map<String, Object> atts2 = new HashMap<String, Object>();
    //        atts2.put(Room.ALIASES, Collections.singletonList(new Alias(Technology.H323, AliasType.E164, "950087201")));
    //        atts2.put(Room.NAME, "shongo-test");
    //        conn.modifyRoom("shongo-testing", atts2, null);

    // test of listRoomParticipants() method
    //        System.out.println("Listing shongo-test room:");
    //        Collection<RoomParticipant> shongoUsers = conn.listRoomParticipants("shongo-test");
    //        for (RoomParticipant ru : shongoUsers) {
    //            System.out.println("  - " + ru.getUserId() + " (" + ru.getDisplayName() + ")");
    //        }
    //        System.out.println("Listing done");

    // user connect by alias
    //        String ruId = conn.dialRoomParticipant("shongo-test", new Alias(Technology.H323, AliasType.E164, "950081038"));
    //        System.out.println("Added user " + ruId);
    // user connect by address
    //        String ruId2 = conn.dialRoomParticipant("shongo-test", "147.251.54.102");
    // user disconnect
    //        conn.disconnectRoomParticipant("shongo-test", "participant1");

    //        System.out.println("All done, disconnecting");

    // test of modifyRoomParticipant
    //        Map<String, Object> attributes = new HashMap<String, Object>();
    //        attributes.put(RoomParticipant.VIDEO_ENABLED, Boolean.TRUE);
    //        attributes.put(RoomParticipant.DISPLAY_NAME, "Ondrej Bouda");
    //        conn.modifyRoomParticipant("shongo-test", "3447", attributes);

    //Room room = conn.getRoom("shongo-test");

    connector.disconnect();
}

From source file:AdminExample.java

public static void main(String[] args) {
    HttpURLConnection connection = null;
    StringBuilder response = new StringBuilder();

    //We are using Jackson JSON parser to serialize and deserialize the JSON. See http://wiki.fasterxml.com/JacksonHome
    //Feel free to use which ever library you prefer.
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    String accessToken = "";//Insert your access token here. Note this must be from an account that is an Admin of an account.
    String user1Email = ""; //You need access to these two email account.
    String user2Email = ""; //Note Gmail and Hotmail allow email aliasing. 
    //joe@gmail.com will get email sent to joe+user1@gmail.com 

    try {/*from w  w w . j av  a 2  s  .  c  o m*/
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Adding user " + user1Email);

        //Add the users:
        User user = new User();
        user.setEmail(user1Email);
        user.setAdmin(false);
        user.setLicensedSheetCreator(true);

        connection = (HttpURLConnection) new URL(USERS_URL).openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), user);
        Result<User> newUser1Result = mapper.readValue(connection.getInputStream(),
                new TypeReference<Result<User>>() {
                });
        System.out.println(
                "User " + newUser1Result.result.email + " added with userId " + newUser1Result.result.getId());

        user = new User();
        user.setEmail(user2Email);
        user.setAdmin(true);
        user.setLicensedSheetCreator(true);

        connection = (HttpURLConnection) new URL(USERS_URL).openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), user);
        Result<User> newUser2Result = mapper.readValue(connection.getInputStream(),
                new TypeReference<Result<User>>() {
                });
        System.out.println(
                "User " + newUser2Result.result.email + " added with userId " + newUser2Result.result.getId());
        System.out.println("Please visit the email inbox for the users " + user1Email + " and  " + user2Email
                + " and confirm membership to the account.");
        System.out.print("Press Enter to continue");
        in.readLine();

        //List all the users of the org
        connection = (HttpURLConnection) new URL(USERS_URL).openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        List<User> users = mapper.readValue(connection.getInputStream(), new TypeReference<List<User>>() {
        });

        System.out.println("The following are members of your account: ");

        for (User orgUser : users) {
            System.out.println("\t" + orgUser.getEmail());
        }

        //Create a sheet as the admin
        Sheet newSheet = new Sheet();
        newSheet.setName("Admin's Sheet");
        newSheet.setColumns(Arrays.asList(new Column("Column 1", "TEXT_NUMBER", null, true, null),
                new Column("Column 2", "TEXT_NUMBER", null, null, null),
                new Column("Column 3", "TEXT_NUMBER", null, null, null)));
        connection = (HttpURLConnection) new URL(SHEETS_URL).openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), newSheet);
        mapper.readValue(connection.getInputStream(), new TypeReference<Result<Sheet>>() {
        });

        //Create a sheet as user1
        newSheet = new Sheet();
        newSheet.setName("User 1's Sheet");
        newSheet.setColumns(Arrays.asList(new Column("Column 1", "TEXT_NUMBER", null, true, null),
                new Column("Column 2", "TEXT_NUMBER", null, null, null),
                new Column("Column 3", "TEXT_NUMBER", null, null, null)));
        connection = (HttpURLConnection) new URL(SHEETS_URL).openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        //Here is where the magic happens - Any action performed in this call will be on behalf of the
        //user provided. Note that this person must be a confirmed member of your org. 
        //Also note that the email address is url-encoded.
        connection.addRequestProperty("Assume-User", URLEncoder.encode(user1Email, "UTF-8"));
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), newSheet);
        mapper.readValue(connection.getInputStream(), new TypeReference<Result<Sheet>>() {
        });

        //Create a sheet as user2
        newSheet = new Sheet();
        newSheet.setName("User 2's Sheet");
        newSheet.setColumns(Arrays.asList(new Column("Column 1", "TEXT_NUMBER", null, true, null),
                new Column("Column 2", "TEXT_NUMBER", null, null, null),
                new Column("Column 3", "TEXT_NUMBER", null, null, null)));
        connection = (HttpURLConnection) new URL(SHEETS_URL).openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Assume-User", URLEncoder.encode(user2Email, "UTF-8"));
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), newSheet);
        mapper.readValue(connection.getInputStream(), new TypeReference<Result<Sheet>>() {
        });

        //List all the sheets in the org:
        System.out.println("The following sheets are owned by members of your account: ");
        connection = (HttpURLConnection) new URL(USERS_SHEETS_URL).openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        List<Sheet> allSheets = mapper.readValue(connection.getInputStream(), new TypeReference<List<Sheet>>() {
        });

        for (Sheet orgSheet : allSheets) {
            System.out.println("\t" + orgSheet.getName() + " - " + orgSheet.getOwner());
        }

        //Now delete user1 and transfer their sheets to user2
        connection = (HttpURLConnection) new URL(USER_URL.replace(ID, newUser1Result.getResult().getId() + "")
                + "?transferTo=" + newUser2Result.getResult().getId()).openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Assume-User", URLEncoder.encode(user2Email, "UTF-8"));
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setRequestMethod("DELETE");
        Result<Object> resultObject = mapper.readValue(connection.getInputStream(),
                new TypeReference<Result<Object>>() {
                });

        System.out.println("Sheets transferred : " + resultObject.getSheetsTransferred());

    } catch (IOException e) {

        InputStream is = connection == null ? null : ((HttpURLConnection) connection).getErrorStream();
        if (is != null) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            String line;
            try {
                response = new StringBuilder();
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();
                Result<?> result = mapper.readValue(response.toString(), Result.class);
                System.err.println(result.message);

            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
        e.printStackTrace();

    } catch (Exception e) {
        System.out.println("Something broke: " + e.getMessage());
        e.printStackTrace();
    }
}

From source file:msgsend.java

public static void main(String[] argv) {
    String to, subject = null, from = null, cc = null, bcc = null, url = null;
    String mailhost = null;//from ww w  . ja va 2  s .  co m
    String mailer = "msgsend";
    String file = null;
    String protocol = null, host = null, user = null, password = null;
    String record = null; // name of folder in which to record mail
    boolean debug = false;
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    int optind;

    /*
     * Process command line arguments.
     */
    for (optind = 0; optind < argv.length; optind++) {
        if (argv[optind].equals("-T")) {
            protocol = argv[++optind];
        } else if (argv[optind].equals("-H")) {
            host = argv[++optind];
        } else if (argv[optind].equals("-U")) {
            user = argv[++optind];
        } else if (argv[optind].equals("-P")) {
            password = argv[++optind];
        } else if (argv[optind].equals("-M")) {
            mailhost = argv[++optind];
        } else if (argv[optind].equals("-f")) {
            record = argv[++optind];
        } else if (argv[optind].equals("-a")) {
            file = argv[++optind];
        } else if (argv[optind].equals("-s")) {
            subject = argv[++optind];
        } else if (argv[optind].equals("-o")) { // originator
            from = argv[++optind];
        } else if (argv[optind].equals("-c")) {
            cc = argv[++optind];
        } else if (argv[optind].equals("-b")) {
            bcc = argv[++optind];
        } else if (argv[optind].equals("-L")) {
            url = argv[++optind];
        } else if (argv[optind].equals("-d")) {
            debug = true;
        } else if (argv[optind].equals("--")) {
            optind++;
            break;
        } else if (argv[optind].startsWith("-")) {
            System.out.println("Usage: msgsend [[-L store-url] | [-T prot] [-H host] [-U user] [-P passwd]]");
            System.out.println("\t[-s subject] [-o from-address] [-c cc-addresses] [-b bcc-addresses]");
            System.out.println("\t[-f record-mailbox] [-M transport-host] [-a attach-file] [-d] [address]");
            System.exit(1);
        } else {
            break;
        }
    }

    try {
        /*
         * Prompt for To and Subject, if not specified.
         */
        if (optind < argv.length) {
            // XXX - concatenate all remaining arguments
            to = argv[optind];
            System.out.println("To: " + to);
        } else {
            System.out.print("To: ");
            System.out.flush();
            to = in.readLine();
        }
        if (subject == null) {
            System.out.print("Subject: ");
            System.out.flush();
            subject = in.readLine();
        } else {
            System.out.println("Subject: " + subject);
        }

        /*
         * Initialize the JavaMail Session.
         */
        Properties props = System.getProperties();
        // XXX - could use Session.getTransport() and Transport.connect()
        // XXX - assume we're using SMTP
        if (mailhost != null)
            props.put("mail.smtp.host", mailhost);

        // Get a Session object
        Session session = Session.getInstance(props, null);
        if (debug)
            session.setDebug(true);

        /*
         * Construct the message and send it.
         */
        Message msg = new MimeMessage(session);
        if (from != null)
            msg.setFrom(new InternetAddress(from));
        else
            msg.setFrom();

        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        if (cc != null)
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        if (bcc != null)
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));

        msg.setSubject(subject);

        String text = collect(in);

        if (file != null) {
            // Attach the specified file.
            // We need a multipart message to hold the attachment.
            MimeBodyPart mbp1 = new MimeBodyPart();
            mbp1.setText(text);
            MimeBodyPart mbp2 = new MimeBodyPart();
            mbp2.attachFile(file);
            MimeMultipart mp = new MimeMultipart();
            mp.addBodyPart(mbp1);
            mp.addBodyPart(mbp2);
            msg.setContent(mp);
        } else {
            // If the desired charset is known, you can use
            // setText(text, charset)
            msg.setText(text);
        }

        msg.setHeader("X-Mailer", mailer);
        msg.setSentDate(new Date());

        // send the thing off
        Transport.send(msg);

        System.out.println("\nMail was sent successfully.");

        /*
         * Save a copy of the message, if requested.
         */
        if (record != 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();
            }

            // Get record Folder.  Create if it does not exist.
            Folder folder = store.getFolder(record);
            if (folder == null) {
                System.err.println("Can't get record folder.");
                System.exit(1);
            }
            if (!folder.exists())
                folder.create(Folder.HOLDS_MESSAGES);

            Message[] msgs = new Message[1];
            msgs[0] = msg;
            folder.appendMessages(msgs);

            System.out.println("Mail was recorded successfully.");
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:DIA_Umpire_Quant.DIA_Umpire_Quant.java

/**
 * @param args the command line arguments
 *//*  w  w w. j  ava  2 s. c  om*/
public static void main(String[] args) throws FileNotFoundException, IOException, Exception {
    System.out.println(
            "=================================================================================================");
    System.out.println("DIA-Umpire quantitation with targeted re-extraction analysis (version: "
            + UmpireInfo.GetInstance().Version + ")");
    if (args.length != 1) {
        System.out.println(
                "command format error, it should be like: java -jar -Xmx10G DIA_Umpire_Quant.jar diaumpire_quant.params");
        return;
    }
    try {
        ConsoleLogger.SetConsoleLogger(Level.INFO);
        ConsoleLogger.SetFileLogger(Level.DEBUG, FilenameUtils.getFullPath(args[0]) + "diaumpire_quant.log");
    } catch (Exception e) {
    }

    try {

        Logger.getRootLogger().info("Version: " + UmpireInfo.GetInstance().Version);
        Logger.getRootLogger().info("Parameter file:" + args[0]);

        BufferedReader reader = new BufferedReader(new FileReader(args[0]));
        String line = "";
        String WorkFolder = "";
        int NoCPUs = 2;

        String UserMod = "";
        String Combined_Prot = "";
        String InternalLibID = "";
        String ExternalLibPath = "";
        String ExternalLibDecoyTag = "DECOY";
        boolean DefaultProtFiltering = true;
        boolean DataSetLevelPepFDR = false;
        float ProbThreshold = 0.99f;
        float ExtProbThreshold = 0.99f;
        float Freq = 0f;
        int TopNPep = 6;
        int TopNFrag = 6;
        float MinFragMz = 200f;
        String FilterWeight = "GW";
        float MinWeight = 0.9f;
        float RTWindow_Int = -1f;
        float RTWindow_Ext = -1f;

        TandemParam tandemPara = new TandemParam(DBSearchParam.SearchInstrumentType.TOF5600);
        HashMap<String, File> AssignFiles = new HashMap<>();
        boolean InternalLibSearch = false;
        boolean ExternalLibSearch = false;

        boolean ExportSaint = false;
        boolean SAINT_MS1 = false;
        boolean SAINT_MS2 = true;

        HashMap<String, String[]> BaitList = new HashMap<>();
        HashMap<String, String> BaitName = new HashMap<>();
        HashMap<String, String[]> ControlList = new HashMap<>();
        HashMap<String, String> ControlName = new HashMap<>();

        //<editor-fold defaultstate="collapsed" desc="Reading parameter file">
        while ((line = reader.readLine()) != null) {
            line = line.trim();
            Logger.getRootLogger().info(line);
            if (!"".equals(line) && !line.startsWith("#")) {
                //System.out.println(line);
                if (line.equals("==File list begin")) {
                    do {
                        line = reader.readLine();
                        line = line.trim();
                        if (line.equals("==File list end")) {
                            continue;
                        } else if (!"".equals(line)) {
                            File newfile = new File(line);
                            if (newfile.exists()) {
                                AssignFiles.put(newfile.getAbsolutePath(), newfile);
                            } else {
                                Logger.getRootLogger().info("File: " + newfile + " does not exist.");
                            }
                        }
                    } while (!line.equals("==File list end"));
                }
                if (line.split("=").length < 2) {
                    continue;
                }
                String type = line.split("=")[0].trim();
                String value = line.split("=")[1].trim();
                switch (type) {
                case "TargetedExtraction": {
                    InternalLibSearch = Boolean.parseBoolean(value);
                    break;
                }
                case "InternalLibSearch": {
                    InternalLibSearch = Boolean.parseBoolean(value);
                    break;
                }
                case "ExternalLibSearch": {
                    ExternalLibSearch = Boolean.parseBoolean(value);
                    break;
                }

                case "Path": {
                    WorkFolder = value;
                    break;
                }
                case "path": {
                    WorkFolder = value;
                    break;
                }
                case "Thread": {
                    NoCPUs = Integer.parseInt(value);
                    break;
                }
                case "Fasta": {
                    tandemPara.FastaPath = value;
                    break;
                }
                case "Combined_Prot": {
                    Combined_Prot = value;
                    break;
                }
                case "DefaultProtFiltering": {
                    DefaultProtFiltering = Boolean.parseBoolean(value);
                    break;
                }
                case "DecoyPrefix": {
                    if (!"".equals(value)) {
                        tandemPara.DecoyPrefix = value;
                    }
                    break;
                }
                case "UserMod": {
                    UserMod = value;
                    break;
                }
                case "ProteinFDR": {
                    tandemPara.ProtFDR = Float.parseFloat(value);
                    break;
                }
                case "PeptideFDR": {
                    tandemPara.PepFDR = Float.parseFloat(value);
                    break;
                }
                case "DataSetLevelPepFDR": {
                    DataSetLevelPepFDR = Boolean.parseBoolean(value);
                    break;
                }
                case "InternalLibID": {
                    InternalLibID = value;
                    break;
                }
                case "ExternalLibPath": {
                    ExternalLibPath = value;
                    break;
                }
                case "ExtProbThreshold": {
                    ExtProbThreshold = Float.parseFloat(value);
                    break;
                }
                case "RTWindow_Int": {
                    RTWindow_Int = Float.parseFloat(value);
                    break;
                }
                case "RTWindow_Ext": {
                    RTWindow_Ext = Float.parseFloat(value);
                    break;
                }
                case "ExternalLibDecoyTag": {
                    ExternalLibDecoyTag = value;
                    if (ExternalLibDecoyTag.endsWith("_")) {
                        ExternalLibDecoyTag = ExternalLibDecoyTag.substring(0,
                                ExternalLibDecoyTag.length() - 1);
                    }
                    break;
                }
                case "ProbThreshold": {
                    ProbThreshold = Float.parseFloat(value);
                    break;
                }
                case "ReSearchProb": {
                    //ReSearchProb = Float.parseFloat(value);
                    break;
                }
                case "FilterWeight": {
                    FilterWeight = value;
                    break;
                }
                case "MinWeight": {
                    MinWeight = Float.parseFloat(value);
                    break;
                }
                case "TopNFrag": {
                    TopNFrag = Integer.parseInt(value);
                    break;
                }
                case "TopNPep": {
                    TopNPep = Integer.parseInt(value);
                    break;
                }
                case "Freq": {
                    Freq = Float.parseFloat(value);
                    break;
                }
                case "MinFragMz": {
                    MinFragMz = Float.parseFloat(value);
                    break;
                }

                //<editor-fold defaultstate="collapsed" desc="SaintOutput">
                case "ExportSaintInput": {
                    ExportSaint = Boolean.parseBoolean(value);
                    break;
                }
                case "QuantitationType": {
                    switch (value) {
                    case "MS1": {
                        SAINT_MS1 = true;
                        SAINT_MS2 = false;
                        break;
                    }
                    case "MS2": {
                        SAINT_MS1 = false;
                        SAINT_MS2 = true;
                        break;
                    }
                    case "BOTH": {
                        SAINT_MS1 = true;
                        SAINT_MS2 = true;
                        break;
                    }
                    }
                    break;
                }
                //                    case "BaitInputFile": {
                //                        SaintBaitFile = value;
                //                        break;
                //                    }
                //                    case "PreyInputFile": {
                //                        SaintPreyFile = value;
                //                        break;
                //                    }
                //                    case "InterationInputFile": {
                //                        SaintInteractionFile = value;
                //                        break;
                //                    }
                default: {
                    if (type.startsWith("BaitName_")) {
                        BaitName.put(type.substring(9), value);
                    }
                    if (type.startsWith("BaitFile_")) {
                        BaitList.put(type.substring(9), value.split("\t"));
                    }
                    if (type.startsWith("ControlName_")) {
                        ControlName.put(type.substring(12), value);
                    }
                    if (type.startsWith("ControlFile_")) {
                        ControlList.put(type.substring(12), value.split("\t"));
                    }
                    break;
                }
                //</editor-fold>                    
                }
            }
        }
        //</editor-fold>

        //Initialize PTM manager using compomics library
        PTMManager.GetInstance();
        if (!UserMod.equals("")) {
            PTMManager.GetInstance().ImportUserMod(UserMod);
        }

        //Check if the fasta file can be found
        if (!new File(tandemPara.FastaPath).exists()) {
            Logger.getRootLogger().info("Fasta file :" + tandemPara.FastaPath
                    + " cannot be found, the process will be terminated, please check.");
            System.exit(1);
        }

        //Check if the prot.xml file can be found
        if (!new File(Combined_Prot).exists()) {
            Logger.getRootLogger().info("ProtXML file: " + Combined_Prot
                    + " cannot be found, the export protein summary table will be empty.");
        }

        LCMSID protID = null;

        //Parse prot.xml and generate protein master list given an FDR 
        if (Combined_Prot != null && !Combined_Prot.equals("")) {
            protID = LCMSID.ReadLCMSIDSerialization(Combined_Prot);
            if (!"".equals(Combined_Prot) && protID == null) {
                protID = new LCMSID(Combined_Prot, tandemPara.DecoyPrefix, tandemPara.FastaPath);
                ProtXMLParser protxmlparser = new ProtXMLParser(protID, Combined_Prot, 0f);
                //Use DIA-Umpire default protein FDR calculation
                if (DefaultProtFiltering) {
                    protID.RemoveLowLocalPWProtein(0.8f);
                    protID.RemoveLowMaxIniProbProtein(0.9f);
                    protID.FilterByProteinDecoyFDRUsingMaxIniProb(tandemPara.DecoyPrefix, tandemPara.ProtFDR);
                } //Get protein FDR calculation without other filtering
                else {
                    protID.FilterByProteinDecoyFDRUsingLocalPW(tandemPara.DecoyPrefix, tandemPara.ProtFDR);
                }
                protID.LoadSequence();
                protID.WriteLCMSIDSerialization(Combined_Prot);
            }
            Logger.getRootLogger().info("Protein No.:" + protID.ProteinList.size());
        }
        HashMap<String, HashMap<String, FragmentPeak>> IDSummaryFragments = new HashMap<>();

        //Generate DIA file list
        ArrayList<DIAPack> FileList = new ArrayList<>();

        File folder = new File(WorkFolder);
        if (!folder.exists()) {
            Logger.getRootLogger().info("The path : " + WorkFolder + " cannot be found.");
            System.exit(1);
        }
        for (final File fileEntry : folder.listFiles()) {
            if (fileEntry.isFile()
                    && (fileEntry.getAbsolutePath().toLowerCase().endsWith(".mzxml")
                            | fileEntry.getAbsolutePath().toLowerCase().endsWith(".mzml"))
                    && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q1.mzxml")
                    && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q2.mzxml")
                    && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q3.mzxml")) {
                AssignFiles.put(fileEntry.getAbsolutePath(), fileEntry);
            }
            if (fileEntry.isDirectory()) {
                for (final File fileEntry2 : fileEntry.listFiles()) {
                    if (fileEntry2.isFile()
                            && (fileEntry2.getAbsolutePath().toLowerCase().endsWith(".mzxml")
                                    | fileEntry2.getAbsolutePath().toLowerCase().endsWith(".mzml"))
                            && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q1.mzxml")
                            && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q2.mzxml")
                            && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q3.mzxml")) {
                        AssignFiles.put(fileEntry2.getAbsolutePath(), fileEntry2);
                    }
                }
            }
        }

        Logger.getRootLogger().info("No. of files assigned :" + AssignFiles.size());
        for (File fileEntry : AssignFiles.values()) {
            Logger.getRootLogger().info(fileEntry.getAbsolutePath());
            String mzXMLFile = fileEntry.getAbsolutePath();
            if (mzXMLFile.toLowerCase().endsWith(".mzxml") | mzXMLFile.toLowerCase().endsWith(".mzml")) {
                DIAPack DiaFile = new DIAPack(mzXMLFile, NoCPUs);
                FileList.add(DiaFile);
                HashMap<String, FragmentPeak> FragMap = new HashMap<>();
                IDSummaryFragments.put(FilenameUtils.getBaseName(mzXMLFile), FragMap);
                Logger.getRootLogger().info(
                        "=================================================================================================");
                Logger.getRootLogger().info("Processing " + mzXMLFile);
                if (!DiaFile.LoadDIASetting()) {
                    Logger.getRootLogger().info("Loading DIA setting failed, job is incomplete");
                    System.exit(1);
                }
                if (!DiaFile.LoadParams()) {
                    Logger.getRootLogger().info("Loading parameters failed, job is incomplete");
                    System.exit(1);
                }
            }
        }

        LCMSID combinePepID = null;
        if (DataSetLevelPepFDR) {
            combinePepID = LCMSID.ReadLCMSIDSerialization(WorkFolder + "combinePepID.SerFS");
            if (combinePepID == null) {
                FDR_DataSetLevel fdr = new FDR_DataSetLevel();
                fdr.GeneratePepIonList(FileList, tandemPara, WorkFolder + "combinePepID.SerFS");
                combinePepID = fdr.combineID;
                combinePepID.WriteLCMSIDSerialization(WorkFolder + "combinePepID.SerFS");
            }
        }

        //process each DIA file for quantification based on untargeted identifications
        for (DIAPack DiaFile : FileList) {
            long time = System.currentTimeMillis();
            Logger.getRootLogger().info("Loading identification results " + DiaFile.Filename + "....");

            //If the LCMSID serialization is found
            if (!DiaFile.ReadSerializedLCMSID()) {
                DiaFile.ParsePepXML(tandemPara, combinePepID);
                DiaFile.BuildStructure();
                if (!DiaFile.MS1FeatureMap.ReadPeakCluster()) {
                    Logger.getRootLogger().info("Loading peak and structure failed, job is incomplete");
                    System.exit(1);
                }
                DiaFile.MS1FeatureMap.ClearMonoisotopicPeakOfCluster();
                //Generate mapping between index of precursor feature and pseudo MS/MS scan index 
                DiaFile.GenerateClusterScanNomapping();
                //Doing quantification
                DiaFile.AssignQuant();
                DiaFile.ClearStructure();
            }
            DiaFile.IDsummary.ReduceMemoryUsage();
            time = System.currentTimeMillis() - time;
            Logger.getRootLogger().info(DiaFile.Filename + " processed time:"
                    + String.format("%d hour, %d min, %d sec", TimeUnit.MILLISECONDS.toHours(time),
                            TimeUnit.MILLISECONDS.toMinutes(time)
                                    - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(time)),
                            TimeUnit.MILLISECONDS.toSeconds(time)
                                    - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(time))));
        }

        //<editor-fold defaultstate="collapsed" desc="Targete re-extraction using internal library">            
        Logger.getRootLogger().info(
                "=================================================================================================");
        if (InternalLibSearch && FileList.size() > 1) {
            Logger.getRootLogger().info("Module C: Targeted extraction using internal library");

            FragmentLibManager libManager = FragmentLibManager.ReadFragmentLibSerialization(WorkFolder,
                    InternalLibID);
            if (libManager == null) {
                Logger.getRootLogger().info("Building internal spectral library");
                libManager = new FragmentLibManager(InternalLibID);
                ArrayList<LCMSID> LCMSIDList = new ArrayList<>();
                for (DIAPack dia : FileList) {
                    LCMSIDList.add(dia.IDsummary);
                }
                libManager.ImportFragLibTopFrag(LCMSIDList, Freq, TopNFrag);
                libManager.WriteFragmentLibSerialization(WorkFolder);
            }
            libManager.ReduceMemoryUsage();

            Logger.getRootLogger()
                    .info("Building retention time prediction model and generate candidate peptide list");
            for (int i = 0; i < FileList.size(); i++) {
                FileList.get(i).IDsummary.ClearMappedPep();
            }
            for (int i = 0; i < FileList.size(); i++) {
                for (int j = i + 1; j < FileList.size(); j++) {
                    RTAlignedPepIonMapping alignment = new RTAlignedPepIonMapping(WorkFolder,
                            FileList.get(i).GetParameter(), FileList.get(i).IDsummary,
                            FileList.get(j).IDsummary);
                    alignment.GenerateModel();
                    alignment.GenerateMappedPepIon();
                }
                FileList.get(i).ExportID();
                FileList.get(i).IDsummary = null;
            }

            Logger.getRootLogger().info("Targeted matching........");
            for (DIAPack diafile : FileList) {
                if (diafile.IDsummary == null) {
                    diafile.ReadSerializedLCMSID();
                }
                if (!diafile.IDsummary.GetMappedPepIonList().isEmpty()) {
                    diafile.UseMappedIon = true;
                    diafile.FilterMappedIonByProb = false;
                    diafile.BuildStructure();
                    diafile.MS1FeatureMap.ReadPeakCluster();
                    diafile.MS1FeatureMap.ClearMonoisotopicPeakOfCluster();
                    diafile.GenerateMassCalibrationRTMap();
                    diafile.TargetedExtractionQuant(false, libManager, 1.1f, RTWindow_Int);
                    diafile.MS1FeatureMap.ClearAllPeaks();
                    diafile.IDsummary.ReduceMemoryUsage();
                    diafile.IDsummary.RemoveLowProbMappedIon(ProbThreshold);
                    diafile.ExportID();
                    Logger.getRootLogger().info("Peptide ions: " + diafile.IDsummary.GetPepIonList().size()
                            + " Mapped ions: " + diafile.IDsummary.GetMappedPepIonList().size());
                    diafile.ClearStructure();
                }
                diafile.IDsummary = null;
                System.gc();
            }
            Logger.getRootLogger().info(
                    "=================================================================================================");
        }
        //</editor-fold>

        //<editor-fold defaultstate="collapsed" desc="Targeted re-extraction using external library">
        //External library search
        if (ExternalLibSearch) {
            Logger.getRootLogger().info("Module C: Targeted extraction using external library");

            //Read exteranl library
            FragmentLibManager ExlibManager = FragmentLibManager.ReadFragmentLibSerialization(WorkFolder,
                    FilenameUtils.getBaseName(ExternalLibPath));
            if (ExlibManager == null) {
                ExlibManager = new FragmentLibManager(FilenameUtils.getBaseName(ExternalLibPath));

                //Import traML file
                ExlibManager.ImportFragLibByTraML(ExternalLibPath, ExternalLibDecoyTag);
                //Check if there are decoy spectra
                ExlibManager.CheckDecoys();
                //ExlibManager.ImportFragLibBySPTXT(ExternalLibPath);
                ExlibManager.WriteFragmentLibSerialization(WorkFolder);
            }
            Logger.getRootLogger()
                    .info("No. of peptide ions in external lib:" + ExlibManager.PeptideFragmentLib.size());
            for (DIAPack diafile : FileList) {
                if (diafile.IDsummary == null) {
                    diafile.ReadSerializedLCMSID();
                }
                //Generate RT mapping
                RTMappingExtLib RTmap = new RTMappingExtLib(diafile.IDsummary, ExlibManager,
                        diafile.GetParameter());
                RTmap.GenerateModel();
                RTmap.GenerateMappedPepIon();

                diafile.BuildStructure();
                diafile.MS1FeatureMap.ReadPeakCluster();
                diafile.GenerateMassCalibrationRTMap();
                //Perform targeted re-extraction
                diafile.TargetedExtractionQuant(false, ExlibManager, ProbThreshold, RTWindow_Ext);
                diafile.MS1FeatureMap.ClearAllPeaks();
                diafile.IDsummary.ReduceMemoryUsage();
                //Remove target IDs below the defined probability threshold
                diafile.IDsummary.RemoveLowProbMappedIon(ExtProbThreshold);
                diafile.ExportID();
                diafile.ClearStructure();
                Logger.getRootLogger().info("Peptide ions: " + diafile.IDsummary.GetPepIonList().size()
                        + " Mapped ions: " + diafile.IDsummary.GetMappedPepIonList().size());
            }
        }
        //</editor-fold>

        //<editor-fold defaultstate="collapsed" desc="Peptide and fragment selection">
        Logger.getRootLogger().info("Peptide and fragment selection across the whole dataset");
        ArrayList<LCMSID> SummaryList = new ArrayList<>();
        for (DIAPack diafile : FileList) {
            if (diafile.IDsummary == null) {
                diafile.ReadSerializedLCMSID();
                diafile.IDsummary.ClearAssignPeakCluster();
                //diafile.IDsummary.ClearPSMs();                    
            }
            if (protID != null) {
                //Generate protein list according to mapping of peptide ions for each DIA file to the master protein list
                diafile.IDsummary.GenerateProteinByRefIDByPepSeq(protID, true);
                diafile.IDsummary.ReMapProPep();
            }
            if ("GW".equals(FilterWeight)) {
                diafile.IDsummary.SetFilterByGroupWeight();
            } else if ("PepW".equals(FilterWeight)) {
                diafile.IDsummary.SetFilterByWeight();
            }
            SummaryList.add(diafile.IDsummary);
        }
        FragmentSelection fragselection = new FragmentSelection(SummaryList);
        fragselection.freqPercent = Freq;
        fragselection.MinFragMZ = MinFragMz;
        fragselection.GeneratePepFragScoreMap();
        fragselection.GenerateTopFragMap(TopNFrag);
        fragselection.GenerateProtPepScoreMap(MinWeight);
        fragselection.GenerateTopPepMap(TopNPep);
        //</editor-fold>

        //<editor-fold defaultstate="collapsed" desc="Writing general reports">                 
        ExportTable export = new ExportTable(WorkFolder, SummaryList, IDSummaryFragments, protID,
                fragselection);
        export.Export(TopNPep, TopNFrag, Freq);
        //</editor-fold>

        //<editor-fold defaultstate="collapsed" desc="//<editor-fold defaultstate="collapsed" desc="Generate SAINT input files">
        if (ExportSaint && protID != null) {
            HashMap<String, DIAPack> Filemap = new HashMap<>();
            for (DIAPack DIAfile : FileList) {
                Filemap.put(DIAfile.GetBaseName(), DIAfile);
            }

            FileWriter baitfile = new FileWriter(WorkFolder + "SAINT_Bait_" + DateTimeTag.GetTag() + ".txt");
            FileWriter preyfile = new FileWriter(WorkFolder + "SAINT_Prey_" + DateTimeTag.GetTag() + ".txt");
            FileWriter interactionfileMS1 = null;
            FileWriter interactionfileMS2 = null;
            if (SAINT_MS1) {
                interactionfileMS1 = new FileWriter(
                        WorkFolder + "SAINT_Interaction_MS1_" + DateTimeTag.GetTag() + ".txt");
            }
            if (SAINT_MS2) {
                interactionfileMS2 = new FileWriter(
                        WorkFolder + "SAINT_Interaction_MS2_" + DateTimeTag.GetTag() + ".txt");
            }
            HashMap<String, String> PreyID = new HashMap<>();

            for (String samplekey : ControlName.keySet()) {
                String name = ControlName.get(samplekey);
                for (String file : ControlList.get(samplekey)) {
                    baitfile.write(FilenameUtils.getBaseName(file) + "\t" + name + "\t" + "C\n");
                    LCMSID IDsummary = Filemap.get(FilenameUtils.getBaseName(file)).IDsummary;
                    if (SAINT_MS1) {
                        SaintOutput(protID, IDsummary, fragselection, interactionfileMS1, file, name, PreyID,
                                1);
                    }
                    if (SAINT_MS2) {
                        SaintOutput(protID, IDsummary, fragselection, interactionfileMS2, file, name, PreyID,
                                2);
                    }
                }
            }
            for (String samplekey : BaitName.keySet()) {
                String name = BaitName.get(samplekey);
                for (String file : BaitList.get(samplekey)) {
                    baitfile.write(FilenameUtils.getBaseName(file) + "\t" + name + "\t" + "T\n");
                    LCMSID IDsummary = Filemap.get(FilenameUtils.getBaseName(file)).IDsummary;
                    if (SAINT_MS1) {
                        SaintOutput(protID, IDsummary, fragselection, interactionfileMS1, file, name, PreyID,
                                1);
                    }
                    if (SAINT_MS2) {
                        SaintOutput(protID, IDsummary, fragselection, interactionfileMS2, file, name, PreyID,
                                2);
                    }
                }
            }
            baitfile.close();
            if (SAINT_MS1) {
                interactionfileMS1.close();
            }
            if (SAINT_MS2) {
                interactionfileMS2.close();
            }
            for (String AccNo : PreyID.keySet()) {
                preyfile.write(AccNo + "\t" + PreyID.get(AccNo) + "\n");
            }
            preyfile.close();
        }

        //</editor-fold>

        Logger.getRootLogger().info("Job done");
        Logger.getRootLogger().info(
                "=================================================================================================");

    } catch (Exception e) {
        Logger.getRootLogger().error(ExceptionUtils.getStackTrace(e));
        throw e;
    }
}

From source file:net.sf.extjwnl.cli.ewn.java

public static void main(String[] args) throws IOException, JWNLException {
    if (args.length < 1) {
        System.out.println(USAGE);
        System.exit(0);/*  ww w.  ja  v a  2 s . co  m*/
    }
    //find dictionary
    Dictionary d = null;
    File config = new File(defaultConfig);
    if (!config.exists()) {
        if (System.getenv().containsKey("WNHOME")) {
            String wnHomePath = System.getenv().get("WNHOME");
            File wnHome = new File(wnHomePath);
            if (wnHome.exists()) {
                d = Dictionary.getFileBackedInstance(wnHomePath);
            } else {
                log.error("Cannot find dictionary. Make sure " + defaultConfig
                        + " is available or WNHOME variable is set.");
            }
        }
    } else {
        d = Dictionary.getInstance(new FileInputStream(config));
    }

    if (null != d) {
        //parse and execute command line
        if ((-1 < args[0].indexOf('%') && -1 < args[0].indexOf(':')) || "-script".equals(args[0])
                || (-1 < args[0].indexOf('#'))) {
            d.edit();
            //edit
            if ("-script".equals(args[0])) {
                if (args.length < 2) {
                    log.error("Filename missing for -script command");
                    System.exit(1);
                } else {
                    File script = new File(args[1]);
                    if (script.exists()) {
                        //load into args
                        ArrayList<String> newArgs = new ArrayList<String>();
                        BufferedReader in = new BufferedReader(
                                new InputStreamReader(new FileInputStream(script), "UTF-8"));
                        try {
                            String str;
                            while ((str = in.readLine()) != null) {
                                String[] bits = str.split(" ");
                                StringBuilder tempArg = null;
                                for (String bit : bits) {
                                    int quoteCnt = 0;
                                    for (int j = 0; j < bit.length(); j++) {
                                        if ('"' == bit.charAt(j)) {
                                            quoteCnt++;
                                        }
                                    }
                                    if (null != tempArg) {
                                        if (0 == quoteCnt) {
                                            tempArg.append(" ").append(bit);
                                        } else {
                                            tempArg.append(" ").append(bit.replaceAll("\"\"", "\""));
                                            if (1 == (quoteCnt % 2)) {
                                                newArgs.add(
                                                        tempArg.toString().substring(1, tempArg.length() - 1));
                                                tempArg = null;
                                            }
                                        }
                                    } else {
                                        if (0 == quoteCnt) {
                                            newArgs.add(bit);
                                        } else {
                                            if (1 == (quoteCnt % 2)) {
                                                tempArg = new StringBuilder(bit.replaceAll("\"\"", "\""));
                                            } else {
                                                newArgs.add(bit.replaceAll("\"\"", "\""));
                                            }
                                        }
                                    }
                                }
                                if (null != tempArg) {
                                    newArgs.add(tempArg.toString());
                                }
                            }
                        } finally {
                            try {
                                in.close();
                            } catch (IOException e) {
                                //nop
                            }
                        }
                        args = newArgs.toArray(args);
                    }
                }
            }

            Word workWord = null;
            String key = null;
            String lemma = null;
            int lexFileNum = -1;
            int lexId = -1;
            //                String headLemma = null;
            //                int headLexId = -1;
            POS pos = null;
            String derivation = null;

            for (int i = 0; i < args.length; i++) {
                if (null == key && '-' != args[i].charAt(0)
                        && ((-1 < args[i].indexOf('%') && -1 < args[i].indexOf(':')))) {
                    key = args[i];
                    log.info("Searching " + key + "...");
                    if (null != key) {
                        workWord = d.getWordBySenseKey(key);
                    }
                    if (null == workWord) {
                        //parse sensekey
                        lemma = key.substring(0, key.indexOf('%')).replace('_', ' ');
                        String posId = key.substring(key.indexOf('%') + 1, key.indexOf(':'));
                        if ("1".equals(posId) || "2".equals(posId) || "3".equals(posId) || "4".equals(posId)
                                || "5".equals(posId)) {
                            pos = POS.getPOSForId(Integer.parseInt(posId));
                            String lexFileString = key.substring(key.indexOf(':') + 1);
                            if (-1 < lexFileString.indexOf(':')) {
                                lexFileNum = Integer
                                        .parseInt(lexFileString.substring(0, lexFileString.indexOf(':')));
                                if (lexFileString.indexOf(':') + 1 < lexFileString.length()) {
                                    String lexIdString = lexFileString
                                            .substring(lexFileString.indexOf(':') + 1);
                                    if (-1 < lexIdString.indexOf(':')) {
                                        lexId = Integer
                                                .parseInt(lexIdString.substring(0, lexIdString.indexOf(':')));
                                        //                                            if (lexIdString.indexOf(':') + 1 < lexIdString.length()) {
                                        //                                                headLemma = lexIdString.substring(lexIdString.indexOf(':') + 1);
                                        //                                                if (-1 < headLemma.indexOf(':')) {
                                        //                                                    headLemma = headLemma.substring(0, headLemma.indexOf(':'));
                                        //                                                    if (null != headLemma && !"".equals(headLemma) && lexIdString.lastIndexOf(':') + 1 < lexIdString.length()) {
                                        //                                                        headLexId = Integer.parseInt(lexIdString.substring(lexIdString.lastIndexOf(':') + 1));
                                        //                                                    }
                                        //                                                } else {
                                        //                                                    log.error("Malformed sensekey " + key);
                                        //                                                    System.exit(1);
                                        //                                                }
                                        //                                            }
                                    } else {
                                        log.error("Malformed sensekey " + key);
                                        System.exit(1);
                                    }
                                } else {
                                    log.error("Malformed sensekey " + key);
                                    System.exit(1);
                                }
                            } else {
                                log.error("Malformed sensekey " + key);
                                System.exit(1);
                            }
                        } else {
                            log.error("Malformed sensekey " + key);
                            System.exit(1);
                        }
                    }
                } else if (-1 < args[i].indexOf('#')) {
                    if (2 < args[i].length()) {
                        derivation = args[i].substring(2);
                        if (null == derivation) {
                            log.error("Missing derivation");
                            System.exit(1);
                        } else {
                            pos = POS.getPOSForKey(args[i].substring(0, 1));
                            if (null == pos) {
                                log.error("POS " + args[i] + " is not recognized for derivation " + derivation);
                                System.exit(1);
                            }
                        }
                    }
                }

                if ("-add".equals(args[i])) {
                    if (null == key) {
                        log.error("Missing sensekey");
                        System.exit(1);
                    }
                    if (null != workWord) {
                        log.error("Duplicate sensekey " + workWord.getSenseKey());
                        System.exit(1);
                    }
                    log.info("Creating " + pos.getLabel() + " synset...");
                    Synset tempSynset = d.createSynset(pos);
                    log.info("Creating word " + lemma + "...");
                    workWord = new Word(d, tempSynset, 1, lemma);
                    workWord.setLexId(lexId);
                    tempSynset.getWords().add(workWord);
                    tempSynset.setLexFileNum(lexFileNum);
                    key = null;
                }

                if ("-remove".equals(args[i])) {
                    if (null == workWord) {
                        log.error("Missing sensekey");
                        System.exit(1);
                    } else {
                        d.removeSynset(workWord.getSynset());
                        workWord = null;
                        key = null;
                    }
                }

                if ("-addword".equals(args[i])) {
                    if (null == workWord) {
                        log.error("Missing sensekey");
                        System.exit(1);
                    } else {
                        i++;
                        if (i < args.length && '-' != args[i].charAt(0)) {
                            Word tempWord = new Word(d, workWord.getSynset(),
                                    workWord.getSynset().getWords().size() + 1, args[i]);
                            workWord.getSynset().getWords().add(tempWord);
                            key = null;
                        } else {
                            log.error(
                                    "Missing word for addword command for sensekey " + workWord.getSenseKey());
                            System.exit(1);
                        }
                    }
                }

                if ("-removeword".equals(args[i])) {
                    if (null == workWord) {
                        log.error("Missing sensekey");
                        System.exit(1);
                    } else {
                        workWord.getSynset().getWords().remove(workWord);
                        key = null;
                    }
                }

                if ("-setgloss".equals(args[i])) {
                    if (null == workWord) {
                        log.error("Missing sensekey");
                        System.exit(1);
                    } else {
                        i++;
                        if (i < args.length && '-' != args[i].charAt(0)) {
                            workWord.getSynset().setGloss(args[i]);
                            key = null;
                        } else {
                            log.error("Missing gloss for setgloss command for sensekey "
                                    + workWord.getSenseKey());
                            System.exit(1);
                        }
                    }
                }

                if ("-setadjclus".equals(args[i])) {
                    if (null == workWord) {
                        log.error("Missing sensekey");
                        System.exit(1);
                    } else {
                        i++;
                        if (i < args.length && '-' != args[i].charAt(0)) {
                            workWord.getSynset().setIsAdjectiveCluster(Boolean.parseBoolean(args[i]));
                            key = null;
                        } else {
                            log.error("Missing flag for setadjclus command for sensekey "
                                    + workWord.getSenseKey());
                            System.exit(1);
                        }
                    }
                }

                if ("-setverbframe".equals(args[i])) {
                    if (null == workWord) {
                        log.error("Missing sensekey");
                        System.exit(1);
                    } else {
                        i++;
                        if (i < args.length) {
                            if (workWord instanceof Verb) {
                                Verb verb = (Verb) workWord;
                                if ('-' == args[i].charAt(0)) {
                                    verb.getVerbFrameFlags().clear(Integer.parseInt(args[i].substring(1)));
                                } else {
                                    verb.getVerbFrameFlags().set(Integer.parseInt(args[i]));
                                }
                            } else {
                                log.error("Word at " + workWord.getSenseKey() + " should be verb");
                                System.exit(1);
                            }
                            key = null;
                        } else {
                            log.error("Missing index for setverbframe command for sensekey "
                                    + workWord.getSenseKey());
                            System.exit(1);
                        }
                    }
                }

                if ("-setverbframeall".equals(args[i])) {
                    if (null == workWord) {
                        log.error("Missing sensekey");
                        System.exit(1);
                    } else {
                        i++;
                        if (i < args.length) {
                            if (workWord.getSynset() instanceof VerbSynset) {
                                if ('-' == args[i].charAt(0)) {
                                    workWord.getSynset().getVerbFrameFlags()
                                            .clear(Integer.parseInt(args[i].substring(1)));
                                } else {
                                    workWord.getSynset().getVerbFrameFlags().set(Integer.parseInt(args[i]));
                                }
                            } else {
                                log.error("Synset at " + workWord.getSenseKey() + " should be verb");
                                System.exit(1);
                            }
                            key = null;
                        } else {
                            log.error("Missing index for setverbframeall command for sensekey "
                                    + workWord.getSenseKey());
                            System.exit(1);
                        }
                    }
                }

                if ("-setlexfile".equals(args[i])) {
                    if (null == workWord) {
                        log.error("Missing sensekey");
                        System.exit(1);
                    } else {
                        i++;
                        if (i < args.length && '-' != args[i].charAt(0)) {
                            if (-1 < args[i].indexOf('.')) {
                                workWord.getSynset()
                                        .setLexFileNum(LexFileNameLexFileIdMap.getMap().get(args[i]));
                            } else {
                                workWord.getSynset().setLexFileNum(Integer.parseInt(args[i]));
                            }
                        } else {
                            log.error("Missing file number or name for setlexfile command for sensekey "
                                    + workWord.getSenseKey());
                            System.exit(1);
                        }
                    }
                }

                if ("-addptr".equals(args[i])) {
                    if (null == workWord) {
                        log.error("Missing sensekey");
                        System.exit(1);
                    } else {
                        i++;
                        if (i < args.length) {
                            Word targetWord = d.getWordBySenseKey(args[i]);
                            if (null != targetWord) {
                                i++;
                                if (i < args.length) {
                                    PointerType pt = PointerType.getPointerTypeForKey(args[i]);
                                    if (null != pt) {
                                        Pointer p;
                                        if (pt.isLexical()) {
                                            p = new Pointer(pt, workWord, targetWord);
                                        } else {
                                            p = new Pointer(pt, workWord.getSynset(), targetWord.getSynset());
                                        }
                                        if (!workWord.getSynset().getPointers().contains(p)) {
                                            workWord.getSynset().getPointers().add(p);
                                        } else {
                                            log.error("Duplicate pointer of type " + pt + " to "
                                                    + targetWord.getSenseKey()
                                                    + " in addptr command for sensekey "
                                                    + workWord.getSenseKey());
                                            System.exit(1);
                                        }
                                    } else {
                                        log.error("Invalid pointer type at " + args[i]
                                                + " in addptr command for sensekey " + workWord.getSenseKey());
                                        System.exit(1);
                                    }
                                } else {
                                    log.error("Missing pointer type at " + args[i]
                                            + " in addptr command for sensekey " + workWord.getSenseKey());
                                    System.exit(1);
                                }
                            } else {
                                log.error("Missing target at " + args[i] + " in addptr command for sensekey "
                                        + workWord.getSenseKey());
                                System.exit(1);
                            }
                            key = null;
                        } else {
                            log.error("Missing sensekey for addptr command for sensekey "
                                    + workWord.getSenseKey());
                            System.exit(1);
                        }
                    }
                }

                if ("-removeptr".equals(args[i])) {
                    if (null == workWord) {
                        log.error("Missing sensekey");
                        System.exit(1);
                    } else {
                        i++;
                        if (i < args.length) {
                            Word targetWord = d.getWordBySenseKey(args[i]);
                            if (null != targetWord) {
                                i++;
                                if (i < args.length) {
                                    PointerType pt = PointerType.getPointerTypeForKey(args[i]);
                                    if (null != pt) {
                                        Pointer p;
                                        if (pt.isLexical()) {
                                            p = new Pointer(pt, workWord, targetWord);
                                        } else {
                                            p = new Pointer(pt, workWord.getSynset(), targetWord.getSynset());
                                        }
                                        if (workWord.getSynset().getPointers().contains(p)) {
                                            workWord.getSynset().getPointers().remove(p);
                                        } else {
                                            log.error("Missing pointer of type " + pt + " to "
                                                    + targetWord.getSenseKey()
                                                    + " in removeptr command for sensekey "
                                                    + workWord.getSenseKey());
                                            System.exit(1);
                                        }
                                    } else {
                                        log.error("Invalid pointer type at " + args[i]
                                                + " in removeptr command for sensekey "
                                                + workWord.getSenseKey());
                                        System.exit(1);
                                    }
                                } else {
                                    log.error("Missing pointer type at " + args[i]
                                            + " in removeptr command for sensekey " + workWord.getSenseKey());
                                    System.exit(1);
                                }
                            } else {
                                log.error("Missing target at " + args[i] + " in removeptr command for sensekey "
                                        + workWord.getSenseKey());
                                System.exit(1);
                            }
                            key = null;
                        } else {
                            log.error("Missing sensekey for removeptr command for sensekey "
                                    + workWord.getSenseKey());
                            System.exit(1);
                        }
                    }
                }

                if ("-setlexid".equals(args[i])) {
                    if (null == workWord) {
                        log.error("Missing sensekey");
                        System.exit(1);
                    } else {
                        i++;
                        if (i < args.length && '-' != args[i].charAt(0)) {
                            workWord.setLexId(Integer.parseInt(args[i]));
                            key = null;
                        } else {
                            log.error("Missing lexid for setlexid command for sensekey "
                                    + workWord.getSenseKey());
                            System.exit(1);
                        }
                    }
                }

                if ("-setusecount".equals(args[i])) {
                    if (null == workWord) {
                        log.error("Missing sensekey");
                        System.exit(1);
                    } else {
                        i++;
                        if (i < args.length && '-' != args[i].charAt(0)) {
                            workWord.setUseCount(Integer.parseInt(args[i]));
                            key = null;
                        } else {
                            log.error("Missing count for setusecount command for sensekey "
                                    + workWord.getSenseKey());
                            System.exit(1);
                        }
                    }
                }

                if ("-addexc".equals(args[i])) {
                    i++;
                    if (i < args.length && '-' != args[i].charAt(0)) {
                        String baseform = args[i];
                        Exc e = d.getException(pos, derivation);
                        if (null != e) {
                            if (null != e.getExceptions()) {
                                if (!e.getExceptions().contains(baseform)) {
                                    e.getExceptions().add(baseform);
                                }
                            }
                        } else {
                            ArrayList<String> list = new ArrayList<String>(1);
                            list.add(baseform);
                            d.createException(pos, derivation, list);
                        }
                        derivation = null;
                    } else {
                        log.error("Missing baseform for addexc command for derivation " + derivation);
                        System.exit(1);
                    }
                }

                if ("-removeexc".equals(args[i])) {
                    Exc e = d.getException(pos, derivation);
                    if (null != e) {
                        i++;
                        if (i < args.length && '-' != args[i].charAt(0)) {
                            String baseform = args[i];
                            if (null != e.getExceptions()) {
                                if (e.getExceptions().contains(baseform)) {
                                    e.getExceptions().remove(baseform);
                                }
                                if (0 == e.getExceptions().size()) {
                                    d.removeException(e);
                                }
                            }
                        } else {
                            d.removeException(e);
                        }
                    } else {
                        log.error("Missing derivation " + derivation);
                        System.exit(1);
                    }
                    derivation = null;
                }
            }

            d.save();
        } else {
            //browse
            String key = args[0];
            if (1 == args.length) {
                for (POS pos : POS.getAllPOS()) {
                    IndexWord iw = d.getIndexWord(pos, key);
                    if (null == iw) {
                        System.out.println("\nNo information available for " + pos.getLabel() + " " + key);
                    } else {
                        System.out.println(
                                "\nInformation available for " + iw.getPOS().getLabel() + " " + iw.getLemma());
                        printAvailableInfo(iw);
                    }
                    if (null != d.getMorphologicalProcessor()) {
                        List<String> forms = d.getMorphologicalProcessor().lookupAllBaseForms(pos, key);
                        if (null != forms) {
                            for (String form : forms) {
                                if (!key.equals(form)) {
                                    iw = d.getIndexWord(pos, form);
                                    if (null != iw) {
                                        System.out.println("\nInformation available for "
                                                + iw.getPOS().getLabel() + " " + iw.getLemma());
                                        printAvailableInfo(iw);
                                    }
                                }
                            }
                        }
                    }
                }
            } else {
                boolean needHelp = false;
                boolean needGloss = false;
                boolean needLex = false;
                boolean needOffset = false;
                boolean needSenseNum = false;
                boolean needSenseKeys = false;
                int needSense = 0;
                for (String arg : args) {
                    if ("-h".equals(arg)) {
                        needHelp = true;
                    }
                    if ("-g".equals(arg)) {
                        needGloss = true;
                    }
                    if ("-a".equals(arg)) {
                        needLex = true;
                    }
                    if ("-o".equals(arg)) {
                        needOffset = true;
                    }
                    if ("-s".equals(arg)) {
                        needSenseNum = true;
                    }
                    if ("-k".equals(arg)) {
                        needSenseKeys = true;
                    }
                    if (arg.startsWith("-n") && 2 < arg.length()) {
                        needSense = Integer.parseInt(arg.substring(2));
                    }
                }

                for (String arg : args) {
                    if (arg.startsWith("-ants") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println(
                                    "Display synsets containing direct antonyms of the search string.\n" + "\n"
                                            + "Direct antonyms are a pair of words between which there is an\n"
                                            + "associative bond built up by co-occurrences.\n" + "\n"
                                            + "Antonym synsets are preceded by \"=>\".");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nAntonyms of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.ANTONYM, 1, needSense, needGloss, needLex, needOffset,
                                    needSenseNum, needSenseKeys);
                        }
                    } //ants

                    if (arg.startsWith("-hype") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println(
                                    "Recursively display hypernym (superordinate) tree for the search\n"
                                            + "string.\n" + "\n"
                                            + "Hypernym is the generic term used to designate a whole class of\n"
                                            + "specific instances.  Y is a hypernym of X if X is a (kind of) Y.\n"
                                            + "\n"
                                            + "Hypernym synsets are preceded by \"=>\", and are indented from\n"
                                            + "the left according to their level in the hierarchy.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nHypernyms of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.HYPERNYM, PointerUtils.INFINITY, needSense, needGloss,
                                    needLex, needOffset, needSenseNum, needSenseKeys);
                        }
                    } //hype

                    if (arg.startsWith("-hypo") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println(
                                    "Display immediate hyponyms (subordinates) for the search string.\n" + "\n"
                                            + "Hyponym is the generic term used to designate a member of a class.\n"
                                            + "X is a hyponym of Y if X is a (kind of) Y.\n" + "\n"
                                            + "Hyponym synsets are preceded by \"=>\".");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nHyponyms of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.HYPONYM, 1, needSense, needGloss, needLex, needOffset,
                                    needSenseNum, needSenseKeys);
                        }
                    } //hypo

                    if (arg.startsWith("-tree") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println(
                                    "Display hyponym (subordinate) tree for the search string.  This is\n"
                                            + "a recursive search that finds the hyponyms of each hyponym. \n"
                                            + "\n"
                                            + "Hyponym is the generic term used to designate a member of a class.\n"
                                            + "X is a hyponym of Y if X is a (kind of) Y. \n" + "\n"
                                            + "Hyponym synsets are preceded by \"=>\", and are indented from the left\n"
                                            + "according to their level in the hierarchy.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nHyponyms of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.HYPONYM, PointerUtils.INFINITY, needSense, needGloss,
                                    needLex, needOffset, needSenseNum, needSenseKeys);
                        }
                    } //tree

                    if (arg.startsWith("-enta") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println(
                                    "Recursively display entailment relations of the search string.\n" + "\n"
                                            + "The action represented by the verb X entails Y if X cannot be done\n"
                                            + "unless Y is, or has been, done.\n" + "\n"
                                            + "Entailment synsets are preceded by \"=>\", and are indented from the left\n"
                                            + "according to their level in the hierarchy.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nEntailment of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.ENTAILMENT, PointerUtils.INFINITY, needSense,
                                    needGloss, needLex, needOffset, needSenseNum, needSenseKeys);
                        }
                    } //enta

                    if (arg.startsWith("-syns") && 6 == arg.length()) {
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nSynonyms of " + p.getLabel() + " " + iw.getLemma());
                            if (POS.ADJECTIVE == p) {
                                if (needHelp) {
                                    System.out.println(
                                            "Display synonyms and synsets related to synsets containing\n"
                                                    + "the search string.  If the search string is in a head synset\n"
                                                    + "the 'cluster's' satellite synsets are displayed.  If the search\n"
                                                    + "string is in a satellite synset, its head synset is displayed.\n"
                                                    + "If the search string is a pertainym the word or synset that it\n"
                                                    + "pertains to is displayed.\n" + "\n"
                                                    + "A cluster is a group of adjective synsets that are organized around\n"
                                                    + "antonymous pairs or triplets.  An adjective cluster contains two or more\n"
                                                    + "head synsets that contan antonyms.  Each head synset has one or more\n"
                                                    + "satellite synsets.\n" + "\n"
                                                    + "A head synset contains at least one word that has a direct antonym\n"
                                                    + "in another head synset of the same cluster.\n" + "\n"
                                                    + "A satellite synset represents a concept that is similar in meaning to\n"
                                                    + "the concept represented by its head synset.\n" + "\n"
                                                    + "Direct antonyms are a pair of words between which there is an\n"
                                                    + "associative bond built up by co-occurrences.\n" + "\n"
                                                    + "Direct antonyms are printed in parentheses following the adjective.\n"
                                                    + "The position of an adjective in relation to the noun may be restricted\n"
                                                    + "to the prenominal, postnominal or predicative position.  Where present\n"
                                                    + "these restrictions are noted in parentheses.\n" + "\n"
                                                    + "A pertainym is a relational adjective, usually defined by such phrases\n"
                                                    + "as \"of or pertaining to\" and that does not have an antonym.  It pertains\n"
                                                    + "to a noun or another pertainym.\n" + "\n"
                                                    + "Senses contained in head synsets are displayed above the satellites,\n"
                                                    + "which are indented and preceded by \"=>\".  Senses contained in\n"
                                                    + "satellite synsets are displayed with the head synset below.  The head\n"
                                                    + "synset is preceded by \"=>\".\n" + "\n"
                                                    + "Pertainym senses display the word or synsets that the search string\n"
                                                    + "pertains to.");
                                }
                                tracePointers(iw, PointerType.SIMILAR_TO, 1, needSense, needGloss, needLex,
                                        needOffset, needSenseNum, needSenseKeys);
                                tracePointers(iw, PointerType.PARTICIPLE_OF, 1, needSense, needGloss, needLex,
                                        needOffset, needSenseNum, needSenseKeys);
                            }

                            if (POS.ADVERB == p) {
                                if (needHelp) {
                                    System.out.println(
                                            "Display synonyms and synsets related to synsets containing\n"
                                                    + "the search string.  If the search string is a pertainym the word\n"
                                                    + "or synset that it pertains to is displayed.\n" + "\n"
                                                    + "A pertainym is a relational adverb that is derived from an adjective.\n"
                                                    + "\n"
                                                    + "Pertainym senses display the word that the search string is derived from\n"
                                                    + "and the adjective synset that contains the word.  If the adjective synset\n"
                                                    + "is a satellite synset, its head synset is also displayed.");
                                }
                                tracePointers(iw, PointerType.PERTAINYM, 1, needSense, needGloss, needLex,
                                        needOffset, needSenseNum, needSenseKeys);
                            }

                            if (POS.NOUN == p || POS.VERB == p) {
                                if (needHelp) {
                                    System.out.println(
                                            "Recursively display hypernym (superordinate) tree for the search\n"
                                                    + "string.\n" + "\n"
                                                    + "Hypernym is the generic term used to designate a whole class of\n"
                                                    + "specific instances.  Y is a hypernym of X if X is a (kind of) Y.\n"
                                                    + "\n"
                                                    + "Hypernym synsets are preceded by \"=>\", and are indented from\n"
                                                    + "the left according to their level in the hierarchy.");
                                }
                                tracePointers(iw, PointerType.HYPERNYM, PointerUtils.INFINITY, needSense,
                                        needGloss, needLex, needOffset, needSenseNum, needSenseKeys);
                            }
                        }
                    } //syns

                    if (arg.startsWith("-smem") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println("Display all holonyms of the search string.\n" + "\n"
                                    + "A holonym is the name of the whole of which the 'meronym' names a part.\n"
                                    + "Y is a holonym of X if X is a part of Y.\n" + "\n"
                                    + "A meronym is the name of a constituent part, the substance of, or a\n"
                                    + "member of something.  X is a meronym of Y if X is a part of Y.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nMember Holonyms of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.MEMBER_HOLONYM, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                        }
                    } //smem

                    if (arg.startsWith("-ssub") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println("Display all holonyms of the search string.\n" + "\n"
                                    + "A holonym is the name of the whole of which the 'meronym' names a part.\n"
                                    + "Y is a holonym of X if X is a part of Y.\n" + "\n"
                                    + "A meronym is the name of a constituent part, the substance of, or a\n"
                                    + "member of something.  X is a meronym of Y if X is a part of Y.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nSubstance Holonyms of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.SUBSTANCE_HOLONYM, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                        }
                    } //ssub

                    if (arg.startsWith("-sprt") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println("Display all holonyms of the search string.\n" + "\n"
                                    + "A holonym is the name of the whole of which the 'meronym' names a part.\n"
                                    + "Y is a holonym of X if X is a part of Y.\n" + "\n"
                                    + "A meronym is the name of a constituent part, the substance of, or a\n"
                                    + "member of something.  X is a meronym of Y if X is a part of Y.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nPart Holonyms of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.PART_HOLONYM, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                        }
                    } //sprt

                    if (arg.startsWith("-memb") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println("Display all meronyms of the search string. \n" + "\n"
                                    + "A meronym is the name of a constituent part, the substance of, or a\n"
                                    + "member of something.  X is a meronym of Y if X is a part of Y.\n" + "\n"
                                    + "A holonym is the name of the whole of which the meronym names a part.\n"
                                    + "Y is a holonym of X if X is a part of Y.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nMember Meronyms of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.MEMBER_MERONYM, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                        }
                    } //memb

                    if (arg.startsWith("-subs") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println("Display all meronyms of the search string. \n" + "\n"
                                    + "A meronym is the name of a constituent part, the substance of, or a\n"
                                    + "member of something.  X is a meronym of Y if X is a part of Y.\n" + "\n"
                                    + "A holonym is the name of the whole of which the meronym names a part.\n"
                                    + "Y is a holonym of X if X is a part of Y.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nSubstance Meronyms of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.SUBSTANCE_MERONYM, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                        }
                    } //subs

                    if (arg.startsWith("-part") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println("Display all meronyms of the search string. \n" + "\n"
                                    + "A meronym is the name of a constituent part, the substance of, or a\n"
                                    + "member of something.  X is a meronym of Y if X is a part of Y.\n" + "\n"
                                    + "A holonym is the name of the whole of which the meronym names a part.\n"
                                    + "Y is a holonym of X if X is a part of Y.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nPart Meronyms of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.PART_MERONYM, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                        }
                    } //part

                    if (arg.startsWith("-mero") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println("Display all meronyms of the search string. \n" + "\n"
                                    + "A meronym is the name of a constituent part, the substance of, or a\n"
                                    + "member of something.  X is a meronym of Y if X is a part of Y.\n" + "\n"
                                    + "A holonym is the name of the whole of which the meronym names a part.\n"
                                    + "Y is a holonym of X if X is a part of Y.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nMeronyms of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.MEMBER_MERONYM, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                            tracePointers(iw, PointerType.SUBSTANCE_MERONYM, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                            tracePointers(iw, PointerType.PART_MERONYM, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                        }
                    } //mero

                    if (arg.startsWith("-holo") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println("Display all holonyms of the search string.\n" + "\n"
                                    + "A holonym is the name of the whole of which the 'meronym' names a part.\n"
                                    + "Y is a holonym of X if X is a part of Y.\n" + "\n"
                                    + "A meronym is the name of a constituent part, the substance of, or a\n"
                                    + "member of something.  X is a meronym of Y if X is a part of Y.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nHolonyms of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.MEMBER_HOLONYM, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                            tracePointers(iw, PointerType.SUBSTANCE_HOLONYM, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                            tracePointers(iw, PointerType.PART_HOLONYM, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                        }
                    } //holo

                    if (arg.startsWith("-caus") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println("Recursively display CAUSE TO relations of the search string.\n"
                                    + "\n"
                                    + "The action represented by the verb X causes the action represented by\n"
                                    + "the verb Y.\n" + "\n"
                                    + "CAUSE TO synsets are preceded by \"=>\", and are indented from the left\n"
                                    + "according to their level in the hierarchy.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\n'Cause to' of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.CAUSE, PointerUtils.INFINITY, needSense, needGloss,
                                    needLex, needOffset, needSenseNum, needSenseKeys);
                        }
                    } //caus

                    if (arg.startsWith("-pert") && 6 == arg.length()) {
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nPertainyms of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.PERTAINYM, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                        }
                    } //pert

                    if (arg.startsWith("-attr") && 6 == arg.length()) {
                        POS p = POS.getPOSForKey(arg.substring(5));
                        if (needHelp) {
                            if (POS.NOUN == p) {
                                System.out
                                        .println("Display adjectives for which search string is an attribute.");
                            }
                            if (POS.ADJECTIVE == p) {
                                System.out.println("Display nouns that are attributes of search string.");
                            }
                        }
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nAttributes of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.ATTRIBUTE, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                        }
                    } //attr

                    if (arg.startsWith("-deri") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println(
                                    "Display derived forms - nouns and verbs that are related morphologically.\n"
                                            + "Each related synset is preceeded by its part of speech. Each word in the\n"
                                            + "synset is followed by its sense number.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nDerived forms of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.NOMINALIZATION, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                        }
                    } //deri

                    if (arg.startsWith("-domn") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println("Display domain to which this synset belongs.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nDomain of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.CATEGORY, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                            tracePointers(iw, PointerType.USAGE, 1, needSense, needGloss, needLex, needOffset,
                                    needSenseNum, needSenseKeys);
                            tracePointers(iw, PointerType.REGION, 1, needSense, needGloss, needLex, needOffset,
                                    needSenseNum, needSenseKeys);
                        }
                    } //domn

                    if (arg.startsWith("-domt") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println("Display all synsets belonging to the domain.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nDomain of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.CATEGORY_MEMBER, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                            tracePointers(iw, PointerType.USAGE_MEMBER, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                            tracePointers(iw, PointerType.REGION_MEMBER, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                        }
                    } //domt

                    if (arg.startsWith("-faml") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println(
                                    "Display familiarity and polysemy information for the search string.\n"
                                            + "The polysemy count is the number of senses in WordNet.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            String[] freqs = { "extremely rare", "very rare", "rare", "uncommon", "common",
                                    "familiar", "very familiar", "extremely familiar" };
                            String[] pos = { "a noun", "a verb", "an adjective", "an adverb" };
                            int cnt = iw.getSenses().size();
                            int familiar = 0;
                            if (cnt == 0) {
                                familiar = 0;
                            }
                            if (cnt == 1) {
                                familiar = 1;
                            }
                            if (cnt == 2) {
                                familiar = 2;
                            }
                            if (cnt >= 3 && cnt <= 4) {
                                familiar = 3;
                            }
                            if (cnt >= 5 && cnt <= 8) {
                                familiar = 4;
                            }
                            if (cnt >= 9 && cnt <= 16) {
                                familiar = 5;
                            }
                            if (cnt >= 17 && cnt <= 32) {
                                familiar = 6;
                            }
                            if (cnt > 32) {
                                familiar = 7;
                            }
                            System.out.println("\n" + iw.getLemma() + " used as " + pos[p.getId() - 1] + " is "
                                    + freqs[familiar] + " (polysemy count = " + cnt + ")");
                        }
                    } //faml

                    if (arg.startsWith("-fram") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println(
                                    "Display applicable verb sentence frames for the search string.\n" + "\n"
                                            + "A frame is a sentence template illustrating the usage of a verb.\n"
                                            + "\n"
                                            + "Verb sentence frames are preceded with the string \"*>\" if a sentence\n"
                                            + "frame is acceptable for all of the words in the synset, and with \"=>\"\n"
                                            + "if a sentence frame is acceptable for the search string only.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nVerb frames of " + p.getLabel() + " " + iw.getLemma());
                            for (int i = 0; i < iw.getSenses().size(); i++) {
                                Synset synset = iw.getSenses().get(i);
                                for (String vf : synset.getVerbFrames()) {
                                    System.out.println("\t*> " + vf);
                                }
                                for (Word word : synset.getWords()) {
                                    if (iw.getLemma().equalsIgnoreCase(word.getLemma())) {
                                        if (word instanceof Verb) {
                                            Verb verb = (Verb) word;
                                            for (String vf : verb.getVerbFrames()) {
                                                System.out.println("\t=> " + vf);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    } //fram

                    if (arg.startsWith("-hmer") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println(
                                    "Display meronyms for search string tree.  This is a recursive search\n"
                                            + "the prints all the meronyms of the search string and all of its\n"
                                            + "hypernyms. \n" + "\n"
                                            + "A meronym is the name of a constituent part, the substance of, or a\n"
                                            + "member of something.  X is a meronym of Y if X is a part of Y.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nMeronyms of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.MEMBER_MERONYM, PointerUtils.INFINITY, needSense,
                                    needGloss, needLex, needOffset, needSenseNum, needSenseKeys);
                            tracePointers(iw, PointerType.SUBSTANCE_MERONYM, PointerUtils.INFINITY, needSense,
                                    needGloss, needLex, needOffset, needSenseNum, needSenseKeys);
                            tracePointers(iw, PointerType.PART_MERONYM, PointerUtils.INFINITY, needSense,
                                    needGloss, needLex, needOffset, needSenseNum, needSenseKeys);
                        }
                    } //hmer

                    if (arg.startsWith("-hhol") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println(
                                    "\"Display holonyms for search string tree.  This is a recursive search\n"
                                            + "that prints all the holonyms of the search string and all of the\n"
                                            + "holonym's holonyms.\n" + "\n"
                                            + "A holonym is the name of the whole of which the meronym names a part.\n"
                                            + "Y is a holonym of X if X is a part of Y.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nHolonyms of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.MEMBER_HOLONYM, PointerUtils.INFINITY, needSense,
                                    needGloss, needLex, needOffset, needSenseNum, needSenseKeys);
                            tracePointers(iw, PointerType.SUBSTANCE_HOLONYM, PointerUtils.INFINITY, needSense,
                                    needGloss, needLex, needOffset, needSenseNum, needSenseKeys);
                            tracePointers(iw, PointerType.PART_HOLONYM, PointerUtils.INFINITY, needSense,
                                    needGloss, needLex, needOffset, needSenseNum, needSenseKeys);
                        }
                    } //hhol

                    if (arg.startsWith("-mero") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out.println("Display all meronyms of the search string. \n" + "\n"
                                    + "A meronym is the name of a constituent part, the substance of, or a\n"
                                    + "member of something.  X is a meronym of Y if X is a part of Y.\n" + "\n"
                                    + "A holonym is the name of the whole of which the meronym names a part.\n"
                                    + "Y is a holonym of X if X is a part of Y.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        IndexWord iw = d.lookupIndexWord(p, key);
                        if (null != iw) {
                            System.out.println("\nMeronyms of " + p.getLabel() + " " + iw.getLemma());
                            tracePointers(iw, PointerType.MEMBER_MERONYM, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                            tracePointers(iw, PointerType.SUBSTANCE_MERONYM, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                            tracePointers(iw, PointerType.PART_MERONYM, 1, needSense, needGloss, needLex,
                                    needOffset, needSenseNum, needSenseKeys);
                        }
                    } //mero

                    if (arg.startsWith("-grep") && 6 == arg.length()) {
                        if (needHelp) {
                            System.out
                                    .println("Print all strings in the database containing the search string\n"
                                            + "as an individual word, or as the first or last string in a word or\n"
                                            + "collocation.");
                        }
                        POS p = POS.getPOSForKey(arg.substring(5));
                        System.out.println("\nGrep of " + p.getLabel() + " " + key);
                        Iterator<IndexWord> ii = d.getIndexWordIterator(p, key);
                        while (ii.hasNext()) {
                            System.out.println(ii.next().getLemma());
                        }
                    } //grep

                    if ("-over".equals(arg)) {
                        for (POS pos : POS.getAllPOS()) {
                            if (null != d.getMorphologicalProcessor()) {
                                IndexWord iw = d.getIndexWord(pos, key);
                                //for plurals like species, glasses
                                if (null != iw && key.equals(iw.getLemma())) {
                                    printOverview(pos, iw, needGloss, needLex, needOffset, needSenseNum,
                                            needSenseKeys);
                                }

                                List<String> forms = d.getMorphologicalProcessor().lookupAllBaseForms(pos, key);
                                if (null != forms) {
                                    for (String form : forms) {
                                        if (!form.equals(key)) {
                                            iw = d.getIndexWord(pos, form);
                                            if (null != iw) {
                                                printOverview(pos, iw, needGloss, needLex, needOffset,
                                                        needSenseNum, needSenseKeys);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    } //over
                }
            }
        }
    }
}

From source file:smtpsend.java

public static void main(String[] argv) {
    String to, subject = null, from = null, cc = null, bcc = null, url = null;
    String mailhost = null;/* w ww  .ja v  a 2s  . c o  m*/
    String mailer = "smtpsend";
    String file = null;
    String protocol = null, host = null, user = null, password = null;
    String record = null; // name of folder in which to record mail
    boolean debug = false;
    boolean verbose = false;
    boolean auth = false;
    boolean ssl = false;
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    int optind;

    for (optind = 0; optind < argv.length; optind++) {
        if (argv[optind].equals("-T")) {
            protocol = argv[++optind];
        } else if (argv[optind].equals("-H")) {
            host = argv[++optind];
        } else if (argv[optind].equals("-U")) {
            user = argv[++optind];
        } else if (argv[optind].equals("-P")) {
            password = argv[++optind];
        } else if (argv[optind].equals("-M")) {
            mailhost = argv[++optind];
        } else if (argv[optind].equals("-f")) {
            record = argv[++optind];
        } else if (argv[optind].equals("-a")) {
            file = argv[++optind];
        } else if (argv[optind].equals("-s")) {
            subject = argv[++optind];
        } else if (argv[optind].equals("-o")) { // originator
            from = argv[++optind];
        } else if (argv[optind].equals("-c")) {
            cc = argv[++optind];
        } else if (argv[optind].equals("-b")) {
            bcc = argv[++optind];
        } else if (argv[optind].equals("-L")) {
            url = argv[++optind];
        } else if (argv[optind].equals("-d")) {
            debug = true;
        } else if (argv[optind].equals("-v")) {
            verbose = true;
        } else if (argv[optind].equals("-A")) {
            auth = true;
        } else if (argv[optind].equals("-S")) {
            ssl = true;
        } else if (argv[optind].equals("--")) {
            optind++;
            break;
        } else if (argv[optind].startsWith("-")) {
            System.out.println("Usage: smtpsend [[-L store-url] | [-T prot] [-H host] [-U user] [-P passwd]]");
            System.out.println("\t[-s subject] [-o from-address] [-c cc-addresses] [-b bcc-addresses]");
            System.out.println("\t[-f record-mailbox] [-M transport-host] [-d] [-a attach-file]");
            System.out.println("\t[-v] [-A] [-S] [address]");
            System.exit(1);
        } else {
            break;
        }
    }

    try {
        if (optind < argv.length) {
            // XXX - concatenate all remaining arguments
            to = argv[optind];
            System.out.println("To: " + to);
        } else {
            System.out.print("To: ");
            System.out.flush();
            to = in.readLine();
        }
        if (subject == null) {
            System.out.print("Subject: ");
            System.out.flush();
            subject = in.readLine();
        } else {
            System.out.println("Subject: " + subject);
        }

        Properties props = System.getProperties();
        if (mailhost != null)
            props.put("mail.smtp.host", mailhost);
        if (auth)
            props.put("mail.smtp.auth", "true");

        // Get a Session object
        Session session = Session.getInstance(props, null);
        if (debug)
            session.setDebug(true);

        // construct the message
        Message msg = new MimeMessage(session);
        if (from != null)
            msg.setFrom(new InternetAddress(from));
        else
            msg.setFrom();

        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        if (cc != null)
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        if (bcc != null)
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));

        msg.setSubject(subject);

        String text = collect(in);

        if (file != null) {
            // Attach the specified file.
            // We need a multipart message to hold the attachment.
            MimeBodyPart mbp1 = new MimeBodyPart();
            mbp1.setText(text);
            MimeBodyPart mbp2 = new MimeBodyPart();
            mbp2.attachFile(file);
            MimeMultipart mp = new MimeMultipart();
            mp.addBodyPart(mbp1);
            mp.addBodyPart(mbp2);
            msg.setContent(mp);
        } else {
            // If the desired charset is known, you can use
            // setText(text, charset)
            msg.setText(text);
        }

        msg.setHeader("X-Mailer", mailer);
        msg.setSentDate(new Date());

        // send the thing off
        /*
         * The simple way to send a message is this:
         * 
         * Transport.send(msg);
         * 
         * But we're going to use some SMTP-specific features for demonstration
         * purposes so we need to manage the Transport object explicitly.
         */
        SMTPTransport t = (SMTPTransport) session.getTransport(ssl ? "smtps" : "smtp");
        try {
            if (auth)
                t.connect(mailhost, user, password);
            else
                t.connect();
            t.sendMessage(msg, msg.getAllRecipients());
        } finally {
            if (verbose)
                System.out.println("Response: " + t.getLastServerResponse());
            t.close();
        }

        System.out.println("\nMail was sent successfully.");

        // Keep a copy, if requested.

        if (record != 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();
            }

            // Get record Folder. Create if it does not exist.
            Folder folder = store.getFolder(record);
            if (folder == null) {
                System.err.println("Can't get record folder.");
                System.exit(1);
            }
            if (!folder.exists())
                folder.create(Folder.HOLDS_MESSAGES);

            Message[] msgs = new Message[1];
            msgs[0] = msg;
            folder.appendMessages(msgs);

            System.out.println("Mail was recorded successfully.");
        }

    } catch (Exception e) {
        if (e instanceof SendFailedException) {
            MessagingException sfe = (MessagingException) e;
            if (sfe instanceof SMTPSendFailedException) {
                SMTPSendFailedException ssfe = (SMTPSendFailedException) sfe;
                System.out.println("SMTP SEND FAILED:");
                if (verbose)
                    System.out.println(ssfe.toString());
                System.out.println("  Command: " + ssfe.getCommand());
                System.out.println("  RetCode: " + ssfe.getReturnCode());
                System.out.println("  Response: " + ssfe.getMessage());
            } else {
                if (verbose)
                    System.out.println("Send failed: " + sfe.toString());
            }
            Exception ne;
            while ((ne = sfe.getNextException()) != null && ne instanceof MessagingException) {
                sfe = (MessagingException) ne;
                if (sfe instanceof SMTPAddressFailedException) {
                    SMTPAddressFailedException ssfe = (SMTPAddressFailedException) sfe;
                    System.out.println("ADDRESS FAILED:");
                    if (verbose)
                        System.out.println(ssfe.toString());
                    System.out.println("  Address: " + ssfe.getAddress());
                    System.out.println("  Command: " + ssfe.getCommand());
                    System.out.println("  RetCode: " + ssfe.getReturnCode());
                    System.out.println("  Response: " + ssfe.getMessage());
                } else if (sfe instanceof SMTPAddressSucceededException) {
                    System.out.println("ADDRESS SUCCEEDED:");
                    SMTPAddressSucceededException ssfe = (SMTPAddressSucceededException) sfe;
                    if (verbose)
                        System.out.println(ssfe.toString());
                    System.out.println("  Address: " + ssfe.getAddress());
                    System.out.println("  Command: " + ssfe.getCommand());
                    System.out.println("  RetCode: " + ssfe.getReturnCode());
                    System.out.println("  Response: " + ssfe.getMessage());
                }
            }
        } else {
            System.out.println("Got Exception: " + e);
            if (verbose)
                e.printStackTrace();
        }
    }
}

From source file:smtpsend.java

/**
 * Example of how to extend the SMTPTransport class.
 * This example illustrates how to issue the XACT
 * command before the SMTPTransport issues the DATA
 * command.// w  w  w  .  j av a2  s.  com
 *
public static class SMTPExtension extends SMTPTransport {
public SMTPExtension(Session session, URLName url) {
   super(session, url);
   // to check that we're being used
   System.out.println("SMTPExtension: constructed");
}
        
protected synchronized OutputStream data() throws MessagingException {
   if (supportsExtension("XACCOUNTING"))
  issueCommand("XACT", 250);
   return super.data();
}
}
 */

public static void main(String[] argv) {
    String to, subject = null, from = null, cc = null, bcc = null, url = null;
    String mailhost = null;
    String mailer = "smtpsend";
    String file = null;
    String protocol = null, host = null, user = null, password = null;
    String record = null; // name of folder in which to record mail
    boolean debug = false;
    boolean verbose = false;
    boolean auth = false;
    String prot = "smtp";
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    int optind;

    /*
     * Process command line arguments.
     */
    for (optind = 0; optind < argv.length; optind++) {
        if (argv[optind].equals("-T")) {
            protocol = argv[++optind];
        } else if (argv[optind].equals("-H")) {
            host = argv[++optind];
        } else if (argv[optind].equals("-U")) {
            user = argv[++optind];
        } else if (argv[optind].equals("-P")) {
            password = argv[++optind];
        } else if (argv[optind].equals("-M")) {
            mailhost = argv[++optind];
        } else if (argv[optind].equals("-f")) {
            record = argv[++optind];
        } else if (argv[optind].equals("-a")) {
            file = argv[++optind];
        } else if (argv[optind].equals("-s")) {
            subject = argv[++optind];
        } else if (argv[optind].equals("-o")) { // originator
            from = argv[++optind];
        } else if (argv[optind].equals("-c")) {
            cc = argv[++optind];
        } else if (argv[optind].equals("-b")) {
            bcc = argv[++optind];
        } else if (argv[optind].equals("-L")) {
            url = argv[++optind];
        } else if (argv[optind].equals("-d")) {
            debug = true;
        } else if (argv[optind].equals("-v")) {
            verbose = true;
        } else if (argv[optind].equals("-A")) {
            auth = true;
        } else if (argv[optind].equals("-S")) {
            prot = "smtps";
        } else if (argv[optind].equals("--")) {
            optind++;
            break;
        } else if (argv[optind].startsWith("-")) {
            System.out.println("Usage: smtpsend [[-L store-url] | [-T prot] [-H host] [-U user] [-P passwd]]");
            System.out.println("\t[-s subject] [-o from-address] [-c cc-addresses] [-b bcc-addresses]");
            System.out.println("\t[-f record-mailbox] [-M transport-host] [-d] [-a attach-file]");
            System.out.println("\t[-v] [-A] [-S] [address]");
            System.exit(1);
        } else {
            break;
        }
    }

    try {
        /*
         * Prompt for To and Subject, if not specified.
         */
        if (optind < argv.length) {
            // XXX - concatenate all remaining arguments
            to = argv[optind];
            System.out.println("To: " + to);
        } else {
            System.out.print("To: ");
            System.out.flush();
            to = in.readLine();
        }
        if (subject == null) {
            System.out.print("Subject: ");
            System.out.flush();
            subject = in.readLine();
        } else {
            System.out.println("Subject: " + subject);
        }

        /*
         * Initialize the JavaMail Session.
         */
        Properties props = System.getProperties();
        if (mailhost != null)
            props.put("mail." + prot + ".host", mailhost);
        if (auth)
            props.put("mail." + prot + ".auth", "true");

        /*
         * Create a Provider representing our extended SMTP transport
         * and set the property to use our provider.
         *
        Provider p = new Provider(Provider.Type.TRANSPORT, prot,
        "smtpsend$SMTPExtension", "JavaMail demo", "no version");
        props.put("mail." + prot + ".class", "smtpsend$SMTPExtension");
         */

        // Get a Session object
        Session session = Session.getInstance(props, null);
        if (debug)
            session.setDebug(true);

        /*
         * Register our extended SMTP transport.
         *
        session.addProvider(p);
         */

        /*
         * Construct the message and send it.
         */
        Message msg = new MimeMessage(session);
        if (from != null)
            msg.setFrom(new InternetAddress(from));
        else
            msg.setFrom();

        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        if (cc != null)
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        if (bcc != null)
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));

        msg.setSubject(subject);

        String text = collect(in);

        if (file != null) {
            // Attach the specified file.
            // We need a multipart message to hold the attachment.
            MimeBodyPart mbp1 = new MimeBodyPart();
            mbp1.setText(text);
            MimeBodyPart mbp2 = new MimeBodyPart();
            mbp2.attachFile(file);
            MimeMultipart mp = new MimeMultipart();
            mp.addBodyPart(mbp1);
            mp.addBodyPart(mbp2);
            msg.setContent(mp);
        } else {
            // If the desired charset is known, you can use
            // setText(text, charset)
            msg.setText(text);
        }

        msg.setHeader("X-Mailer", mailer);
        msg.setSentDate(new Date());

        // send the thing off
        /*
         * The simple way to send a message is this:
         *
        Transport.send(msg);
         *
         * But we're going to use some SMTP-specific features for
         * demonstration purposes so we need to manage the Transport
         * object explicitly.
         */
        SMTPTransport t = (SMTPTransport) session.getTransport(prot);
        try {
            if (auth)
                t.connect(mailhost, user, password);
            else
                t.connect();
            t.sendMessage(msg, msg.getAllRecipients());
        } finally {
            if (verbose)
                System.out.println("Response: " + t.getLastServerResponse());
            t.close();
        }

        System.out.println("\nMail was sent successfully.");

        /*
         * Save a copy of the message, if requested.
         */
        if (record != 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();
            }

            // Get record Folder.  Create if it does not exist.
            Folder folder = store.getFolder(record);
            if (folder == null) {
                System.err.println("Can't get record folder.");
                System.exit(1);
            }
            if (!folder.exists())
                folder.create(Folder.HOLDS_MESSAGES);

            Message[] msgs = new Message[1];
            msgs[0] = msg;
            folder.appendMessages(msgs);

            System.out.println("Mail was recorded successfully.");
        }

    } catch (Exception e) {
        /*
         * Handle SMTP-specific exceptions.
         */
        if (e instanceof SendFailedException) {
            MessagingException sfe = (MessagingException) e;
            if (sfe instanceof SMTPSendFailedException) {
                SMTPSendFailedException ssfe = (SMTPSendFailedException) sfe;
                System.out.println("SMTP SEND FAILED:");
                if (verbose)
                    System.out.println(ssfe.toString());
                System.out.println("  Command: " + ssfe.getCommand());
                System.out.println("  RetCode: " + ssfe.getReturnCode());
                System.out.println("  Response: " + ssfe.getMessage());
            } else {
                if (verbose)
                    System.out.println("Send failed: " + sfe.toString());
            }
            Exception ne;
            while ((ne = sfe.getNextException()) != null && ne instanceof MessagingException) {
                sfe = (MessagingException) ne;
                if (sfe instanceof SMTPAddressFailedException) {
                    SMTPAddressFailedException ssfe = (SMTPAddressFailedException) sfe;
                    System.out.println("ADDRESS FAILED:");
                    if (verbose)
                        System.out.println(ssfe.toString());
                    System.out.println("  Address: " + ssfe.getAddress());
                    System.out.println("  Command: " + ssfe.getCommand());
                    System.out.println("  RetCode: " + ssfe.getReturnCode());
                    System.out.println("  Response: " + ssfe.getMessage());
                } else if (sfe instanceof SMTPAddressSucceededException) {
                    System.out.println("ADDRESS SUCCEEDED:");
                    SMTPAddressSucceededException ssfe = (SMTPAddressSucceededException) sfe;
                    if (verbose)
                        System.out.println(ssfe.toString());
                    System.out.println("  Address: " + ssfe.getAddress());
                    System.out.println("  Command: " + ssfe.getCommand());
                    System.out.println("  RetCode: " + ssfe.getReturnCode());
                    System.out.println("  Response: " + ssfe.getMessage());
                }
            }
        } else {
            System.out.println("Got Exception: " + e);
            if (verbose)
                e.printStackTrace();
        }
    }
}

From source file:edu.cmu.lti.oaqa.apps.Client.java

public static void main(String args[]) {
    BufferedReader inp = new BufferedReader(new InputStreamReader(System.in));

    Options opt = new Options();

    Option o = new Option(PORT_SHORT_PARAM, PORT_LONG_PARAM, true, PORT_DESC);
    o.setRequired(true);//from  w w w. j  a  v a 2 s .  com
    opt.addOption(o);
    o = new Option(HOST_SHORT_PARAM, HOST_LONG_PARAM, true, HOST_DESC);
    o.setRequired(true);
    opt.addOption(o);
    opt.addOption(K_SHORT_PARAM, K_LONG_PARAM, true, K_DESC);
    opt.addOption(R_SHORT_PARAM, R_LONG_PARAM, true, R_DESC);
    opt.addOption(QUERY_TIME_SHORT_PARAM, QUERY_TIME_LONG_PARAM, true, QUERY_TIME_DESC);
    opt.addOption(RET_OBJ_SHORT_PARAM, RET_OBJ_LONG_PARAM, false, RET_OBJ_DESC);
    opt.addOption(RET_EXTERN_ID_SHORT_PARAM, RET_EXTERN_ID_LONG_PARAM, false, RET_EXTERN_ID_DESC);

    CommandLineParser parser = new org.apache.commons.cli.GnuParser();

    try {
        CommandLine cmd = parser.parse(opt, args);

        String host = cmd.getOptionValue(HOST_SHORT_PARAM);

        String tmp = null;

        tmp = cmd.getOptionValue(PORT_SHORT_PARAM);

        int port = -1;

        try {
            port = Integer.parseInt(tmp);
        } catch (NumberFormatException e) {
            Usage("Port should be integer!");
        }

        boolean retObj = cmd.hasOption(RET_OBJ_SHORT_PARAM);
        boolean retExternId = cmd.hasOption(RET_EXTERN_ID_SHORT_PARAM);

        String queryTimeParams = cmd.getOptionValue(QUERY_TIME_SHORT_PARAM);
        if (null == queryTimeParams)
            queryTimeParams = "";

        SearchType searchType = SearchType.kKNNSearch;
        int k = 0;
        double r = 0;

        if (cmd.hasOption(K_SHORT_PARAM)) {
            if (cmd.hasOption(R_SHORT_PARAM)) {
                Usage("Range search is not allowed if the KNN search is specified!");
            }
            tmp = cmd.getOptionValue(K_SHORT_PARAM);
            try {
                k = Integer.parseInt(tmp);
            } catch (NumberFormatException e) {
                Usage("K should be integer!");
            }
            searchType = SearchType.kKNNSearch;
        } else if (cmd.hasOption(R_SHORT_PARAM)) {
            if (cmd.hasOption(K_SHORT_PARAM)) {
                Usage("KNN search is not allowed if the range search is specified!");
            }
            searchType = SearchType.kRangeSearch;
            tmp = cmd.getOptionValue(R_SHORT_PARAM);
            try {
                r = Double.parseDouble(tmp);
            } catch (NumberFormatException e) {
                Usage("The range value should be numeric!");
            }
        } else {
            Usage("One has to specify either range or KNN-search parameter");
        }

        String separator = System.getProperty("line.separator");

        StringBuffer sb = new StringBuffer();
        String s;

        while ((s = inp.readLine()) != null) {
            sb.append(s);
            sb.append(separator);
        }

        String queryObj = sb.toString();

        try {
            TTransport transport = new TSocket(host, port);
            transport.open();

            TProtocol protocol = new TBinaryProtocol(transport);
            QueryService.Client client = new QueryService.Client(protocol);

            if (!queryTimeParams.isEmpty())
                client.setQueryTimeParams(queryTimeParams);

            List<ReplyEntry> res = null;

            long t1 = System.nanoTime();

            if (searchType == SearchType.kKNNSearch) {
                System.out.println(String.format("Running a %d-NN search", k));
                res = client.knnQuery(k, queryObj, retExternId, retObj);
            } else {
                System.out.println(String.format("Running a range search (r=%g)", r));
                res = client.rangeQuery(r, queryObj, retExternId, retObj);
            }

            long t2 = System.nanoTime();

            System.out.println(String.format("Finished in %g ms", (t2 - t1) / 1e6));

            for (ReplyEntry e : res) {
                System.out.println(String.format("id=%d dist=%g %s", e.getId(), e.getDist(),
                        retExternId ? "externId=" + e.getExternId() : ""));
                if (retObj)
                    System.out.println(e.getObj());
            }

            transport.close(); // Close transport/socket !
        } catch (TException te) {
            System.err.println("Apache Thrift exception: " + te);
            te.printStackTrace();
        }

    } catch (ParseException e) {
        Usage("Cannot parse arguments");
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }
}