Example usage for java.io InputStreamReader InputStreamReader

List of usage examples for java.io InputStreamReader InputStreamReader

Introduction

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

Prototype

public InputStreamReader(InputStream in) 

Source Link

Document

Creates an InputStreamReader that uses the default charset.

Usage

From source file:examples.nntp.post.java

public final static void main(String[] args) {
    String from, subject, newsgroup, filename, server, organization;
    String references;//from   w  ww .  ja  v a2s  . c o m
    BufferedReader stdin;
    FileReader fileReader = null;
    SimpleNNTPHeader header;
    NNTPClient client;

    if (args.length < 1) {
        System.err.println("Usage: post newsserver");
        System.exit(1);
    }

    server = args[0];

    stdin = new BufferedReader(new InputStreamReader(System.in));

    try {
        System.out.print("From: ");
        System.out.flush();

        from = stdin.readLine();

        System.out.print("Subject: ");
        System.out.flush();

        subject = stdin.readLine();

        header = new SimpleNNTPHeader(from, subject);

        System.out.print("Newsgroup: ");
        System.out.flush();

        newsgroup = stdin.readLine();
        header.addNewsgroup(newsgroup);

        while (true) {
            System.out.print("Additional Newsgroup <Hit enter to end>: ");
            System.out.flush();

            // Of course you don't want to do this because readLine() may be null
            newsgroup = stdin.readLine().trim();

            if (newsgroup.length() == 0)
                break;

            header.addNewsgroup(newsgroup);
        }

        System.out.print("Organization: ");
        System.out.flush();

        organization = stdin.readLine();

        System.out.print("References: ");
        System.out.flush();

        references = stdin.readLine();

        if (organization != null && organization.length() > 0)
            header.addHeaderField("Organization", organization);

        if (references != null && organization.length() > 0)
            header.addHeaderField("References", references);

        header.addHeaderField("X-Newsreader", "NetComponents");

        System.out.print("Filename: ");
        System.out.flush();

        filename = stdin.readLine();

        try {
            fileReader = new FileReader(filename);
        } catch (FileNotFoundException e) {
            System.err.println("File not found. " + e.getMessage());
            System.exit(1);
        }

        client = new NNTPClient();
        client.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));

        client.connect(server);

        if (!NNTPReply.isPositiveCompletion(client.getReplyCode())) {
            client.disconnect();
            System.err.println("NNTP server refused connection.");
            System.exit(1);
        }

        if (client.isAllowedToPost()) {
            Writer writer = client.postArticle();

            if (writer != null) {
                writer.write(header.toString());
                Util.copyReader(fileReader, writer);
                writer.close();
                client.completePendingCommand();
            }
        }

        fileReader.close();

        client.logout();

        client.disconnect();
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:com.mycompany.mavenproject4.web.java

/**
 * @param args the command line arguments
 *///from w  w  w .  j a  v  a  2s  .  c  o  m
public static void main(String[] args) {
    System.out.println("Enter your choice do you want to work with \n 1.PostGreSQL \n 2.Redis \n 3.Mongodb");
    InputStreamReader IORdatabase = new InputStreamReader(System.in);
    BufferedReader BIOdatabase = new BufferedReader(IORdatabase);
    String Str1 = null;
    try {
        Str1 = BIOdatabase.readLine();
    } catch (Exception E7) {
        System.out.println(E7.getMessage());
    }

    // loading data from the CSV file 

    CsvReader data = null;

    try {
        data = new CsvReader("\\data\\Consumer_Complaints.csv");
    } catch (FileNotFoundException EB) {
        System.out.println(EB.getMessage());
    }
    int noofcolumn = 5;
    int noofrows = 100;
    int loops = 0;

    try {
        data = new CsvReader("\\data\\Consumer_Complaints.csv");
    } catch (FileNotFoundException E) {
        System.out.println(E.getMessage());
    }

    String[][] Dataarray = new String[noofrows][noofcolumn];
    try {
        while (data.readRecord()) {
            String v;
            String[] x;
            v = data.getRawRecord();
            x = v.split(",");
            for (int j = 0; j < noofcolumn; j++) {
                String value = null;
                int z = j;
                value = x[z];
                try {
                    Dataarray[loops][j] = value;
                } catch (Exception E) {
                    System.out.println(E.getMessage());
                }
                // System.out.println(Dataarray[iloop][j]);
            }
            loops = loops + 1;
        }
    } catch (IOException Em) {
        System.out.println(Em.getMessage());
    }

    data.close();

    // connection to Database 
    switch (Str1) {
    // postgre code goes here 
    case "1":

        Connection Conn = null;
        Statement Stmt = null;
        URI dbUri = null;
        String choice = null;
        InputStreamReader objin = new InputStreamReader(System.in);
        BufferedReader objbuf = new BufferedReader(objin);
        try {
            Class.forName("org.postgresql.Driver");
        } catch (Exception E1) {
            System.out.println(E1.getMessage());
        }
        String username = "ahkyjdavhedkzg";
        String password = "2f7c3_MBJbIy1uJsFyn7zebkhY";
        String dbUrl = "jdbc:postgresql://ec2-54-83-199-54.compute-1.amazonaws.com:5432/d2l6hq915lp9vi?ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory";

        // now update data in the postgress Database 

        /*  for(int i=0;i<RowCount;i++)
           {
                try 
        {
                          
        Conn= DriverManager.getConnection(dbUrl, username, password);    
        Stmt = Conn.createStatement();
                  String Connection_String = "insert into Webdata (Id,Product,state,Submitted,Complaintid) values (' "+ Dataarray[i][0]+" ',' "+ Dataarray[i][1]+" ',' "+ Dataarray[i][2]+" ',' "+ Dataarray[i][3]+" ',' "+ Dataarray[i][4]+" ')";
         Stmt.executeUpdate(Connection_String);
                  Conn.close();
        }
        catch(SQLException E4)
                  {
           System.out.println(E4.getMessage());
        }
           }
           */
        // Quering with the Database 

        System.out.println("1. Display Data ");
        System.out.println("2. Select data based on primary key");
        System.out.println("3. Select data based on Other attributes e.g Name");
        System.out.println("Enter your Choice ");
        try {
            choice = objbuf.readLine();
        } catch (IOException E) {
            System.out.println(E.getMessage());
        }
        switch (choice) {
        case "1":
            try {
                Conn = DriverManager.getConnection(dbUrl, username, password);
                Stmt = Conn.createStatement();
                String Connection_String = " Select * from Webdata;";
                ResultSet objRS = Stmt.executeQuery(Connection_String);
                while (objRS.next()) {
                    System.out.println(" ID: " + objRS.getInt("ID"));
                    System.out.println("Product Name: " + objRS.getString("Product"));
                    System.out.println("Which state: " + objRS.getString("State"));
                    System.out.println("Sumbitted through: " + objRS.getString("Submitted"));
                    System.out.println("Complain Number: " + objRS.getString("Complaintid"));
                    Conn.close();
                }

            } catch (Exception E2) {
                System.out.println(E2.getMessage());
            }

            break;

        case "2":

            System.out.println("Enter Id(Primary Key) :");
            InputStreamReader objkey = new InputStreamReader(System.in);
            BufferedReader objbufkey = new BufferedReader(objkey);
            int key = 0;
            try {
                key = Integer.parseInt(objbufkey.readLine());
            } catch (IOException E) {
                System.out.println(E.getMessage());
            }
            try {
                Conn = DriverManager.getConnection(dbUrl, username, password);
                Stmt = Conn.createStatement();
                String Connection_String = " Select * from Webdata where Id=" + key + ";";
                ResultSet objRS = Stmt.executeQuery(Connection_String);
                while (objRS.next()) {
                    //System.out.println(" ID: " + objRS.getInt("ID"));
                    System.out.println("Product Name: " + objRS.getString("Product"));
                    System.out.println("Which state: " + objRS.getString("State"));
                    System.out.println("Sumbitted through: " + objRS.getString("Submitted"));
                    System.out.println("Complain Number: " + objRS.getString("Complaintid"));
                    Conn.close();
                }

            } catch (Exception E2) {
                System.out.println(E2.getMessage());
            }
            break;

        case "3":
            //String Name=null;
            System.out.println("Enter Complaintid to find the record");

            // Scanner input = new Scanner(System.in);
            //
            int Number = 0;
            try {
                InputStreamReader objname = new InputStreamReader(System.in);
                BufferedReader objbufname = new BufferedReader(objname);

                Number = Integer.parseInt(objbufname.readLine());
            } catch (Exception E10) {
                System.out.println(E10.getMessage());
            }
            //System.out.println(Name);
            try {
                Conn = DriverManager.getConnection(dbUrl, username, password);
                Stmt = Conn.createStatement();
                String Connection_String = " Select * from Webdata where complaintid=" + Number + ";";
                //2
                System.out.println(Connection_String);
                ResultSet objRS = Stmt.executeQuery(Connection_String);
                while (objRS.next()) {
                    int id = objRS.getInt("id");
                    System.out.println(" ID: " + id);
                    System.out.println("Product Name: " + objRS.getString("Product"));
                    String state = objRS.getString("state");
                    System.out.println("Which state: " + state);
                    String Submitted = objRS.getString("submitted");
                    System.out.println("Sumbitted through: " + Submitted);
                    String Complaintid = objRS.getString("complaintid");
                    System.out.println("Complain Number: " + Complaintid);

                }
                Conn.close();
            } catch (Exception E2) {
                System.out.println(E2.getMessage());
            }
            break;
        }
        try {
            Conn.close();
        } catch (SQLException E6) {
            System.out.println(E6.getMessage());
        }
        break;

    // Redis code goes here 

    case "2":
        int Length = 0;
        String ID = null;
        Length = 100;

        // Connection to Redis 
        Jedis jedis = new Jedis("pub-redis-13274.us-east-1-2.1.ec2.garantiadata.com", 13274);
        jedis.auth("rfJ8OLjlv9NjRfry");
        System.out.println("Connected to Redis Database");

        // Storing values in the database 

        /* 
        for(int i=0;i<Length;i++)
        { 
         //Store data in redis 
            int j=i+1;
        jedis.hset("Record:" + j , "Product", Dataarray[i][1]);
        jedis.hset("Record:" + j , "State ", Dataarray[i][2]);
        jedis.hset("Record:" + j , "Submitted", Dataarray[i][3]);
        jedis.hset("Record:" + j , "Complaintid", Dataarray[i][4]);
                
        }
        */
        System.out.println(
                "Search by \n 11.Get records through primary key \n 22.Get Records through Complaintid \n 33.Display ");
        InputStreamReader objkey = new InputStreamReader(System.in);
        BufferedReader objbufkey = new BufferedReader(objkey);
        String str2 = null;
        try {
            str2 = objbufkey.readLine();
        } catch (IOException E) {
            System.out.println(E.getMessage());
        }
        switch (str2) {
        case "11":
            System.out.print("Enter Primary Key : ");
            InputStreamReader IORKey = new InputStreamReader(System.in);
            BufferedReader BIORKey = new BufferedReader(IORKey);
            String ID1 = null;
            try {
                ID1 = BIORKey.readLine();
            } catch (IOException E3) {
                System.out.println(E3.getMessage());
            }

            Map<String, String> properties = jedis.hgetAll("Record:" + Integer.parseInt(ID1));
            for (Map.Entry<String, String> entry : properties.entrySet()) {
                System.out.println("Product:" + jedis.hget("Record:" + Integer.parseInt(ID1), "Product"));
                System.out.println("State:" + jedis.hget("Record:" + Integer.parseInt(ID1), "State"));
                System.out.println("Submitted:" + jedis.hget("Record:" + Integer.parseInt(ID1), "Submitted"));
                System.out
                        .println("Complaintid:" + jedis.hget("Record:" + Integer.parseInt(ID1), "Complaintid"));
            }
            break;

        case "22":
            System.out.print(" Enter Complaintid  : ");
            InputStreamReader IORName1 = new InputStreamReader(System.in);
            BufferedReader BIORName1 = new BufferedReader(IORName1);

            String ID2 = null;
            try {
                ID2 = BIORName1.readLine();
            } catch (IOException E3) {
                System.out.println(E3.getMessage());
            }
            for (int i = 0; i < 100; i++) {
                Map<String, String> properties3 = jedis.hgetAll("Record:" + i);
                for (Map.Entry<String, String> entry : properties3.entrySet()) {
                    String value = entry.getValue();
                    if (entry.getValue().equals(ID2)) {
                        System.out
                                .println("Product:" + jedis.hget("Record:" + Integer.parseInt(ID2), "Product"));
                        System.out.println("State:" + jedis.hget("Record:" + Integer.parseInt(ID2), "State"));
                        System.out.println(
                                "Submitted:" + jedis.hget("Record:" + Integer.parseInt(ID2), "Submitted"));
                        System.out.println(
                                "Complaintid:" + jedis.hget("Record:" + Integer.parseInt(ID2), "Complaintid"));
                    }

                }
            }

            break;

        case "33":
            for (int i = 1; i < 21; i++) {
                Map<String, String> properties3 = jedis.hgetAll("Record:" + i);
                for (Map.Entry<String, String> entry : properties3.entrySet()) {

                    System.out.println("Product:" + jedis.hget("Record:" + i, "Product"));
                    System.out.println("State:" + jedis.hget("Record:" + i, "State"));
                    System.out.println("Submitted:" + jedis.hget("Record:" + i, "Submitted"));
                    System.out.println("Complaintid:" + jedis.hget("Record:" + i, "Complaintid"));

                }
            }
            break;
        }

        break;

    // mongo db 

    case "3":
        MongoClient mongo = new MongoClient(new MongoClientURI(
                "mongodb://naikhpratik:naikhpratik@ds053964.mongolab.com:53964/heroku_6t7n587f"));
        DB db;
        db = mongo.getDB("heroku_6t7n587f");
        // storing values in the database 
        /*for(int i=0;i<100;i++)
         {
             BasicDBObject document = new BasicDBObject();
            document.put("Id", i+1);
            document.put("Product", Dataarray[i][1]);
            document.put("State", Dataarray[i][2]);    
            document.put("Submitted", Dataarray[i][3]);    
            document.put("Complaintid", Dataarray[i][4]); 
            db.getCollection("Naiknaik").insert(document);
                  
         }*/
        System.out.println("Search by \n 1.Enter Primary key \n 2.Enter Complaintid \n 3.Display");
        InputStreamReader objkey6 = new InputStreamReader(System.in);
        BufferedReader objbufkey6 = new BufferedReader(objkey6);
        String str3 = null;
        try {
            str3 = objbufkey6.readLine();
        } catch (IOException E) {
            System.out.println(E.getMessage());
        }
        switch (str3) {
        case "1":
            System.out.println("Enter the Primary Key");
            InputStreamReader IORPkey = new InputStreamReader(System.in);
            BufferedReader BIORPkey = new BufferedReader(IORPkey);
            int Pkey = 0;
            try {
                Pkey = Integer.parseInt(BIORPkey.readLine());
            } catch (IOException E) {
                System.out.println(E.getMessage());
            }
            BasicDBObject inQuery = new BasicDBObject();
            inQuery.put("Id", Pkey);
            DBCursor cursor = db.getCollection("Naiknaik").find(inQuery);
            while (cursor.hasNext()) {
                // System.out.println(cursor.next());
                System.out.println(cursor.next());
            }
            break;
        case "2":
            System.out.println("Enter the Product to Search");
            InputStreamReader objName = new InputStreamReader(System.in);
            BufferedReader objbufName = new BufferedReader(objName);
            String Name = null;
            try {
                Name = objbufName.readLine();
            } catch (IOException E) {
                System.out.println(E.getMessage());
            }
            BasicDBObject inQuery1 = new BasicDBObject();
            inQuery1.put("Product", Name);
            DBCursor cursor1 = db.getCollection("Naiknaik").find(inQuery1);
            while (cursor1.hasNext()) {
                // System.out.println(cursor.next());
                System.out.println(cursor1.next());
            }
            break;

        case "3":
            for (int i = 1; i < 21; i++) {
                BasicDBObject inQuerya = new BasicDBObject();
                inQuerya.put("_id", i);
                DBCursor cursora = db.getCollection("Naiknaik").find(inQuerya);
                while (cursora.hasNext()) {
                    // System.out.println(cursor.next());
                    System.out.println(cursora.next());
                }
            }
            break;
        }
        break;

    }

}

From source file:examples.nntp.PostMessage.java

public static void main(String[] args) {
    String from, subject, newsgroup, filename, server, organization;
    String references;//from  w  ww.  j a  va  2s  .  c o m
    BufferedReader stdin;
    FileReader fileReader = null;
    SimpleNNTPHeader header;
    NNTPClient client;

    if (args.length < 1) {
        System.err.println("Usage: post newsserver");
        System.exit(1);
    }

    server = args[0];

    stdin = new BufferedReader(new InputStreamReader(System.in));

    try {
        System.out.print("From: ");
        System.out.flush();

        from = stdin.readLine();

        System.out.print("Subject: ");
        System.out.flush();

        subject = stdin.readLine();

        header = new SimpleNNTPHeader(from, subject);

        System.out.print("Newsgroup: ");
        System.out.flush();

        newsgroup = stdin.readLine();
        header.addNewsgroup(newsgroup);

        while (true) {
            System.out.print("Additional Newsgroup <Hit enter to end>: ");
            System.out.flush();

            // Of course you don't want to do this because readLine() may be null
            newsgroup = stdin.readLine().trim();

            if (newsgroup.length() == 0) {
                break;
            }

            header.addNewsgroup(newsgroup);
        }

        System.out.print("Organization: ");
        System.out.flush();

        organization = stdin.readLine();

        System.out.print("References: ");
        System.out.flush();

        references = stdin.readLine();

        if (organization != null && organization.length() > 0) {
            header.addHeaderField("Organization", organization);
        }

        if (references != null && references.length() > 0) {
            header.addHeaderField("References", references);
        }

        header.addHeaderField("X-Newsreader", "NetComponents");

        System.out.print("Filename: ");
        System.out.flush();

        filename = stdin.readLine();

        try {
            fileReader = new FileReader(filename);
        } catch (FileNotFoundException e) {
            System.err.println("File not found. " + e.getMessage());
            System.exit(1);
        }

        client = new NNTPClient();
        client.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));

        client.connect(server);

        if (!NNTPReply.isPositiveCompletion(client.getReplyCode())) {
            client.disconnect();
            System.err.println("NNTP server refused connection.");
            System.exit(1);
        }

        if (client.isAllowedToPost()) {
            Writer writer = client.postArticle();

            if (writer != null) {
                writer.write(header.toString());
                Util.copyReader(fileReader, writer);
                writer.close();
                client.completePendingCommand();
            }
        }

        if (fileReader != null) {
            fileReader.close();
        }

        client.logout();

        client.disconnect();
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:Grep0.java

public static void main(String[] args) throws IOException {
    BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
    if (args.length != 1) {
        System.err.println("Usage: MatchLines pattern");
        System.exit(1);//from ww w. j  av a2s .  c o m
    }
    Pattern patt = Pattern.compile(args[0]);
    Matcher matcher = patt.matcher("");
    String line = null;
    while ((line = is.readLine()) != null) {
        matcher.reset(line);
        if (matcher.find()) {
            System.out.println("MATCH: " + line);
        }
    }
}

From source file:HelloSmartsheet.java

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

    //We are using Jackson JSON parser to 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);

    try {/*  w  ww  . j av  a2s  .com*/

        System.out.println("STARTING HelloSmartsheet...");
        //Create a BufferedReader to read user input.
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

        System.out.print("Enter Smartsheet API access token:");
        String accessToken = in.readLine();
        System.out.println("Fetching list of your sheets...");
        //Create a connection and fetch the list of sheets
        connection = (HttpURLConnection) new URL(GET_SHEETS_URL).openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line;
        //Read the response line by line.
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();
        //Use Jackson to conver the JSON string to a List of Sheets
        List<Sheet> sheets = mapper.readValue(response.toString(), new TypeReference<List<Sheet>>() {
        });
        if (sheets.size() == 0) {
            System.out.println("You don't have any sheets.  Goodbye!");
            return;
        }
        System.out.println("Total sheets: " + sheets.size());
        int i = 1;
        for (Sheet sheet : sheets) {
            System.out.println(i++ + ": " + sheet.name);
        }
        System.out.print("Enter the number of the sheet you want to share: ");

        //Prompt the user to provide the sheet number, the email address, and the access level
        Integer sheetNumber = Integer.parseInt(in.readLine().trim()); //NOTE: for simplicity, error handling and input validation is neglected.
        Sheet chosenSheet = sheets.get(sheetNumber - 1);

        System.out.print("Enter an email address to share " + chosenSheet.getName() + " to: ");
        String email = in.readLine();

        System.out.print("Choose an access level (VIEWER, EDITOR, EDITOR_SHARE, ADMIN) for " + email + ": ");
        String accessLevel = in.readLine();

        //Create a share object
        Share share = new Share();
        share.setEmail(email);
        share.setAccessLevel(accessLevel);

        System.out.println("Sharing " + chosenSheet.name + " to " + email + " as " + accessLevel + ".");

        //Create a connection. Note the SHARE_SHEET_URL uses /sheet as opposed to /sheets (with an 's')
        connection = (HttpURLConnection) new URL(SHARE_SHEET_URL.replace(SHEET_ID, "" + chosenSheet.getId()))
                .openConnection();
        connection.setDoOutput(true);
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");

        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
        //Serialize the Share object
        writer.write(mapper.writeValueAsString(share));
        writer.close();

        //Read the response and parse the JSON
        reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        response = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }

        Result result = mapper.readValue(response.toString(), Result.class);
        System.out.println("Sheet shared successfully, share ID " + result.result.id);
        System.out.println("Press any key to quit.");
        in.read();

    } catch (IOException e) {
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(((HttpURLConnection) connection).getErrorStream()));
        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.out.println(result.message);
        } catch (IOException e1) {
            e1.printStackTrace();
        }

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

}

From source file:com.xiangzhurui.util.email.SMTPMail.java

public static void main(String[] args) {
    String sender, recipient, subject, filename, server, cc;
    List<String> ccList = new ArrayList<String>();
    BufferedReader stdin;// www  .j a va 2s. c  om
    FileReader fileReader = null;
    Writer writer;
    SimpleSMTPHeader header;
    SMTPClient client;

    if (args.length < 1) {
        System.err.println("Usage: mail smtpserver");
        System.exit(1);
    }

    server = args[0];

    stdin = new BufferedReader(new InputStreamReader(System.in));

    try {
        System.out.print("From: ");
        System.out.flush();

        sender = stdin.readLine();

        System.out.print("To: ");
        System.out.flush();

        recipient = stdin.readLine();

        System.out.print("Subject: ");
        System.out.flush();

        subject = stdin.readLine();

        header = new SimpleSMTPHeader(sender, recipient, subject);

        while (true) {
            System.out.print("CC <enter one address per line, hit enter to end>: ");
            System.out.flush();

            cc = stdin.readLine();

            if (cc == null || cc.length() == 0) {
                break;
            }

            header.addCC(cc.trim());
            ccList.add(cc.trim());
        }

        System.out.print("Filename: ");
        System.out.flush();

        filename = stdin.readLine();

        try {
            fileReader = new FileReader(filename);
        } catch (FileNotFoundException e) {
            System.err.println("File not found. " + e.getMessage());
        }

        client = new SMTPClient();
        client.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));

        client.connect(server);

        if (!SMTPReply.isPositiveCompletion(client.getReplyCode())) {
            client.disconnect();
            System.err.println("SMTP server refused connection.");
            System.exit(1);
        }

        client.login();

        client.setSender(sender);
        client.addRecipient(recipient);

        for (String recpt : ccList) {
            client.addRecipient(recpt);
        }

        writer = client.sendMessageData();

        if (writer != null) {
            writer.write(header.toString());
            Util.copyReader(fileReader, writer);
            writer.close();
            client.completePendingCommand();
        }

        if (fileReader != null) {
            fileReader.close();
        }

        client.logout();

        client.disconnect();
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:no.uib.tools.OnthologyHttpClient.java

public static void main(String[] args) {
    try {/*  w w w .ja v  a  2s .co m*/
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet getRequest = new HttpGet(
                "http://www.ebi.ac.uk/ols/api/ontologies/mod/terms/http%253A%252F%252Fpurl.obolibrary.org%252Fobo%252FMOD_00861/descendants?size=2002");
        getRequest.addHeader("accept", "application/json");

        HttpResponse response = httpClient.execute(getRequest);

        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException("Failed to get the PSIMOD onthology : HTTP error code : "
                    + response.getStatusLine().getStatusCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

        String output;
        FileWriter fw = new FileWriter("./mod.json");
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            System.out.println(output);
            fw.write(output);
        }

        fw.close();
        httpClient.close();

    } catch (ClientProtocolException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();
    }

}

From source file:TreeNode.java

public static void main(String[] argv) throws IOException {
    BinaryTree bt = new BinaryTree();
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    int val;
    char ch = ' ';
    String clearbuffer;//from   www . j av a  2  s . co  m
    do {
        System.out.print("Enter a number: ");
        val = Integer.parseInt(br.readLine());
        bt.insert(val);
        System.out.print("Do you wish to enter more values (Y/N).....");
        ch = (char) br.read();
        clearbuffer = br.readLine();
    } while (ch == 'y' || ch == 'Y');
    System.out.println("Postorder traversal of given tree is: ");
    bt.postorder();
    System.out.println("Preorder traversal of given tree is: ");
    bt.preorder();
    System.out.println("Inorder traversal of given tree is: ");
    bt.inorder();
}

From source file:com.navercorp.client.Main.java

public static void main(String[] args) {
    Client clnt = null;/*w w w. j  av  a2s. com*/
    try {
        CommandLine cmd = new DefaultParser()
                .parse(new Options().addOption("z", true, "zookeeper address (ip:port,ip:port,...)")
                        .addOption("t", true, "zookeeper connection timeout")
                        .addOption("c", true, "command and arguments"), args);

        final String connectionString = cmd.hasOption("z") ? cmd.getOptionValue("z") : "127.0.0.1:2181";
        final int timeout = cmd.hasOption("t") ? Integer.valueOf(cmd.getOptionValue("t")) : 10000;
        clnt = new Client(connectionString, timeout);

        String command;
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        while ((command = in.readLine()) != null) {
            printResult(clnt.execute(command.split(" ")));
        }
        System.exit(Code.OK.n());
    } catch (ParseException e) {
        e.printStackTrace(System.err);
        System.err.println(Client.getUsage());
        System.exit(INVALID_ARGUMENT.n());
    } catch (IOException e) {
        e.printStackTrace(System.err);
        System.exit(ZK_CONNECTION_LOSS.n());
    } catch (InterruptedException e) {
        e.printStackTrace(System.err);
        System.exit(INTERNAL_ERROR.n());
    } finally {
        if (clnt != null) {
            try {
                clnt.close();
            } catch (Exception e) {
                ; // nothing to do
            }
        }
    }
}

From source file:com.aestel.chemistry.openEye.fp.FPDictionarySorter.java

public static void main(String... args) throws IOException {
    long start = System.currentTimeMillis();
    int iCounter = 0;
    int fpCounter = 0;

    // create command line Options object
    Options options = new Options();
    Option opt = new Option("i", true, "input file [.ism,.sdf,...]");
    opt.setRequired(true);// w  w w .  j a  v  a 2s .c  om
    options.addOption(opt);

    opt = new Option("fpType", true, "fingerPrintType: maccs|linear7|linear7*4");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option("sampleFract", true, "fraction of input molecules to use (Default=1)");
    opt.setRequired(false);
    options.addOption(opt);

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

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

    if (args.length != 0) {
        exitWithHelp(options);
    }

    String type = cmd.getOptionValue("fpType");
    boolean updateDictionaryFile = false;
    boolean hashUnknownFrag = false;
    Fingerprinter fprinter = Fingerprinter.createFingerprinter(type, updateDictionaryFile, hashUnknownFrag);
    OEMolBase mol = new OEGraphMol();

    String inFile = cmd.getOptionValue("i");
    oemolistream ifs = new oemolistream(inFile);

    double fract = 2D;
    String tmp = cmd.getOptionValue("sampleFract");
    if (tmp != null)
        fract = Double.parseDouble(tmp);

    Random rnd = new Random();

    LearningStrcutureCodeMapper mapper = (LearningStrcutureCodeMapper) fprinter.getMapper();
    int dictSize = mapper.getMaxIdx() + 1;
    int[] freq = new int[dictSize];

    while (oechem.OEReadMolecule(ifs, mol)) {
        iCounter++;
        if (rnd.nextDouble() < fract) {
            fpCounter++;

            Fingerprint fp = fprinter.getFingerprint(mol);
            for (int bit : fp.getBits())
                freq[bit]++;
        }

        if (iCounter % 100 == 0)
            System.err.print(".");
        if (iCounter % 4000 == 0) {
            System.err.printf(" %d %d %dsec\n", iCounter, fpCounter,
                    (System.currentTimeMillis() - start) / 1000);
        }
    }

    System.err.printf("FPDictionarySorter: Read %d structures calculated %d fprints in %d sec\n", iCounter,
            fpCounter, (System.currentTimeMillis() - start) / 1000);

    mapper.reSortDictionary(freq);
    mapper.writeDictionary();
    fprinter.close();
}