Example usage for java.util List get

List of usage examples for java.util List get

Introduction

In this page you can find the example usage for java.util List get.

Prototype

E get(int index);

Source Link

Document

Returns the element at the specified position in this list.

Usage

From source file:edu.pitt.dbmi.facebase.hd.HumanDataController.java

/** Entry point to application.  Firstly it gathers properties from hd.properties file on CLASSPATH 
 * Most properties are localisms to do with file path information, database connection strings, 
 * and TrueCrypt program operation.  Hopefully the application can run by only editing entries in 
 * hd.properties file.  hd.properties has normal java properties fragility but also app-specific 
 * fragility--for example, the sshServerUrl must end with a colon, as in root@server:
 * Notice that program properties can also be set below--by filling in the empty strings following 
 * declaration AND commenting-out the try-catch clause that follows which gathers these properties 
 * from hd.properties.  /*from  w  w w  . j a v a  2s .  co m*/
 */
public static void main(String[] args) {
    /** holds human-readable error data to be passed to addError() */
    String errorString = "";

    log.info("HumanDataController Started");
    /** length of time to sleep in between each polling loop, 5secs is responsive, 5mins is alot */
    String sleepFor = "";
    /** Prefix path where TrueCrypt write operations will be performed (i.e. /tmp or /var/tmp), no trailing-slash */
    String trueCryptBasePath = "";
    /** TrueCrypt volume file extension (probably .tc or .zip) */
    String trueCryptExtension = "";
    /** Middle-of-path directory name to be created where TrueCrypt volume will be mounted */
    String trueCryptMountpoint = "";
    /** Human Data Server database credentials */
    String hdDbUser = "";
    String hdPasswd = "";
    String hdJdbcUrl = "";
    /** Hub database credentials */
    String fbDbUser = "";
    String fbPasswd = "";
    String fbJdbcUrl = "";
    /** Full path to truecrypt binary, (ie /usr/bin/truecrypt) */
    String trueCryptBin = "";
    /** Full path to scp binary, (ie /usr/bin/scp) */
    String scpBin = "";
    /** user@host portion of scp destination argument (ie. root@www.server.com:) */
    String sshServerUrl = "";
    /** file full path portion of scp destination argument (ie. /usr/local/downloads/) */
    String finalLocation = "";
    /** Full path to touch binary, (ie /bin/touch) */
    String touchBin = "";
    /** hardcoded truecrypt parameters; run "truecrypt -h" to learn about these */
    String algorithm = "";
    String hash = "";
    String filesystem = "";
    String volumeType = "";
    String randomSource = "";
    String protectHidden = "";
    String extraArgs = "";

    /** truecrypt parameters are packed into a map so we only pass one arg (this map) to method invoking truecrypt */
    HashMap<String, String> trueCryptParams = new HashMap<String, String>();
    trueCryptParams.put("trueCryptBin", "");
    trueCryptParams.put("scpBin", "");
    trueCryptParams.put("sshServerUrl", "");
    trueCryptParams.put("finalLocation", "");
    trueCryptParams.put("touchBin", "");
    trueCryptParams.put("algorithm", "");
    trueCryptParams.put("hash", "");
    trueCryptParams.put("filesystem", "");
    trueCryptParams.put("volumeType", "");
    trueCryptParams.put("randomSource", "");
    trueCryptParams.put("protectHidden", "");
    trueCryptParams.put("extraArgs", "");

    try {
        /** The properties file name is hardcoded to hd.properties--cannot be changed--this file must be on or at root of classpath */
        final Configuration config = new PropertiesConfiguration("hd.properties");
        sleepFor = config.getString("sleepFor");
        hubURL = config.getString("hubURL");
        responseTrigger = config.getString("responseTrigger");
        trueCryptBasePath = config.getString("trueCryptBasePath");
        trueCryptExtension = config.getString("trueCryptExtension");
        trueCryptMountpoint = config.getString("trueCryptMountpoint");
        hdDbUser = config.getString("hdDbUser");
        hdPasswd = config.getString("hdPasswd");
        hdJdbcUrl = config.getString("hdJdbcUrl");
        fbDbUser = config.getString("fbDbUser");
        fbPasswd = config.getString("fbPasswd");
        fbJdbcUrl = config.getString("fbJdbcUrl");
        trueCryptBin = config.getString("trueCryptBin");
        scpBin = config.getString("scpBin");
        sshServerUrl = config.getString("sshServerUrl");
        finalLocation = config.getString("finalLocation");
        touchBin = config.getString("touchBin");
        algorithm = config.getString("algorithm");
        hash = config.getString("hash");
        filesystem = config.getString("filesystem");
        volumeType = config.getString("volumeType");
        randomSource = config.getString("randomSource");
        protectHidden = config.getString("protectHidden");
        extraArgs = config.getString("extraArgs");

        trueCryptParams.put("trueCryptBin", trueCryptBin);
        trueCryptParams.put("scpBin", scpBin);
        trueCryptParams.put("sshServerUrl", sshServerUrl);
        trueCryptParams.put("finalLocation", finalLocation);
        trueCryptParams.put("touchBin", touchBin);
        trueCryptParams.put("algorithm", algorithm);
        trueCryptParams.put("hash", hash);
        trueCryptParams.put("filesystem", filesystem);
        trueCryptParams.put("volumeType", volumeType);
        trueCryptParams.put("randomSource", randomSource);
        trueCryptParams.put("protectHidden", protectHidden);
        trueCryptParams.put("extraArgs", extraArgs);
        log.debug("properties file loaded successfully");
    } catch (final ConfigurationException e) {
        errorString = "Properties file problem";
        String logString = e.getMessage();
        addError(errorString, logString);
        log.error(errorString);
    }
    log.debug("initialize static class variable HumanDataManager declared earlier");
    hdm = new HumanDataManager(hdDbUser, hdPasswd, hdJdbcUrl);
    log.debug("declare and initialize InstructionQueueManager");
    InstructionQueueManager iqm = new InstructionQueueManager(fbDbUser, fbPasswd, fbJdbcUrl);
    log.debug("pass to the logfile/console all startup parameters for troubleshooting");
    log.info("HumanDataController started with these settings from hd.properties: " + "hubURL=" + hubURL + " "
            + "responseTrigger=" + responseTrigger + " " + "trueCryptBasePath=" + trueCryptBasePath + " "
            + "trueCryptExtension=" + trueCryptExtension + " " + "trueCryptMountpoint=" + trueCryptMountpoint
            + " " + "hdDbUser=" + hdDbUser + " " + "hdPasswd=" + hdPasswd + " " + "hdJdbcUrl=" + hdJdbcUrl + " "
            + "fbDbUser=" + fbDbUser + " " + "fbPasswd=" + fbPasswd + " " + "fbJdbcUrl=" + fbJdbcUrl + " "
            + "trueCryptBin=" + trueCryptBin + " " + "scpBin=" + scpBin + " " + "sshServerUrl=" + sshServerUrl
            + " " + "finalLocation=" + finalLocation + " " + "touchBin=" + touchBin + " " + "algorithm="
            + algorithm + " " + "hash=" + hash + " " + "filesystem=" + filesystem + " " + "volumeType="
            + volumeType + " " + "randomSource=" + randomSource + " " + "protectHidden=" + protectHidden + " "
            + "extraArgs=" + extraArgs);
    log.debug("Enter infinite loop where program will continuously poll Hub server database for new requests");
    while (true) {
        log.debug("LOOP START");
        try {
            Thread.sleep(Integer.parseInt(sleepFor) * 1000);
        } catch (InterruptedException ie) {
            errorString = "Failed to sleep, got interrupted.";
            log.error(errorString, ie);
            addError(errorString, ie.getMessage());
        }
        log.debug(
                "About to invoke InstructionQueueManager.queryInstructions()--Hibernate to fb_queue starts NOW");
        List<InstructionQueueItem> aiqi = iqm.queryInstructions();
        log.debug("Currently there are " + aiqi.size() + " items in the queue");
        InstructionQueueItem iqi;
        String instructionName = "";
        log.debug("About to send http request -status- telling Hub we are alive:");
        httpGetter("status", "0");
        if (aiqi.size() > 0) {
            log.debug(
                    "There is at least one request, status=pending, queue item; commence processing of most recent item");
            iqi = aiqi.get(0);
            log.debug("About to get existing user key, or create a new one, via fb_keychain Hibernate");
            FbKey key = hdm.queryKey(iqi.getUid());
            log.debug(
                    "About to pull the JSON Instructions string, and other items, from the InstructionQueueItem");
            String instructionsString = iqi.getInstructions();
            instructionName = iqi.getName();
            log.debug("About to create a new FileManager object with:");
            log.debug(instructionName + trueCryptBasePath + trueCryptExtension + trueCryptMountpoint);
            FileManager fm = new FileManager(instructionName, trueCryptBasePath, trueCryptExtension,
                    trueCryptMountpoint);
            ArrayList<Instructions> ali = new ArrayList<Instructions>();
            log.debug(
                    "FileManager.makeInstructionsObjects() creates multiple Instruction objects from the InstructionQueueItem.getInstructions() value");
            if (fm.makeInstructionsObjects(instructionsString, ali)) {
                log.debug("FileManager.makeInstructionsObjects() returned true");
            } else {
                errorString = "FileManager.makeInstructionsObjects() returned false";
                log.error(errorString);
                addError(errorString, "");
            }
            log.debug(
                    "FileManager.makeFiles() uses its list of Instruction objects and calls its makeFiles() method to make/get requested data files");
            if (fm.makeFiles(ali)) {
                log.debug("FileManager.makeFiles() returned true");
            } else {
                errorString = "FileManager.makeFiles() returned false";
                log.error(errorString);
                addError(errorString, "");
            }
            //sends the size/100000 as seconds(100k/sec)...needs to be real seconds.");
            long bytesPerSecond = 100000;
            Long timeToMake = new Long(fm.getSize() / bytesPerSecond);
            String timeToMakeString = timeToMake.toString();
            log.debug("Send http request -status- to Hub with total creation time estimate:");
            log.debug(timeToMakeString);
            httpGetter("status", timeToMakeString);
            log.debug(
                    "Update the queue_item row with the total size of the data being packaged with InstructionQueueManager.updateInstructionSize()");
            if (iqm.updateInstructionSize(fm.getSize(), iqi.getQid())) {
                log.debug("InstructionQueueManager.updateInstructionSize() returned true");
            } else {
                errorString = "InstructionQueueManager.updateInstructionSize() returned false";
                log.error(errorString);
                addError(errorString, "");
            }
            log.debug("About to make new TrueCryptManager with these args:");
            log.debug(key.getEncryption_key() + fm.getSize() + fm.getTrueCryptPath()
                    + fm.getTrueCryptVolumePath() + trueCryptParams);
            TrueCryptManager tcm = new TrueCryptManager(key.getEncryption_key(), fm.getSize(),
                    fm.getTrueCryptPath(), fm.getTrueCryptVolumePath(), trueCryptParams);
            if (tcm.touchVolume()) {
                log.debug("TrueCryptManager.touchVolume() returned true, touched file");
            } else {
                errorString = "TrueCryptManager.touchVolume() returned false";
                log.error(errorString);
                addError(errorString, "");
            }
            if (tcm.makeVolume()) {
                log.debug("TrueCryptManager.makeVolume() returned true, created TrueCrypt volume");
            } else {
                errorString = "TrueCryptManager.makeVolume() returned false";
                log.error(errorString);
                addError(errorString, "");
            }
            if (tcm.mountVolume()) {
                log.debug("TrueCryptManager.mountVolume() returned true, mounted TrueCrypt volume");
            } else {
                errorString = "TrueCryptManager.mountVolume() returned false";
                log.error(errorString);
                addError(errorString, "");
            }
            if (fm.copyFilesToVolume(ali)) {
                log.debug(
                        "TrueCryptManager.copyFilesToVolume() returned true, copied requested files to mounted volume");
            } else {
                errorString = "TrueCryptManager.copyFilesToVolume() returned false";
                log.error(errorString);
                addError(errorString, "");
            }
            if (tcm.disMountVolume()) {
                log.debug("TrueCryptManager.disMountVolume() returned true, umounted TrueCrypt volume");
            } else {
                errorString = "TrueCryptManager.disMountVolume() returned false";
                log.error(errorString);
                addError(errorString, "");
            }
            if (tcm.sendVolumeToFinalLocation()) {
                log.debug(
                        "TrueCryptManager.sendVolumeToFinalLocation() returned true, copied TrueCrypt volume to retreivable, final location");
            } else {
                errorString = "TrueCryptManager.sendVolumeToFinalLocation() returned false";
                log.error(errorString);
                addError(errorString, "");
            }
            if (iqm.updateInstructionToCompleted(tcm.getFinalLocation() + fm.getTrueCryptFilename(),
                    fm.getSize(), iqi.getQid(), getErrors(), getLogs())) {
                log.debug("InstructionQueueManager.updateInstructionToCompleted() returned true");
                log.debug(
                        "Processing of queue item is almost finished, updated fb_queue item row with location, size, status, errors, logs:");
                log.debug(tcm.getFinalLocation() + fm.getTrueCryptFilename() + fm.getSize() + iqi.getQid()
                        + getErrors() + getLogs());
            } else {
                errorString = "InstructionQueueManager.updateInstructionToCompleted() returned false";
                log.error(errorString);
                addError(errorString, "");
            }
            log.debug("About to send http request -update- telling Hub which item is finished.");
            httpGetter("update", iqi.getHash());
            log.debug("Finished processing pending queue item, status should now be complete or error");
        } else {
            log.debug("Zero queue items");
        }
        log.debug("LOOP END");
    }
}

From source file:edu.stanford.epad.common.pixelmed.TIFFMasksToDSOConverter.java

/**
 * @param args/*from  ww w. j ava  2 s  .c  o m*/
 */
public static void main(String[] args) {
    if (args.length < 3) {
        System.out.println(
                "\n\nInvalid arguments.\n\nUsage: java -classpath epad-ws-1.1-jar-with-dependencies.jar edu.stanford.epad.common.pixelmed.TIFFMasksToDSOConverter tiffFolder dicomFolder outputDSO.dcm");
        return;
    }
    String maskFilesDirectory = args[0];
    String dicomFilesDirectory = args[1];
    String outputFileName = args[2];
    //String maskFilesDirectory = "/Stanford/rlabs/data/tiffmasks";
    //String dicomFilesDirectory = "/Stanford/rlabs/data/dicoms";
    //String outputFileName = "/Stanford/rlabs/data/output/dso.dcm";

    List<String> dicomFilePaths = listFilesInAlphabeticOrder(dicomFilesDirectory);
    for (int i = 0; i < dicomFilePaths.size(); i++) {
        if (!dicomFilePaths.get(i).toLowerCase().endsWith(".dcm")) {
            System.out.println("Removing DICOM file " + dicomFilePaths.get(i));
            dicomFilePaths.remove(i);
            i--;
        }
    }
    if (dicomFilePaths.size() == 0) {
        System.out.println("No DICOM files found");
        return;
    }

    List<String> maskFilePaths = listFilesInAlphabeticOrder(maskFilesDirectory);
    for (int i = 0; i < maskFilePaths.size(); i++) {
        if (!maskFilePaths.get(i).toLowerCase().endsWith(".tif")
                && !maskFilePaths.get(i).toLowerCase().endsWith(".tiff")) {
            System.out.println("Removing tif file " + maskFilePaths.get(i));
            maskFilePaths.remove(i);
            i--;
        }
    }
    // Flip them because the code expects that
    List<String> reverseMaskFilePaths = new ArrayList<String>();
    for (int i = maskFilePaths.size(); i > 0; i--) {
        reverseMaskFilePaths.add(maskFilePaths.get(i - 1));
    }
    if (maskFilePaths.size() == 0) {
        System.out.println("No Tif Mask files found");
        return;
    }

    if (dicomFilePaths.size() > maskFilePaths.size())
        dicomFilePaths = dicomFilePaths.subList(0, reverseMaskFilePaths.size());
    else if (reverseMaskFilePaths.size() > dicomFilePaths.size())
        reverseMaskFilePaths = reverseMaskFilePaths.subList(0, dicomFilePaths.size());

    try {
        TIFFMasksToDSOConverter converter = new TIFFMasksToDSOConverter();
        String[] uids = null;
        if (args.length > 3)
            uids = converter.generateDSO(reverseMaskFilePaths, dicomFilePaths, outputFileName, args[3]);
        else
            uids = converter.generateDSO(reverseMaskFilePaths, dicomFilePaths, outputFileName);
        System.out
                .println("DICOM Segmentation Object created. SeriesUID:" + uids[0] + " InstanceUID:" + uids[1]);
    } catch (Exception e) {
        System.err.println(e);
        e.printStackTrace(System.err);
        System.exit(0);
    }
}

From source file:bear.core.BearMain.java

/**
 * -VbearMain.appConfigDir=src/main/groovy/examples -VbearMain.buildDir=.bear/classes -VbearMain.script=dumpSampleGrid -VbearMain.projectClass=SecureSocialDemoProject -VbearMain.propertiesFile=.bear/test.properties
 *//*from   ww  w .  j a  v  a 2  s.  c  o m*/
public static void main(String[] args) throws Exception {
    int i = ArrayUtils.indexOf(args, "--log-level");

    if (i != -1) {
        LoggingBooter.changeLogLevel(LogManager.ROOT_LOGGER_NAME, Level.toLevel(args[i + 1]));
    }

    i = ArrayUtils.indexOf(args, "-q");

    if (i != -1) {
        LoggingBooter.changeLogLevel(LogManager.ROOT_LOGGER_NAME, Level.WARN);
    }

    GlobalContext global = GlobalContext.getInstance();

    BearMain bearMain = null;

    try {
        bearMain = new BearMain(global, getCompilerManager(), args);
    } catch (Exception e) {
        if (e.getClass().getSimpleName().equals("MissingRequiredOptionException")) {
            System.out.println(e.getMessage());
        } else {
            Throwables.getRootCause(e).printStackTrace();
        }

        System.exit(-1);
    }

    if (bearMain.checkHelpAndVersion()) {
        return;
    }

    AppOptions2 options2 = bearMain.options;

    if (options2.has(AppOptions2.UNPACK_DEMOS)) {
        String filesAsText = ProjectGenerator.readResource("/demoFiles.txt");

        int count = 0;

        for (String resource : filesAsText.split("::")) {
            File dest = new File(BEAR_DIR + resource);
            System.out.printf("copying %s to %s...%n", resource, dest);

            writeStringToFile(dest, ProjectGenerator.readResource(resource));

            count++;
        }

        System.out.printf("extracted %d files%n", count);

        return;
    }

    if (options2.has(AppOptions2.CREATE_NEW)) {
        String dashedTitle = options2.get(AppOptions2.CREATE_NEW);

        String user = options2.get(AppOptions2.USER);
        String pass = options2.get(AppOptions2.PASSWORD);

        List<String> hosts = options2.getList(AppOptions2.HOSTS);

        List<String> template;

        if (options2.has(AppOptions2.TEMPLATE)) {
            template = options2.getList(AppOptions2.TEMPLATE);
        } else {
            template = emptyList();
        }

        ProjectGenerator g = new ProjectGenerator(dashedTitle, user, pass, hosts, template);

        if (options2.has(AppOptions2.ORACLE_USER)) {
            g.oracleUser = options2.get(AppOptions2.ORACLE_USER);
        }

        if (options2.has(AppOptions2.ORACLE_PASSWORD)) {
            g.oraclePassword = options2.get(AppOptions2.ORACLE_PASSWORD);
        }

        File projectFile = new File(BEAR_DIR, g.getProjectTitle() + ".groovy");
        File pomFile = new File(BEAR_DIR, "pom.xml");

        writeStringToFile(projectFile, g.processTemplate("TemplateProject.template"));

        writeStringToFile(new File(BEAR_DIR, dashedTitle + ".properties"),
                g.processTemplate("project-properties.template"));
        writeStringToFile(new File(BEAR_DIR, "demos.properties"),
                g.processTemplate("project-properties.template"));
        writeStringToFile(new File(BEAR_DIR, "bear-fx.properties"),
                g.processTemplate("bear-fx.properties.template"));

        writeStringToFile(pomFile, g.generatePom(dashedTitle));

        System.out.printf("Created project file: %s%n", projectFile.getPath());
        System.out.printf("Created maven pom: %s%n", pomFile.getPath());

        System.out.println("\nProject files have been created. You may now: " + "\n a) Run `bear "
                + g.getShortName() + ".ls` to quick-test your minimal setup"
                + "\n b) Import the project to IDE or run smoke tests, find more details at the project wiki: https://github.com/chaschev/bear/wiki/.");

        return;
    }

    Bear bear = global.bear;

    if (options2.has(AppOptions2.QUIET)) {
        global.put(bear.quiet, true);
        LoggingBooter.changeLogLevel(LogManager.ROOT_LOGGER_NAME, Level.WARN);
    }

    if (options2.has(AppOptions2.USE_UI)) {
        global.put(bear.useUI, true);
    }

    if (options2.has(AppOptions2.NO_UI)) {
        global.put(bear.useUI, false);
    }

    List<?> list = options2.getOptionSet().nonOptionArguments();

    if (list.size() > 1) {
        throw new IllegalArgumentException("too many arguments: " + list + ", "
                + "please specify an invoke line, project.method(arg1, arg2)");
    }

    if (list.isEmpty()) {
        throw new UnsupportedOperationException("todo implement running a single project");
    }

    String invokeLine = (String) list.get(0);

    String projectName;
    String method;

    if (invokeLine.contains(".")) {
        projectName = StringUtils.substringBefore(invokeLine, ".");
        method = StringUtils.substringAfter(invokeLine, ".");
    } else {
        projectName = invokeLine;
        method = null;
    }

    if (method == null || method.isEmpty())
        method = "deploy()";
    if (!method.contains("("))
        method += "()";

    Optional<CompiledEntry<? extends BearProject>> optional = bearMain.compileManager.findProject(projectName);

    if (!optional.isPresent()) {
        throw new IllegalArgumentException("project was not found: " + projectName + ", loaded classes: \n"
                + Joiner.on("\n").join(bearMain.compileManager.findProjects()) + ", searched in: "
                + bearMain.compileManager.getSourceDirs() + ", ");
    }

    BearProject project = OpenBean.newInstance(optional.get().aClass).injectMain(bearMain);

    GroovyShell shell = new GroovyShell();

    shell.setVariable("project", project);
    shell.evaluate("project." + method);
}

From source file:ke.co.tawi.babblesms.server.utils.randomgenerate.IncomingLogGenerator.java

/**
 * @param args/*from  w  w  w .j a  v a2  s. co  m*/
 */
public static void main(String[] args) {
    System.out.println("Have started IncomingSMSGenerator.");
    File outFile = new File("/tmp/logs/incomingSMS.csv");
    RandomDataGenerator randomDataImpl = new RandomDataGenerator();

    String randomStrFile = "/tmp/random.txt";

    List<String> randomStrings = new ArrayList<>();
    int randStrLength = 0;

    long startDate = 1412380800; // Unix time in seconds for Oct 4 2014
    long stopDate = 1420070340; // Unix time for in seconds Dec 31 2014

    SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 2011-06-01 00:16:45" 

    List<String> shortcodeUuids = new ArrayList<>();
    shortcodeUuids.add("094def52-bc18-4a9e-9b84-c34cc6476c75");
    shortcodeUuids.add("e9570c5d-0cc4-41e5-81df-b0674e9dda1e");
    shortcodeUuids.add("a118c8ea-f831-4288-986d-35e22c91fc4d");
    shortcodeUuids.add("a2688d72-291b-470c-8926-31a903f5ed0c");
    shortcodeUuids.add("9bef62f6-e682-4efd-98e9-ca41fa4ef993");

    int shortcodeCount = shortcodeUuids.size() - 1;

    try {
        randomStrings = FileUtils.readLines(new File(randomStrFile));
        randStrLength = randomStrings.size();

        for (int j = 0; j < 30000; j++) {
            FileUtils.write(outFile,
                    // shortcodeUuids.get(randomDataImpl.nextInt(0, shortcodeCount)) + "|"   // Destination 
                    UUID.randomUUID().toString() + "|" // Unique Code
                            + randomDataImpl.nextLong(new Long("254700000000").longValue(),
                                    new Long("254734999999").longValue())
                            + "|" // Origin
                            + shortcodeUuids.get(randomDataImpl.nextInt(0, shortcodeCount)) + "|"
                            + randomStrings.get(randomDataImpl.nextInt(0, randStrLength - 1)) + "|" // Message
                            + "N|" // deleted
                            + dateFormatter.format(
                                    new Date(randomDataImpl.nextLong(startDate, stopDate) * 1000))
                            + "\n", // smsTime                  
                    true); // Append to file                              
        }

    } catch (IOException e) {
        System.err.println("IOException in main.");
        e.printStackTrace();
    }

    System.out.println("Have finished IncomingSMSGenerator.");
}

From source file:SheetStructure.java

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

    //We are using Jackson JSON parser to serialize and deserialize the JSON. See http://wiki.fasterxml.com/JacksonHome
    //Feel free to use which ever library you prefer.
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    String accessToken = "";//Insert your access token here.

    try {//from  w  w  w.j  av  a2  s . c o  m

        System.out.println("Starting HelloSmartsheet2: Betty's Bake Sale...");
        //First Create a new sheet.
        String sheetName = "Betty's Bake Sale";
        //We will be using POJOs to represent the REST request objects. We will convert these to and from JSON using Jackson JSON.
        //Their structure directly relates to the JSON that gets passed through the API.
        //Note that these POJOs are included as static inner classes to keep this to one file. Normally they would be broken out.
        Sheet newSheet = new Sheet();
        newSheet.setName(sheetName);
        newSheet.setColumns(Arrays.asList(new Column("Baked Goods", "TEXT_NUMBER", null, true, null),
                new Column("Baker", "CONTACT_LIST", null, null, null),
                new Column("Price Per Item", "TEXT_NUMBER", null, null, null),
                new Column("Gluten Free?", "CHECKBOX", "FLAG", null, null), new Column("Status", "PICKLIST",
                        null, null, Arrays.asList("Started", "Finished", "Delivered"))));
        connection = (HttpURLConnection) new URL(GET_SHEETS_URL).openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), newSheet);
        Result<Sheet> newSheetResult = mapper.readValue(connection.getInputStream(),
                new TypeReference<Result<Sheet>>() {
                });
        newSheet = newSheetResult.getResult();
        System.out.println("Sheet " + newSheet.getName() + " created, id: " + newSheet.getId());

        //Now add a column:
        String columnName = "Delivery Date";
        System.out.println("Adding column " + columnName + " to " + sheetName);
        Column newColumn = new Column(columnName, "DATE", 5);

        connection = (HttpURLConnection) new URL(SHEET_COLUMNS_URL.replace(ID, "" + newSheet.getId()))
                .openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), newColumn);
        Result<Column> newColumnResult = mapper.readValue(connection.getInputStream(),
                new TypeReference<Result<Column>>() {
                });

        System.out.println(
                "Column " + newColumnResult.getResult().getTitle() + " added to " + newSheet.getName());

        //Next, we will get the list of Columns from the API. We could figure this out based on what the server has returned in the result, but we'll just ask the API for it.
        System.out.println("Fetching " + newSheet.getName() + " sheet columns...");
        connection = (HttpURLConnection) new URL(SHEET_COLUMNS_URL.replace(ID, "" + newSheet.getId()))
                .openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        List<Column> allColumns = mapper.readValue(connection.getInputStream(),
                new TypeReference<List<Column>>() {
                });
        System.out.println("Fetched.");

        //Now we will be adding rows
        System.out.println("Inserting rows into " + newSheet.getName());
        List<Row> rows = new ArrayList<Row>();
        rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Brownies"),
                new Cell(allColumns.get(1).id, "julieann@example.com"), new Cell(allColumns.get(2).id, "$1"),
                new Cell(allColumns.get(3).id, Boolean.TRUE), new Cell(allColumns.get(4).id, "Finished"))));
        rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Snickerdoodles"),
                new Cell(allColumns.get(1).id, "stevenelson@example.com"), new Cell(allColumns.get(2).id, "$1"),
                new Cell(allColumns.get(3).id, Boolean.FALSE), new Cell(allColumns.get(4).id, "Delivered"),
                new Cell(allColumns.get(5).id, "2013-09-04"))));
        rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Rice Krispy Treats"),
                new Cell(allColumns.get(1).id, "rickthames@example.com"),
                new Cell(allColumns.get(2).id, "$.50"), new Cell(allColumns.get(3).id, Boolean.TRUE),
                new Cell(allColumns.get(4).id, "Started"))));
        rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Muffins"),
                new Cell(allColumns.get(1).id, "sandrassmart@example.com"),
                new Cell(allColumns.get(2).id, "$1.50"), new Cell(allColumns.get(3).id, Boolean.FALSE),
                new Cell(allColumns.get(4).id, "Finished"))));
        rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Chocolate Chip Cookies"),
                new Cell(allColumns.get(1).id, "janedaniels@example.com"), new Cell(allColumns.get(2).id, "$1"),
                new Cell(allColumns.get(3).id, Boolean.FALSE), new Cell(allColumns.get(4).id, "Delivered"),
                new Cell(allColumns.get(5).id, "2013-09-05"))));
        rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Ginger Snaps"),
                new Cell(allColumns.get(1).id, "nedbarnes@example.com"), new Cell(allColumns.get(2).id, "$.50"),
                new Cell(allColumns.get(3).id, Boolean.TRUE),
                new Cell(allColumns.get(4).id, "Unknown", false)))); //Note that this one is strict=false. This is because "Unknown" was not one of the original options when the column was created.

        RowWrapper rowWrapper = new RowWrapper();
        rowWrapper.setToBottom(true);
        rowWrapper.setRows(rows);

        connection = (HttpURLConnection) new URL(SHEET_ROWS_URL.replace(ID, "" + newSheet.getId()))
                .openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), rowWrapper);
        Result<List<Row>> newRowsResult = mapper.readValue(connection.getInputStream(),
                new TypeReference<Result<List<Row>>>() {
                });
        System.out.println("Added " + newRowsResult.getResult().size() + " rows to " + newSheet.getName());

        //Move a row to the top.
        System.out.println("Moving row 6 to the top.");
        RowWrapper moveToTop = new RowWrapper();
        moveToTop.setToTop(true);

        connection = (HttpURLConnection) new URL(
                ROW_URL.replace(ID, "" + newRowsResult.getResult().get(5).getId())).openConnection();
        connection.setRequestMethod("PUT");
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), moveToTop);
        mapper.readValue(connection.getInputStream(), new TypeReference<Result<List<Row>>>() {
        });

        System.out.println("Row 6 moved to top.");

        //Insert empty rows for spacing
        rows = new ArrayList<Row>();
        rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, ""))));
        rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Delivered"))));
        rowWrapper = new RowWrapper();
        rowWrapper.setToBottom(true);
        rowWrapper.setRows(rows);

        connection = (HttpURLConnection) new URL(SHEET_ROWS_URL.replace(ID, "" + newSheet.getId()))
                .openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), rowWrapper);
        Result<List<Row>> spacerRowsResult = mapper.readValue(connection.getInputStream(),
                new TypeReference<Result<List<Row>>>() {
                });
        System.out.println("Added " + spacerRowsResult.getResult().size() + " rows to " + newSheet.getName());

        //Move Delivered rows to be children of the last spacer row.
        System.out.println("Moving delivered rows to Delivered section...");
        Long[] deliveredRowIds = new Long[] { newRowsResult.result.get(1).getId(),
                newRowsResult.result.get(4).getId() };
        RowWrapper parentRowLocation = new RowWrapper();
        parentRowLocation.setParentId(spacerRowsResult.getResult().get(1).getId());

        for (Long deliveredId : deliveredRowIds) {
            System.out.println("Moving " + deliveredId + " to Delivered.");
            connection = (HttpURLConnection) new URL(ROW_URL.replace(ID, "" + deliveredId)).openConnection();
            connection.setRequestMethod("PUT");
            connection.addRequestProperty("Authorization", "Bearer " + accessToken);
            connection.addRequestProperty("Content-Type", "application/json");
            connection.setDoOutput(true);
            mapper.writeValue(connection.getOutputStream(), parentRowLocation);
            mapper.readValue(connection.getInputStream(), new TypeReference<Result<List<Row>>>() {
            });
            System.out.println("Row id " + deliveredId + " moved.");
        }

        System.out.println("Appending additional rows to items in progress...");

        List<Row> siblingRows = new ArrayList<Row>();
        siblingRows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Scones"),
                new Cell(allColumns.get(1).id, "tomlively@example.com"),
                new Cell(allColumns.get(2).id, "$1.50"), new Cell(allColumns.get(3).id, Boolean.TRUE),
                new Cell(allColumns.get(4).id, "Finished"))));
        siblingRows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Lemon Bars"),
                new Cell(allColumns.get(1).id, "rickthames@example.com"), new Cell(allColumns.get(2).id, "$1"),
                new Cell(allColumns.get(3).id, Boolean.FALSE), new Cell(allColumns.get(4).id, "Started"))));
        rowWrapper = new RowWrapper();
        rowWrapper.setSiblingId(newRowsResult.getResult().get(3).getId());
        rowWrapper.setRows(siblingRows);

        connection = (HttpURLConnection) new URL(SHEET_ROWS_URL.replace(ID, "" + newSheet.getId()))
                .openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), rowWrapper);
        Result<List<Row>> siblingRowsResult = mapper.readValue(connection.getInputStream(),
                new TypeReference<Result<List<Row>>>() {
                });
        System.out.println("Added " + siblingRowsResult.getResult().size() + " rows to " + newSheet.getName());

        System.out.println("Moving Status column to index 1...");
        Column statusColumn = allColumns.get(4);
        Column moveColumn = new Column();
        moveColumn.setIndex(1);
        moveColumn.setTitle(statusColumn.title);
        moveColumn.setSheetId(newSheet.getId());
        moveColumn.setType(statusColumn.getType());
        connection = (HttpURLConnection) new URL(COLUMN_URL.replace(ID, "" + statusColumn.getId()))
                .openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        connection.setRequestMethod("PUT");

        mapper.writeValue(connection.getOutputStream(), moveColumn);
        Result<Column> movedColumnResult = mapper.readValue(connection.getInputStream(),
                new TypeReference<Result<Column>>() {
                });
        System.out.println("Moved column " + movedColumnResult.getResult().getId());
        System.out.println("Completed Hellosmartsheet2: Betty's Bake Sale.");
    } catch (IOException e) {
        InputStream is = ((HttpURLConnection) connection).getErrorStream();
        if (is != null) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            String line;
            try {
                response = new StringBuilder();
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();
                Result<?> result = mapper.readValue(response.toString(), Result.class);
                System.err.println(result.message);

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

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

}

From source file:com.github.vatbub.awsvpnlauncher.Main.java

public static void main(String[] args) {
    Common.getInstance().setAppName("awsVpnLauncher");
    FOKLogger.enableLoggingOfUncaughtExceptions();
    prefs = new Preferences(Main.class.getName());

    // enable the shutdown hook
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        if (session != null) {
            if (session.isConnected()) {
                session.disconnect();//from  w w  w.  j  a  v  a2  s.co  m
            }
        }
    }));

    UpdateChecker.completeUpdate(args, (oldVersion, oldFile) -> {
        if (oldVersion != null) {
            FOKLogger.info(Main.class.getName(), "Successfully upgraded " + Common.getInstance().getAppName()
                    + " from v" + oldVersion.toString() + " to v" + Common.getInstance().getAppVersion());
        }
    });
    List<String> argsAsList = new ArrayList<>(Arrays.asList(args));

    for (String arg : args) {
        if (arg.toLowerCase().matches("mockappversion=.*")) {
            // Set the mock version
            String version = arg.substring(arg.toLowerCase().indexOf('=') + 1);
            Common.getInstance().setMockAppVersion(version);
            argsAsList.remove(arg);
        } else if (arg.toLowerCase().matches("mockbuildnumber=.*")) {
            // Set the mock build number
            String buildnumber = arg.substring(arg.toLowerCase().indexOf('=') + 1);
            Common.getInstance().setMockBuildNumber(buildnumber);
            argsAsList.remove(arg);
        } else if (arg.toLowerCase().matches("mockpackaging=.*")) {
            // Set the mock packaging
            String packaging = arg.substring(arg.toLowerCase().indexOf('=') + 1);
            Common.getInstance().setMockPackaging(packaging);
            argsAsList.remove(arg);
        }
    }

    args = argsAsList.toArray(new String[0]);

    try {
        mvnRepoConfig = new Config(
                new URL("https://www.dropbox.com/s/vnhs4nax2lczccf/mavenRepoConfig.properties?dl=1"),
                Main.class.getResource("mvnRepoFallbackConfig.properties"), true, "mvnRepoCachedConfig", true);
        projectConfig = new Config(
                new URL("https://www.dropbox.com/s/d36hwrrufoxfmm7/projectConfig.properties?dl=1"),
                Main.class.getResource("projectFallbackConfig.properties"), true, "projectCachedConfig", true);
    } catch (IOException e) {
        FOKLogger.log(Main.class.getName(), Level.SEVERE, "Could not load the remote config", e);
    }

    try {
        installUpdates(args);
    } catch (Exception e) {
        FOKLogger.log(Main.class.getName(), Level.SEVERE, "Could not install updates", e);
    }

    if (args.length == 0) {
        // not enough arguments
        printHelpMessage();
        throw new NotEnoughArgumentsException();
    }

    switch (args[0].toLowerCase()) {
    case "setup":
        setup();
        break;
    case "launch":
        initAWSConnection();
        launch();
        break;
    case "terminate":
        initAWSConnection();
        terminate();
        break;
    case "config":
        // require a second arg
        if (args.length == 2) {
            // not enough arguments
            printHelpMessage();
            throw new NotEnoughArgumentsException();
        }

        config(Property.valueOf(args[1]), args[2]);
        break;
    case "getconfig":
        // require a second arg
        if (args.length == 1) {
            // not enough arguments
            printHelpMessage();
            throw new NotEnoughArgumentsException();
        }

        getConfig(Property.valueOf(args[1]));
        break;
    case "printconfig":
        printConfig();
        break;
    case "deleteconfig":
        // require a second arg
        if (args.length == 1) {
            // not enough arguments
            printHelpMessage();
            throw new NotEnoughArgumentsException();
        }

        deleteConfig(Property.valueOf(args[1]));
        break;
    case "ssh":
        String sshInstanceId;
        if (args.length == 2) {
            // a instanceID is specified
            sshInstanceId = args[1];
        } else {
            String instanceIdsPrefValue = prefs.getPreference("instanceIDs", "");
            if (instanceIdsPrefValue.equals("")) {
                throw new NotEnoughArgumentsException(
                        "No instanceId was specified to connect to and no instanceId was saved in the preference file. Please either start another instance using the launch command or specify the instance id of the instance to connect to as a additional parameter.");
            }

            List<String> instanceIds = Arrays.asList(instanceIdsPrefValue.split(";"));
            if (instanceIds.size() == 1) {
                // exactly one instance found
                sshInstanceId = instanceIds.get(0);
            } else {
                FOKLogger.severe(Main.class.getName(), "Multiple instance ids found:");

                for (String instanceId : instanceIds) {
                    FOKLogger.severe(Main.class.getName(), instanceId);
                }
                throw new NotEnoughArgumentsException(
                        "Multiple instance ids were found in the preference file. Please specify the instance id of the instance to connect to as a additional parameter.");
            }
        }

        initAWSConnection();
        ssh(sshInstanceId);
        break;
    default:
        printHelpMessage();
    }
}

From source file:com.github.xmltopdf.JasperPdfGenerator.java

/**.
 * @param args//from w w w  .  j a  va 2 s  . c om
 *            the arguments
 * @throws IOException in case IO error
 */
public static void main(String[] args) throws IOException {
    if (args.length == 0) {
        LOG.info(null, USAGE);
        return;
    }
    List<String> templates = new ArrayList<String>();
    List<String> xmls = new ArrayList<String>();
    List<String> types = new ArrayList<String>();
    for (String arg : args) {
        if (arg.endsWith(".jrxml")) {
            templates.add(arg);
        } else if (arg.endsWith(".xml")) {
            xmls.add(arg);
        } else if (arg.startsWith(DOC_TYPE)) {
            types = Arrays
                    .asList(arg.substring(DOC_TYPE.length()).replaceAll("\\s+", "").toUpperCase().split(","));
        }
    }
    if (templates.isEmpty()) {
        LOG.info(null, USAGE);
        return;
    }
    if (types.isEmpty()) {
        types.add("PDF");
    }
    for (String type : types) {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        if (DocType.valueOf(type) != null) {
            new JasperPdfGenerator().createDocument(templates, xmls, os, DocType.valueOf(type));
            os.writeTo(
                    new FileOutputStream(templates.get(0).replaceFirst("\\.jrxml$", "." + type.toLowerCase())));
        }
    }
}

From source file:diffhunter.DiffHunter.java

/**
 * @param args the command line arguments
 * @throws org.apache.commons.cli.ParseException
 * @throws java.io.IOException//from w ww  .  j a v  a  2 s.c o  m
 */
public static void main(String[] args) throws ParseException, IOException {

    //String test_ = Paths.get("J:\\VishalData\\additional\\", "Sasan" + "_BDB").toAbsolutePath().toString();

    // TODO code application logic here
    /*args = new String[]
    {
    "-i", "-b", "J:\\VishalData\\additional\\Ptbp2_E18_5_cortex_CLIP_mm9_plus_strand_sorted.bed", "-r", "J:\\VishalData\\additional\\mouse_mm9.txt", "-o", "J:\\VishalData"
    };*/

    /*args = new String[]
    {
    "-c", "-r", "J:\\VishalData\\additional\\mouse_mm9.txt", "-1", "J:\\VishalData\\Ptbp2_Adult_testis_CLIP_mm9_plus_strand_sorted_BDB", "-2", "J:\\VishalData\\Ptbp2_E18_5_cortex_CLIP_mm9_plus_strand_sorted_BDB", "-w", "200", "-s", "50", "-o", "J:\\VishalData"
    };*/
    Options options = new Options();

    // add t option
    options.addOption("i", "index", false, "Indexing BED files.");
    options.addOption("b", "bed", true, "bed file to be indexed");
    options.addOption("o", "output", true, "Folder that the index/comparison file will be created.");
    options.addOption("r", "reference", true, "Reference annotation file to be used for indexing");
    options.addOption("c", "compare", false, "Finding differences between two conditions");
    options.addOption("1", "first", true, "First sample index location");
    options.addOption("2", "second", true, "Second sample index location");
    options.addOption("w", "window", true, "Length of window for identifying differences");
    options.addOption("s", "sliding", true, "Length of sliding");

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

    boolean indexing = false;
    boolean comparing = false;

    //Indexing!
    if (cmd.hasOption("i")) {
        //if(cmd.hasOption("1"))
        //System.err.println("sasan");

        //System.out.println("sasa");
        indexing = true;

    } else if (cmd.hasOption("c")) {
        //System.err.println("");
        comparing = true;

    } else {
        //System.err.println("Option is not deteced.");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("diffhunter", options);
        return;
    }

    //Indexing is selected
    //
    if (indexing == true) {
        //Since indexing is true.
        //User have to provide file for indexing.
        if (!(cmd.hasOption("o") || cmd.hasOption("r") || cmd.hasOption("b"))) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("diffhunter", options);
            return;
        }
        String bedfile_ = cmd.getOptionValue("b");
        String reference_file = cmd.getOptionValue("r");
        String folder_loc = cmd.getOptionValue("o");

        String sample_name = FilenameUtils.getBaseName(bedfile_);

        try (Database B2 = BerkeleyDB_Box.Get_BerkeleyDB(
                Paths.get(folder_loc, sample_name + "_BDB").toAbsolutePath().toString(), true, sample_name)) {
            Indexer indexing_ = new Indexer(reference_file);
            indexing_.Make_Index(B2, bedfile_,
                    Paths.get(folder_loc, sample_name + "_BDB").toAbsolutePath().toString());
            B2.close();

        }
    } else if (comparing == true) {
        if (!(cmd.hasOption("o") || cmd.hasOption("w") || cmd.hasOption("s") || cmd.hasOption("1")
                || cmd.hasOption("2"))) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("diffhunter", options);
            return;
        }
        String folder_loc = cmd.getOptionValue("o");
        int window_ = Integer.parseInt(cmd.getOptionValue("w"));
        //int window_=600;

        int slide_ = Integer.parseInt(cmd.getOptionValue("s"));

        String first = cmd.getOptionValue("1").replace("_BDB", "");
        String second = cmd.getOptionValue("2").replace("_BDB", "");
        String reference_file = cmd.getOptionValue("r");
        //String folder_loc=cmd.getOptionValue("o");

        String sample_name_first = FilenameUtils.getBaseName(first);
        String sample_name_second = FilenameUtils.getBaseName(second);

        Database B1 = BerkeleyDB_Box.Get_BerkeleyDB(first + "_BDB", false, sample_name_first);
        Database B2 = BerkeleyDB_Box.Get_BerkeleyDB(second + "_BDB", false, sample_name_second);

        List<String> first_condition_genes = Files
                .lines(Paths.get(first + "_BDB", sample_name_first + ".txt").toAbsolutePath())
                .collect(Collectors.toList());
        List<String> second_condition_genes = Files
                .lines(Paths.get(second + "_BDB", sample_name_second + ".txt").toAbsolutePath())
                .collect(Collectors.toList());
        System.out.println("First and second condition are loaded!!! ");
        List<String> intersection_ = new ArrayList<>(first_condition_genes);
        intersection_.retainAll(second_condition_genes);

        BufferedWriter output = new BufferedWriter(
                new FileWriter(Paths.get(folder_loc, "differences_" + window_ + "_s" + slide_ + "_c" + ".txt")
                        .toAbsolutePath().toString(), false));
        List<Result_Window> final_results = Collections.synchronizedList(new ArrayList<>());
        Worker_New worker_class = new Worker_New();
        worker_class.Read_Reference(reference_file);

        while (!intersection_.isEmpty()) {
            List<String> selected_genes = new ArrayList<>();
            //if (intersection_.size()<=10000){selected_genes.addAll(intersection_.subList(0, intersection_.size()));}
            //else selected_genes.addAll(intersection_.subList(0, 10000));
            if (intersection_.size() <= intersection_.size()) {
                selected_genes.addAll(intersection_.subList(0, intersection_.size()));
            } else {
                selected_genes.addAll(intersection_.subList(0, intersection_.size()));
            }
            intersection_.removeAll(selected_genes);
            //System.out.println("Intersection count is:"+intersection_.size());
            //final List<Result_Window> resultssss_=new ArrayList<>();
            IntStream.range(0, selected_genes.size()).parallel().forEach(i -> {
                System.out.println(selected_genes.get(i) + "\tprocessing......");
                String gene_of_interest = selected_genes.get(i);//"ENSG00000142657|PGD";//intersection_.get(6);////"ENSG00000163395|IGFN1";//"ENSG00000270066|SCARNA2";
                int start = worker_class.dic_genes.get(gene_of_interest).start_loc;
                int end = worker_class.dic_genes.get(gene_of_interest).end_loc;

                Map<Integer, Integer> first_ = Collections.EMPTY_MAP;
                try {
                    first_ = BerkeleyDB_Box.Get_Coord_Read(B1, gene_of_interest);
                } catch (IOException | ClassNotFoundException ex) {
                    Logger.getLogger(DiffHunter.class.getName()).log(Level.SEVERE, null, ex);
                }

                Map<Integer, Integer> second_ = Collections.EMPTY_MAP;
                try {
                    second_ = BerkeleyDB_Box.Get_Coord_Read(B2, gene_of_interest);
                } catch (IOException | ClassNotFoundException ex) {
                    Logger.getLogger(DiffHunter.class.getName()).log(Level.SEVERE, null, ex);
                }
                List<Window> top_windows_first = worker_class.Get_Top_Windows(window_, first_, slide_);
                List<Window> top_windows_second = worker_class.Get_Top_Windows(window_, second_, slide_);
                //System.out.println("passed for window peak call for gene \t"+selected_genes.get(i));
                // System.out.println("top_window_first_Count\t"+top_windows_first.size());
                // System.out.println("top_window_second_Count\t"+top_windows_second.size());
                if (top_windows_first.isEmpty() && top_windows_second.isEmpty()) {
                    return;
                }

                List<Result_Window> res_temp = new Worker_New().Get_Significant_Windows(gene_of_interest, start,
                        end, top_windows_first, top_windows_second, second_, first_, sample_name_first,
                        sample_name_second, 0.01);
                if (!res_temp.isEmpty()) {
                    final_results.addAll(res_temp);//final_results.addAll(worker_class.Get_Significant_Windows(gene_of_interest, start, end, top_windows_first, top_windows_second, second_, first_, first_condition, second_condition, 0.01));

                } //System.out.println(selected_genes.get(i)+"\tprocessed.");

            });

            /*selected_genes.parallelStream().forEach(i ->
             {
                    
                    
             });*/
            List<Double> pvals = new ArrayList<>();

            for (int i = 0; i < final_results.size(); i++) {
                pvals.add(final_results.get(i).p_value);
            }
            List<Double> qvals = MultipleTestCorrection.benjaminiHochberg(pvals);

            System.out.println("Writing to file...");
            output.append("Gene_Symbol\tContributing_Sample\tStart\tEnd\tOddsRatio\tp_Value\tFDR");
            output.newLine();

            for (int i = 0; i < final_results.size(); i++) {
                Result_Window item = final_results.get(i);
                output.append(item.associated_gene_symbol + "\t" + item.contributing_windows + "\t"
                        + item.start_loc + "\t" + item.end_loc + "\t" + item.oddsratio_ + "\t" + item.p_value
                        + "\t" + qvals.get(i)); //+ "\t" + item.average_other_readcount_cotributing + "\t" + item.average_other_readcount_cotributing + "\t" + item.average_window_readcount_non + "\t" + item.average_other_readcount_non);
                output.newLine();
            }

            /* for (Result_Window item : final_results)
             {
            output.append(item.associated_gene_symbol + "\t" + item.contributing_windows + "\t" + item.start_loc + "\t" + item.end_loc + "\t" + item.oddsratio_ + "\t" + item.p_value); //+ "\t" + item.average_other_readcount_cotributing + "\t" + item.average_other_readcount_cotributing + "\t" + item.average_window_readcount_non + "\t" + item.average_other_readcount_non);
            output.newLine();
             }
               */
            final_results.clear();

        }
        output.close();

    }
    System.out.println("Done.");

}

From source file:io.amient.kafka.metrics.DiscoveryTool.java

public static void main(String[] args) throws IOException {

    OptionParser parser = new OptionParser();

    parser.accepts("help", "Print usage help");
    OptionSpec<String> zookeeper = parser.accepts("zookeeper", "Address of the seed zookeeper server")
            .withRequiredArg().required();
    OptionSpec<String> dashboard = parser
            .accepts("dashboard", "Grafana dashboard name to be used in all generated configs")
            .withRequiredArg().required();
    OptionSpec<String> dashboardPath = parser
            .accepts("dashboard-path", "Grafana location, i.e. `./instance/.data/grafana/dashboards`")
            .withRequiredArg();//from   w w  w .  j av a 2  s.  c  om
    OptionSpec<String> topic = parser.accepts("topic", "Name of the metrics topic to consume measurements from")
            .withRequiredArg();
    OptionSpec<String> influxdb = parser
            .accepts("influxdb", "InfluxDB connect URL (including user and password)").withRequiredArg();
    OptionSpec<String> interval = parser.accepts("interval", "JMX scanning interval in seconds")
            .withRequiredArg().defaultsTo("10");
    //TODO --influxdb-database (DEFAULT_DATABASE)
    //TODO --dashboard-datasource (DEFAULT_DATASOURCE)

    if (args.length == 0 || args[0] == "-h" || args[0] == "--help") {
        parser.printHelpOn(System.err);
        System.exit(0);
    }

    OptionSet opts = parser.parse(args);

    try {

        DiscoveryTool tool = new DiscoveryTool(opts.valueOf(zookeeper));

        try {
            List<String> topics = tool.getKafkaTopics();
            List<Broker> brokers = tool.getKafkaBrokers();
            int interval_s = Integer.parseInt(opts.valueOf(interval));

            if (opts.has(dashboard) && opts.has(dashboardPath)) {
                tool.generateDashboard(opts.valueOf(dashboard), brokers, topics, DEFAULT_DATASOURCE,
                        opts.valueOf(dashboardPath), interval_s).save();
            }

            if (opts.has(topic)) {
                //producer/reporter settings
                System.out.println("kafka.metrics.topic=" + opts.valueOf(topic));
                System.out.println("kafka.metrics.polling.interval=" + interval_s + "s");
                //TODO --producer-bootstrap for truly non-intrusive agent deployment,
                // i.e. when producing to a different cluster from the one being discovered
                System.out.println("kafka.metrics.bootstrap.servers=" + brokers.get(0).hostPort());
                //consumer settings
                System.out.println("consumer.topic=" + opts.valueOf(topic));
                System.out.println("consumer.zookeeper.connect=" + opts.valueOf(zookeeper));
                System.out.println("consumer.group.id=kafka-metrics-" + opts.valueOf(dashboard));
            }

            if (!opts.has(influxdb) || !opts.has(topic)) {
                tool.generateScannerConfig(brokers, opts.valueOf(dashboard), interval_s).list(System.out);
            }

            if (opts.has(influxdb)) {
                URL url = new URL(opts.valueOf(influxdb));
                System.out.println("influxdb.database=" + DEFAULT_DATABASE);
                System.out.println("influxdb.url=" + url.toString());
                if (url.getUserInfo() != null) {
                    System.out.println("influxdb.username=" + url.getUserInfo().split(":")[0]);
                    if (url.getUserInfo().contains(":")) {
                        System.out.println("influxdb.password=" + url.getUserInfo().split(":")[1]);
                    }
                }
            }

            System.out.flush();
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(3);
        } finally {
            tool.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(2);
    }

}

From source file:daemon.dicomnode.DcmRcv.java

@SuppressWarnings("unchecked")
public static void main(String[] args) {
    CommandLine cl = parse(args);/* w  w  w  .  j  av a2s.c  om*/
    DcmRcv dcmrcv = new DcmRcv(cl.hasOption("device") ? cl.getOptionValue("device") : "DCMRCV");
    final List<String> argList = cl.getArgList();
    String port = argList.get(0);
    String[] aetPort = split(port, ':', 1);
    dcmrcv.setPort(parseInt(aetPort[1], "illegal port number", 1, 0xffff));
    if (aetPort[0] != null) {
        String[] aetHost = split(aetPort[0], '@', 0);
        dcmrcv.setAEtitle(aetHost[0]);
        if (aetHost[1] != null) {
            dcmrcv.setHostname(aetHost[1]);
        }
    }

    if (cl.hasOption("dest"))
        dcmrcv.setDestination(cl.getOptionValue("dest"));
    if (cl.hasOption("calling2dir"))
        dcmrcv.setCalling2Dir(loadProperties(cl.getOptionValue("calling2dir")));
    if (cl.hasOption("called2dir"))
        dcmrcv.setCalled2Dir(loadProperties(cl.getOptionValue("called2dir")));
    if (cl.hasOption("callingdefdir"))
        dcmrcv.setCallingDefDir(cl.getOptionValue("callingdefdir"));
    if (cl.hasOption("calleddefdir"))
        dcmrcv.setCalledDefDir(cl.getOptionValue("calleddefdir"));
    if (cl.hasOption("journal"))
        dcmrcv.setJournal(cl.getOptionValue("journal"));
    if (cl.hasOption("journalfilepath"))
        dcmrcv.setJournalFilePathFormat(cl.getOptionValue("journalfilepath"));

    if (cl.hasOption("defts"))
        dcmrcv.setTransferSyntax(ONLY_DEF_TS);
    else if (cl.hasOption("native"))
        dcmrcv.setTransferSyntax(cl.hasOption("bigendian") ? NATIVE_TS : NATIVE_LE_TS);
    else if (cl.hasOption("bigendian"))
        dcmrcv.setTransferSyntax(NON_RETIRED_TS);
    if (cl.hasOption("scretraets"))
        dcmrcv.setStgCmtRetrieveAETs(cl.getOptionValue("scretraets"));
    if (cl.hasOption("scretraet"))
        dcmrcv.setStgCmtRetrieveAET(cl.getOptionValue("scretraet"));
    dcmrcv.setStgCmtReuseFrom(cl.hasOption("screusefrom"));
    dcmrcv.setStgCmtReuseTo(cl.hasOption("screuseto"));
    if (cl.hasOption("scport")) {
        dcmrcv.setStgCmtPort(parseInt(cl.getOptionValue("scport"), "illegal port number", 1, 0xffff));
    }
    if (cl.hasOption("scdelay"))
        dcmrcv.setStgCmtDelay(parseInt(cl.getOptionValue("scdelay"), "illegal argument of option -scdelay", 0,
                Integer.MAX_VALUE));
    if (cl.hasOption("scretry"))
        dcmrcv.setStgCmtRetry(parseInt(cl.getOptionValue("scretry"), "illegal argument of option -scretry", 0,
                Integer.MAX_VALUE));
    if (cl.hasOption("scretryperiod"))
        dcmrcv.setStgCmtRetryPeriod(parseInt(cl.getOptionValue("scretryperiod"),
                "illegal argument of option -scretryperiod", 1000, Integer.MAX_VALUE));
    if (cl.hasOption("connectTO"))
        dcmrcv.setConnectTimeout(parseInt(cl.getOptionValue("connectTO"),
                "illegal argument of option -connectTO", 1, Integer.MAX_VALUE));
    if (cl.hasOption("reaper"))
        dcmrcv.setAssociationReaperPeriod(parseInt(cl.getOptionValue("reaper"),
                "illegal argument of option -reaper", 1, Integer.MAX_VALUE));
    if (cl.hasOption("rspTO"))
        dcmrcv.setDimseRspTimeout(parseInt(cl.getOptionValue("rspTO"), "illegal argument of option -rspTO", 1,
                Integer.MAX_VALUE));
    if (cl.hasOption("acceptTO"))
        dcmrcv.setAcceptTimeout(parseInt(cl.getOptionValue("acceptTO"), "illegal argument of option -acceptTO",
                1, Integer.MAX_VALUE));
    if (cl.hasOption("idleTO"))
        dcmrcv.setIdleTimeout(parseInt(cl.getOptionValue("idleTO"), "illegal argument of option -idleTO", 1,
                Integer.MAX_VALUE));
    if (cl.hasOption("requestTO"))
        dcmrcv.setRequestTimeout(parseInt(cl.getOptionValue("requestTO"),
                "illegal argument of option -requestTO", 1, Integer.MAX_VALUE));
    if (cl.hasOption("releaseTO"))
        dcmrcv.setReleaseTimeout(parseInt(cl.getOptionValue("releaseTO"),
                "illegal argument of option -releaseTO", 1, Integer.MAX_VALUE));
    if (cl.hasOption("soclosedelay"))
        dcmrcv.setSocketCloseDelay(parseInt(cl.getOptionValue("soclosedelay"),
                "illegal argument of option -soclosedelay", 1, 10000));
    if (cl.hasOption("rspdelay"))
        dcmrcv.setDimseRspDelay(
                parseInt(cl.getOptionValue("rspdelay"), "illegal argument of option -rspdelay", 0, 10000));
    if (cl.hasOption("rcvpdulen"))
        dcmrcv.setMaxPDULengthReceive(
                parseInt(cl.getOptionValue("rcvpdulen"), "illegal argument of option -rcvpdulen", 1, 10000)
                        * KB);
    if (cl.hasOption("sndpdulen"))
        dcmrcv.setMaxPDULengthSend(
                parseInt(cl.getOptionValue("sndpdulen"), "illegal argument of option -sndpdulen", 1, 10000)
                        * KB);
    if (cl.hasOption("sosndbuf"))
        dcmrcv.setSendBufferSize(
                parseInt(cl.getOptionValue("sosndbuf"), "illegal argument of option -sosndbuf", 1, 10000) * KB);
    if (cl.hasOption("sorcvbuf"))
        dcmrcv.setReceiveBufferSize(
                parseInt(cl.getOptionValue("sorcvbuf"), "illegal argument of option -sorcvbuf", 1, 10000) * KB);
    if (cl.hasOption("bufsize"))
        dcmrcv.setFileBufferSize(
                parseInt(cl.getOptionValue("bufsize"), "illegal argument of option -bufsize", 1, 10000) * KB);

    dcmrcv.setPackPDV(!cl.hasOption("pdv1"));
    dcmrcv.setTcpNoDelay(!cl.hasOption("tcpdelay"));
    if (cl.hasOption("async"))
        dcmrcv.setMaxOpsPerformed(
                parseInt(cl.getOptionValue("async"), "illegal argument of option -async", 0, 0xffff));
    dcmrcv.initTransferCapability();
    if (cl.hasOption("tls")) {
        String cipher = cl.getOptionValue("tls");
        if ("NULL".equalsIgnoreCase(cipher)) {
            dcmrcv.setTlsWithoutEncyrption();
        } else if ("3DES".equalsIgnoreCase(cipher)) {
            dcmrcv.setTls3DES_EDE_CBC();
        } else if ("AES".equalsIgnoreCase(cipher)) {
            dcmrcv.setTlsAES_128_CBC();
        } else {
            exit("Invalid parameter for option -tls: " + cipher);
        }
        if (cl.hasOption("tls1")) {
            dcmrcv.setTlsProtocol(TLS1);
        } else if (cl.hasOption("ssl3")) {
            dcmrcv.setTlsProtocol(SSL3);
        } else if (cl.hasOption("no_tls1")) {
            dcmrcv.setTlsProtocol(NO_TLS1);
        } else if (cl.hasOption("no_ssl3")) {
            dcmrcv.setTlsProtocol(NO_SSL3);
        } else if (cl.hasOption("no_ssl2")) {
            dcmrcv.setTlsProtocol(NO_SSL2);
        }
        dcmrcv.setTlsNeedClientAuth(!cl.hasOption("noclientauth"));

        if (cl.hasOption("keystore")) {
            dcmrcv.setKeyStoreURL(cl.getOptionValue("keystore"));
        }
        if (cl.hasOption("keystorepw")) {
            dcmrcv.setKeyStorePassword(cl.getOptionValue("keystorepw"));
        }
        if (cl.hasOption("keypw")) {
            dcmrcv.setKeyPassword(cl.getOptionValue("keypw"));
        }
        if (cl.hasOption("truststore")) {
            dcmrcv.setTrustStoreURL(cl.getOptionValue("truststore"));
        }
        if (cl.hasOption("truststorepw")) {
            dcmrcv.setTrustStorePassword(cl.getOptionValue("truststorepw"));
        }
        try {
            dcmrcv.initTLS();
        } catch (Exception e) {
            System.err.println("ERROR: Failed to initialize TLS context:" + e.getMessage());
            System.exit(2);
        }
    }
    try {
        dcmrcv.start();
    } catch (IOException e) {
        e.printStackTrace();
    }
}