Example usage for org.json.simple JSONObject put

List of usage examples for org.json.simple JSONObject put

Introduction

In this page you can find the example usage for org.json.simple JSONObject put.

Prototype

V put(K key, V value);

Source Link

Document

Associates the specified value with the specified key in this map (optional operation).

Usage

From source file:contractEditor.SPConfFileEditor.java

public static void main(String[] args) {

    JSONObject obj = new JSONObject();
    ArrayList fileList = new ArrayList();

    fileList.add("confSP" + File.separator + "HOST1.json");
    fileList.add("confSP" + File.separator + "HOST2.json");
    fileList.add("confSP" + File.separator + "HOST3.json");
    fileList.add("confSP" + File.separator + "HOST4.json");

    obj.put("contract_list_of_SP", fileList);

    try {/*ww  w.ja v a  2s  .c o  m*/

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

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

    System.out.print(obj);

}

From source file:contractEditor.contractClients.java

public static void main(String[] args) {

    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", "18_GB");
    serviceDescription.put("VM1_purpose", "dev");
    serviceDescription.put("VM1_data", "private");
    serviceDescription.put("VM1_application", "internal");

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

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

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

    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);/* w  w w  .  j  a  va  2 s. c o  m*/
    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: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   w  w  w  . j  a  v a 2  s  .  com

    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:com.thesmartweb.swebrank.Main.java

/**
 * @param args the command line arguments
 *///from w  ww. j  av  a  2s  .c o  m
public static void main(String[] args) {
    Path input_path = Paths.get("//mnt//var//DBs//inputsL10//nba//");//input directory
    String output_parent_directory = "//mnt//var//DBs//outputsConfL10//nba//";//output directory
    String config_path = "//mnt//var//DBs//config//";//input directory
    //---Disable apache log manually----
    //System.setProperty("org.apache.commons.logging.Log","org.apache.commons.logging.impl.NoOpLog");
    System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Log4JLogger");
    //--------------Domain that is searched----------
    String domain = "";
    //------------------search engine related options----------------------
    List<String> queries = null;
    int results_number = 0;//the number of results that are returned from each search engine
    List<Boolean> enginechoice = null;
    //list element #0. True/False Bing
    //list element #1. True/False Google
    //list element #2. True/False Yahoo!
    //list element #3. True/False Merged
    //-----------Moz options---------------------
    List<Boolean> mozMetrics = null;
    //The list is going to contain the moz related input in the following order
    //list element #1. True/False, True we use Moz API, false not
    //list element #2. True if we use Domain Authority
    //list element #3. True if we use External MozRank
    //list element #4. True if we use MozRank
    //list element #5. True if we use MozTrust
    //list element #6. True if we use Subdomain MozRank
    //list element #7. True if we use Page Authority
    //only one is used (the first to be set to true)
    boolean moz_threshold_option = false;//set to true we use the threshold
    Double moz_threshold = 0.0;//if we want to have a threshold in moz
    int top_count_moz = 0;//if we want to get the moz top-something results
    //---------------Semantic Analysis method----------------
    List<Boolean> ContentSemantics = null;
    int SensebotConcepts = 0;//define the amount of concepts that sensebot is going to recognize
    List<Double> SWebRankSettings = null;
    //------(string)directory is going to be used later-----
    String output_child_directory;
    //-------we get all the paths of the txt (input) files from the input directory-------
    DataManipulation getfiles = new DataManipulation();//class responsible for the extraction of paths
    Collection<File> inputs_files;//array to include the paths of the txt files
    inputs_files = getfiles.getinputfiles(input_path.toString(), "txt");//method to retrieve all the path of the input documents
    //------------read the txt files------------
    for (File input : inputs_files) {
        ReadInput ri = new ReadInput();//function to read the input
        boolean check_reading_input = ri.perform(input);
        if (check_reading_input) {
            domain = ri.domain;
            //----------
            queries = ri.queries;
            results_number = ri.results_number;
            enginechoice = ri.enginechoice;
            //------------
            mozMetrics = ri.mozMetrics;
            moz_threshold_option = ri.moz_threshold_option;
            moz_threshold = ri.moz_threshold.doubleValue();
            //---------------
            ContentSemantics = ri.ContentSemantics;
            SWebRankSettings = ri.SWebRankSettings;
        }
        int top_visible = 0;//option to set the amount of results you can get in the merged search engine
        //------if we choose to use a Moz metric or Visibility score for our ranking, we need to set the results_number for the search engines to its max which is 50 
        //-----we set the top results number for moz or Visibility rank----
        if (mozMetrics.get(0) || enginechoice.get(3)) {
            if (mozMetrics.get(0)) {
                top_count_moz = results_number;
            } //if moz is true, top_count_moz gets the value of result number
            if (enginechoice.get(3)) {
                top_visible = results_number;
            } //if merged engine is true, top_visible gets the value of result number
            results_number = 50;//this is the max amount of results that you can get from the search engine APIs
        }
        //-----if we want to use Moz we should check first if it works
        if (mozMetrics.get(0)) {
            Moz Moz = new Moz();
            //---if it works, moz remains true, otherwise it is set to false
            mozMetrics.add(0, Moz.check(config_path));
            //if it is false and we have chosen to use Visibility score with Moz, we reset back to the standard settings (ranking and not merged)
            //therefore, we reset the number of results from 50 to the top_count_moz which contained the original number of results
            if (!mozMetrics.get(0)) {
                if (!enginechoice.get(3)) {
                    results_number = top_count_moz;
                }
            }
        }
        //----------we set the wordLists that we are going to use---------------------
        List<String> finalList = new ArrayList<String>();//finalList is going to contain all the content in the end
        Total_analysis ta = new Total_analysis();//we call total analysis
        int iteration_counter = 0;//the iteration_counter is used in order to count the number of iterations of the algorithm and to be checked with perf_limit
        //this list of arraylists  is going to contain all the wordLists that are produced for every term of the String[] query,
        //in order to calculate the NGD scores between every term of the wordList and the term that was used as query in order to produce the spesific wordList
        List<ArrayList<String>> array_wordLists = new ArrayList<>();
        List<String> wordList_previous = new ArrayList<>();
        List<String> wordList_new = new ArrayList<>();
        double convergence = 0;//we create the convergence percentage and initialize it
        String conv_percentages = "";//string that contains all the convergence percentages
        DataManipulation wordsmanipulation = new DataManipulation();//method to manipulate various word data (String, list<String>, etc)
        do { //if we run the algorithm for the 1st time we already have the query so we skip the loop below that produces the new array of query
            if (iteration_counter != 0) {
                wordList_previous = wordList_new;
                //we add the previous wordList to the finalList
                finalList = wordsmanipulation.AddAList(wordList_previous, finalList);
                List<String> query_new_list_total = new ArrayList<>();
                int iteration_previous = iteration_counter - 1;
                Combinations_Engine cn = new Combinations_Engine();//call the class to combine the terms produced
                for (String query : queries) {
                    List<String> ids = new ArrayList<>();
                    if (enginechoice.get(0)) {
                        String id = domain + "/" + query + "/bing" + "/" + iteration_previous;
                        ids.add(id);
                    }
                    if (enginechoice.get(1)) {
                        String id = domain + "/" + query + "/google" + "/" + iteration_previous;
                        ids.add(id);
                    }
                    if (enginechoice.get(2)) {
                        String id = domain + "/" + query + "/yahoo" + "/" + iteration_previous;
                        ids.add(id);
                    }
                    ElasticGetWordList ESget = new ElasticGetWordList();//we call this class to get the wordlist from the Elastic Search
                    List<String> maxWords = ESget.getMaxWords(ids, SWebRankSettings.get(9).intValue(),
                            config_path);//we are going to get a max amount of words
                    int query_index = queries.indexOf(query);
                    int size_query_new = SWebRankSettings.get(10).intValue();//the amount of new queries we are willing to create
                    //we create the new queries for every query of the previous round by combining the words produced from this query
                    List<String> query_new_list = cn.perform(maxWords, SWebRankSettings.get(7), queries,
                            SWebRankSettings.get(6), query_index, size_query_new, config_path);
                    //we add the list of new queries to the total list that containas all the new queries
                    query_new_list_total.addAll(query_new_list);
                    System.out.println("query pointer=" + query_index + "");
                }
                //---------------------the following cleans a list from null and duplicates
                query_new_list_total = wordsmanipulation.clearListString(query_new_list_total);
                //--------------we create the new directory that our files are going to be saved 
                String txt_directory = FilenameUtils.getBaseName(input.getName());
                output_child_directory = output_parent_directory + txt_directory + "_level_" + iteration_counter
                        + "//";
                //----------------append the wordlist to a file------------------
                wordsmanipulation.AppendWordList(query_new_list_total,
                        output_child_directory + "queries_" + iteration_counter + ".txt");
                if (query_new_list_total.size() < 1) {
                    break;
                } //if we don't create new queries we end the while loop
                //total analysis' function is going to do all the work and return back what we need
                ta = new Total_analysis();
                ta.perform(wordList_previous, iteration_counter, output_child_directory, domain, enginechoice,
                        query_new_list_total, results_number, top_visible, mozMetrics, moz_threshold_option,
                        moz_threshold.doubleValue(), top_count_moz, ContentSemantics, SensebotConcepts,
                        SWebRankSettings, config_path);
                //we get the array of wordlists
                array_wordLists = ta.getarray_wordLists();
                //get the wordlist that includes all the new queries
                wordList_new = ta.getwordList_total();
                //---------------------the following cleans a list from null and duplicates-------------
                wordList_new = wordsmanipulation.clearListString(wordList_new);
                //----------------append the wordlist to a file--------------------
                wordsmanipulation.AppendWordList(wordList_new, output_child_directory + "wordList.txt");
                //the concergence percentage of this iteration
                convergence = ta.getConvergence();//we are going to use convergence score to check the convergence
                //a string that contains all the convergence percentage for each round separated by \n character
                conv_percentages = conv_percentages + "\n" + convergence;
                //a file that is going to include the convergence percentages
                wordsmanipulation.AppendString(conv_percentages,
                        output_child_directory + "convergence_percentage.txt");
                //we add the new wordList to the finalList
                finalList = wordsmanipulation.AddAList(wordList_new, finalList);
                //we set the query array to be equal to the query new total that we have created
                queries = query_new_list_total;
                //we increment the iteration_counter in order to count the iterations of the algorithm and to use the perf_limit
                iteration_counter++;
            } else {//the following source code is performed on the 1st run of the loop
                    //------------we extract the parent path of the file 
                String txt_directory = FilenameUtils.getBaseName(input.getName());
                //----------we create a string that is going to be used for the corresponding directory of outputs
                output_child_directory = output_parent_directory + txt_directory + "_level_" + iteration_counter
                        + "//";
                //we call total analysis function performOld
                ta.perform(wordList_new, iteration_counter, output_child_directory, domain, enginechoice,
                        queries, results_number, top_visible, mozMetrics, moz_threshold_option,
                        moz_threshold.doubleValue(), top_count_moz, ContentSemantics, SensebotConcepts,
                        SWebRankSettings, config_path);
                //we get the array of wordlists
                array_wordLists = ta.getarray_wordLists();
                //get the wordlist that includes all the new queries
                wordList_new = ta.getwordList_total();
                //---------------------the following cleans a list from null and duplicates
                wordList_new = wordsmanipulation.clearListString(wordList_new);
                //----------------append the wordlist to a file
                wordsmanipulation.AppendWordList(wordList_new, output_child_directory + "wordList.txt");
                //-----------------------------------------
                iteration_counter++;//increase the iteration_counter that counts the iterations of the algorithm
            }
        } while (convergence < SWebRankSettings.get(5).doubleValue()
                && iteration_counter < SWebRankSettings.get(8).intValue());//while the convergence percentage is below the limit and the iteration_counter below the performance limit
        if (iteration_counter == 1) {
            finalList = wordsmanipulation.AddAList(wordList_new, finalList);
        }
        //--------------------content List----------------
        if (!finalList.isEmpty()) {
            //---------------------the following cleans the final list from null and duplicates
            finalList = wordsmanipulation.clearListString(finalList);
            //write the keywords to a file
            boolean flag_file = false;//boolean flag to declare successful write to file
            flag_file = wordsmanipulation.AppendWordList(finalList,
                    output_parent_directory + "total_content.txt");
            if (!flag_file) {
                System.out.print("can not create the content file for: " + output_parent_directory
                        + "total_content.txt");
            }
        }
        //we are going to save the total content with its convergence on the ElasticSearch cluster in a separated index
        //Node node = nodeBuilder().client(true).clusterName("lshrankldacluster").node();
        //Client client = node.client();
        //get the elastic search indexes in a list
        List<String> elasticIndexes = ri.GetKeyFile(config_path, "elasticSearchIndexes");
        Settings settings = ImmutableSettings.settingsBuilder().put("cluster.name", "lshrankldacluster")
                .build();
        Client client = new TransportClient(settings)
                .addTransportAddress(new InetSocketTransportAddress("localhost", 9300));
        JSONObject objEngineLevel = new JSONObject();
        objEngineLevel.put("TotalContent", finalList);//we save the total content
        objEngineLevel.put("Convergences", conv_percentages);//we save the convergence percentages
        IndexRequest indexReq = new IndexRequest(elasticIndexes.get(0), "content", domain);//we save also the domain 
        indexReq.source(objEngineLevel);
        IndexResponse indexRes = client.index(indexReq).actionGet();
        //node.close();
        client.close();
        //----------------------convergence percentages writing to file---------------
        //use the conv_percentages string
        if (conv_percentages.length() != 0) {
            boolean flag_file = false;//boolean flag to declare successful write to file
            flag_file = wordsmanipulation.AppendString(conv_percentages,
                    output_parent_directory + "convergence_percentages.txt");
            if (!flag_file) {
                System.out.print("can not create the convergence file for: " + output_parent_directory
                        + "convergence_percentages.txt");
            }
        }
    }
}

From source file:at.nonblocking.cliwix.cli.CliwixCliClient.java

public static void main(String[] args) throws Exception {
    Options options = null;//from   w  ww  . j a  v  a 2 s  .c o m

    try {
        options = Options.parseArgs(args);
    } catch (CliwixCliClientArgumentException e) {
        if (debug)
            console.printStacktrace(e);
        console.printlnError("Error: Invalid arguments: " + e.getMessage());
        Options.printUsage();
        console.exit(EXIT_STATUS_FAIL);
        return;
    }

    if (options == null || Options.COMMAND_HELP.equals(options.getCommand())) {
        Options.printUsage();
        console.exit(0);
        return;
    }

    if (Options.COMMAND_CREATE_CONFIG.equals(options.getCommand())) {
        if (args.length < 2) {
            console.printlnError("Error: No config file location given!");
            console.exit(EXIT_STATUS_FAIL);
            return;
        }
        File configFile = new File(args[1]);
        options.copyDefaultPropertiesTo(configFile);
        console.println("Configuration saved under: " + configFile.getAbsolutePath());
        console.exit(0);
        return;
    }

    debug = options.isDebug();

    String cliwixServerUrl = options.getServerCliwixUrl();
    String username = options.getServerUsername();
    String password = options.getServerPassword();

    if (cliwixServerUrl == null) {
        console.printlnError("Error: Property server.cliwix.url is required!");
        console.exit(EXIT_STATUS_FAIL);
        return;
    }

    cookieManager.clear();

    //Login
    if (username != null && password != null) {
        JSONObject loginData = new JSONObject();
        loginData.put("username", username);
        loginData.put("password", password);
        JSONObject result = postJson(cliwixServerUrl, "/services/login", loginData);
        JSONObject loginResult = (JSONObject) result.get("loginResult");

        if (loginResult.get("succeeded") == Boolean.TRUE) {
            console.println("Login successful");
        } else {
            console.printlnError("Error: Login failed! Reason: " + loginData.get("errorMessage"));
            console.exit(EXIT_STATUS_FAIL);
            return;
        }

    } else if (username != null) {
        console.printlnError("Error: If -user is set -pass is required!");
        console.exit(EXIT_STATUS_FAIL);
        return;
    } else if (password != null) {
        console.printlnError("Error: If -pass is set -user is required!");
        console.exit(EXIT_STATUS_FAIL);
        return;
    }

    switch (options.getCommand()) {
    case Options.COMMAND_INFO:
        doInfo(cliwixServerUrl, options);
        break;
    case Options.COMMAND_EXPORT:
        doExport(cliwixServerUrl, options);
        break;
    case Options.COMMAND_IMPORT:
        doImport(cliwixServerUrl, options);
        break;
    default:
    case Options.COMMAND_HELP:
        Options.printUsage();
    }
}

From source file:com.entertailion.java.caster.Main.java

/**
 * @param args// w  w w. j  a  v a  2  s . co m
 */
public static void main(String[] args) {
    // http://commons.apache.org/proper/commons-cli/usage.html
    Option help = new Option("h", "help", false, "Print this help message");
    Option version = new Option("V", "version", false, "Print version information");
    Option list = new Option("l", "list", false, "List ChromeCast devices");
    Option verbose = new Option("v", "verbose", false, "Verbose debug logging");
    Option transcode = new Option("t", "transcode", false, "Transcode media; -f also required");
    Option rest = new Option("r", "rest", false, "REST API server");

    Option url = OptionBuilder.withLongOpt("stream").hasArg().withValueSeparator()
            .withDescription("HTTP URL for streaming content; -d also required").create("s");

    Option server = OptionBuilder.withLongOpt("device").hasArg().withValueSeparator()
            .withDescription("ChromeCast device IP address").create("d");

    Option id = OptionBuilder.withLongOpt("app-id").hasArg().withValueSeparator()
            .withDescription("App ID for whitelisted device").create("id");

    Option mediaFile = OptionBuilder.withLongOpt("file").hasArg().withValueSeparator()
            .withDescription("Local media file; -d also required").create("f");

    Option transcodingParameters = OptionBuilder.withLongOpt("transcode-parameters").hasArg()
            .withValueSeparator().withDescription("Transcode parameters; -t also required").create("tp");

    Option restPort = OptionBuilder.withLongOpt("rest-port").hasArg().withValueSeparator()
            .withDescription("REST API port; default 8080").create("rp");

    Options options = new Options();
    options.addOption(help);
    options.addOption(version);
    options.addOption(list);
    options.addOption(verbose);
    options.addOption(url);
    options.addOption(server);
    options.addOption(id);
    options.addOption(mediaFile);
    options.addOption(transcode);
    options.addOption(transcodingParameters);
    options.addOption(rest);
    options.addOption(restPort);
    // create the command line parser
    CommandLineParser parser = new PosixParser();

    //String[] arguments = new String[] { "-vr" };

    try {
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);
        Option[] lineOptions = line.getOptions();
        if (lineOptions.length == 0) {
            System.out.println("caster: try 'java -jar caster.jar -h' for more information");
            System.exit(0);
        }

        Log.setVerbose(line.hasOption("v"));

        // Custom app-id
        if (line.hasOption("id")) {
            Log.d(LOG_TAG, line.getOptionValue("id"));
            appId = line.getOptionValue("id");
        }

        // Print version
        if (line.hasOption("V")) {
            System.out.println("Caster version " + VERSION);
        }

        // List ChromeCast devices
        if (line.hasOption("l")) {
            final DeviceFinder deviceFinder = new DeviceFinder(new DeviceFinderListener() {

                @Override
                public void discoveringDevices(DeviceFinder deviceFinder) {
                    Log.d(LOG_TAG, "discoveringDevices");
                }

                @Override
                public void discoveredDevices(DeviceFinder deviceFinder) {
                    Log.d(LOG_TAG, "discoveredDevices");
                    TrackedDialServers trackedDialServers = deviceFinder.getTrackedDialServers();
                    for (DialServer dialServer : trackedDialServers) {
                        System.out.println(dialServer.toString()); // keep system for output
                    }
                }

            });
            deviceFinder.discoverDevices();
        }

        // Stream media from internet
        if (line.hasOption("s") && line.hasOption("d")) {
            Log.d(LOG_TAG, line.getOptionValue("d"));
            Log.d(LOG_TAG, line.getOptionValue("s"));
            try {
                Playback playback = new Playback(platform, appId,
                        new DialServer(InetAddress.getByName(line.getOptionValue("d"))),
                        new PlaybackListener() {
                            private int time;
                            private int duration;
                            private int state;

                            @Override
                            public void updateTime(Playback playback, int time) {
                                Log.d(LOG_TAG, "updateTime: " + time);
                                this.time = time;
                            }

                            @Override
                            public void updateDuration(Playback playback, int duration) {
                                Log.d(LOG_TAG, "updateDuration: " + duration);
                                this.duration = duration;
                            }

                            @Override
                            public void updateState(Playback playback, int state) {
                                Log.d(LOG_TAG, "updateState: " + state);
                                // Stop the app if the video reaches the end
                                if (time > 0 && time == duration && state == 0) {
                                    playback.doStop();
                                    System.exit(0);
                                }
                            }

                            public int getTime() {
                                return time;
                            }

                            public int getDuration() {
                                return duration;
                            }

                            public int getState() {
                                return state;
                            }

                        });
                playback.stream(line.getOptionValue("s"));
            } catch (Exception e) {
                e.printStackTrace();
                System.exit(1);
            }
        }

        // Play local media file
        if (line.hasOption("f") && line.hasOption("d")) {
            Log.d(LOG_TAG, line.getOptionValue("d"));
            Log.d(LOG_TAG, line.getOptionValue("f"));

            final String file = line.getOptionValue("f");
            String device = line.getOptionValue("d");

            try {
                Playback playback = new Playback(platform, appId, new DialServer(InetAddress.getByName(device)),
                        new PlaybackListener() {
                            private int time;
                            private int duration;
                            private int state;

                            @Override
                            public void updateTime(Playback playback, int time) {
                                Log.d(LOG_TAG, "updateTime: " + time);
                                this.time = time;
                            }

                            @Override
                            public void updateDuration(Playback playback, int duration) {
                                Log.d(LOG_TAG, "updateDuration: " + duration);
                                this.duration = duration;
                            }

                            @Override
                            public void updateState(Playback playback, int state) {
                                Log.d(LOG_TAG, "updateState: " + state);
                                // Stop the app if the video reaches the end
                                if (time > 0 && time == duration && state == 0) {
                                    playback.doStop();
                                    System.exit(0);
                                }
                            }

                            public int getTime() {
                                return time;
                            }

                            public int getDuration() {
                                return duration;
                            }

                            public int getState() {
                                return state;
                            }

                        });
                if (line.hasOption("t") && line.hasOption("tp")) {
                    playback.setTranscodingParameters(line.getOptionValue("tp"));
                }
                playback.play(file, line.hasOption("t"));
            } catch (Exception e) {
                e.printStackTrace();
                System.exit(1);
            }
        }

        // REST API server
        if (line.hasOption("r")) {
            final DeviceFinder deviceFinder = new DeviceFinder(new DeviceFinderListener() {

                @Override
                public void discoveringDevices(DeviceFinder deviceFinder) {
                    Log.d(LOG_TAG, "discoveringDevices");
                }

                @Override
                public void discoveredDevices(DeviceFinder deviceFinder) {
                    Log.d(LOG_TAG, "discoveredDevices");
                    TrackedDialServers trackedDialServers = deviceFinder.getTrackedDialServers();
                    for (DialServer dialServer : trackedDialServers) {
                        Log.d(LOG_TAG, dialServer.toString());
                    }
                }

            });
            deviceFinder.discoverDevices();

            int port = 0;
            if (line.hasOption("rp")) {
                try {
                    port = Integer.parseInt(line.getOptionValue("rp"));
                } catch (NumberFormatException e) {
                    Log.e(LOG_TAG, "invalid rest port", e);
                }
            }

            Playback.startWebserver(port, new WebListener() {
                String[] prefixes = { "/playback", "/devices" };
                HashMap<String, Playback> playbackMap = new HashMap<String, Playback>();
                HashMap<String, RestPlaybackListener> playbackListenerMap = new HashMap<String, RestPlaybackListener>();

                final class RestPlaybackListener implements PlaybackListener {
                    private String device;
                    private int time;
                    private int duration;
                    private int state;

                    public RestPlaybackListener(String device) {
                        this.device = device;
                    }

                    @Override
                    public void updateTime(Playback playback, int time) {
                        Log.d(LOG_TAG, "updateTime: " + time);
                        this.time = time;
                    }

                    @Override
                    public void updateDuration(Playback playback, int duration) {
                        Log.d(LOG_TAG, "updateDuration: " + duration);
                        this.duration = duration;
                    }

                    @Override
                    public void updateState(Playback playback, int state) {
                        Log.d(LOG_TAG, "updateState: " + state);
                        this.state = state;
                        // Stop the app if the video reaches the end
                        if (this.time > 0 && this.time == this.duration && state == 0) {
                            playback.doStop();
                            playbackMap.remove(device);
                            playbackListenerMap.remove(device);
                        }
                    }

                    public int getTime() {
                        return time;
                    }

                    public int getDuration() {
                        return duration;
                    }

                    public int getState() {
                        return state;
                    }

                }

                @Override
                public Response handleRequest(String uri, String method, Properties header, Properties parms) {
                    Log.d(LOG_TAG, "handleRequest: " + uri);

                    if (method.equals("GET")) {
                        if (uri.startsWith(prefixes[0])) { // playback
                            String device = parms.getProperty("device");
                            if (device != null) {
                                RestPlaybackListener playbackListener = playbackListenerMap.get(device);
                                if (playbackListener != null) {
                                    // https://code.google.com/p/json-simple/wiki/EncodingExamples
                                    JSONObject obj = new JSONObject();
                                    obj.put("time", playbackListener.getTime());
                                    obj.put("duration", playbackListener.getDuration());
                                    switch (playbackListener.getState()) {
                                    case 0:
                                        obj.put("state", "idle");
                                        break;
                                    case 1:
                                        obj.put("state", "stopped");
                                        break;
                                    case 2:
                                        obj.put("state", "playing");
                                        break;
                                    default:
                                        obj.put("state", "idle");
                                        break;
                                    }
                                    return new Response(HttpServer.HTTP_OK, "text/plain", obj.toJSONString());
                                } else {
                                    // Nothing is playing
                                    JSONObject obj = new JSONObject();
                                    obj.put("time", 0);
                                    obj.put("duration", 0);
                                    obj.put("state", "stopped");
                                    return new Response(HttpServer.HTTP_OK, "text/plain", obj.toJSONString());
                                }
                            }
                        } else if (uri.startsWith(prefixes[1])) { // devices
                            // https://code.google.com/p/json-simple/wiki/EncodingExamples
                            JSONArray list = new JSONArray();
                            TrackedDialServers trackedDialServers = deviceFinder.getTrackedDialServers();
                            for (DialServer dialServer : trackedDialServers) {
                                JSONObject obj = new JSONObject();
                                obj.put("name", dialServer.getFriendlyName());
                                obj.put("ip_address", dialServer.getIpAddress().getHostAddress());
                                list.add(obj);
                            }
                            return new Response(HttpServer.HTTP_OK, "text/plain", list.toJSONString());
                        }
                    } else if (method.equals("POST")) {
                        if (uri.startsWith(prefixes[0])) { // playback
                            String device = parms.getProperty("device");
                            if (device != null) {
                                String stream = parms.getProperty("stream");
                                String file = parms.getProperty("file");
                                String state = parms.getProperty("state");
                                String transcode = parms.getProperty("transcode");
                                String transcodeParameters = parms.getProperty("transcode-parameters");
                                Log.d(LOG_TAG, "transcodeParameters=" + transcodeParameters);
                                if (stream != null) {
                                    try {
                                        if (playbackMap.get(device) == null) {
                                            DialServer dialServer = deviceFinder.getTrackedDialServers()
                                                    .findDialServer(InetAddress.getByName(device));
                                            if (dialServer != null) {
                                                RestPlaybackListener playbackListener = new RestPlaybackListener(
                                                        device);
                                                playbackMap.put(device, new Playback(platform, appId,
                                                        dialServer, playbackListener));
                                                playbackListenerMap.put(device, playbackListener);
                                            }
                                        }
                                        Playback playback = playbackMap.get(device);
                                        if (playback != null) {
                                            playback.stream(stream);
                                            return new Response(HttpServer.HTTP_OK, "text/plain", "Ok");
                                        }
                                    } catch (Exception e1) {
                                        Log.e(LOG_TAG, "playback", e1);
                                    }
                                } else if (file != null) {
                                    try {
                                        if (playbackMap.get(device) == null) {
                                            DialServer dialServer = deviceFinder.getTrackedDialServers()
                                                    .findDialServer(InetAddress.getByName(device));
                                            if (dialServer != null) {
                                                RestPlaybackListener playbackListener = new RestPlaybackListener(
                                                        device);
                                                playbackMap.put(device, new Playback(platform, appId,
                                                        dialServer, playbackListener));
                                                playbackListenerMap.put(device, playbackListener);
                                            }
                                        }
                                        Playback playback = playbackMap.get(device);
                                        if (transcodeParameters != null) {
                                            playback.setTranscodingParameters(transcodeParameters);
                                        }
                                        if (playback != null) {
                                            playback.play(file, transcode != null);
                                            return new Response(HttpServer.HTTP_OK, "text/plain", "Ok");
                                        }
                                    } catch (Exception e1) {
                                        Log.e(LOG_TAG, "playback", e1);
                                    }
                                } else if (state != null) {
                                    try {
                                        if (playbackMap.get(device) == null) {
                                            DialServer dialServer = deviceFinder.getTrackedDialServers()
                                                    .findDialServer(InetAddress.getByName(device));
                                            if (dialServer != null) {
                                                RestPlaybackListener playbackListener = new RestPlaybackListener(
                                                        device);
                                                playbackMap.put(device, new Playback(platform, appId,
                                                        dialServer, playbackListener));
                                                playbackListenerMap.put(device, playbackListener);
                                            }
                                        }
                                        Playback playback = playbackMap.get(device);
                                        if (playback != null) {
                                            // Handle case where current app wasn't started with caster
                                            playback.setDialServer(deviceFinder.getTrackedDialServers()
                                                    .findDialServer(InetAddress.getByName(device)));
                                            // Change the playback state
                                            if (state.equals("play")) {
                                                playback.doPlay();
                                                return new Response(HttpServer.HTTP_OK, "text/plain", "Ok");
                                            } else if (state.equals("pause")) {
                                                playback.doPause();
                                                return new Response(HttpServer.HTTP_OK, "text/plain", "Ok");
                                            } else if (state.equals("stop")) {
                                                playback.doStop();
                                                playbackMap.remove(device);
                                                playbackListenerMap.remove(device);
                                                return new Response(HttpServer.HTTP_OK, "text/plain", "Ok");
                                            } else {
                                                Log.e(LOG_TAG, "playback invalid state: " + state);
                                            }
                                        }
                                    } catch (Exception e1) {
                                        Log.e(LOG_TAG, "playback", e1);
                                    }
                                }
                            }
                        }
                    }

                    return new Response(HttpServer.HTTP_BADREQUEST, "text/plain", "Bad Request");
                }

                @Override
                public String[] uriPrefixes() {
                    return prefixes;
                }

            });
            Log.d(LOG_TAG, "REST server ready");

            // Run forever...
            while (true) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                }
            }
        }

        // Print help
        if (line.hasOption("h")) {
            printHelp(options);
        }
    } catch (ParseException exp) {
        System.out.println("ERROR: " + exp.getMessage());
        System.out.println();
        printHelp(options);
    }
}

From source file:com.owly.clnt.OwlyClnt.java

/**
 * @param args/*from   w w w .  ja v  a2s  . co m*/
 *            First argument in the port where webserver is going to start
 */
public static void main(String[] args) {

    Logger log = Logger.getLogger(OwlyClnt.class);
    log.debug("Executing OwlyClnt");

    if (args.length == 1) {

        String clientport = args[0];
        setPort(Integer.parseInt(clientport));
        log.debug("Port to run  :" + clientport);

        // URL used for generating the VMstat of the server
        get(new Route("/OwlyClnt/Stats_Vmstat") {
            @Override
            public Object handle(Request request, Response response) {

                Logger log = Logger.getLogger(OwlyClnt.class);
                log.debug("Calling Stats_Vmstat");

                OSValidator osValidator = new OSValidator();
                log.debug("operating System " + osValidator.getOS());

                JSONObject json = new JSONObject();

                if (osValidator.isWindows()) {

                    StatsWinTypeperf testStats = new StatsWinTypeperf();

                    try {
                        json = testStats.getWinTypeperf();

                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                } else {
                    if (OSValidator.isUnix()) {

                        StatsVmstat testStats = new StatsVmstat();

                        try {
                            json = testStats.getJSONVmStat();
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    } else {
                        json.put("StatType", "NOK");

                    }

                }

                return json.toString();

            }

        });

        // URL used for generating the TopCPU of the server
        get(new Route("/OwlyClnt/Stats_TopCPU") {
            @Override
            public Object handle(Request request, Response response) {

                Logger log = Logger.getLogger(OwlyClnt.class);
                log.debug("Calling Stats_Vmstat");

                OSValidator osValidator = new OSValidator();
                log.debug("operating System " + osValidator.getOS());

                JSONObject topCpuStatJson = new JSONObject();

                if (OSValidator.isUnix()) {

                    StatsTopCpu testStats = new StatsTopCpu();

                    try {
                        topCpuStatJson = testStats.getJSONTopCpu();
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                } else {
                    topCpuStatJson.put("StatType", "NOK");

                }

                return topCpuStatJson.toString();
            }
        });

        // Url used for executing a healthcheck and see if the server is
        // available
        get(new Route("/healthCheck") {
            @Override
            public Object handle(Request request, Response response) {

                JSONObject objJSON = new JSONObject();
                objJSON.put("StatusServer", "OK");

                return objJSON.toString();
            }
        });

    } else {
        System.out.println("ERROR : you need to specify port number -> ./OwlyClnt port ");
    }

}

From source file:fr.bmartel.protocol.google.main.LaunchOauthApiServer.java

/**
 * The main method./*from w w  w.  jav a2 s .  c  om*/
 *
 * @param args the arguments
 */
public static void main(String[] args) {

    webPath = "";
    clientId = "";
    clientSecret = "";

    if (args.length == 3) {

        for (int i = 0; i < 3; i++) {
            if (args[i].toLowerCase().startsWith("webpath="))
                webPath = args[i].substring(args[i].indexOf("webpath=") + "webpath=".length() + 1,
                        args[i].length());
            if (args[i].toLowerCase().startsWith("clientid="))
                clientId = args[i].substring(args[i].indexOf("clientid=") + "clientid=".length() + 1,
                        args[i].length());
            if (args[i].toLowerCase().startsWith("clientsecret="))
                clientSecret = args[i].substring(
                        args[i].indexOf("clientsecret=") + "clientsecret=".length() + 1, args[i].length());
        }

        if (webPath.equals("")) {
            printHelp("Error web path is missing");
            return;
        } else if (clientId.equals("")) {
            printHelp("Error client Id is missing");
            return;
        } else if (clientSecret.equals("")) {
            printHelp("Error client secret is missing");
            return;
        }
    } else {
        printHelp("");
        return;
    }
    // start http server
    HttpServer server = new HttpServer(SERVER_PORT);

    websocketServer = new WebsocketServer(WEBSOCKET_SERVER_PORT);

    websocketServer.addServerEventListener(new IClientEventListener() {

        @SuppressWarnings("unchecked")
        @Override
        public void onMessageReceivedFromClient(final IWebsocketClient client, String message) {

            JSONObject obj = (JSONObject) JSONValue.parse(message);

            if (obj != null && obj.containsKey(JsonConstants.API_ACTION)) {

                System.out.println("[API] > " + obj.toJSONString());

                String action = obj.get(JsonConstants.API_ACTION).toString();

                if (action != null) {
                    if (action.equals(JsonConstants.API_REGISTRATION_STATE)) {

                        JSONObject registrationResponse = new JSONObject();

                        if (calendarNotifManager != null
                                && calendarNotifManager.getOauthRegistration() != null) {

                            registrationResponse.put(JsonConstants.GOOGLE_OAUTH_DEVICE_CODE,
                                    calendarNotifManager.getOauthRegistration().getDeviceCode());
                            registrationResponse.put(JsonConstants.GOOGLE_OAUTH_EXPIRING_BEFORE,
                                    calendarNotifManager.getOauthRegistration().getExpiringBefore());
                            registrationResponse.put(JsonConstants.GOOGLE_OAUTH_INTERVAL,
                                    calendarNotifManager.getOauthRegistration().getInterval());
                            registrationResponse.put(JsonConstants.GOOGLE_OAUTH_USERCODE,
                                    calendarNotifManager.getOauthRegistration().getUserCode());
                            registrationResponse.put(JsonConstants.GOOGLE_OAUTH_VERIFICATION_URL,
                                    calendarNotifManager.getOauthRegistration().getVerificationUrl());

                        }

                        System.out.println("[API] < " + registrationResponse.toJSONString());
                        client.sendMessage(registrationResponse.toJSONString());

                    } else if (action.equals(JsonConstants.API_TOKEN_STATE)) {

                        JSONObject requestTokenResponse = new JSONObject();

                        if (calendarNotifManager != null && calendarNotifManager.getCurrentToken() != null) {

                            requestTokenResponse.put(JsonConstants.GOOGLE_OAUTH_ACCESS_TOKEN,
                                    calendarNotifManager.getCurrentToken().getAccessToken());
                            requestTokenResponse.put(JsonConstants.GOOGLE_OAUTH_TOKEN_TYPE,
                                    calendarNotifManager.getCurrentToken().getTokenType());
                            requestTokenResponse.put(JsonConstants.GOOGLE_OAUTH_EXPIRE_IN,
                                    calendarNotifManager.getCurrentToken().getExpiresIn());

                        }
                        System.out.println("[API] < " + requestTokenResponse.toJSONString());
                        client.sendMessage(requestTokenResponse.toJSONString());

                    } else if (action.equals(JsonConstants.API_REGISTRATION)) {

                        calendarNotifManager = new CalendarNotifManager(clientId, clientSecret);

                        calendarNotifManager.requestDeviceAuth(new IOauthDeviceResponseListener() {

                            @Override
                            public void onResponseReceived(OauthForDeviceResponse response) {
                                if (response != null) {
                                    JSONObject registrationResponse = new JSONObject();
                                    registrationResponse.put(JsonConstants.GOOGLE_OAUTH_DEVICE_CODE,
                                            response.getDeviceCode());
                                    registrationResponse.put(JsonConstants.GOOGLE_OAUTH_EXPIRING_BEFORE,
                                            response.getExpiringBefore());
                                    registrationResponse.put(JsonConstants.GOOGLE_OAUTH_INTERVAL,
                                            response.getInterval());
                                    registrationResponse.put(JsonConstants.GOOGLE_OAUTH_USERCODE,
                                            response.getUserCode());
                                    registrationResponse.put(JsonConstants.GOOGLE_OAUTH_VERIFICATION_URL,
                                            response.getVerificationUrl());

                                    System.out.println("[API] < " + registrationResponse.toJSONString());

                                    client.sendMessage(registrationResponse.toJSONString());
                                }
                            }
                        });
                    } else if (action.equals(JsonConstants.API_REQUEST_TOKEN)) {

                        if (calendarNotifManager != null) {
                            calendarNotifManager.requestToken(new IRequestTokenListener() {

                                @Override
                                public void onRequestTokenReceived(OauthToken token) {
                                    if (token != null) {
                                        JSONObject requestTokenResponse = new JSONObject();
                                        requestTokenResponse.put(JsonConstants.GOOGLE_OAUTH_ACCESS_TOKEN,
                                                token.getAccessToken());
                                        requestTokenResponse.put(JsonConstants.GOOGLE_OAUTH_TOKEN_TYPE,
                                                token.getTokenType());
                                        requestTokenResponse.put(JsonConstants.GOOGLE_OAUTH_EXPIRE_IN,
                                                token.getExpiresIn());

                                        System.out.println("[API] < " + requestTokenResponse.toJSONString());

                                        client.sendMessage(requestTokenResponse.toJSONString());
                                    }
                                }

                                @Override
                                public void onRequestTokenError(String description) {
                                    String response = "{\"error\":\"request token error\",\"error_description\":\""
                                            + description + "\"}";

                                    System.out.println("[API] < " + response);

                                    client.sendMessage(response);
                                }
                            });
                        }
                    } else if (action.equals(JsonConstants.API_REVOKE_TOKEN)) {

                        if (calendarNotifManager != null) {
                            calendarNotifManager.revokeToken(new IRevokeTokenListener() {

                                @Override
                                public void onSuccess() {

                                    System.out.println("[API] < " + "{\"revokeToken\":\"success\"}");

                                    client.sendMessage("{\"revokeToken\":\"success\"}");
                                }

                                @Override
                                public void onError(String description) {

                                    String response = "{\"error\":\"request token error\",\"error_description\":\""
                                            + description + "\"}";

                                    System.out.println("[API] < " + response);

                                    client.sendMessage(response);
                                }
                            });
                        }
                    } else if (action.equals(JsonConstants.API_USER_PROFILE)) {
                        if (calendarNotifManager != null) {
                            calendarNotifManager.getUserProfileManager()
                                    .getUserProfile(new IUserProfileListener() {

                                        @Override
                                        public void onSuccess(UserProfile userProfile) {
                                            if (userProfile != null) {
                                                JSONObject userProfileResponse = new JSONObject();
                                                userProfileResponse.put(JsonConstants.GOOGLE_API_PROFILE_GENDER,
                                                        userProfile.getGender());
                                                userProfileResponse.put(
                                                        JsonConstants.GOOGLE_API_PROFILE_DISPLAY_NAME,
                                                        userProfile.getDisplayName());
                                                userProfileResponse.put(
                                                        JsonConstants.GOOGLE_API_PROFILE_FAMILY_NAME,
                                                        userProfile.getFamilyName());
                                                userProfileResponse.put(
                                                        JsonConstants.GOOGLE_API_PROFILE_GIVEN_NAME,
                                                        userProfile.getGivenName());
                                                userProfileResponse.put(
                                                        JsonConstants.GOOGLE_API_PROFILE_LANGUAGE,
                                                        userProfile.getLanguage());

                                                System.out.println(
                                                        "[API] < " + userProfileResponse.toJSONString());

                                                client.sendMessage(userProfileResponse.toJSONString());
                                            }
                                        }

                                        @Override
                                        public void onError(String description) {

                                            String response = "{\"error\":\"request token error\",\"error_description\":\""
                                                    + description + "\"}";

                                            System.out.println("[API] < " + response);

                                            client.sendMessage(response);
                                        }
                                    });
                        }
                    } else if (action.equals(JsonConstants.API_CREATE_EVENT)
                            && obj.containsKey(JsonConstants.API_DATE_BEGIN)
                            && obj.containsKey(JsonConstants.API_DATE_END)
                            && obj.containsKey(JsonConstants.API_SUMMARY)) {

                        String dateBegin = obj.get(JsonConstants.API_DATE_BEGIN).toString();
                        String dateEnd = obj.get(JsonConstants.API_DATE_END).toString();
                        String summary = obj.get(JsonConstants.API_SUMMARY).toString();

                        if (calendarNotifManager != null) {

                            calendarNotifManager.getCalendarManager().createEvent(dateBegin, dateEnd, summary,
                                    new ICreateEventListener() {

                                        @Override
                                        public void onError(String description) {

                                            String response = "{\"error\":\"request token error\",\"error_description\":\""
                                                    + description + "\"}";

                                            System.out.println("[API] < " + response);

                                            client.sendMessage(
                                                    "{\"error\":\"request token error\",\"error_description\":\""
                                                            + description + "\"}");
                                        }

                                        @Override
                                        public void onCreateSuccess(String id) {

                                            String response = "{\"createEvent\":\"success\",\"eventId\":\"" + id
                                                    + "\"}";

                                            System.out.println("[API] < " + response);

                                            client.sendMessage(response);
                                        }
                                    });
                        }
                    } else if (action.equals(JsonConstants.API_DELETE_EVENT)
                            && obj.containsKey(JsonConstants.API_EVENT_ID)) {

                        final String eventId = obj.get(JsonConstants.API_EVENT_ID).toString();

                        calendarNotifManager.getCalendarManager().deleteEvent(eventId,
                                new IDeleteEventListener() {

                                    @Override
                                    public void onSuccess() {

                                        String response = "{\"deleteEvent\":\"success\",\"eventId\":\""
                                                + eventId + "\"}";

                                        System.out.println("[API] < " + response);

                                        client.sendMessage(response);
                                    }

                                    @Override
                                    public void onError(String description) {

                                        String response = "{\"error\":\"request token error\",\"error_description\":\""
                                                + description + "\"}";

                                        System.out.println("[API] < " + response);

                                        client.sendMessage(response);
                                    }
                                });

                    } else if (action.equals(JsonConstants.API_GET_EVENTS)
                            && obj.containsKey(JsonConstants.API_DATE_BEGIN)
                            && obj.containsKey(JsonConstants.API_DATE_END) && obj.containsKey("searchText")
                            && calendarNotifManager != null) {

                        String dateBegin = obj.get(JsonConstants.API_DATE_BEGIN).toString();
                        String dateEnd = obj.get(JsonConstants.API_DATE_END).toString();
                        String searchText = obj.get(JsonConstants.API_SEARCH_TEXT).toString();

                        calendarNotifManager.getCalendarManager().getEventList(dateBegin, dateEnd, searchText,
                                new IEventListListener() {

                                    @Override
                                    public void onEventListReceived(List<CalendarEvents> calendarEventList) {

                                        String response = "{\"eventList\":" + CalendarUtils
                                                .convertCalendarListToJsonArray(calendarEventList)
                                                .toJSONString() + "}";

                                        System.out.println("[API] < " + response);

                                        client.sendMessage(response);
                                    }

                                    @Override
                                    public void onError(String description) {

                                        String response = "{\"error\":\"request token error\",\"error_description\":\""
                                                + description + "\"}";

                                        System.out.println("[API] < " + response);

                                        client.sendMessage(response);
                                    }
                                });

                    } else if (action.equals(JsonConstants.API_SUBSCRIBE_EVENT)
                            && obj.containsKey(JsonConstants.API_EVENT_ID)
                            && obj.containsKey(JsonConstants.API_TIME_ABOUT_TO_START)) {

                        String eventId = obj.get(JsonConstants.API_EVENT_ID).toString();
                        int timeAboutToStart = Integer
                                .parseInt(obj.get(JsonConstants.API_TIME_ABOUT_TO_START).toString());

                        calendarNotifManager.getNotificationManager().subscribeEvent(eventId, timeAboutToStart,
                                new IEventListener() {

                                    @Override
                                    public void onEventStart(String eventId, String summary) {

                                        String response = "{\"subscribedEvent\":\"" + eventId
                                                + "\",\"eventType\":\"started\",\"summary\":\"" + summary
                                                + "\"}";

                                        System.out.println("[API] < " + response);

                                        client.sendMessage(response);
                                    }

                                    @Override
                                    public void onEventAboutToStart(String eventId, String summary) {

                                        String response = "{\"subscribedEvent\":\"" + eventId
                                                + "\",\"eventType\":\"aboutToStart\",\"summary\":\"" + summary
                                                + "\"}";

                                        System.out.println("[API] < " + response);

                                        client.sendMessage(response);
                                    }
                                });

                    } else if (action.equals(JsonConstants.API_UNSUBSCRIBE_EVENT)
                            && obj.containsKey(JsonConstants.API_EVENT_ID)) {
                        String eventId = obj.get(JsonConstants.API_EVENT_ID).toString();

                        calendarNotifManager.getNotificationManager().unsubscribeEvent(eventId);
                    } else {
                        System.out.println("[API] Error api target is inconsistent");
                    }
                }
            }
        }

        @Override
        public void onClientConnection(IWebsocketClient client) {
            System.out.println("Websocket client connected");
        }

        @Override
        public void onClientClose(IWebsocketClient client) {
            System.out.println("Websocket client disconnected");
        }
    });

    Runnable websocketTask = new Runnable() {

        @Override
        public void run() {
            websocketServer.start();
        }
    };

    Thread thread = new Thread(websocketTask, "WEBSOCKET_THREAD");

    thread.start();

    server.addServerEventListener(new IHttpServerEventListener() {

        @Override
        public void onHttpFrameReceived(IHttpFrame httpFrame, HttpStates receptionStates,
                IHttpStream httpStream) {

            // check if http frame is OK
            if (receptionStates == HttpStates.HTTP_FRAME_OK) {

                // you can check here http frame type (response or request
                // frame)
                if (httpFrame.isHttpRequestFrame()) {

                    // we want to send a message to client for http GET
                    // request on page with uri /index
                    if (httpFrame.getMethod().equals("GET") && httpFrame.getUri().equals("/gcalendar")) {

                        String defaultPage = "";
                        try {
                            defaultPage = FileUtils.readFile(webPath + "/index.html", "UTF-8");
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                        // return default html page for this HTTP Server
                        httpStream.writeHttpFrame(new HttpResponseFrame(StatusCodeList.OK,
                                new HttpVersion(1, 1), new HashMap<String, String>(), defaultPage.getBytes())
                                        .toString().getBytes());

                    } else if (httpFrame.getMethod().equals("GET")
                            && (httpFrame.getUri().endsWith(".css") || httpFrame.getUri().endsWith(".js"))) {

                        String defaultPage = "";
                        try {
                            defaultPage = FileUtils.readFile(webPath + httpFrame.getUri(), "UTF-8");
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                        // return default html page for this HTTP Server
                        httpStream.writeHttpFrame(new HttpResponseFrame(StatusCodeList.OK,
                                new HttpVersion(1, 1), new HashMap<String, String>(), defaultPage.getBytes())
                                        .toString().getBytes());
                    }
                }
            }
        }
    });

    server.start();
    thread.interrupt();

}

From source file:agileinterop.AgileInterop.java

/**
 * @param args the command line arguments
 *//* www .  j a  v a2 s .  c om*/
public static void main(String[] args) {
    JSONObject obj;

    try {
        String username, password, agileUrl, operation, body;

        username = args[0];
        password = args[1];
        agileUrl = args[2];
        operation = args[3];
        body = args[4];

        // Connect to Agile
        Agile.connect(username, password, agileUrl);

        switch (operation) {
        case "getPSRData":
            obj = getPSRData(body);
            break;
        case "getPSRList":
            obj = getPSRList(body);
            break;
        case "getPSRCellValues":
            obj = getPSRCellValues(body);
            break;
        case "getRelatedPSRs":
            obj = getRelatedPSRs(body);
            break;
        case "createRelatedPSRs":
            obj = createRelatedPSRs(body);
            break;
        case "writeNewDataToPSRs":
            obj = writeNewDataToPSRs(body);
            break;
        case "attachFileToPSR":
            obj = attachFileToPSR(body);
            break;
        case "crawlAgileByDateOriginated":
            obj = crawlAgileByDateOriginated(body);
            break;
        case "crawlAgileByPSRList":
            obj = crawlAgileByPSRList(body);
            break;
        default:
            throw new AssertionError();
        }

        obj.put("status", "success");

    } catch (APIException | ParseException | InterruptedException ex) {
        obj = new JSONObject();
        obj.put("status", "error");
        obj.put("data", ex.getMessage());
    } catch (Exception ex) {
        obj = new JSONObject();
        obj.put("status", "error");
        obj.put("data", ex.getMessage());
    }

    System.out.print(obj.toJSONString());
}

From source file:module.entities.UsernameChecker.CheckOpengovUsernames.java

/**
 * @param args the command line arguments
 *//*from w  ww. ja  v a 2 s  .c  o  m*/
public static void main(String[] args) throws SQLException, IOException {
    //        args = new String[1];
    //        args[0] = "searchConf.txt";
    Date d = new Date();
    long milTime = d.getTime();
    long execStart = System.nanoTime();
    Timestamp startTime = new Timestamp(milTime);
    long lStartTime;
    long lEndTime = 0;
    int status_id = 1;
    JSONObject obj = new JSONObject();
    if (args.length != 1) {
        System.out.println("None or too many argument parameters where defined! "
                + "\nPlease provide ONLY the configuration file name as the only argument.");
    } else {
        try {
            configFile = args[0];
            initLexicons();
            Database.init();
            lStartTime = System.currentTimeMillis();
            System.out.println("Opengov username identification process started at: " + startTime);
            usernameCheckerId = Database.LogUsernameChecker(lStartTime);
            TreeMap<Integer, String> OpenGovUsernames = Database.GetOpenGovUsers();
            HashSet<ReportEntry> report_names = new HashSet<>();
            if (OpenGovUsernames.size() > 0) {
                for (int userID : OpenGovUsernames.keySet()) {
                    String DBusername = Normalizer
                            .normalize(OpenGovUsernames.get(userID).toUpperCase(locale), Normalizer.Form.NFD)
                            .replaceAll("\\p{M}", "");
                    String username = "";
                    int type;
                    String[] splitUsername = DBusername.split(" ");
                    if (checkNameInLexicons(splitUsername)) {
                        for (String splText : splitUsername) {
                            username += splText + " ";
                        }
                        type = 1;
                    } else if (checkOrgInLexicons(splitUsername)) {
                        for (String splText : splitUsername) {
                            username += splText + " ";
                        }
                        type = 2;
                    } else {
                        username = DBusername;
                        type = -1;
                    }
                    ReportEntry cerEntry = new ReportEntry(userID, username.trim(), type);
                    report_names.add(cerEntry);
                }
                status_id = 2;
                obj.put("message", "Opengov username checker finished with no errors");
                obj.put("details", "");
                Database.UpdateOpengovUsersReportName(report_names);
                lEndTime = System.currentTimeMillis();
            } else {
                status_id = 2;
                obj.put("message", "Opengov username checker finished with no errors");
                obj.put("details", "No usernames needed to be checked");
                lEndTime = System.currentTimeMillis();
            }
        } catch (Exception ex) {
            System.err.println(ex.getMessage());
            status_id = 3;
            obj.put("message", "Opengov username checker encountered an error");
            obj.put("details", ex.getMessage().toString());
            lEndTime = System.currentTimeMillis();
        }
    }
    long execEnd = System.nanoTime();
    long executionTime = (execEnd - execStart);
    System.out.println("Total process time: " + (((executionTime / 1000000) / 1000) / 60) + " minutes.");
    Database.UpdateLogUsernameChecker(lEndTime, status_id, usernameCheckerId, obj);
    Database.closeConnection();
}