Example usage for java.util HashMap put

List of usage examples for java.util HashMap put

Introduction

In this page you can find the example usage for java.util HashMap put.

Prototype

public V put(K key, V value) 

Source Link

Document

Associates the specified value with the specified key in this map.

Usage

From source file:com.oracle.tutorial.jdbc.CoffeesTable.java

public static void main(String[] args) {
    JDBCTutorialUtilities myJDBCTutorialUtilities;
    Connection myConnection = null;

    if (args[0] == null) {
        System.err.println("Properties file not specified at command line");
        return;/*from w  w w.j a  va2s  .c o  m*/
    } else {
        try {
            myJDBCTutorialUtilities = new JDBCTutorialUtilities(args[0]);
        } catch (Exception e) {
            System.err.println("Problem reading properties file " + args[0]);
            e.printStackTrace();
            return;
        }
    }

    try {
        myConnection = myJDBCTutorialUtilities.getConnection();

        // Java DB does not have an SQL create database command; it does require createDatabase
        //      JDBCTutorialUtilities.createDatabase(myConnection,
        //                                           myJDBCTutorialUtilities.dbName,
        //                                           myJDBCTutorialUtilities.dbms);
        //
        //      JDBCTutorialUtilities.initializeTables(myConnection,
        //                                             myJDBCTutorialUtilities.dbName,
        //                                             myJDBCTutorialUtilities.dbms);

        CoffeesTable myCoffeeTable = new CoffeesTable(myConnection, myJDBCTutorialUtilities.dbName,
                myJDBCTutorialUtilities.dbms);

        System.out.println("\nContents of COFFEES table:");
        CoffeesTable.viewTable(myConnection);

        System.out.println("\nRaising coffee prices by 25%");
        myCoffeeTable.modifyPrices(1.25f);

        System.out.println("\nInserting a new row:");
        myCoffeeTable.insertRow("Kona", 150, 10.99f, 0, 0);
        CoffeesTable.viewTable(myConnection);

        System.out.println("\nUpdating sales of coffee per week:");
        HashMap<String, Integer> salesCoffeeWeek = new HashMap<String, Integer>();
        salesCoffeeWeek.put("Colombian", 175);
        salesCoffeeWeek.put("French_Roast", 150);
        salesCoffeeWeek.put("Espresso", 60);
        salesCoffeeWeek.put("Colombian_Decaf", 155);
        salesCoffeeWeek.put("French_Roast_Decaf", 90);
        myCoffeeTable.updateCoffeeSales(salesCoffeeWeek);
        CoffeesTable.viewTable(myConnection);

        System.out.println("\nModifying prices by percentage");

        myCoffeeTable.modifyPricesByPercentage("Colombian", 0.10f, 9.00f);

        System.out.println("\nCOFFEES table after modifying prices by percentage:");

        myCoffeeTable.viewTable(myConnection);

        System.out.println("\nPerforming batch updates; adding new coffees");
        myCoffeeTable.batchUpdate();
        myCoffeeTable.viewTable(myConnection);

        //      System.out.println("\nDropping Coffee and Suplliers table:");
        //      
        //      myCoffeeTable.dropTable();
        //      mySuppliersTable.dropTable();

    } catch (SQLException e) {
        JDBCTutorialUtilities.printSQLException(e);
    } finally {
        JDBCTutorialUtilities.closeConnection(myConnection);
    }
}

From source file:evaluation.evaluation1VMPolicyGeneration.java

public static void main(String[] args) {

    int VMNumber = 5;
    int attributeNumber = 20;

    JSONObject obj = new JSONObject();
    obj.put("name", "clientTemplate");
    obj.put("context", "VM-deployment");
    //obj.put("Context", new Integer);

    HashMap serviceRequirement = new HashMap();

    HashMap serviceDescription = new HashMap();
    serviceRequirement.put("VM1_volume", "1_GB");
    serviceDescription.put("VM1_purpose", "dev");
    serviceDescription.put("VM1_data", "private");
    serviceDescription.put("VM1_application", "internal");

    for (int j = 5; j < attributeNumber; j++) {
        serviceDescription.put("VM1_other" + j, "other");
    }//from  ww  w  .  j a va2s  .  c om

    serviceRequirement.put("VM2_volume", "2_GB");
    serviceDescription.put("VM2_purpose", "prod");
    serviceDescription.put("VM2_data", "public");
    serviceDescription.put("VM2_application", "business");

    for (int j = 5; j < attributeNumber; j++) {
        serviceDescription.put("VM2_other" + j, "other");
    }

    serviceRequirement.put("VM3_volume", "1_GB");
    serviceDescription.put("VM3_purpose", "test");
    serviceDescription.put("VM3_data", "public");
    serviceDescription.put("VM3_application", "business");

    for (int j = 5; j < attributeNumber; j++) {
        serviceDescription.put("VM3_other" + j, "other");
    }

    serviceRequirement.put("VM4_volume", "12_GB");
    serviceDescription.put("VM4_purpose", "prod");
    serviceDescription.put("VM4_data", "public");
    serviceDescription.put("VM4_application", "business");

    for (int j = 5; j < attributeNumber; j++) {
        serviceDescription.put("VM4_other" + j, "other");
    }

    for (int i = 5; i < VMNumber; i++) {
        serviceRequirement.put("VM" + i + "_volume", "20_GB");
        serviceDescription.put("VM" + i + "_purpose", "prod");
        serviceDescription.put("VM" + i + "_data", "public");
        serviceDescription.put("VM" + i + "_application", "business");
        for (int j = 5; j < attributeNumber; j++) {
            serviceDescription.put("VM" + i + "_other" + j, "other");
        }

    }

    obj.put("serviceRequirement", serviceRequirement);
    obj.put("serviceDescription", serviceDescription);

    HashMap gauranteeTerm = new HashMap();
    gauranteeTerm.put("VM1_availability", "more_97_percentage");
    gauranteeTerm.put("VM2_availability", "more_99_percentage");
    gauranteeTerm.put("VM3_availability", "more_95_percentage");
    gauranteeTerm.put("VM4_availability", "more_99_percentage");
    obj.put("gauranteeTerm", gauranteeTerm);

    //Constraint1

    HashMap host_rule1 = new HashMap();
    HashMap VM_rule1 = new HashMap();
    host_rule1.put("certificate", "true");
    VM_rule1.put("purpose", "dev");

    ArrayList rule1 = new ArrayList();
    rule1.add("permission");
    rule1.add(host_rule1);
    rule1.add(VM_rule1);

    HashMap host_rule1_2 = new HashMap();
    HashMap VM_rule1_2 = new HashMap();
    host_rule1_2.put("certificate", "true");
    VM_rule1_2.put("purpose", "prod");

    ArrayList rule1_2 = new ArrayList();
    rule1_2.add("permission");
    rule1_2.add(host_rule1_2);
    rule1_2.add(VM_rule1_2);

    HashMap host_rule1_3 = new HashMap();
    HashMap VM_rule1_3 = new HashMap();
    host_rule1_3.put("certificate", "true");
    VM_rule1_3.put("purpose", "test");

    ArrayList rule1_3 = new ArrayList();
    rule1_3.add("permission");
    rule1_3.add(host_rule1_3);
    rule1_3.add(VM_rule1_3);

    HashMap host_rule2 = new HashMap();
    HashMap VM_rule2 = new HashMap();
    host_rule2.put("location", "France");
    VM_rule2.put("ID", "VM2");

    ArrayList rule2 = new ArrayList();
    rule2.add("permission");
    rule2.add(host_rule2);
    rule2.add(VM_rule2);

    HashMap host_rule2_1 = new HashMap();
    HashMap VM_rule2_1 = new HashMap();
    host_rule2_1.put("location", "UK");
    VM_rule2_1.put("ID", "VM2");

    ArrayList rule2_1 = new ArrayList();
    rule2_1.add("permission");
    rule2_1.add(host_rule2_1);
    rule2_1.add(VM_rule2_1);

    HashMap host_rule3 = new HashMap();
    HashMap VM_rule3 = new HashMap();
    host_rule3.put("location", "France");
    VM_rule3.put("application", "business");

    ArrayList rule3 = new ArrayList();
    rule3.add("permission");
    rule3.add(host_rule3);
    rule3.add(VM_rule3);

    HashMap host_rule3_1 = new HashMap();
    HashMap VM_rule3_1 = new HashMap();
    host_rule3_1.put("location", "UK");
    VM_rule3_1.put("application", "business");

    ArrayList rule3_1 = new ArrayList();
    rule3_1.add("permission");
    rule3_1.add(host_rule3_1);
    rule3_1.add(VM_rule3_1);

    HashMap VMSeperation_rule_1_1 = new HashMap();
    HashMap VMSeperation_rule_1_2 = new HashMap();

    VMSeperation_rule_1_1.put("ID", "VM1");
    VMSeperation_rule_1_2.put("ID", "VM3");

    ArrayList rule4 = new ArrayList();
    rule4.add("separation");
    rule4.add(VMSeperation_rule_1_1);
    rule4.add(VMSeperation_rule_1_2);

    ArrayList policyInConstraint1 = new ArrayList();
    policyInConstraint1.add(rule1);
    policyInConstraint1.add(rule1_2);
    policyInConstraint1.add(rule1_3);

    policyInConstraint1.add(rule2);
    policyInConstraint1.add(rule2_1);

    policyInConstraint1.add(rule3);
    policyInConstraint1.add(rule3_1);

    policyInConstraint1.add(rule4);

    ArrayList creationConstraint1 = new ArrayList();
    creationConstraint1.add("RP4");
    creationConstraint1.add("true");
    creationConstraint1.add("true");
    creationConstraint1.add(policyInConstraint1);

    ArrayList totalConstraint = new ArrayList();
    totalConstraint.add(creationConstraint1);

    obj.put("creationConstraint", totalConstraint);

    try {

        FileWriter file = new FileWriter("confClient" + File.separator + "test3.json");
        file.write(obj.toJSONString());
        file.flush();
        file.close();

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

    System.out.print(obj);

    /*
            
    JSONParser parser = new JSONParser();
            
    try {
            
    Object obj2 = parser.parse(new FileReader("test2.json"));
            
    JSONObject jsonObject = (JSONObject) obj2;
            
        HashMap serviceDescription2=(HashMap) jsonObject.get("serviceDescription");
                 
        method.printHashMap(serviceDescription2);
                
                
        HashMap gauranteeTerm2=(HashMap) jsonObject.get("gauranteeTerm");
                 
        method.printHashMap(gauranteeTerm2);
                
                
                
        ArrayList creationConstraint=(ArrayList) jsonObject.get("creationConstraint");
                
        method.printArrayList(creationConstraint);
            
            
    } catch (FileNotFoundException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    } catch (ParseException e) {
    e.printStackTrace();
    }
            
            
            
            
            
    */

}

From source file:it.polimi.tower4clouds.rdf_history_db.Main.java

public static void main(String[] args) {
    //      args = "-fakemessages 10 -waitfakemessages 1000".split(" ");

    PropertiesConfiguration releaseProperties = null;
    try {/* ww w  . j  av  a  2s  .co  m*/
        releaseProperties = new PropertiesConfiguration("release.properties");
    } catch (ConfigurationException e) {
        logger.error("Internal error", e);
        System.exit(1);
    }
    APP_NAME = releaseProperties.getString("application.name");
    APP_FILE_NAME = releaseProperties.getString("dist.file.name");
    APP_VERSION = releaseProperties.getString("release.version");

    Main m = new Main();
    JCommander jc = new JCommander(m, args);

    if (m.help) {
        jc.setProgramName(APP_FILE_NAME);
        jc.usage();
        System.exit(0);
    }

    logger.info("{} {}", APP_NAME, APP_VERSION);

    HashMap<String, String> paramsMap = new HashMap<String, String>();

    for (ParameterDescription param : jc.getParameters())
        if (param.isAssigned()) {
            String name = param.getLongestName().replaceAll("-", "");
            String value = null;
            try {
                value = Main.class.getField(name).get(m).toString();
            } catch (Exception e) {
            }

            paramsMap.put(name, value);
        }

    perform(paramsMap);
}

From source file:com.yahoo.ycsb.db.AsyncHBaseClient.java

public static void main(String[] args) {
    if (args.length != 4) {
        System.out.println("usage: ahc zkquorum zkpath threadcount operation_count");
        System.exit(0);/* ww  w. ja  v  a 2  s.c o m*/
    }

    final int keyspace = 10000; //120000000;
    final String zkQuorum = args[0];
    final String zkPath = args[1];
    final int threadcount = Integer.parseInt(args[2]);
    final int opcount = Integer.parseInt(args[3]) / threadcount;

    Vector<Thread> allthreads = new Vector<Thread>();

    for (int i = 0; i < threadcount; i++) {
        Thread t = new Thread() {
            public void run() {
                try {
                    Random random = new Random();

                    AsyncHBaseClient cli = new AsyncHBaseClient();

                    Properties props = new Properties();
                    props.setProperty("columnfamily", "f1");
                    props.setProperty("zkquorum", zkQuorum);
                    props.setProperty("zkpath", zkPath);
                    props.setProperty("debug", "true");
                    cli.setProperties(props);

                    cli.init();

                    HashMap<String, ByteIterator> result = Maps.newHashMap();

                    long accum = 0;

                    for (int i = 0; i < opcount; i++) {
                        int keynum = random.nextInt(keyspace);
                        String key = "user" + keynum;
                        long st = System.currentTimeMillis();
                        int rescode;

                        HashMap<String, ByteIterator> hm = Maps.newHashMap();
                        hm.put("field1", new ByteArrayByteIterator("value1".getBytes("UTF-8")));
                        hm.put("field2", new ByteArrayByteIterator("value2".getBytes("UTF-8")));
                        hm.put("field3", new ByteArrayByteIterator("value3".getBytes("UTF-8")));
                        hm.put("efield", new ByteArrayByteIterator(HBaseClient.EMPTY_ARRAY));
                        rescode = cli.insert("bench", key, hm);
                        HashSet<String> s = Sets.newHashSet();
                        s.add("field1");
                        s.add("field2");

                        rescode = cli.read("bench", key, s, result);
                        rescode = cli.delete("bench", key);
                        rescode = cli.read("bench", key, s, result);

                        HashSet<String> scanFields = Sets.newHashSet();
                        scanFields.add("field1");
                        scanFields.add("field3");
                        Vector<HashMap<String, ByteIterator>> scanResults = new Vector<HashMap<String, ByteIterator>>();
                        rescode = cli.scan("bench", "user2", 20, null, scanResults);

                        long en = System.currentTimeMillis();

                        accum += (en - st);

                        if (rescode != Ok) {
                            System.out.println("Error " + rescode + " for " + key);
                        }

                        if (i % 10 == 0) {
                            System.out.println(
                                    i + " operations, average latency: " + (((double) accum) / ((double) i)));
                        }
                    }

                    System.out.println(new ToStringBuilder(cli._client.stats(), ToStringStyle.MULTI_LINE_STYLE)
                            .toString());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        allthreads.add(t);
    }

    long st = System.currentTimeMillis();
    for (Thread t : allthreads) {
        t.start();
    }

    for (Thread t : allthreads) {
        try {
            t.join();
        } catch (InterruptedException e) {
        }
    }
    long en = System.currentTimeMillis();

    System.out.println("Throughput: " + ((1000.0) * (((double) (opcount * threadcount)) / ((double) (en - st))))
            + " ops/sec");

}

From source file:com.imaginary.home.cloud.api.call.LocationCall.java

static public void main(String... args) throws Exception {
    if (args.length < 1) {
        System.err.println("You must specify an action");
        System.exit(-1);/*from   w w w .  j av a2s  .com*/
        return;
    }
    String action = args[0];

    if (action.equalsIgnoreCase("initializePairing")) {
        if (args.length < 5) {
            System.err.println("You must specify a location ID");
            System.exit(-2);
            return;
        }
        String endpoint = args[1];
        String locationId = args[2];
        String apiKeyId = args[3];
        String apiKeySecret = args[4];

        HashMap<String, Object> act = new HashMap<String, Object>();

        act.put("action", "initializePairing");

        HttpParams params = new BasicHttpParams();

        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        //noinspection deprecation
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
        HttpProtocolParams.setUserAgent(params, "Imaginary Home");

        HttpClient client = new DefaultHttpClient(params);

        HttpPut method = new HttpPut(endpoint + "/location/" + locationId);
        long timestamp = System.currentTimeMillis();

        method.addHeader("Content-Type", "application/json");
        method.addHeader("x-imaginary-version", CloudService.VERSION);
        method.addHeader("x-imaginary-timestamp", String.valueOf(timestamp));
        method.addHeader("x-imaginary-api-key", apiKeyId);
        method.addHeader("x-imaginary-signature", CloudService.sign(apiKeySecret.getBytes("utf-8"),
                "put:/location/" + locationId + ":" + apiKeyId + ":" + timestamp + ":" + CloudService.VERSION));

        //noinspection deprecation
        method.setEntity(new StringEntity((new JSONObject(act)).toString(), "application/json", "UTF-8"));

        HttpResponse response;
        StatusLine status;

        try {
            response = client.execute(method);
            status = response.getStatusLine();
        } catch (IOException e) {
            e.printStackTrace();
            throw new CommunicationException(e);
        }
        if (status.getStatusCode() == HttpServletResponse.SC_OK) {
            String json = EntityUtils.toString(response.getEntity());
            JSONObject u = new JSONObject(json);

            System.out.println((u.has("pairingCode") && !u.isNull("pairingCode")) ? u.getString("pairingCode")
                    : "--no code--");
        } else {
            System.err.println("Failed to initialize pairing  (" + status.getStatusCode() + ": "
                    + EntityUtils.toString(response.getEntity()));
            System.exit(status.getStatusCode());
        }
    } else if (action.equalsIgnoreCase("create")) {
        if (args.length < 7) {
            System.err.println("create ENDPOINT NAME DESCRIPTION TIMEZONE API_KEY_ID API_KEY_SECRET");
            System.exit(-2);
            return;
        }
        String endpoint = args[1];
        String name = args[2];
        String description = args[3];
        String tz = args[4];
        String apiKeyId = args[5];
        String apiKeySecret = args[6];

        HashMap<String, Object> lstate = new HashMap<String, Object>();

        lstate.put("name", name);
        lstate.put("description", description);
        lstate.put("timeZone", tz);

        HttpParams params = new BasicHttpParams();

        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        //noinspection deprecation
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
        HttpProtocolParams.setUserAgent(params, "Imaginary Home");

        HttpClient client = new DefaultHttpClient(params);

        HttpPost method = new HttpPost(endpoint + "/location");
        long timestamp = System.currentTimeMillis();

        System.out.println(
                "Signing: " + "post:/location:" + apiKeyId + ":" + timestamp + ":" + CloudService.VERSION);
        method.addHeader("Content-Type", "application/json");
        method.addHeader("x-imaginary-version", CloudService.VERSION);
        method.addHeader("x-imaginary-timestamp", String.valueOf(timestamp));
        method.addHeader("x-imaginary-api-key", apiKeyId);
        method.addHeader("x-imaginary-signature", CloudService.sign(apiKeySecret.getBytes("utf-8"),
                "post:/location:" + apiKeyId + ":" + timestamp + ":" + CloudService.VERSION));

        //noinspection deprecation
        method.setEntity(new StringEntity((new JSONObject(lstate)).toString(), "application/json", "UTF-8"));

        HttpResponse response;
        StatusLine status;

        try {
            response = client.execute(method);
            status = response.getStatusLine();
        } catch (IOException e) {
            e.printStackTrace();
            throw new CommunicationException(e);
        }
        if (status.getStatusCode() == HttpServletResponse.SC_CREATED) {
            String json = EntityUtils.toString(response.getEntity());
            JSONObject u = new JSONObject(json);

            System.out.println((u.has("locationId") && !u.isNull("locationId")) ? u.getString("locationId")
                    : "--no location--");
        } else {
            System.err.println("Failed to create location  (" + status.getStatusCode() + ": "
                    + EntityUtils.toString(response.getEntity()));
            System.exit(status.getStatusCode());
        }
    } else {
        System.err.println("No such action: " + action);
        System.exit(-3);
    }
}

From source file:carmen.demo.LocationResolverDemo.java

public static void main(String[] args)
        throws ParseException, FileNotFoundException, IOException, ClassNotFoundException {
    // Parse the command line.
    String[] manditory_args = { "input_file" };
    createCommandLineOptions();/*from ww w.j  av  a 2 s. c o  m*/
    CommandLineUtilities.initCommandLineParameters(args, LocationResolverDemo.options, manditory_args);

    // Get options
    String inputFile = CommandLineUtilities.getOptionValue("input_file");
    String outputFile = null;
    if (CommandLineUtilities.hasArg("output_file")) {
        outputFile = CommandLineUtilities.getOptionValue("output_file");
    }

    logger.info("Creating LocationResolver.");
    LocationResolver resolver = LocationResolver.getLocationResolver();

    Scanner scanner = Utils.createScanner(inputFile);

    Writer writer = null;
    if (outputFile != null) {
        writer = Utils.createWriter(outputFile);
        logger.info("Saving geolocated tweets to: " + outputFile);
    }
    ObjectMapper mapper = new ObjectMapper();
    int numResolved = 0;
    int total = 0;
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        @SuppressWarnings("unchecked")
        HashMap<String, Object> tweet = (HashMap<String, Object>) mapper.readValue(line, Map.class);

        total++;
        Location location = resolver.resolveLocationFromTweet(tweet);

        if (location != null) {
            logger.debug("Found location: " + location.toString());
            numResolved++;
        }
        if (writer != null) {
            if (location != null) {
                tweet.put("location", Location.createJsonFromLocation(location));
            }
            mapper.writeValue(writer, tweet);
            writer.write("\n");
        }

    }
    scanner.close();
    if (writer != null)
        writer.close();

    logger.info("Resolved locations for " + numResolved + " of " + total + " tweets.");
}

From source file:br.usp.ime.lapessc.xflow2.core.VCSMiner.java

public static void main(String[] args) {
    HashMap<String, List<FolderArtifactDTO>> map = new HashMap<String, List<FolderArtifactDTO>>();

    List<FolderArtifactDTO> list = map.get("path");
    if (list == null)
        list = new ArrayList<FolderArtifactDTO>();
    list.add(new FolderArtifactDTO());
    map.put("path", list);
    System.out.println(map);//w  w  w.  j  a  v  a  2 s  .  c  o  m
}

From source file:com.example.bigtable.simplecli.HBaseCLI.java

/**
 * The main method for the CLI. This method takes the command line
 * arguments and runs the appropriate commands.
 *//*  w  w  w  .j a  v a2 s  .  c  om*/
public static void main(String[] args) {
    // We use Apache commons-cli to check for a help option.
    Options options = new Options();
    Option help = new Option("help", "print this message");
    options.addOption(help);

    // create the parser
    CommandLineParser parser = new BasicParser();
    CommandLine line = null;
    try {
        // parse the command line arguments
        line = parser.parse(options, args);
    } catch (ParseException exp) {
        // oops, something went wrong
        System.err.println(exp.getMessage());
        usage();
        System.exit(1);
    }

    // Create a list of commands that are supported. Each
    // command defines a run method and some methods for
    // printing help.
    // See the definition of each command below.
    HashMap<String, Command> commands = new HashMap<String, Command>();
    commands.put("create", new CreateCommand("create"));
    commands.put("scan", new ScanCommand("scan"));
    commands.put("get", new GetCommand("get"));
    commands.put("put", new PutCommand("put"));
    commands.put("list", new ListCommand("list"));

    Command command = null;
    List<String> argsList = Arrays.asList(args);
    if (argsList.size() > 0) {
        command = commands.get(argsList.get(0));
    }

    // Check for the help option and if it's there
    // display the appropriate help.
    if (line.hasOption("help")) {
        // If there is a command listed (e.g. create -help)
        // then show the help for that command
        if (command == null) {
            help(commands.values());
        } else {
            help(command);
        }
        System.exit(0);
    } else if (command == null) {
        // No valid command was given so print the usage.
        usage();
        System.exit(0);
    }

    try {
        Connection connection = ConnectionFactory.createConnection();

        try {
            try {
                // Run the command with the arguments after the command name.
                command.run(connection, argsList.subList(1, argsList.size()));
            } catch (InvalidArgsException e) {
                System.out.println("ERROR: Invalid arguments");
                usage(command);
                System.exit(0);
            }
        } finally {
            // Make sure the connection is closed even if
            // an exception occurs.
            connection.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:ch.epfl.lsir.xin.test.SVDPPTest.java

/**
 * @param args//  w  w  w .j av  a2 s.com
 */
public static void main(String[] args) throws Exception {
    // TODO Auto-generated method stub

    PrintWriter logger = new PrintWriter(".//results//SVDPP");

    PropertiesConfiguration config = new PropertiesConfiguration();
    config.setFile(new File("conf//SVDPlusPlus.properties"));
    try {
        config.load();
    } catch (ConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    logger.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " Read rating data...");
    logger.flush();
    DataLoaderFile loader = new DataLoaderFile(".//data//MoveLens100k.txt");
    loader.readSimple();
    DataSetNumeric dataset = loader.getDataset();
    System.out.println("Number of ratings: " + dataset.getRatings().size() + " Number of users: "
            + dataset.getUserIDs().size() + " Number of items: " + dataset.getItemIDs().size());
    logger.println("Number of ratings: " + dataset.getRatings().size() + ", Number of users: "
            + dataset.getUserIDs().size() + ", Number of items: " + dataset.getItemIDs().size());
    logger.flush();

    double totalMAE = 0;
    double totalRMSE = 0;
    double totalPrecision = 0;
    double totalRecall = 0;
    double totalMAP = 0;
    double totalNDCG = 0;
    double totalMRR = 0;
    double totalAUC = 0;
    int F = 5;
    logger.println(F + "- folder cross validation.");
    logger.flush();
    ArrayList<ArrayList<NumericRating>> folders = new ArrayList<ArrayList<NumericRating>>();
    for (int i = 0; i < F; i++) {
        folders.add(new ArrayList<NumericRating>());
    }
    while (dataset.getRatings().size() > 0) {
        int index = new Random().nextInt(dataset.getRatings().size());
        int r = new Random().nextInt(F);
        folders.get(r).add(dataset.getRatings().get(index));
        dataset.getRatings().remove(index);
    }

    for (int folder = 1; folder <= F; folder++) {
        System.out.println("Folder: " + folder);
        logger.println("Folder: " + folder);
        logger.flush();
        ArrayList<NumericRating> trainRatings = new ArrayList<NumericRating>();
        ArrayList<NumericRating> testRatings = new ArrayList<NumericRating>();
        for (int i = 0; i < folders.size(); i++) {
            if (i == folder - 1)//test data
            {
                testRatings.addAll(folders.get(i));
            } else {//training data
                trainRatings.addAll(folders.get(i));
            }
        }

        //create rating matrix
        HashMap<String, Integer> userIDIndexMapping = new HashMap<String, Integer>();
        HashMap<String, Integer> itemIDIndexMapping = new HashMap<String, Integer>();
        for (int i = 0; i < dataset.getUserIDs().size(); i++) {
            userIDIndexMapping.put(dataset.getUserIDs().get(i), i);
        }
        for (int i = 0; i < dataset.getItemIDs().size(); i++) {
            itemIDIndexMapping.put(dataset.getItemIDs().get(i), i);
        }
        RatingMatrix trainRatingMatrix = new RatingMatrix(dataset.getUserIDs().size(),
                dataset.getItemIDs().size());
        for (int i = 0; i < trainRatings.size(); i++) {
            trainRatingMatrix.set(userIDIndexMapping.get(trainRatings.get(i).getUserID()),
                    itemIDIndexMapping.get(trainRatings.get(i).getItemID()), trainRatings.get(i).getValue());
        }
        RatingMatrix testRatingMatrix = new RatingMatrix(dataset.getUserIDs().size(),
                dataset.getItemIDs().size());
        for (int i = 0; i < testRatings.size(); i++) {
            if (testRatings.get(i).getValue() < 5)
                continue;
            testRatingMatrix.set(userIDIndexMapping.get(testRatings.get(i).getUserID()),
                    itemIDIndexMapping.get(testRatings.get(i).getItemID()), testRatings.get(i).getValue());
        }
        System.out.println("Training: " + trainRatingMatrix.getTotalRatingNumber() + " vs Test: "
                + testRatingMatrix.getTotalRatingNumber());

        logger.println("Initialize a SVD++ recommendation model.");
        logger.flush();
        SVDPlusPlus algo = new SVDPlusPlus(trainRatingMatrix, false,
                ".//localModels//" + config.getString("NAME"));
        algo.setLogger(logger);
        algo.build();
        algo.saveModel(".//localModels//" + config.getString("NAME"));
        logger.println("Save the model.");
        logger.flush();

        //rating prediction accuracy
        double RMSE = 0;
        double MAE = 0;
        double precision = 0;
        double recall = 0;
        double map = 0;
        double ndcg = 0;
        double mrr = 0;
        double auc = 0;
        int count = 0;
        for (int i = 0; i < testRatings.size(); i++) {
            NumericRating rating = testRatings.get(i);
            double prediction = algo.predict(userIDIndexMapping.get(rating.getUserID()),
                    itemIDIndexMapping.get(rating.getItemID()), false);
            if (prediction > algo.getMaxRating())
                prediction = algo.getMaxRating();
            if (prediction < algo.getMinRating())
                prediction = algo.getMinRating();
            if (Double.isNaN(prediction)) {
                System.out.println("no prediction");
                continue;
            }
            MAE = MAE + Math.abs(rating.getValue() - prediction);
            RMSE = RMSE + Math.pow((rating.getValue() - prediction), 2);
            count++;
        }
        MAE = MAE / count;
        RMSE = Math.sqrt(RMSE / count);
        totalMAE = totalMAE + MAE;
        totalRMSE = totalRMSE + RMSE;
        System.out.println("Folder --- MAE: " + MAE + " RMSE: " + RMSE);
        logger.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " Folder --- MAE: "
                + MAE + " RMSE: " + RMSE);
        //ranking accuracy
        if (algo.getTopN() > 0) {
            HashMap<Integer, ArrayList<ResultUnit>> results = new HashMap<Integer, ArrayList<ResultUnit>>();
            for (int i = 0; i < trainRatingMatrix.getRow(); i++) {
                ArrayList<ResultUnit> rec = algo.getRecommendationList(i);
                if (rec == null)
                    continue;
                int total = testRatingMatrix.getUserRatingNumber(i);
                if (total == 0)//this user is ignored
                    continue;
                results.put(i, rec);
            }
            RankResultGenerator generator = new RankResultGenerator(results, algo.getTopN(), testRatingMatrix);
            precision = generator.getPrecisionN();
            totalPrecision = totalPrecision + precision;
            recall = generator.getRecallN();
            totalRecall = totalRecall + recall;
            map = generator.getMAPN();
            totalMAP = totalMAP + map;
            ndcg = generator.getNDCGN();
            totalNDCG = totalNDCG + ndcg;
            mrr = generator.getMRRN();
            totalMRR = totalMRR + mrr;
            auc = generator.getAUC();
            totalAUC = totalAUC + auc;
            System.out.println("Folder --- precision: " + precision + " recall: " + recall + " map: " + map
                    + " ndcg: " + ndcg + " mrr: " + mrr + " auc: " + auc);
            logger.println("Folder --- precision: " + precision + " recall: " + recall + " map: " + map
                    + " ndcg: " + ndcg + " mrr: " + mrr + " auc: " + auc);
        }

        logger.flush();
    }

    System.out.println("MAE: " + totalMAE / F + " RMSE: " + totalRMSE / F);
    System.out.println("Precision@N: " + totalPrecision / F);
    System.out.println("Recall@N: " + totalRecall / F);
    System.out.println("MAP@N: " + totalMAP / F);
    System.out.println("MRR@N: " + totalMRR / F);
    System.out.println("NDCG@N: " + totalNDCG / F);
    System.out.println("AUC@N: " + totalAUC / F);

    logger.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "\n" + "MAE: "
            + totalMAE / F + " RMSE: " + totalRMSE / F + "\n" + "Precision@N: " + totalPrecision / F + "\n"
            + "Recall@N: " + totalRecall / F + "\n" + "MAP@N: " + totalMAP / F + "\n" + "MRR@N: " + totalMRR / F
            + "\n" + "NDCG@N: " + totalNDCG / F + "\n" + "AUC@N: " + totalAUC / F);
    logger.flush();
    logger.close();
}

From source file:ch.epfl.lsir.xin.test.ItemBasedCFTest.java

/**
 * @param args/*from ww w . ja v  a2s  . c o  m*/
 */
public static void main(String[] args) throws Exception {
    // TODO Auto-generated method stub

    PrintWriter logger = new PrintWriter(".//results//ItemBasedCF");
    PropertiesConfiguration config = new PropertiesConfiguration();
    config.setFile(new File(".//conf//ItemBasedCF.properties"));
    try {
        config.load();
    } catch (ConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    logger.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " Read rating data...");
    DataLoaderFile loader = new DataLoaderFile(".//data//MoveLens100k.txt");
    loader.readSimple();
    DataSetNumeric dataset = loader.getDataset();
    System.out.println("Number of ratings: " + dataset.getRatings().size() + " Number of users: "
            + dataset.getUserIDs().size() + " Number of items: " + dataset.getItemIDs().size());
    logger.println("Number of ratings: " + dataset.getRatings().size() + ", Number of users: "
            + dataset.getUserIDs().size() + ", Number of items: " + dataset.getItemIDs().size());
    logger.flush();

    double totalMAE = 0;
    double totalRMSE = 0;
    double totalPrecision = 0;
    double totalRecall = 0;
    double totalMAP = 0;
    double totalNDCG = 0;
    double totalMRR = 0;
    double totalAUC = 0;
    int F = 5;
    logger.println(F + "- folder cross validation.");
    ArrayList<ArrayList<NumericRating>> folders = new ArrayList<ArrayList<NumericRating>>();
    for (int i = 0; i < F; i++) {
        folders.add(new ArrayList<NumericRating>());
    }

    while (dataset.getRatings().size() > 0) {
        int index = new Random().nextInt(dataset.getRatings().size());
        int r = new Random().nextInt(F);
        folders.get(r).add(dataset.getRatings().get(index));
        dataset.getRatings().remove(index);
    }

    for (int folder = 1; folder <= F; folder++) {
        logger.println("Folder: " + folder);
        System.out.println("Folder: " + folder);
        ArrayList<NumericRating> trainRatings = new ArrayList<NumericRating>();
        ArrayList<NumericRating> testRatings = new ArrayList<NumericRating>();
        for (int i = 0; i < folders.size(); i++) {
            if (i == folder - 1)//test data
            {
                testRatings.addAll(folders.get(i));
            } else {//training data
                trainRatings.addAll(folders.get(i));
            }
        }

        //create rating matrix
        HashMap<String, Integer> userIDIndexMapping = new HashMap<String, Integer>();
        HashMap<String, Integer> itemIDIndexMapping = new HashMap<String, Integer>();
        for (int i = 0; i < dataset.getUserIDs().size(); i++) {
            userIDIndexMapping.put(dataset.getUserIDs().get(i), i);
        }
        for (int i = 0; i < dataset.getItemIDs().size(); i++) {
            itemIDIndexMapping.put(dataset.getItemIDs().get(i), i);
        }
        RatingMatrix trainRatingMatrix = new RatingMatrix(dataset.getUserIDs().size(),
                dataset.getItemIDs().size());
        for (int i = 0; i < trainRatings.size(); i++) {
            trainRatingMatrix.set(userIDIndexMapping.get(trainRatings.get(i).getUserID()),
                    itemIDIndexMapping.get(trainRatings.get(i).getItemID()), trainRatings.get(i).getValue());
        }
        trainRatingMatrix.calculateGlobalAverage();
        trainRatingMatrix.calculateItemsMean();
        RatingMatrix testRatingMatrix = new RatingMatrix(dataset.getUserIDs().size(),
                dataset.getItemIDs().size());
        for (int i = 0; i < testRatings.size(); i++) {
            testRatingMatrix.set(userIDIndexMapping.get(testRatings.get(i).getUserID()),
                    itemIDIndexMapping.get(testRatings.get(i).getItemID()), testRatings.get(i).getValue());
        }
        System.out.println("Training: " + trainRatingMatrix.getTotalRatingNumber() + " vs Test: "
                + testRatingMatrix.getTotalRatingNumber());
        logger.println("Initialize a item based collaborative filtering recommendation model.");
        ItemBasedCF algo = new ItemBasedCF(trainRatingMatrix);
        algo.setLogger(logger);
        algo.build();//if read local model, no need to build the model
        algo.saveModel(".//localModels//" + config.getString("NAME"));
        logger.println("Save the model.");
        logger.flush();

        //rating prediction accuracy
        double RMSE = 0;
        double MAE = 0;
        double precision = 0;
        double recall = 0;
        double map = 0;
        double ndcg = 0;
        double mrr = 0;
        double auc = 0;
        int count = 0;
        for (int i = 0; i < testRatings.size(); i++) {
            NumericRating rating = testRatings.get(i);
            double prediction = algo.predict(userIDIndexMapping.get(rating.getUserID()),
                    itemIDIndexMapping.get(rating.getItemID()), false);
            if (prediction > algo.getMaxRating())
                prediction = algo.getMaxRating();
            if (prediction < algo.getMinRating())
                prediction = algo.getMinRating();

            if (Double.isNaN(prediction)) {
                System.out.println("no prediction");
                continue;
            }
            MAE = MAE + Math.abs(rating.getValue() - prediction);
            RMSE = RMSE + Math.pow((rating.getValue() - prediction), 2);
            count++;
        }
        MAE = MAE / count;
        RMSE = Math.sqrt(RMSE / count);
        totalMAE = totalMAE + MAE;
        totalRMSE = totalRMSE + RMSE;
        System.out.println("Folder --- MAE: " + MAE + " RMSE: " + RMSE);
        logger.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " Folder --- MAE: "
                + MAE + " RMSE: " + RMSE);

        //ranking accuracy
        if (algo.getTopN() > 0) {
            HashMap<Integer, ArrayList<ResultUnit>> results = new HashMap<Integer, ArrayList<ResultUnit>>();
            for (int i = 0; i < trainRatingMatrix.getRow(); i++) {
                //               ArrayList<ResultUnit> rec = algo.getRecommendationList(i);
                //               results.put(i, rec);
                ArrayList<ResultUnit> rec = algo.getRecommendationList(i);
                if (rec == null)
                    continue;
                int total = testRatingMatrix.getUserRatingNumber(i);
                if (total == 0)//this user is ignored
                    continue;
                results.put(i, rec);
            }
            RankResultGenerator generator = new RankResultGenerator(results, algo.getTopN(), testRatingMatrix,
                    trainRatingMatrix);
            precision = generator.getPrecisionN();
            totalPrecision = totalPrecision + precision;
            recall = generator.getRecallN();
            totalRecall = totalRecall + recall;
            map = generator.getMAPN();
            totalMAP = totalMAP + map;
            ndcg = generator.getNDCGN();
            totalNDCG = totalNDCG + ndcg;
            mrr = generator.getMRRN();
            totalMRR = totalMRR + mrr;
            auc = generator.getAUC();
            totalAUC = totalAUC + auc;
            System.out.println("Folder --- precision: " + precision + " recall: " + recall + " map: " + map
                    + " ndcg: " + ndcg + " mrr: " + mrr + " auc: " + auc);
            logger.append("Folder --- precision: " + precision + " recall: " + recall + " map: " + map
                    + " ndcg: " + ndcg + " mrr: " + mrr + " auc: " + auc + "\n");
        }
    }

    System.out.println("MAE: " + totalMAE / F + " RMSE: " + totalRMSE / F);
    System.out.println("Precision@N: " + totalPrecision / F);
    System.out.println("Recall@N: " + totalRecall / F);
    System.out.println("MAP@N: " + totalMAP / F);
    System.out.println("MRR@N: " + totalMRR / F);
    System.out.println("NDCG@N: " + totalNDCG / F);
    System.out.println("AUC@N: " + totalAUC / F);
    System.out.println("similarity: " + config.getString("SIMILARITY"));
    //MAE: 0.7227232762922241 RMSE: 0.9225576790122603 (MovieLens 100K, shrinkage 2500, neighbor size 40, PCC)
    //MAE: 0.7250636319353241 RMSE: 0.9242305485411567 (MovieLens 100K, shrinkage 25, neighbor size 40, PCC)
    //MAE: 0.7477213243604459 RMSE: 0.9512195004171138 (MovieLens 100K, shrinkage 2500, neighbor size 40, COSINE)

    logger.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "\n" + "MAE: "
            + totalMAE / F + " RMSE: " + totalRMSE / F + "\n" + "Precision@N: " + totalPrecision / F + "\n"
            + "Recall@N: " + totalRecall / F + "\n" + "MAP@N: " + totalMAP / F + "\n" + "MRR@N: " + totalMRR / F
            + "\n" + "NDCG@N: " + totalNDCG / F + "\n" + "AUC@N: " + totalAUC / F);
    logger.flush();
    logger.close();
}