Example usage for java.lang String toString

List of usage examples for java.lang String toString

Introduction

In this page you can find the example usage for java.lang String toString.

Prototype

public String toString() 

Source Link

Document

This object (which is already a string!) is itself returned.

Usage

From source file:ui.TestRest.java

public static void main(String[] args) throws IOException {
    RestTemplate restTemplate = new RestTemplate();
    String response = restTemplate.getForObject(
            "http://api.apixu.com/v1/current.json?key=aebe5a3f024040ff9bf112640160705&q=Brussel", String.class);
    //System.out.println(response.getConditions().toString());
    System.out.println(response.toString());

    //System.out.println(response.toString());

    //RestTemplate restTemplate = new RestTemplate();
    // ObjectMapper jacksonObjectMapper = new ObjectMapper();

    // LinkedHashMap map= restTemplate.getForObject("http://api.apixu.com/v1/current.json?key=aebe5a3f024040ff9bf112640160705&q=Brussel", LinkedHashMap.class);
    //Weather weatherDescription = jacksonObjectMapper.convertValue(map.get("current"), Weather.class);

    //String weatherCondition = jacksonObjectMapper.convertValue(map.get("current"), String.class);

    //  Current current = restTemplate.getForObject("http://api.apixu.com/v1/current.json?key=aebe5a3f024040ff9bf112640160705&q=Brussel", Current.class);
    // DatabaseFacade service = new DatabaseFacade();

    // System.out.println(service.getWeather());
    // System.out.println(weatherCondition.toString());
    // System.out.println(service.getWeather());

}

From source file:org.vuphone.vandyupon.test.EventRatingRequestTest.java

public static void main(String[] args) {
    HttpClient c = new DefaultHttpClient();
    HttpPost post = new HttpPost("http://localhost:8080/vandyupon/events/");
    post.addHeader("Content-Type", "application/x-www-form-urlencoded");

    String params = "type=eventpost&eventname=Test&starttime=" + System.currentTimeMillis() + "&endtime="
            + (System.currentTimeMillis() + 6000000)
            + "&userid=chris&resp=xml&desc=a%20new%20event&locationlat=36.1437&locationlon=-86.8046";
    post.setEntity(new ByteArrayEntity(params.toString().getBytes()));

    try {//w w  w  . j a va 2 s .  c om
        HttpResponse resp = c.execute(post);
        resp.getEntity().writeTo(System.out);
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:UnitTest4.java

public static void main(String args[]) {
    System.setProperty("org.slf4j.simpleLogger.showDateTime", "true");
    System.setProperty("org.slf4j.simpleLogger.showThreadName", "true");
    System.setProperty("org.slf4j.simpleLogger.levelInBrackets", "true");
    System.setProperty("org.slf4j.simpleLogger.dateTimeFormat", "yyyy-MM-dd HH:mm:ss:SSS Z");
    System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "debug");
    System.setProperty("org.slf4j.simpleLogger.showLogName", "true");

    final Logger log = LoggerFactory.getLogger(UnitTest4.class);
    UnitTest4.log = log;//w  ww  .j  a v a  2  s  .c om
    System.out.println("hdfjkv \'dfdgdf\'dgdf");
    try {

        throw new Exception();
    } catch (Throwable e) {

        log.debug(e.toString());
        //log.debug(" Cause : " + e.getCause().toString());
        StackTraceElement stacka[] = e.getStackTrace();
        for (StackTraceElement stack : stacka) {
            log.debug(" StackTrace : " + stack.toString());
        }
    }

    String a[] = new String[10];
    a[0] = "hwedf";
    a[6] = "wdeeg";
    log.debug("a.toString() : {}", a.toString());

    /*
    List<Integer> list = new ArrayList<Integer>();
    for (Integer i : list) {
            
    System.out.println(i);
    }
    System.out.println("ok");
    try {
       //Test2.execute();
    } catch (Exception e) { e.printStackTrace(); }
    */
}

From source file:dhr.uploadtomicrobit.FirmwareGenerator.java

/**
 * @param args/*from  w  ww.  ja  va 2s .  c om*/
 * @throws IOException 
 */

public static void main(String[] args) throws IOException {
    // TODO Auto-generated method stub
    int[] ar = { 1, 2, 3, 66, 77, 8, 89, 123 };

    String simple = "# Add your Python code here. E.g.\n";
    simple = simple + "from microbit import *\n";
    simple = simple + "while True:\n";
    simple = simple + "\tdisplay.scroll('Great It Works!')\n";
    simple = simple + "\tdisplay.show(Image.HEART)\n";
    simple = simple + "\tsleep(2000)\n";

    String script = simple;

    FirmwareGenerator fg = new FirmwareGenerator();

    String output = fg.generateFirmware(simple);

    File file = new File("firmware.hex");
    FileUtils.writeStringToFile(file, output.toString(), Charset.forName("ISO-8859-1"));

}

From source file:com.sociesc.findasmartphonespark.Main.java

public static void main(String[] args) {
    String apiPrefix = "api/v1/";

    //setIpAddress("192.168.56.1");
    setPort(9010);/*from   w  w w .  j a  va2s .co m*/

    try {
        Logger.getLogger(Main.class.getName()).log(Level.INFO, "Criando banco de dados");
        DatabaseUtils.seedDatabase();
    } catch (SQLException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }

    Dao<User> userDao = new Dao(User.class);

    get(apiPrefix + "/hello/:name", (request, response) -> {
        ObjectMapper objectMapper = new ObjectMapper();

        /*ArrayList<AccessPoint> arrayAp = new ArrayList<AccessPoint>();
                
        for (int i = 0; i < 10; i++) {
        AccessPoint ap = new AccessPoint();
        ap.setBSSID("AP" + i);
        ap.setSSID("00:00:00:0" + i);
        ap.setRSSI(-50 + i);
        ap.setSala("Sala" + i);
                
        arrayAp.add(ap);
                
        //System.out.println("Nome: " + ap.getBSSID() + " - Mac: " + ap.getSSID() + " - Sinal: " + ap.getRSSI());
        }
                
        String retornoJson = rwJson.writeJson(arrayAp);*/

        //objectMapper.readValue(URLDecoder.decode(request.params(":name"), "UTF-8"), new TypeReference(String("lol")));
        ArrayList<AccessPoint> arrayAp = null;
        try {
            arrayAp = rwJson.readJson(URLDecoder.decode(request.params(":name"), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return arrayAp.get(0).getBSSID();

        //return "Hello: " + request.params(":name");
        //return arrayAp[0].get;
    });

    post(apiPrefix + "/findUser/:data", (request, response) -> {
        String userId = request.params(":data");

        ArrayList<AccessPoint> aps = rwJson.readJson(userId.toString());

        /*JsonObject json = new JsonObject();
                
        try {
        json = JsonObject.readFrom(request.params(":data"));
        } catch (Exception ex) {
        System.out.println("erro no json:\n" + ex.getMessage());
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        json.add("error", ex.getMessage());
        response.status(500);
        }*/
        try {
            for (int i = 0; i < aps.size(); i++) {
                System.out.println("Nome: " + aps.get(i).getBSSID() + " - Mac: " + aps.get(i).getSSID()
                        + " - Sinal: " + aps.get(i).getRSSI() + " - Sala: " + aps.get(i).getSala());
            }
        } catch (Exception ex) {
            System.out.println("erro no json:\n" + ex.getMessage());
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            //json.add("error", ex.getMessage());
            response.status(500);
            return ex.getMessage();
        }

        return userId.toString();
    });

    /*post(apiPrefix + "/findUser/", (request, response) ->{
     JsonObject json = new JsonObject();
            
    // Informaes do roteador/AP
    String[] BSSID; // basic service set identifier - nome da conexo
    String[] SSID; // service set identifier - identificador nico da conexo
    int[]    RSSI; // received signal strength indicator - potencia do sinal (-87 a -32)
    String   sala;
            
    String jsonBody = request.body();
    JsonObject reqJson = JsonObject.readFrom(jsonBody);
    JsonObject wifiJson = reqJson.get("wifi").asObject();
            
    System.out.println("reqJson.size()" + reqJson.size() + "\nwifiJson.size()" + wifiJson.size());
            
    RSSI = new int[wifiJson.size()];
    BSSID = new String[wifiJson.size()];
    SSID = new String[wifiJson.size()];
            
    try{
        for (int i = 0; i < wifiJson.size(); i++) {
            // recebe informaes das conexes encontradas
            BSSID[i] = wifiJson.get("BSSID").asString();
            SSID[i] = wifiJson.get("SSID").asString();
            RSSI[i] = wifiJson.get("RSSI").asInt();
        }
            
        return json.toString();
    }catch(Exception ex){
        System.out.println("erro no json:\n" + ex.getMessage());
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        json.add("error", ex.getMessage());
        response.status(500);
    }
    return json.toString();
    });*/

    get(apiPrefix + "/users", (request, response) -> {
        JsonObject json = new JsonObject();

        request.params();

        try {
            List<User> users = userDao.findAll();
            JsonArray usersJson = new JsonArray();
            for (User u : users) {
                JsonObject uJson = new JsonObject();
                uJson.add("id", u.getId());
                uJson.add("name", u.getName());
                uJson.add("email", u.getEmail());
                usersJson.add(uJson);
            }
            json.add("users", usersJson);

        } catch (SQLException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            json.add("error", ex.getMessage());
            response.status(500);
        }

        return json.toString();
    });

    /*get(apiPrefix + "/users/:id", (request, response) -> {
    Long userId = Long.parseLong(request.params(":id"));
    JsonObject json = new JsonObject();
    try{
        User user = userDao.findById(userId);
        if(user == null){
            json.add("error", "user not found");
            response.status(404);
            return json.toString();
        }
                
        JsonObject userJson = new JsonObject();
        userJson.add("id", user.getId());
        userJson.add("name", user.getName());
        userJson.add("email", user.getEmail());
        json.add("user", userJson);
        return json.toString();
                
    }catch(Exception ex){
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        json.add("error", ex.getMessage());
        response.status(500);
    }
            
    return json.toString();
    });*/

    delete(apiPrefix + "/users/:id", (request, response) -> {
        Long userId = Long.parseLong(request.params(":id"));
        JsonObject json = new JsonObject();
        try {
            userDao.removeById(userId);
            json.add("message", "user removed");
            response.status(200);
            return json.toString();
        } catch (Exception ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            json.add("error", ex.getMessage());
            response.status(500);
        }

        return json.toString();
    });

    put(apiPrefix + "/users/:id", (request, response) -> {
        Long userId = Long.parseLong(request.params(":id"));
        JsonObject json = new JsonObject();
        try {
            String jsonBody = request.body();
            JsonObject reqJson = JsonObject.readFrom(jsonBody);
            JsonObject userJson = reqJson.get("user").asObject();
            String name = userJson.get("name") != null ? userJson.get("name").asString() : null;
            String email = userJson.get("email") != null ? userJson.get("email").asString() : null;
            String password = userJson.get("password") != null ? userJson.get("password").asString() : null;

            User user = userDao.findById(userId);

            if (name != null)
                user.setName(name);

            if (email != null)
                user.setEmail(email);

            if (password != null) {
                String passwordDigest = DatabaseUtils.criptPass(password);
                user.setPasswordDigest(passwordDigest);
            }

            userDao.update(user);

            JsonObject resUserJson = new JsonObject();
            resUserJson.add("id", user.getId());
            resUserJson.add("name", user.getName());
            resUserJson.add("email", user.getEmail());

            json.add("user", resUserJson);
            return json.toString();

        } catch (Exception ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            json.add("error", ex.getMessage());
            response.status(500);
        }
        return json.toString();
    });

    post(apiPrefix + "/users", (request, response) -> {
        JsonObject json = new JsonObject();
        try {
            String jsonBody = request.body();
            JsonObject reqJson = JsonObject.readFrom(jsonBody);
            JsonObject userJson = reqJson.get("user").asObject();
            User user = new User();
            user.setName(userJson.get("name").asString());
            user.setEmail(userJson.get("email").asString());
            user.setPasswordDigest(DatabaseUtils.criptPass("tempPass"));
            userDao.create(user);

            JsonObject resUserJson = new JsonObject();
            resUserJson.add("id", user.getId());
            resUserJson.add("name", user.getName());
            resUserJson.add("email", user.getEmail());
            resUserJson.add("passwordDigest", user.getPasswordDigest());

            json.add("user", resUserJson);
            return json.toString();
        } catch (Exception ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            json.add("error", ex.getMessage());
            response.status(500);
        }
        return json.toString();
    });

}

From source file:com.github.s4ke.moar.cli.Main.java

public static void main(String[] args) throws ParseException, IOException {
    // create Options object
    Options options = new Options();

    options.addOption("rf", true,
            "file containing the regexes to test against (multiple regexes are separated by one empty line)");
    options.addOption("r", true, "regex to test against");

    options.addOption("mf", true, "file/folder to read the MOA from");
    options.addOption("mo", true, "folder to export the MOAs to (overwrites if existent)");

    options.addOption("sf", true, "file to read the input string(s) from");
    options.addOption("s", true, "string to test the MOA/Regex against");

    options.addOption("m", false, "multiline matching mode (search in string for regex)");

    options.addOption("ls", false, "treat every line of the input string file as one string");
    options.addOption("t", false, "trim lines if -ls is set");

    options.addOption("d", false, "only do determinism check");

    options.addOption("help", false, "prints this dialog");

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(options, args);

    if (args.length == 0 || cmd.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("moar-cli", options);
        return;/*from   w  w w .  jav a  2  s . co  m*/
    }

    List<String> patternNames = new ArrayList<>();
    List<MoaPattern> patterns = new ArrayList<>();
    List<String> stringsToCheck = new ArrayList<>();

    if (cmd.hasOption("r")) {
        String regexStr = cmd.getOptionValue("r");
        try {
            patterns.add(MoaPattern.compile(regexStr));
            patternNames.add(regexStr);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    if (cmd.hasOption("rf")) {
        String fileName = cmd.getOptionValue("rf");
        List<String> regexFileContents = readFileContents(new File(fileName));
        int emptyLineCountAfterRegex = 0;
        StringBuilder regexStr = new StringBuilder();
        for (String line : regexFileContents) {
            if (emptyLineCountAfterRegex >= 1) {
                if (regexStr.length() > 0) {
                    patterns.add(MoaPattern.compile(regexStr.toString()));
                    patternNames.add(regexStr.toString());
                }
                regexStr.setLength(0);
                emptyLineCountAfterRegex = 0;
            }
            if (line.trim().equals("")) {
                if (regexStr.length() > 0) {
                    ++emptyLineCountAfterRegex;
                }
            } else {
                regexStr.append(line);
            }
        }
        if (regexStr.length() > 0) {
            try {
                patterns.add(MoaPattern.compile(regexStr.toString()));
                patternNames.add(regexStr.toString());
            } catch (Exception e) {
                System.out.println(e.getMessage());
                return;
            }
            regexStr.setLength(0);
        }
    }

    if (cmd.hasOption("mf")) {
        String fileName = cmd.getOptionValue("mf");
        File file = new File(fileName);
        if (file.isDirectory()) {
            System.out.println(fileName + " is a directory, using all *.moar files as patterns");
            File[] moarFiles = file.listFiles(pathname -> pathname.getName().endsWith(".moar"));
            for (File moar : moarFiles) {
                String jsonString = readWholeFile(moar);
                patterns.add(MoarJSONSerializer.fromJSON(jsonString));
                patternNames.add(moar.getAbsolutePath());
            }
        } else {
            System.out.println(fileName + " is a single file. using it directly (no check for *.moar suffix)");
            String jsonString = readWholeFile(file);
            patterns.add(MoarJSONSerializer.fromJSON(jsonString));
            patternNames.add(fileName);
        }
    }

    if (cmd.hasOption("s")) {
        String str = cmd.getOptionValue("s");
        stringsToCheck.add(str);
    }

    if (cmd.hasOption("sf")) {
        boolean treatLineAsString = cmd.hasOption("ls");
        boolean trim = cmd.hasOption("t");
        String fileName = cmd.getOptionValue("sf");
        StringBuilder stringBuilder = new StringBuilder();
        boolean firstLine = true;
        for (String str : readFileContents(new File(fileName))) {
            if (treatLineAsString) {
                if (trim) {
                    str = str.trim();
                    if (str.length() == 0) {
                        continue;
                    }
                }
                stringsToCheck.add(str);
            } else {
                if (!firstLine) {
                    stringBuilder.append("\n");
                }
                if (firstLine) {
                    firstLine = false;
                }
                stringBuilder.append(str);
            }
        }
        if (!treatLineAsString) {
            stringsToCheck.add(stringBuilder.toString());
        }
    }

    if (cmd.hasOption("d")) {
        //at this point we have already built the Patterns
        //so just give the user a short note.
        System.out.println("All Regexes seem to be deterministic.");
        return;
    }

    if (patterns.size() == 0) {
        System.out.println("no patterns to check");
        return;
    }

    if (cmd.hasOption("mo")) {
        String folder = cmd.getOptionValue("mo");
        File folderFile = new File(folder);
        if (!folderFile.exists()) {
            System.out.println(folder + " does not exist. creating...");
            if (!folderFile.mkdirs()) {
                System.out.println("folder " + folder + " could not be created");
            }
        }
        int cnt = 0;
        for (MoaPattern pattern : patterns) {
            String patternAsJSON = MoarJSONSerializer.toJSON(pattern);
            try (BufferedWriter writer = new BufferedWriter(
                    new FileWriter(new File(folderFile, "pattern" + ++cnt + ".moar")))) {
                writer.write(patternAsJSON);
            }
        }
        System.out.println("stored " + cnt + " patterns in " + folder);
    }

    if (stringsToCheck.size() == 0) {
        System.out.println("no strings to check");
        return;
    }

    boolean multiline = cmd.hasOption("m");

    for (String string : stringsToCheck) {
        int curPattern = 0;
        for (MoaPattern pattern : patterns) {
            MoaMatcher matcher = pattern.matcher(string);
            if (!multiline) {
                if (matcher.matches()) {
                    System.out.println("\"" + patternNames.get(curPattern) + "\" matches \"" + string + "\"");
                } else {
                    System.out.println(
                            "\"" + patternNames.get(curPattern) + "\" does not match \"" + string + "\"");
                }
            } else {
                StringBuilder buffer = new StringBuilder(string);
                int additionalCharsPerMatch = ("<match>" + "</match>").length();
                int matchCount = 0;
                while (matcher.nextMatch()) {
                    buffer.replace(matcher.getStart() + matchCount * additionalCharsPerMatch,
                            matcher.getEnd() + matchCount * additionalCharsPerMatch,
                            "<match>" + string.substring(matcher.getStart(), matcher.getEnd()) + "</match>");
                    ++matchCount;
                }
                System.out.println(buffer.toString());
            }
        }
        ++curPattern;
    }
}

From source file:playground.dgrether.signalsystems.cottbus.scripts.DgCottbusSignalPlanChartGenerator.java

/**
 * @param args/*from  w  w  w.ja  va  2  s . com*/
 */
public static void main(String[] args) {
    //parameters
    //cottbus
    String runId = "1224";
    String baseDir = DgPaths.REPOS + "runs-svn/";
    int iteration = 500;
    Id<SignalSystem> signalSystemId = Id.create(18, SignalSystem.class);
    double startSecond = 23135.0;
    double endSecond = startSecond + 3600.0;
    startSecond = 8.0 * 3600.0;
    endSecond = startSecond + 3600.0;
    baseDir = baseDir + "run" + runId;

    //cottbus football
    runId = "1222_100_football_fans";
    baseDir = DgPaths.REPOS + "runs-svn/run1222/100_football_fans";
    iteration = 500;
    startSecond = 17.0 * 3600.0;
    endSecond = startSecond + 3600.0;
    signalSystemId = Id.create(1, SignalSystem.class);

    //      koehler strehler 2010
    //      runId = null;
    //      baseDir = "/media/data/work/matsimOutput/koehlerStrehler2010Scenario5SelectBest/";
    //      iteration = 20;
    //      signalSystemId = Id.create(5);
    //      startSecond = 0.0;
    //      endSecond = 900.0;
    //      
    //skript
    OutputDirectoryHierarchy io = null;
    if (runId != null)
        io = new OutputDirectoryHierarchy(baseDir, runId.toString(),
                false ? OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles
                        : OutputDirectoryHierarchy.OverwriteFileSetting.failIfDirectoryExists);
    else
        io = new OutputDirectoryHierarchy(baseDir,
                false ? OutputDirectoryHierarchy.OverwriteFileSetting.overwriteExistingFiles
                        : OutputDirectoryHierarchy.OverwriteFileSetting.failIfDirectoryExists);

    String eventsFilename = io.getIterationFilename(iteration, "events.xml.gz");

    DgSignalEventsCollector eventsCollector = new DgSignalEventsCollector();
    EventsManager events = EventsUtils.createEventsManager();
    events.addHandler(eventsCollector);
    MatsimEventsReader eventsReader = new MatsimEventsReader(events);
    eventsReader.readFile(eventsFilename);

    SortedSet<SignalGroupStateChangedEvent> systemEvents = eventsCollector.getSignalGroupEventsBySystemIdMap()
            .get(signalSystemId);
    log.info("Number of events for system " + signalSystemId + " is: " + systemEvents.size());
    for (SignalGroupStateChangedEvent e : systemEvents) {
        if (e.getTime() >= startSecond && e.getTime() <= endSecond)
            log.debug(e);
    }
    //         
    DgSignalPlanChart chart = new DgSignalPlanChart(startSecond, endSecond);
    chart.addData(systemEvents);
    JFreeChart jfChart = chart.createSignalPlanChart("System plan", "group", "time");

    String chartFileName = io.getIterationFilename(iteration,
            "signal_plan_system_" + signalSystemId + "_from_" + startSecond + "_to_" + endSecond);

    int rowCount = jfChart.getCategoryPlot().getDataset().getRowCount();

    int width = (int) (endSecond - startSecond) * 3;
    writeToPng(chartFileName, jfChart, width, rowCount * 3 + 50);

}

From source file:com.mycompany.myelasticsearch.MainClass.java

/**
 * @param args the command line arguments
 *///  w  ww .  j a  v  a 2s  . co m
public static void main(String[] args) {

    // TODO code application logic here
    Tika tika = new Tika();
    String fileEntry = "C:\\Contract\\Contract1.pdf";
    String filetype = tika.detect(fileEntry);
    System.out.println("FileType " + filetype);
    BodyContentHandler handler = new BodyContentHandler(-1);
    String text = "";
    Metadata metadata = new Metadata();

    FileInputStream inputstream = null;

    try {
        inputstream = new FileInputStream(fileEntry);
    } catch (FileNotFoundException ex) {
        Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex);
    }
    ParseContext pcontext = new ParseContext();

    //parsing the document using PDF parser
    PDFParser pdfparser = new PDFParser();
    try {
        pdfparser.parse(inputstream, handler, metadata, pcontext);
    } catch (IOException ex) {

        Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SAXException ex) {
        Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex);
    } catch (TikaException ex) {
        Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex);
    }
    String docText = "";
    String outputArray[];
    String out[];
    //getting the content of the document
    docText = handler.toString().replaceAll("(/[^\\da-zA-Z.]/)", "");

    // PhraseDetection.getPhrases(docText);
    try {
        Node node = nodeBuilder().node();
        Client client = node.client();
        DocumentReader.parseString(docText, client);
        //"Borrowing should be replaced by the user input key"
        Elastic.getDefinedTerm(client, "definedterms", "term", "1", "Borrowing");
        node.close();
    } catch (FileNotFoundException ex) {
        Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex);
    }
    Stanford.getSentence(docText);

    int definedTermsEnd = docText.indexOf("SCHEDULES");
    String toc = docText.substring(0, definedTermsEnd);
    String c = docText.substring(definedTermsEnd);

    System.out.println("Table of content" + toc);
    System.out.println("--------------------------------");
    System.out.println("content" + c);

    out = toc.split("Article|article|ARTICLE");
    int count = 0;
    String outputArrayString = "";
    int s = 0;
    StringBuffer tocOutput = new StringBuffer();

    for (String o : out) {
        if (count != 0) {
            s = Integer.parseInt(String.valueOf(o.charAt(1)));
            if (s == count) {
                tocOutput.append(o);
                tocOutput.append("JigarAnkitNeeraj");
                System.out.println(s);
            }
        }
        outputArrayString += "Count" + count + o;
        count++;
        System.out.println();
    }
    System.out.println("---------------------------------------------------Content---------");
    count = 1;
    StringBuffer contentOutput = new StringBuffer();

    String splitContent[] = c.split("ARTICLE|Article");
    Node node = nodeBuilder().node();
    Client client = node.client();
    for (String o : splitContent) {
        o = o.replaceAll("[^a-zA-Z0-9.,\\/#!$%\\^&\\*;:{}=\\-_`~()?\\s]+", "");
        o = o.replaceAll("\n", " ");
        char input = o.charAt(1);
        if (input >= '0' && input <= '9') {
            s = Integer.parseInt(String.valueOf(o.charAt(1)));
            if (s == count) {
                //System.out.println(s);
                JSONObject articleJSONObject = new JSONObject();
                contentOutput.append(" \n MyArticlesSeparated \n ");
                articleJSONObject.put("Article" + count, o.toString());
                try {
                    try {
                        JSONObject articleJSONObject1 = new JSONObject();
                        articleJSONObject1.put("hi", "j");
                        client.prepareIndex("contract", "article", String.valueOf(count))
                                .setSource(articleJSONObject.toString()).execute().actionGet();
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                    //"Borrowing should be replaced by the user input key"

                } catch (Exception ex) {
                    Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex);
                }
                System.out.println(s);
                count++;
            }
            //outputArrayString += "Count" + count + o;

            contentOutput.append(o);
        }
    }
    Elastic.getDocument(client, "contract", "article", "1");
    Elastic.searchDocument(client, "contract", "article", "Lenders");
    Elastic.searchDocument(client, "contract", "article", "Negative Covenants");

    Elastic.searchDocument(client, "contract", "article", "Change in Law");
    String tableOfContent[];
    tableOfContent = tocOutput.toString().split("JigarAnkitNeeraj");

    String splitContectsAccordingToArticles[];
    splitContectsAccordingToArticles = contentOutput.toString().split("MyArticlesSeparated");
    int numberOfArticle = splitContectsAccordingToArticles.length;

    int countArticle = 1;
    Double toBeTruncated = new Double("" + countArticle + ".00");

    String section = "Section";
    toBeTruncated += 0.01;

    System.out.println(toBeTruncated);
    String sectionEnd;
    StringBuffer sectionOutput = new StringBuffer();
    int skipFirstArtcile = 0;
    JSONObject obj = new JSONObject();

    for (String article : splitContectsAccordingToArticles) {
        if (skipFirstArtcile != 0) {
            DecimalFormat f = new DecimalFormat("##.00");
            String sectionStart = section + " " + f.format(toBeTruncated);
            int start = article.indexOf(sectionStart);
            toBeTruncated += 0.01;

            System.out.println();
            sectionEnd = section + " " + f.format(toBeTruncated);

            int end = article.indexOf(sectionEnd);
            while (end != -1) {
                sectionStart = section + " " + f.format(toBeTruncated - 0.01);
                sectionOutput.append(" \n Key:" + sectionStart);
                if (start < end) {
                    sectionOutput.append("\n Value:" + article.substring(start, end));
                    obj.put(sectionStart, article.substring(start, end).replaceAll("\\r\\n|\\r|\\n", " "));
                    try {
                        try {
                            JSONObject articleJSONObject1 = new JSONObject();
                            articleJSONObject1.put("hi", "j");
                            client.prepareIndex("contract", "section", String.valueOf(count))
                                    .setSource(obj.toString()).execute().actionGet();
                        } catch (Exception e) {
                            System.out.println(e.getMessage());
                        }
                        //"Borrowing should be replaced by the user input key"

                    } catch (Exception ex) {
                        Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex);
                    }

                }

                start = end;
                toBeTruncated += 0.01;
                sectionEnd = section + " " + f.format(toBeTruncated);
                System.out.println("SectionEnd " + sectionEnd);
                try {
                    end = article.indexOf(sectionEnd);
                } catch (Exception e) {
                    System.out.print(e.getMessage());
                }

                System.out.println("End section index " + end);
            }
            end = article.length() - 1;
            sectionOutput.append(" \n Key:" + sectionStart);
            try {
                sectionOutput.append(" \n Value:" + article.substring(start, end));
                obj.put(sectionStart, article.substring(start, end).replaceAll("\\r\\n|\\r|\\n", " "));
            } catch (Exception e) {
                //What if Article has No Sections
                String numberOnly = article.replaceAll("[^0-9]", "").substring(0, 1);
                String sectionArticle = "ARTICLE " + numberOnly;
                sectionOutput.append(" \n Value:" + article);
                obj.put(sectionArticle, article);

                System.out.println(e.getMessage());
            }

            DecimalFormat ff = new DecimalFormat("##");
            toBeTruncated = Double.valueOf(ff.format(toBeTruncated)) + 1.01;
        }
        skipFirstArtcile++;
    }

    for (String article : splitContectsAccordingToArticles) {
        if (skipFirstArtcile != 0) {
            DecimalFormat f = new DecimalFormat("##.00");
            String sectionStart = section + " " + f.format(toBeTruncated);
            int start = article.indexOf(sectionStart);
            toBeTruncated += 0.01;
            System.out.println();
            sectionEnd = section + " " + f.format(toBeTruncated);

            int end = article.indexOf(sectionEnd);
            while (end != -1) {
                sectionStart = section + " " + f.format(toBeTruncated - 0.01);
                sectionOutput.append(" \n Key:" + sectionStart);
                if (start < end) {
                    sectionOutput.append("\n Value:" + article.substring(start, end));
                    System.out.println(sectionOutput);
                    String patternStr = "\\n\\n+[(]";
                    String paragraphSubstringArray[] = article.substring(start, end).split(patternStr);

                    JSONObject paragraphObject = new JSONObject();
                    int counter = 0;
                    for (String paragraphSubstring : paragraphSubstringArray) {
                        counter++;
                        paragraphObject.put("Paragraph " + counter, paragraphSubstring);

                    }
                    obj.put(sectionStart, paragraphObject);

                }

                start = end;
                toBeTruncated += 0.01;
                sectionEnd = section + " " + f.format(toBeTruncated);
                System.out.println("SectionEnd " + sectionEnd);
                try {
                    end = article.indexOf(sectionEnd);
                } catch (Exception e) {
                    System.out.print(e.getMessage());
                }

                System.out.println("End section index " + end);
            }
            end = article.length() - 1;
            sectionOutput.append(" \n Key:" + sectionStart);
            try {
                sectionOutput.append(" \n Value:" + article.substring(start, end));
                obj.put(sectionStart, article.substring(start, end));
                PhraseDetection.getPhrases(docText);
            } catch (Exception e) {
                //What if Article has No Sections
                String sectionArticle = "ARTICLE";
                System.out.println(e.getMessage());
            }
            DecimalFormat ff = new DecimalFormat("##");
            toBeTruncated = Double.valueOf(ff.format(toBeTruncated)) + 1.01;
        }
        skipFirstArtcile++;
    }

    Elastic.getDocument(client, "contract", "section", "1");
    Elastic.searchDocument(client, "contract", "section", "Lenders");
    Elastic.searchDocument(client, "contract", "section", "Negative Covenants");
    try {
        FileWriter file = new FileWriter("TableOfIndex.txt");
        file.write(tocOutput.toString());
        file.flush();
        file.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        FileWriter file = new FileWriter("Contract3_JSONFile.txt");
        file.write(obj.toString());
        file.flush();
        file.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        FileWriter file = new FileWriter("Contract1_KeyValueSections.txt");
        file.write(sectionOutput.toString());
        file.flush();
        file.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.kappaware.logtrawler.Main.java

@SuppressWarnings("static-access")
static public void main(String[] argv) throws Throwable {

    Config config;// w w  w.  ja v  a 2s . c o m

    Options options = new Options();

    options.addOption(OptionBuilder.hasArg().withArgName("configFile").withLongOpt("config-file")
            .withDescription("JSON configuration file").create("c"));
    options.addOption(OptionBuilder.hasArg().withArgName("folder").withLongOpt("folder")
            .withDescription("Folder to monitor").create("f"));
    options.addOption(OptionBuilder.hasArg().withArgName("exclusion").withLongOpt("exclusion")
            .withDescription("Exclusion regex").create("x"));
    options.addOption(OptionBuilder.hasArg().withArgName("adminEndpoint").withLongOpt("admin-endpoint")
            .withDescription("Endpoint for admin REST").create("e"));
    options.addOption(OptionBuilder.hasArg().withArgName("outputFlow").withLongOpt("output-flow")
            .withDescription("Target to post result on").create("o"));
    options.addOption(OptionBuilder.hasArg().withArgName("hostname").withLongOpt("hostname")
            .withDescription("This hostname").create("h"));
    options.addOption(OptionBuilder.withLongOpt("displayDot").withDescription("Display Dot").create("d"));
    options.addOption(OptionBuilder.hasArg().withArgName("mimeType").withLongOpt("mime-type")
            .withDescription("Valid MIME type").create("m"));
    options.addOption(OptionBuilder.hasArg().withArgName("allowedAdmin").withLongOpt("allowedAdmin")
            .withDescription("Allowed admin network").create("a"));
    options.addOption(OptionBuilder.hasArg().withArgName("configFile").withLongOpt("gen-config-file")
            .withDescription("Generate JSON configuration file").create("g"));
    options.addOption(OptionBuilder.hasArg().withArgName("maxBatchSize").withLongOpt("max-batch-size")
            .withDescription("Max JSON batch (array) size").create("b"));

    CommandLineParser clParser = new BasicParser();
    CommandLine line;
    String configFile = null;
    try {
        // parse the command line argument
        line = clParser.parse(options, argv);
        if (line.hasOption("c")) {
            configFile = line.getOptionValue("c");
            config = Json.fromJson(Config.class,
                    new BufferedReader(new InputStreamReader(new FileInputStream(configFile))));
        } else {
            config = new Config();
        }
        if (line.hasOption("f")) {
            String[] fs = line.getOptionValues("f");
            // Get the first agent (Create it if needed)
            if (config.getAgents() == null || config.getAgents().size() == 0) {
                Config.Agent agent = new Config.Agent("default");
                config.addAgent(agent);
            }
            Config.Agent agent = config.getAgents().iterator().next();
            for (String f : fs) {
                agent.addFolder(new Config.Agent.Folder(f, false));
            }
        }
        if (line.hasOption("e")) {
            String e = line.getOptionValue("e");
            config.setAdminEndpoint(e);
        }
        if (line.hasOption("o")) {
            String[] es = line.getOptionValues("o");
            if (config.getAgents() != null) {
                for (Agent agent : config.getAgents()) {
                    for (String s : es) {
                        agent.addOuputFlow(s);
                    }
                }
            }
        }
        if (line.hasOption("h")) {
            String e = line.getOptionValue("h");
            config.setHostname(e);
        }
        if (line.hasOption("x")) {
            if (config.getAgents() != null) {
                for (Agent agent : config.getAgents()) {
                    if (agent.getFolders() != null) {
                        for (Folder folder : agent.getFolders()) {
                            String[] exs = line.getOptionValues("x");
                            for (String ex : exs) {
                                folder.addExcludedPath(ex);
                            }
                        }
                    }
                }
            }
        }
        if (line.hasOption("m")) {
            if (config.getAgents() != null) {
                for (Agent agent : config.getAgents()) {
                    String[] exs = line.getOptionValues("m");
                    for (String ex : exs) {
                        agent.addLogMimeType(ex);
                    }
                }
            }
        }
        if (line.hasOption("a")) {
            String[] exs = line.getOptionValues("a");
            for (String ex : exs) {
                config.addAdminAllowedNetwork(ex);
            }
        }
        if (line.hasOption("d")) {
            config.setDisplayDot(true);
        }
        if (line.hasOption("b")) {
            Integer i = getIntegerParameter(line, "b");
            if (config.getAgents() != null) {
                for (Agent agent : config.getAgents()) {
                    agent.setOutputMaxBatchSize(i);
                }
            }
        }
        config.setDefault();
        if (line.hasOption("g")) {
            String fileName = line.getOptionValue("g");
            PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(fileName, false)));
            out.println(Json.toJson(config, true));
            out.flush();
            out.close();
            System.exit(0);
        }
    } catch (ParseException exp) {
        // oops, something went wrong
        usage(options, exp.getMessage());
        return;
    }

    try {
        // Check config
        if (config.getAgents() == null || config.getAgents().size() < 1) {
            throw new ConfigurationException("At least one folder to monitor must be provided!");
        }
        Map<String, AgentHandler> agentHandlerByName = new HashMap<String, AgentHandler>();
        for (Config.Agent agent : config.getAgents()) {
            agentHandlerByName.put(agent.getName(), new AgentHandler(agent));
        }
        if (!Utils.isNullOrEmpty(config.getAdminEndpoint())) {
            new AdminServer(config, agentHandlerByName);
        }
    } catch (ConfigurationException e) {
        log.error(e.toString());
        System.exit(1);
    } catch (Throwable t) {
        log.error("Error in main", t);
        System.exit(2);
    }
}

From source file:com.adobe.aem.demo.communities.Loader.java

public static void main(String[] args) {

    String hostname = null;/*from  w w  w .j a  v a  2 s . c  om*/
    String port = null;
    String altport = null;
    String csvfile = null;
    String location = null;
    String language = "en";
    String analytics = null;
    String adminPassword = "admin";
    String[] url = new String[10]; // Handling 10 levels maximum for nested comments 
    boolean reset = false;
    boolean configure = false;
    int urlLevel = 0;
    int row = 0;
    HashMap<String, ArrayList<String>> learningpaths = new HashMap<String, ArrayList<String>>();

    // Command line options for this tool
    Options options = new Options();
    options.addOption("h", true, "Hostname");
    options.addOption("p", true, "Port");
    options.addOption("a", true, "Alternate Port");
    options.addOption("f", true, "CSV file");
    options.addOption("r", false, "Reset");
    options.addOption("u", true, "Admin Password");
    options.addOption("c", false, "Configure");
    options.addOption("s", true, "Analytics Endpoint");
    options.addOption("t", false, "Analytics Tracking");
    CommandLineParser parser = new BasicParser();
    try {
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("h")) {
            hostname = cmd.getOptionValue("h");
        }

        if (cmd.hasOption("p")) {
            port = cmd.getOptionValue("p");
        }

        if (cmd.hasOption("a")) {
            altport = cmd.getOptionValue("a");
        }

        if (cmd.hasOption("f")) {
            csvfile = cmd.getOptionValue("f");
        }

        if (cmd.hasOption("u")) {
            adminPassword = cmd.getOptionValue("u");
        }

        if (cmd.hasOption("t")) {
            if (cmd.hasOption("s")) {
                analytics = cmd.getOptionValue("s");
            }
        }

        if (cmd.hasOption("r")) {
            reset = true;
        }

        if (cmd.hasOption("c")) {
            configure = true;
        }

        if (csvfile == null || port == null || hostname == null) {
            System.out.println(
                    "Request parameters: -h hostname -p port -a alternateport -u adminPassword -f path_to_CSV_file -r (true|false, delete content before import) -c (true|false, post additional properties)");
            System.exit(-1);
        }

    } catch (ParseException ex) {

        logger.error(ex.getMessage());

    }

    String componentType = null;

    try {

        logger.debug("AEM Demo Loader: Processing file " + csvfile);

        // Reading the CSV file, line by line
        Reader in = new FileReader(csvfile);

        Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(in);
        for (CSVRecord record : records) {

            row = row + 1;
            logger.info("Row: " + row + ", new record: " + record.get(0));

            // Let's see if we deal with a comment
            if (record.get(0).startsWith("#")) {

                // We can ignore the comment line and move on
                continue;

            }

            // Let's see if we need to terminate this process
            if (record.get(0).equals(KILL)) {

                System.exit(1);

            }

            // Let's see if we need to create a new Community site
            if (record.get(0).equals(SITE)) {

                // Building the form entity to be posted
                MultipartEntityBuilder builder = MultipartEntityBuilder.create();
                builder.setCharset(MIME.UTF8_CHARSET);
                builder.addTextBody(":operation", "social:createSite",
                        ContentType.create("text/plain", MIME.UTF8_CHARSET));
                builder.addTextBody("_charset_", "UTF-8", ContentType.create("text/plain", MIME.UTF8_CHARSET));

                String urlName = null;

                for (int i = 2; i < record.size() - 1; i = i + 2) {

                    if (record.get(i) != null && record.get(i + 1) != null && record.get(i).length() > 0) {

                        String name = record.get(i).trim();
                        String value = record.get(i + 1).trim();
                        if (value.equals("TRUE")) {
                            value = "true";
                        }
                        if (value.equals("FALSE")) {
                            value = "false";
                        }
                        if (name.equals("urlName")) {
                            urlName = value;
                        }
                        if (name.equals(LANGUAGE)) {
                            language = value;
                        }
                        if (name.equals(BANNER)) {

                            File attachment = new File(
                                    csvfile.substring(0, csvfile.indexOf(".csv")) + File.separator + value);
                            builder.addBinaryBody(BANNER, attachment, ContentType.MULTIPART_FORM_DATA,
                                    attachment.getName());

                        } else if (name.equals(THUMBNAIL)) {

                            File attachment = new File(
                                    csvfile.substring(0, csvfile.indexOf(".csv")) + File.separator + value);
                            builder.addBinaryBody(THUMBNAIL, attachment, ContentType.MULTIPART_FORM_DATA,
                                    attachment.getName());

                        } else {

                            builder.addTextBody(name, value,
                                    ContentType.create("text/plain", MIME.UTF8_CHARSET));

                        }
                    }
                }

                // Site creation
                String siteId = doPost(hostname, port, "/content.social.json", "admin", adminPassword,
                        builder.build(), "response/siteId");

                // Site publishing, if there's a publish instance to publish to
                if (!port.equals(altport)) {

                    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                    nameValuePairs.add(new BasicNameValuePair("id", "nobot"));
                    nameValuePairs.add(new BasicNameValuePair(":operation", "social:publishSite"));
                    nameValuePairs
                            .add(new BasicNameValuePair("path", "/content/sites/" + urlName + "/" + language));

                    doPost(hostname, port, "/communities/sites.html", "admin", adminPassword,
                            new UrlEncodedFormEntity(nameValuePairs), null);

                    // Wait for site to be available on Publish
                    doWait(hostname, altport, "admin", adminPassword,
                            (siteId != null ? siteId : urlName) + "-groupadministrators");
                }

                continue;
            }

            // Let's see if we need to create a new Tag
            if (record.get(0).equals(TAG)) {

                // Building the form entity to be posted
                MultipartEntityBuilder builder = MultipartEntityBuilder.create();
                builder.setCharset(MIME.UTF8_CHARSET);
                builder.addTextBody("_charset_", "UTF-8", ContentType.create("text/plain", MIME.UTF8_CHARSET));

                for (int i = 1; i < record.size() - 1; i = i + 2) {

                    if (record.get(i) != null && record.get(i + 1) != null && record.get(i).length() > 0
                            && record.get(i + 1).length() > 0) {

                        String name = record.get(i).trim();
                        String value = record.get(i + 1).trim();
                        builder.addTextBody(name, value, ContentType.create("text/plain", MIME.UTF8_CHARSET));

                    }
                }

                // Tag creation
                doPost(hostname, port, "/bin/tagcommand", "admin", adminPassword, builder.build(), null);

                continue;
            }

            // Let's see if we need to create a new Community site template, and if we can do it (script run against author instance)
            if (record.get(0).equals(SITETEMPLATE)) {

                // Building the form entity to be posted
                MultipartEntityBuilder builder = MultipartEntityBuilder.create();
                builder.setCharset(MIME.UTF8_CHARSET);
                builder.addTextBody(":operation", "social:createSiteTemplate",
                        ContentType.create("text/plain", MIME.UTF8_CHARSET));
                builder.addTextBody("_charset_", "UTF-8", ContentType.create("text/plain", MIME.UTF8_CHARSET));

                for (int i = 2; i < record.size() - 1; i = i + 2) {

                    if (record.get(i) != null && record.get(i + 1) != null && record.get(i).length() > 0) {

                        String name = record.get(i).trim();
                        String value = record.get(i + 1).trim();
                        builder.addTextBody(name, value, ContentType.create("text/plain", MIME.UTF8_CHARSET));

                    }
                }

                // Site template creation
                doPost(hostname, port, "/content.social.json", "admin", adminPassword, builder.build(), null);

                continue;
            }

            // Let's see if we need to create a new Community group
            if (record.get(0).equals(GROUP)) {

                // Building the form entity to be posted
                MultipartEntityBuilder builder = MultipartEntityBuilder.create();
                builder.setCharset(MIME.UTF8_CHARSET);
                builder.addTextBody(":operation", "social:createCommunityGroup",
                        ContentType.create("text/plain", MIME.UTF8_CHARSET));
                builder.addTextBody("_charset_", "UTF-8", ContentType.create("text/plain", MIME.UTF8_CHARSET));

                for (int i = 3; i < record.size() - 1; i = i + 2) {

                    if (record.get(i) != null && record.get(i + 1) != null && record.get(i).length() > 0) {

                        String name = record.get(i).trim();
                        String value = record.get(i + 1).trim();
                        if (value.equals("TRUE")) {
                            value = "true";
                        }
                        if (value.equals("FALSE")) {
                            value = "false";
                        }
                        if (name.equals(IMAGE)) {

                            File attachment = new File(
                                    csvfile.substring(0, csvfile.indexOf(".csv")) + File.separator + value);
                            builder.addBinaryBody(IMAGE, attachment, ContentType.MULTIPART_FORM_DATA,
                                    attachment.getName());

                        } else {

                            builder.addTextBody(name, value,
                                    ContentType.create("text/plain", MIME.UTF8_CHARSET));

                        }
                    }
                }

                // Group creation
                String memberGroupId = doPost(hostname, port, record.get(1), getUserName(record.get(2)),
                        getPassword(record.get(2), adminPassword), builder.build(), "response/memberGroupId");

                // Wait for group to be available on Publish, if available
                logger.debug("Waiting for completion of Community Group creation");
                doWait(hostname, port, "admin", adminPassword, memberGroupId);

                continue;

            }

            // Let's see if it's simple Sling Delete request
            if (record.get(0).equals(SLINGDELETE)) {

                doDelete(hostname, port, record.get(1), "admin", adminPassword);

                continue;

            }

            // Let's see if we need to add users to an AEM Group
            if ((record.get(0).equals(GROUPMEMBERS) || record.get(0).equals(SITEMEMBERS))
                    && record.get(GROUP_INDEX_NAME) != null) {

                // Checking if we have a member group for this site
                String groupName = record.get(GROUP_INDEX_NAME);
                if (record.get(0).equals(SITEMEMBERS)) {

                    // Let's fetch the siteId for this Community Site Url
                    String siteConfig = doGet(hostname, port, groupName, "admin", adminPassword, null);

                    try {

                        String siteId = new JSONObject(siteConfig).getString("siteId");
                        if (siteId != null)
                            groupName = "community-" + siteId + "-members";
                        logger.debug("Member group name is " + groupName);

                    } catch (Exception e) {

                        logger.error(e.getMessage());

                    }

                }

                // Pause until the group can found
                doWait(hostname, port, "admin", adminPassword, groupName);

                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(new BasicNameValuePair("filter",
                        "[{\"operation\":\"like\",\"rep:principalName\":\"" + groupName + "\"}]"));
                nameValuePairs.add(new BasicNameValuePair("type", "groups"));
                String groupList = doGet(hostname, port,
                        "/libs/social/console/content/content/userlist.social.0.10.json", "admin",
                        adminPassword, nameValuePairs);

                logger.debug("List of groups" + groupList);

                if (groupList.indexOf(groupName) > 0) {

                    logger.debug("Group was found on " + port);
                    try {
                        JSONArray jsonArray = new JSONObject(groupList).getJSONArray("items");
                        if (jsonArray.length() == 1) {
                            JSONObject jsonObject = jsonArray.getJSONObject(0);
                            String groupPath = jsonObject.getString("path");

                            logger.debug("Group path is " + groupPath);

                            // Constructing a multi-part POST for group membership
                            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
                            builder.setCharset(MIME.UTF8_CHARSET);
                            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

                            List<NameValuePair> groupNameValuePairs = buildNVP(record, 2);
                            for (NameValuePair nameValuePair : groupNameValuePairs) {
                                builder.addTextBody(nameValuePair.getName(), nameValuePair.getValue(),
                                        ContentType.create("text/plain", MIME.UTF8_CHARSET));
                            }

                            // Adding the list of group members
                            doPost(hostname, port, groupPath + ".rw.userprops.html", "admin", adminPassword,
                                    builder.build(), null);

                        } else {
                            logger.info("We have more than one match for a group with this name!");
                        }
                    } catch (Exception e) {
                        logger.error(e.getMessage());
                    }
                }

                continue;

            }

            // Let's see if it's user related
            if (record.get(0).equals(USERS)) {

                //First we need to get the path to the user node
                String json = doGet(hostname, port, "/libs/granite/security/currentuser.json",
                        getUserName(record.get(1)), getPassword(record.get(1), adminPassword), null);

                if (json != null) {

                    try {

                        // Fetching the home property
                        String home = new JSONObject(json).getString("home");
                        if (record.get(2).equals(PREFERENCES)) {
                            home = home + "/preferences";
                        } else {
                            home = home + "/profile";
                        }
                        logger.debug(home);

                        // Now we can post all the preferences or the profile
                        List<NameValuePair> nameValuePairs = buildNVP(record, 3);
                        doPost(hostname, port, home, "admin", adminPassword,
                                new UrlEncodedFormEntity(nameValuePairs), null);

                    } catch (Exception e) {
                        logger.error(e.getMessage());
                    }

                }

                continue;

            }

            // Let's see if we deal with a new block of content or just a new entry
            if (record.get(0).equals(CALENDAR) || record.get(0).equals(SLINGPOST)
                    || record.get(0).equals(RATINGS) || record.get(0).equals(BLOG)
                    || record.get(0).equals(JOURNAL) || record.get(0).equals(COMMENTS)
                    || record.get(0).equals(REVIEWS) || record.get(0).equals(FILES)
                    || record.get(0).equals(SUMMARY) || record.get(0).equals(ACTIVITIES)
                    || record.get(0).equals(JOIN) || record.get(0).equals(FOLLOW)
                    || record.get(0).equals(MESSAGE) || record.get(0).equals(ASSET)
                    || record.get(0).equals(AVATAR) || record.get(0).equals(RESOURCE)
                    || record.get(0).equals(LEARNING) || record.get(0).equals(QNA)
                    || record.get(0).equals(FORUM)) {

                // New block of content, we need to reset the processing to first Level
                componentType = record.get(0);
                url[0] = record.get(1);
                urlLevel = 0;

                if (!componentType.equals(SLINGPOST) && reset) {

                    int pos = record.get(1).indexOf("/jcr:content");
                    if (pos > 0)
                        doDelete(hostname, port, "/content/usergenerated" + record.get(1).substring(0, pos),
                                "admin", adminPassword);

                }

                // If the Configure command line flag is set, we try to configure the component with all options enabled
                if (componentType.equals(SLINGPOST) || configure) {

                    String configurePath = getConfigurePath(record.get(1));

                    List<NameValuePair> nameValuePairs = buildNVP(record, 2);
                    if (nameValuePairs.size() > 2) // Only do this when really have configuration settings
                        doPost(hostname, port, configurePath, "admin", adminPassword,
                                new UrlEncodedFormEntity(nameValuePairs), null);

                }

                // We're done with this line, moving on to the next line in the CSV file
                continue;
            }

            // Let's see if we need to indent the list, if it's a reply or a reply to a reply
            if (record.get(1).length() != 1)
                continue; // We need a valid level indicator

            if (Integer.parseInt(record.get(1)) > urlLevel) {
                url[++urlLevel] = location;
                logger.debug("Incremented urlLevel to: " + urlLevel + ", with a new location:" + location);
            } else if (Integer.parseInt(record.get(1)) < urlLevel) {
                urlLevel = Integer.parseInt(record.get(1));
                logger.debug("Decremented urlLevel to: " + urlLevel);
            }

            // Get the credentials or fall back to password
            String password = getPassword(record.get(0), adminPassword);
            String userName = getUserName(record.get(0));

            // Adding the generic properties for all POST requests
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

            if (!componentType.equals(RESOURCE))
                nameValuePairs.add(new BasicNameValuePair("id", "nobot"));

            nameValuePairs.add(new BasicNameValuePair("_charset_", "UTF-8"));

            // Setting some specific fields depending on the content type
            if (componentType.equals(COMMENTS)) {

                nameValuePairs.add(new BasicNameValuePair(":operation", "social:createComment"));
                nameValuePairs.add(new BasicNameValuePair("message", record.get(2)));

            }

            // Creates a forum post (or reply)
            if (componentType.equals(FORUM)) {

                nameValuePairs.add(new BasicNameValuePair(":operation", "social:createForumPost"));
                nameValuePairs.add(new BasicNameValuePair("subject", record.get(2)));
                nameValuePairs.add(new BasicNameValuePair("message", record.get(3)));

            }

            // Follows a user (followedId) for the user posting the request
            if (componentType.equals(FOLLOW)) {

                nameValuePairs.add(new BasicNameValuePair(":operation", "social:follow"));
                nameValuePairs.add(new BasicNameValuePair("userId", "/social/authors/" + userName));
                nameValuePairs.add(new BasicNameValuePair("followedId", "/social/authors/" + record.get(2)));

            }

            // Uploading Avatar picture
            if (componentType.equals(AVATAR)) {

                nameValuePairs.add(new BasicNameValuePair(":operation", "social:changeAvatar"));

            }

            // Joins a user (posting the request) to a Community Group (path)
            if (componentType.equals(JOIN)) {
                nameValuePairs.add(new BasicNameValuePair(":operation", "social:joinCommunityGroup"));
                int pos = url[0].indexOf("/configuration.social.json");
                if (pos > 0)
                    nameValuePairs.add(new BasicNameValuePair("path", url[0].substring(0, pos) + ".html"));
                else
                    continue; // Invalid record
            }

            // Creates a new private message
            if (componentType.equals(MESSAGE)) {
                nameValuePairs.add(new BasicNameValuePair(":operation", "social:createMessage"));
                nameValuePairs.add(new BasicNameValuePair("sendMail", "Sending..."));
                nameValuePairs.add(new BasicNameValuePair("content", record.get(4)));
                nameValuePairs.add(new BasicNameValuePair("subject", record.get(3)));
                nameValuePairs.add(new BasicNameValuePair("serviceSelector", "/bin/community"));
                nameValuePairs.add(new BasicNameValuePair("to", "/social/authors/" + record.get(2)));
                nameValuePairs.add(new BasicNameValuePair("userId", "/social/authors/" + record.get(2)));
                nameValuePairs.add(new BasicNameValuePair(":redirect", "//messaging.html"));
                nameValuePairs.add(new BasicNameValuePair(":formid", "generic_form"));
                nameValuePairs.add(new BasicNameValuePair(":formstart",
                        "/content/sites/communities/messaging/compose/jcr:content/content/primary/start"));
            }

            // Creates a file or a folder
            if (componentType.equals(FILES)) {

                // Top level is always assumed to be a folder, second level files, and third and subsequent levels comments on files
                if (urlLevel == 0) {
                    nameValuePairs.add(new BasicNameValuePair(":operation", "social:createFileLibraryFolder"));
                    nameValuePairs.add(new BasicNameValuePair("name", record.get(2)));
                    nameValuePairs.add(new BasicNameValuePair("message", record.get(3)));
                } else if (urlLevel == 1) {
                    nameValuePairs.add(new BasicNameValuePair(":operation", "social:createComment"));
                }

            }

            // Creates a question, a reply or mark a reply as the best answer
            if (componentType.equals(QNA)) {
                if (urlLevel == 0) {
                    nameValuePairs.add(new BasicNameValuePair(":operation", "social:createQnaPost"));
                    nameValuePairs.add(new BasicNameValuePair("subject", record.get(2)));
                    nameValuePairs.add(new BasicNameValuePair("message", record.get(3)));
                } else if (urlLevel == 1) {
                    nameValuePairs.add(new BasicNameValuePair(":operation", "social:createQnaPost"));
                    nameValuePairs.add(new BasicNameValuePair("message", record.get(3)));
                } else if (urlLevel == 2) {
                    nameValuePairs.add(new BasicNameValuePair(":operation", "social:selectAnswer"));
                }
            }

            // Creates an article or a comment
            if (componentType.equals(JOURNAL) || componentType.equals(BLOG)) {

                nameValuePairs.add(new BasicNameValuePair(":operation", "social:createJournalComment"));
                nameValuePairs.add(new BasicNameValuePair("subject", record.get(2)));
                StringBuffer message = new StringBuffer("<p>" + record.get(3) + "</p>");

                //We might have more paragraphs to add to the blog or journal article
                for (int i = 6; i < record.size(); i++) {
                    if (record.get(i).length() > 0) {
                        message.append("<p>" + record.get(i) + "</p>");
                    }
                }

                //We might have some tags to add to the blog or journal article
                if (record.get(5).length() > 0) {
                    nameValuePairs.add(new BasicNameValuePair("tags", record.get(5)));
                }

                nameValuePairs.add(new BasicNameValuePair("message", message.toString()));

            }

            // Creates a review or a comment
            if (componentType.equals(REVIEWS)) {

                nameValuePairs.add(new BasicNameValuePair("message", record.get(2)));

                // This might be a top level review, or a comment on a review or another comment
                if (urlLevel == 0) {
                    nameValuePairs.add(new BasicNameValuePair(":operation", "social:createReview"));
                    nameValuePairs.add(new BasicNameValuePair("ratings", record.get(3)));
                    if (record.size() > 4 && record.get(4).length() > 0) {
                        // If we are dealing with a non-existent resource, then the design drives the behavior
                        nameValuePairs.add(new BasicNameValuePair("scf:resourceType",
                                "social/reviews/components/hbs/reviews"));
                        nameValuePairs.add(new BasicNameValuePair("scf:included", record.get(4)));
                    }
                } else {
                    nameValuePairs.add(new BasicNameValuePair(":operation", "social:createComment"));
                }

            }

            // Creates a rating
            if (componentType.equals(RATINGS)) {

                nameValuePairs.add(new BasicNameValuePair(":operation", "social:postTallyResponse"));
                nameValuePairs.add(new BasicNameValuePair("tallyType", "Rating"));
                nameValuePairs.add(new BasicNameValuePair("response", record.get(2)));

            }

            // Creates a DAM asset
            if (componentType.equals(ASSET) && record.get(ASSET_INDEX_NAME).length() > 0) {

                nameValuePairs.add(new BasicNameValuePair("fileName", record.get(ASSET_INDEX_NAME)));

            }

            // Creates an enablement resource
            if (componentType.equals(RESOURCE)) {

                nameValuePairs.add(new BasicNameValuePair(":operation", "se:createResource"));

                List<NameValuePair> otherNameValuePairs = buildNVP(record, RESOURCE_INDEX_PROPERTIES);
                nameValuePairs.addAll(otherNameValuePairs);

                // Adding the site
                nameValuePairs.add(new BasicNameValuePair("site",
                        "/content/sites/" + record.get(RESOURCE_INDEX_SITE) + "/resources/en"));

                // Building the cover image fragment
                if (record.get(RESOURCE_INDEX_THUMBNAIL).length() > 0) {
                    nameValuePairs.add(new BasicNameValuePair("cover-image", doThumbnail(hostname, port,
                            adminPassword, csvfile, record.get(RESOURCE_INDEX_THUMBNAIL))));
                } else {
                    nameValuePairs.add(new BasicNameValuePair("cover-image", ""));
                }

                // Building the asset fragment
                String coverPath = "/content/dam/" + record.get(RESOURCE_INDEX_SITE) + "/resource-assets/"
                        + record.get(2) + "/jcr:content/renditions/cq5dam.thumbnail.319.319.png";
                String coverSource = "dam";
                String assets = "[{\"cover-img-path\":\"" + coverPath + "\",\"thumbnail-source\":\""
                        + coverSource
                        + "\",\"asset-category\":\"enablementAsset:dam\",\"resource-asset-name\":null,\"state\":\"A\",\"asset-path\":\"/content/dam/"
                        + record.get(RESOURCE_INDEX_SITE) + "/resource-assets/" + record.get(2) + "\"}]";
                nameValuePairs.add(new BasicNameValuePair("assets", assets));

                logger.debug("assets:" + assets);

            }

            // Creates a learning path
            if (componentType.equals(LEARNING)) {

                nameValuePairs.add(new BasicNameValuePair(":operation", "se:editLearningPath"));

                List<NameValuePair> otherNameValuePairs = buildNVP(record, RESOURCE_INDEX_PROPERTIES);
                nameValuePairs.addAll(otherNameValuePairs);

                // Adding the site
                nameValuePairs.add(new BasicNameValuePair("site",
                        "/content/sites/" + record.get(RESOURCE_INDEX_SITE) + "/resources/en"));

                // Building the cover image fragment
                if (record.get(RESOURCE_INDEX_THUMBNAIL).length() > 0) {
                    nameValuePairs.add(new BasicNameValuePair("card-image", doThumbnail(hostname, port,
                            adminPassword, csvfile, record.get(RESOURCE_INDEX_THUMBNAIL))));
                }

                // Building the learning path fragment
                StringBuffer assets = new StringBuffer("[\"");
                if (learningpaths.get(record.get(2)) != null) {

                    ArrayList<String> paths = learningpaths.get(record.get(2));
                    int i = 0;
                    for (String path : paths) {
                        assets.append("{\\\"type\\\":\\\"linked-resource\\\",\\\"path\\\":\\\"");
                        assets.append(path);
                        assets.append("\\\"}");
                        if (i++ < paths.size() - 1) {
                            assets.append("\",\"");
                        }
                    }

                } else {
                    logger.debug("No asset for this learning path");
                }
                assets.append("\"]");
                nameValuePairs.add(new BasicNameValuePair("learningpath-items", assets.toString()));
                logger.debug("Learning path:" + assets.toString());

            }

            // Creates a calendar event
            if (componentType.equals(CALENDAR)) {

                nameValuePairs.add(new BasicNameValuePair(":operation", "social:createEvent"));
                try {
                    JSONObject event = new JSONObject();

                    // Building the JSON fragment for a new calendar event
                    event.accumulate("subject", record.get(2));
                    event.accumulate("message", record.get(3));
                    event.accumulate("location", record.get(4));
                    event.accumulate("tags", "");
                    event.accumulate("undefined", "update");

                    String startDate = record.get(5);
                    startDate = startDate.replaceAll("YYYY",
                            Integer.toString(Calendar.getInstance().get(Calendar.YEAR)));
                    startDate = startDate.replaceAll("MM",
                            Integer.toString(1 + Calendar.getInstance().get(Calendar.MONTH)));
                    event.accumulate("start", startDate);

                    String endDate = record.get(6);
                    endDate = endDate.replaceAll("YYYY",
                            Integer.toString(Calendar.getInstance().get(Calendar.YEAR)));
                    endDate = endDate.replaceAll("MM",
                            Integer.toString(1 + Calendar.getInstance().get(Calendar.MONTH)));
                    event.accumulate("end", endDate);
                    nameValuePairs.add(new BasicNameValuePair("event", event.toString()));

                } catch (Exception ex) {

                    logger.error(ex.getMessage());

                }

            }

            // Constructing a multi-part POST request
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setCharset(MIME.UTF8_CHARSET);
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            for (NameValuePair nameValuePair : nameValuePairs) {
                builder.addTextBody(nameValuePair.getName(), nameValuePair.getValue(),
                        ContentType.create("text/plain", MIME.UTF8_CHARSET));
            }

            // See if we have attachments for this new post - or some other actions require a form nonetheless
            if ((componentType.equals(ASSET) || componentType.equals(AVATAR) || componentType.equals(FORUM)
                    || (componentType.equals(JOURNAL)) || componentType.equals(BLOG)) && record.size() > 4
                    && record.get(ASSET_INDEX_NAME).length() > 0) {

                File attachment = new File(csvfile.substring(0, csvfile.indexOf(".csv")) + File.separator
                        + record.get(ASSET_INDEX_NAME));

                ContentType ct = ContentType.MULTIPART_FORM_DATA;
                if (record.get(ASSET_INDEX_NAME).indexOf(".mp4") > 0) {
                    ct = ContentType.create("video/mp4", MIME.UTF8_CHARSET);
                } else if (record.get(ASSET_INDEX_NAME).indexOf(".jpg") > 0
                        || record.get(ASSET_INDEX_NAME).indexOf(".jpeg") > 0) {
                    ct = ContentType.create("image/jpeg", MIME.UTF8_CHARSET);
                } else if (record.get(ASSET_INDEX_NAME).indexOf(".png") > 0) {
                    ct = ContentType.create("image/png", MIME.UTF8_CHARSET);
                } else if (record.get(ASSET_INDEX_NAME).indexOf(".pdf") > 0) {
                    ct = ContentType.create("application/pdf", MIME.UTF8_CHARSET);
                } else if (record.get(ASSET_INDEX_NAME).indexOf(".zip") > 0) {
                    ct = ContentType.create("application/zip", MIME.UTF8_CHARSET);
                }
                builder.addBinaryBody("file", attachment, ct, attachment.getName());
                logger.debug("Adding file to payload with name: " + attachment.getName() + " and type: "
                        + ct.getMimeType());

            }

            // If it's a resource or a learning path, we need the path to the resource for subsequent publishing
            String jsonElement = "location";
            if (componentType.equals(RESOURCE)) {
                jsonElement = "changes/argument";
            }
            if (componentType.equals(LEARNING)) {
                jsonElement = "path";
            }
            if (componentType.equals(ASSET)) {
                jsonElement = null;
            }

            // This call generally returns the path to the content fragment that was just created
            location = Loader.doPost(hostname, port, url[urlLevel], userName, password, builder.build(),
                    jsonElement);

            // If we are loading a DAM asset, we are waiting for all renditions to be generated before proceeding
            if (componentType.equals(ASSET)) {
                int pathIndex = url[urlLevel].lastIndexOf(".createasset.html");
                if (pathIndex > 0)
                    doWaitPath(hostname, port, adminPassword, url[urlLevel].substring(0, pathIndex) + "/"
                            + record.get(ASSET_INDEX_NAME) + "/jcr:content/renditions", "nt:file");
            }

            // Let's see if it needs to be added to a learning path
            if (componentType.equals(RESOURCE) && record.get(RESOURCE_INDEX_PATH).length() > 0
                    && location != null) {

                // Adding the location to a list of a resources for this particular Learning Path
                if (learningpaths.get(record.get(RESOURCE_INDEX_PATH)) == null)
                    learningpaths.put(record.get(RESOURCE_INDEX_PATH), new ArrayList<String>());
                logger.debug("Adding resource to Learning path: " + record.get(RESOURCE_INDEX_PATH));
                ArrayList<String> locations = learningpaths.get(record.get(RESOURCE_INDEX_PATH));
                locations.add(location);
                learningpaths.put(record.get(RESOURCE_INDEX_PATH), locations);

            }

            // If it's a Learning Path, we publish it when possible
            if (componentType.equals(LEARNING) && !port.equals(altport) && location != null) {

                // Publishing the learning path 
                List<NameValuePair> publishNameValuePairs = new ArrayList<NameValuePair>();
                publishNameValuePairs.add(new BasicNameValuePair(":operation", "se:publishEnablementContent"));
                publishNameValuePairs.add(new BasicNameValuePair("replication-action", "activate"));
                logger.debug("Publishing a learning path from: " + location);
                Loader.doPost(hostname, port, location, userName, password,
                        new UrlEncodedFormEntity(publishNameValuePairs), null);

                // Waiting for the learning path to be published
                Loader.doWait(hostname, altport, "admin", adminPassword,
                        location.substring(1 + location.lastIndexOf("/")) // Only search for groups with the learning path in it
                );

                // Decorate the resources within the learning path with comments and ratings, randomly generated
                ArrayList<String> paths = learningpaths.get(record.get(2));
                for (String path : paths) {
                    doDecorate(hostname, altport, path, record, analytics);
                }

            }

            // If it's an Enablement Resource, a lot of things need to happen...
            // Step 1. If it's a SCORM resource, we wait for the SCORM metadata workflow to be complete before proceeding
            // Step 2. We publish the resource
            // Step 3. We set a new first published date on the resource (3 weeks earlier) so that reporting data is more meaningful
            // Step 4. We wait for the resource to be available on publish (checking that associated groups are available)
            // Step 5. We retrieve the json for the resource on publish to retrieve the Social endpoints
            // Step 6. We post ratings and comments for each of the enrollees on publish
            if (componentType.equals(RESOURCE) && !port.equals(altport) && location != null) {

                // Wait for the data to be fully copied
                doWaitPath(hostname, port, adminPassword, location + "/assets/asset", "nt:file");

                // If we are dealing with a SCORM asset, we wait a little bit before publishing the resource to that the SCORM workflow is completed 
                if (record.get(2).indexOf(".zip") > 0) {
                    doSleep(10000, "SCORM Resource, waiting for workflow to complete");
                }

                // Publishing the resource 
                List<NameValuePair> publishNameValuePairs = new ArrayList<NameValuePair>();
                publishNameValuePairs.add(new BasicNameValuePair(":operation", "se:publishEnablementContent"));
                publishNameValuePairs.add(new BasicNameValuePair("replication-action", "activate"));
                logger.debug("Publishing a resource from: " + location);
                Loader.doPost(hostname, port, location, userName, password,
                        new UrlEncodedFormEntity(publishNameValuePairs), null);

                // Waiting for the resource to be published
                Loader.doWait(hostname, altport, "admin", adminPassword,
                        location.substring(1 + location.lastIndexOf("/")) // Only search for groups with the resource path in it
                );

                // Setting the first published timestamp so that reporting always comes with 3 weeks of data after building a new demo instance
                DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
                Calendar cal = Calendar.getInstance();
                cal.add(Calendar.DATE, REPORTINGDAYS);
                List<NameValuePair> publishDateNameValuePairs = new ArrayList<NameValuePair>();
                publishDateNameValuePairs
                        .add(new BasicNameValuePair("date-first-published", dateFormat.format(cal.getTime())));
                logger.debug("Setting the publish date for a resource from: " + location);
                doPost(hostname, port, location, userName, password,
                        new UrlEncodedFormEntity(publishDateNameValuePairs), null);

                // Adding comments and ratings for this resource
                doDecorate(hostname, altport, location, record, analytics);

            }

        }
    } catch (IOException e) {

        logger.error(e.getMessage());

    }

}