Example usage for java.io File exists

List of usage examples for java.io File exists

Introduction

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

Prototype

public boolean exists() 

Source Link

Document

Tests whether the file or directory denoted by this abstract pathname exists.

Usage

From source file:edu.ucsd.crbs.cws.App.java

License:asdf

public static void main(String[] args) {
    Job.REFS_ENABLED = false;/*from  w  w  w  .j  a  v a 2  s. c  o m*/
    Workflow.REFS_ENABLED = false;
    try {

        OptionParser parser = new OptionParser() {
            {
                accepts(UPLOAD_WF_ARG, "Add/Update Workflow").withRequiredArg().ofType(File.class)
                        .describedAs("Kepler .kar file");
                //accepts(LOAD_TEST,"creates lots of workflows and jobs");
                accepts(SYNC_WITH_CLUSTER_ARG,
                        "Submits & Synchronizes Workflow Jobs on local cluster with CRBS Workflow Webservice.  Requires --"
                                + PROJECT_ARG + " --" + PORTALNAME_ARG + " --" + PORTAL_URL_ARG + " --"
                                + HELP_EMAIL_ARG).withRequiredArg().ofType(String.class).describedAs("URL");
                accepts(GEN_OLD_KEPLER_XML_ARG, "Generates version 1.x kepler xml for given workflow")
                        .withRequiredArg().ofType(String.class).describedAs("wfid or .kar file");
                accepts(UPLOAD_FILE_ARG, "Registers and uploads Workspace file to REST service")
                        .withRequiredArg().ofType(File.class);
                accepts(REGISTER_FILE_ARG,
                        "Registers Workspace file to REST service (DOES NOT UPLOAD FILE TO REST SERVICE)")
                                .withRequiredArg().ofType(File.class);
                accepts(GET_WORKSPACE_FILE_INFO_ARG, "Outputs JSON of specified workspace file(s)")
                        .withRequiredArg().ofType(String.class).describedAs("workspace file id");
                accepts(GET_WORKFLOW_ARG, "Outputs JSON of specified Workflow").withRequiredArg()
                        .ofType(Long.class).describedAs("Workflow Id");
                accepts(DOWNLOAD_FILE_ARG, "Downloads Workspace file").withRequiredArg().ofType(String.class)
                        .describedAs("workspace file id");
                accepts(UPDATE_PATH_ARG, "Updates Workspace file path").withRequiredArg().ofType(String.class)
                        .describedAs("workspace file id");
                accepts(PATH_ARG,
                        "Sets WorkspaceFile file path.  Used in coordination with --" + UPDATE_PATH_ARG)
                                .withRequiredArg().ofType(String.class).describedAs("file path");
                accepts(URL_ARG,
                        "URL to use with --" + UPLOAD_WF_ARG + ", --" + UPLOAD_FILE_ARG + ", --"
                                + GET_WORKSPACE_FILE_INFO_ARG + " flags").withRequiredArg().ofType(String.class)
                                        .describedAs("URL");
                accepts(EXAMPLE_JSON_ARG,
                        "Outputs example JSON of Job, User, Workflow, and WorkspaceFile objects");
                accepts(WF_EXEC_DIR_ARG, "Workflow Execution Directory").withRequiredArg().ofType(File.class)
                        .describedAs("Directory");
                accepts(WF_DIR_ARG, "Workflows Directory").withRequiredArg().ofType(File.class)
                        .describedAs("Directory");
                accepts(KEPLER_SCRIPT_ARG, "Kepler").withRequiredArg().ofType(File.class).describedAs("Script");
                accepts(QUEUE_ARG, "SGE Queue").withRequiredArg().ofType(String.class).describedAs("Queue");
                accepts(CAST_ARG, "Panfishcast binary").withRequiredArg().ofType(File.class)
                        .describedAs("panfishcast");
                accepts(STAT_ARG, "Panfishstat binary").withRequiredArg().ofType(File.class)
                        .describedAs("panfishstat");
                accepts(LOGIN_ARG, "User Login").withRequiredArg().ofType(String.class).describedAs("username");
                accepts(TOKEN_ARG, "User Token").withRequiredArg().ofType(String.class).describedAs("token");
                accepts(RUN_AS_ARG, "User to run as (for power accounts that can run as other users)")
                        .withRequiredArg().ofType(String.class).describedAs("runas");
                accepts(OWNER_ARG, "Sets owner when creating Workspace file and Workflow").withRequiredArg()
                        .ofType(String.class).describedAs("username");
                accepts(JOB_ID_ARG, "Sets source job id for Workspace file when used with --" + UPLOAD_FILE_ARG
                        + " and --" + REGISTER_FILE_ARG).withRequiredArg().ofType(Long.class)
                                .describedAs("Job Id");
                accepts(MD5_ARG,
                        "Sets md5 for Workspace file when used with --" + UPLOAD_FILE_ARG + " and --"
                                + REGISTER_FILE_ARG).withRequiredArg().ofType(String.class)
                                        .describedAs("MD5 message digest");
                accepts(SIZE_ARG,
                        "Sets size in bytes for Workspace file when used with --" + UPLOAD_FILE_ARG + " and --"
                                + REGISTER_FILE_ARG).withRequiredArg().ofType(Long.class)
                                        .describedAs("Size of file/dir in bytes");
                accepts(RESAVE_WORKSPACEFILE_ARG, "Resaves Workspace file").withRequiredArg().ofType(Long.class)
                        .describedAs("WorkspaceFile Id or -1 to resave all");
                accepts(RESAVE_JOB_ARG, "Resaves Job").withRequiredArg().ofType(Long.class)
                        .describedAs("Job Id or -1 to resave all");
                accepts(RESAVE_WORKFLOW_ARG, "Resaves Workflow").withRequiredArg().ofType(Long.class)
                        .describedAs("Workflow Id or -1 to resave all");
                accepts(PREVIEW_WORKFLOW_ARG,
                        "Preview Workflow on Web, requires --" + URL_ARG
                                + " currently it should be: http://imafish.dynamic.ucsd.edu/cws/makepreview")
                                        .withRequiredArg().ofType(File.class).describedAs("Kepler .kar file");
                accepts(DESCRIPTION_ARG, "Description for WorkspaceFile").withRequiredArg()
                        .ofType(String.class);
                accepts(TYPE_ARG, "Type of WorkspaceFile").withRequiredArg().ofType(String.class);
                accepts(NAME_ARG,
                        "Sets name for Workspace file when used with --" + UPLOAD_FILE_ARG + " and --"
                                + REGISTER_FILE_ARG).withRequiredArg().ofType(String.class)
                                        .describedAs("WorkspaceFile name");
                accepts(REGISTER_JAR_ARG, "Path to Jar to register WorkspaceFiles").withRequiredArg()
                        .ofType(File.class).describedAs("Path to this jar");
                accepts(GET_JOB_ARG, "Gets job from service in JSON format, requires --" + URL_ARG)
                        .withRequiredArg().ofType(Long.class).describedAs("Job Id");
                accepts(GET_WORKSPACE_FILE_ARG,
                        "Gets WorkspaceFile from service in JSON format, requires --" + URL_ARG)
                                .withRequiredArg().ofType(Long.class)
                                .describedAs("WorkspaceFile Id or -1 for all");
                accepts(PROJECT_ARG, "Project name ie CRBS.  Used with --" + SYNC_WITH_CLUSTER_ARG)
                        .withRequiredArg().ofType(String.class);
                accepts(PORTALNAME_ARG, "Portal name ie SLASH portal Used with --" + SYNC_WITH_CLUSTER_ARG)
                        .withRequiredArg().ofType(String.class);
                accepts(PORTAL_URL_ARG,
                        "Portal url ie http://slashsegmentation.com Used with --" + SYNC_WITH_CLUSTER_ARG)
                                .withRequiredArg().ofType(String.class);
                accepts(HELP_EMAIL_ARG, "Help and reply to email address Used with --" + SYNC_WITH_CLUSTER_ARG)
                        .withRequiredArg().ofType(String.class);
                accepts(BCC_EMAIL_ARG, "Blind Carbon copy email address Used with --" + SYNC_WITH_CLUSTER_ARG)
                        .withRequiredArg().ofType(String.class);
                accepts(WORKSPACE_FILE_FAILED_ARG,
                        "Denotes whether workspacefile failed (true) or not (false).  Used with --"
                                + UPDATE_PATH_ARG).withRequiredArg().ofType(Boolean.class)
                                        .describedAs("false = success and true = failed");
                accepts(ERROR_EMAIL_ARG,
                        "Email to receive notifications if errors are encountered.  Used with --"
                                + SYNC_WITH_CLUSTER_ARG).withRequiredArg().ofType(String.class);
                accepts(HELP_ARG).forHelp();
            }
        };

        OptionSet optionSet = null;
        try {
            optionSet = parser.parse(args);
        } catch (OptionException oe) {
            System.err.println("\nThere was an error parsing arguments: " + oe.getMessage() + "\n\n");
            parser.printHelpOn(System.err);
            System.exit(1);
        }

        if (optionSet.has(HELP_ARG) || (!optionSet.has(SYNC_WITH_CLUSTER_ARG) && !optionSet.has(UPLOAD_WF_ARG))
                && !optionSet.has(EXAMPLE_JSON_ARG) && !optionSet.has(UPLOAD_FILE_ARG)
                && !optionSet.has(GET_WORKSPACE_FILE_INFO_ARG) && !optionSet.has(UPDATE_PATH_ARG)
                && !optionSet.has(REGISTER_FILE_ARG) && !optionSet.has(RESAVE_WORKSPACEFILE_ARG)
                && !optionSet.has(RESAVE_JOB_ARG) && !optionSet.has(RESAVE_WORKFLOW_ARG)
                && !optionSet.has(PREVIEW_WORKFLOW_ARG) && !optionSet.has(GEN_OLD_KEPLER_XML_ARG)
                && !optionSet.has(GET_JOB_ARG) && !optionSet.has(GET_WORKSPACE_FILE_ARG)
                && !optionSet.has(GET_WORKFLOW_ARG)) {
            System.out.println(PROGRAM_HELP + "\n");
            parser.printHelpOn(System.out);
            System.exit(0);
        }

        if (optionSet.has(EXAMPLE_JSON_ARG)) {

            renderExampleWorkflowsAndTasksAsJson();
            System.exit(0);
        }

        if (optionSet.has(GET_JOB_ARG)) {
            failIfOptionSetMissingURLOrLoginOrToken(optionSet, "--" + GET_JOB_ARG + " flag");
            getJobAsJson(optionSet);
            System.exit(0);
        }
        if (optionSet.has(GET_WORKSPACE_FILE_ARG)) {
            failIfOptionSetMissingURLOrLoginOrToken(optionSet, "--" + GET_WORKSPACE_FILE_ARG + " flag");
            getWorkspaceFileAsJson(optionSet);
            System.exit(0);
        }
        if (optionSet.has(GET_WORKFLOW_ARG)) {
            failIfOptionSetMissingURLOrLoginOrToken(optionSet, "--" + GET_WORKFLOW_ARG + " flag");
            getWorkflowAsJson(optionSet);
            System.exit(0);
        }

        MultivaluedMapFactory multivaluedMapFactory = new MultivaluedMapFactoryImpl();

        if (optionSet.has(GEN_OLD_KEPLER_XML_ARG)) {
            String workflowFileOrId = (String) optionSet.valueOf(GEN_OLD_KEPLER_XML_ARG);
            File workflowFile = new File(workflowFileOrId);
            Workflow w = null;

            //if value is a file attempt to load it as a workflow file
            if (workflowFile.exists() && workflowFile.isFile()) {
                w = getWorkflowFromFile(workflowFile);
                if (w == null) {
                    throw new Exception("Unable to extract workflow from file: " + workflowFile);
                }
            } else {
                //assume the value is a workflow id and get it from the service
                //but fail if url is missing
                failIfOptionSetMissingURLOrLoginOrToken(optionSet, "--" + GEN_OLD_KEPLER_XML_ARG + " flag");
                User u = getUserFromOptionSet(optionSet);
                WorkflowRestDAOImpl workflowDAO = new WorkflowRestDAOImpl();
                workflowDAO.setRestURL((String) optionSet.valueOf(URL_ARG));
                workflowDAO.setUser(u);
                w = workflowDAO.getWorkflowById(workflowFileOrId, u);
                if (w == null) {
                    throw new Exception("Unable to extract workflow from id: " + workflowFileOrId);
                }
            }

            VersionOneWorkflowXmlWriter xmlWriter = new VersionOneWorkflowXmlWriter();
            StringWriter sw = new StringWriter();
            xmlWriter.write(sw, w);
            System.out.println(sw.toString());
            System.exit(0);

        }

        if (optionSet.has(PREVIEW_WORKFLOW_ARG)) {
            failIfOptionSetMissingURL(optionSet, "--" + PREVIEW_WORKFLOW_ARG + " flag");

            File workflowFile = (File) optionSet.valueOf(PREVIEW_WORKFLOW_ARG);
            Workflow w = getWorkflowFromFile(workflowFile);
            if (w == null) {
                throw new Exception("Unable to extract workflow from file");
            }
            uploadPreviewWorkflowFile((String) optionSet.valueOf(URL_ARG), w);
            System.exit(0);
        }

        if (optionSet.has(REGISTER_FILE_ARG)) {
            addNewWorkspaceFile(optionSet, false, REGISTER_FILE_ARG);
            System.exit(0);
        }

        if (optionSet.has(RESAVE_WORKSPACEFILE_ARG)) {
            failIfOptionSetMissingURLOrLoginOrToken(optionSet, "--" + RESAVE_WORKSPACEFILE_ARG + " flag");
            WorkspaceFileRestDAOImpl workspaceFileDAO = new WorkspaceFileRestDAOImpl();
            User u = getUserFromOptionSet(optionSet);
            workspaceFileDAO.setUser(u);
            workspaceFileDAO.setRestURL((String) optionSet.valueOf(URL_ARG));
            Long workspaceId = (Long) optionSet.valueOf(RESAVE_WORKSPACEFILE_ARG);
            if (workspaceId == -1) {
                System.out.println("Resaving all workspace files");
                List<WorkspaceFile> wsfList = workspaceFileDAO.getWorkspaceFiles(null, null, null, null, null);
                if (wsfList != null) {
                    System.out.println("Found " + wsfList.size() + " workspace files to resave");
                    for (WorkspaceFile wsf : wsfList) {
                        System.out.println("WorkspaceFile Id: " + wsf.getId());
                        workspaceFileDAO.resave(wsf.getId());
                    }
                }
            } else {
                workspaceFileDAO.resave(workspaceId);
            }
            System.exit(0);
        }

        if (optionSet.has(RESAVE_JOB_ARG)) {
            failIfOptionSetMissingURLOrLoginOrToken(optionSet, "--" + RESAVE_JOB_ARG + " flag");
            JobRestDAOImpl jobDAO = new JobRestDAOImpl();
            User u = getUserFromOptionSet(optionSet);
            jobDAO.setUser(u);
            jobDAO.setRestURL((String) optionSet.valueOf(URL_ARG));
            Long jobId = (Long) optionSet.valueOf(RESAVE_JOB_ARG);
            if (jobId == -1) {
                System.out.println("Resaving all jobs");
                List<Job> jobList = jobDAO.getJobs(null, null, null, true, true, Boolean.TRUE);
                if (jobList != null) {
                    System.out.println("Found " + jobList.size() + " jobs to resave");
                    for (Job j : jobList) {
                        System.out.println("job id: " + j.getId());
                        jobDAO.resave(j.getId());
                    }
                }
            } else {
                jobDAO.resave(jobId);
            }
            System.exit(0);
        }

        if (optionSet.has(RESAVE_WORKFLOW_ARG)) {
            failIfOptionSetMissingURLOrLoginOrToken(optionSet, "--" + RESAVE_WORKFLOW_ARG + " flag");
            WorkflowRestDAOImpl workflowDAO = new WorkflowRestDAOImpl();
            User u = getUserFromOptionSet(optionSet);
            workflowDAO.setUser(u);
            workflowDAO.setRestURL((String) optionSet.valueOf(URL_ARG));
            Long workflowId = (Long) optionSet.valueOf(RESAVE_WORKFLOW_ARG);
            if (workflowId == -1) {
                System.out.println("Resaving all workflows");
                List<Workflow> workflowList = workflowDAO.getAllWorkflows(true, Boolean.TRUE);

                if (workflowList != null) {
                    System.out.println("Found " + workflowList.size() + " workflow(s) to resave");
                    for (Workflow w : workflowList) {
                        System.out.println("workflow id: " + w.getId());
                        workflowDAO.resave(w.getId());
                    }
                }
            } else {
                workflowDAO.resave(workflowId);
            }
            System.exit(0);
        }

        if (optionSet.has(UPDATE_PATH_ARG)) {
            failIfOptionSetMissingURLOrLoginOrToken(optionSet, "--" + UPDATE_PATH_ARG + " flag");

            User u = getUserFromOptionSet(optionSet);
            String workspaceId = (String) optionSet.valueOf(UPDATE_PATH_ARG);
            String path = null;
            if (optionSet.has(PATH_ARG)) {
                path = (String) optionSet.valueOf(PATH_ARG);
            }

            String size = null;
            if (optionSet.has(SIZE_ARG)) {
                size = ((Long) optionSet.valueOf(SIZE_ARG)).toString();
            }

            if (optionSet.has(MD5_ARG)) {
                //wsp.setMd5((String)optionSet.valueOf(MD5_ARG));
            }
            Boolean isFailed = null;

            if (optionSet.has(WORKSPACE_FILE_FAILED_ARG)) {
                isFailed = (Boolean) optionSet.valueOf(WORKSPACE_FILE_FAILED_ARG);
            }

            WorkspaceFileRestDAOImpl workspaceFileDAO = new WorkspaceFileRestDAOImpl();
            workspaceFileDAO.setUser(u);
            workspaceFileDAO.setRestURL((String) optionSet.valueOf(URL_ARG));
            workspaceFileDAO.updatePathSizeAndFailStatus(Long.parseLong(workspaceId), path, size, isFailed);

            System.exit(0);
        }

        if (optionSet.has(SYNC_WITH_CLUSTER_ARG)) {
            // @TODO NEED TO MAKE JOPT DO THIS REQUIRED FLAG CHECKING STUFF
            if (!optionSet.has(WF_EXEC_DIR_ARG)) {
                System.err.println(
                        "-" + WF_EXEC_DIR_ARG + " is required with -" + SYNC_WITH_CLUSTER_ARG + " flag");
                System.exit(2);
            }
            if (!optionSet.has(WF_DIR_ARG)) {
                System.err.println("-" + WF_DIR_ARG + " is required with -" + SYNC_WITH_CLUSTER_ARG + " flag");
                System.exit(3);
            }
            if (!optionSet.has(KEPLER_SCRIPT_ARG)) {
                System.err.println(
                        "-" + KEPLER_SCRIPT_ARG + " is required with -" + SYNC_WITH_CLUSTER_ARG + " flag");
                System.exit(4);
            }

            if (!optionSet.has(CAST_ARG)) {
                System.err.println("-" + CAST_ARG + " is required with -" + SYNC_WITH_CLUSTER_ARG + " flag");
                System.exit(5);
            }

            if (!optionSet.has(STAT_ARG)) {
                System.err.println("-" + STAT_ARG + " is required with -" + SYNC_WITH_CLUSTER_ARG + " flag");
                System.exit(6);
            }

            if (!optionSet.has(QUEUE_ARG)) {
                System.err.println("-" + QUEUE_ARG + " is required with -" + SYNC_WITH_CLUSTER_ARG + " flag");
                System.exit(7);
            }

            if (!optionSet.has(REGISTER_JAR_ARG)) {
                System.err.println(
                        "-" + REGISTER_JAR_ARG + " is required with -" + SYNC_WITH_CLUSTER_ARG + " flag");
                System.exit(8);
            }

            failIfOptionSetMissingLoginOrToken(optionSet, "--" + SYNC_WITH_CLUSTER_ARG + " flag");

            File castFile = (File) optionSet.valueOf(CAST_ARG);
            String castPath = castFile.getAbsolutePath();

            File statFile = (File) optionSet.valueOf(STAT_ARG);
            String statPath = statFile.getAbsolutePath();

            String queue = (String) optionSet.valueOf(QUEUE_ARG);

            File wfExecDir = (File) optionSet.valueOf(WF_EXEC_DIR_ARG);
            File wfDir = (File) optionSet.valueOf(WF_DIR_ARG);
            File keplerScript = (File) optionSet.valueOf(KEPLER_SCRIPT_ARG);

            String registerJar = null;
            if (optionSet.has(REGISTER_JAR_ARG)) {
                File registerJarFile = (File) optionSet.valueOf(REGISTER_JAR_ARG);
                registerJar = registerJarFile.getAbsolutePath();
            }
            JobEmailNotificationData emailNotifyData = getJobEmailNotificationData(optionSet);

            User u = getUserFromOptionSet(optionSet);

            ObjectifyService.ofy();
            String url = (String) optionSet.valueOf(SYNC_WITH_CLUSTER_ARG);
            JobRestDAOImpl jobDAO = new JobRestDAOImpl();
            jobDAO.setRestURL(url);
            jobDAO.setUser(u);

            System.out.println("Running sync with cluster");

            WorkspaceFileRestDAOImpl workspaceFileDAO = new WorkspaceFileRestDAOImpl();
            workspaceFileDAO.setRestURL(url);
            workspaceFileDAO.setUser(u);
            JobPath jobPath = new JobPathImpl(wfExecDir.getAbsolutePath());
            WorkspaceFilePathSetterImpl pathSetter = new WorkspaceFilePathSetterImpl(workspaceFileDAO);

            // Submit jobs to scheduler
            JobSubmissionManager submitter = new JobSubmissionManager(jobDAO, workspaceFileDAO, pathSetter,
                    jobPath, wfDir.getAbsolutePath(), keplerScript.getAbsolutePath(), castPath, queue, u, url,
                    registerJar, emailNotifyData);

            submitter.submitJobs();

            // Update job status for all jobs in system
            MapOfJobStatusFactoryImpl jobStatusFactory = new MapOfJobStatusFactoryImpl(statPath);

            WorkflowFailedParser workflowFailedParser = new WorkflowFailedParserImpl();
            JobStatusUpdater updater = new JobStatusUpdater(jobDAO, jobStatusFactory, workflowFailedParser,
                    jobPath);
            updater.updateJobs();

            System.exit(0);
        }

        if (optionSet.has(App.GET_WORKSPACE_FILE_INFO_ARG)) {
            failIfOptionSetMissingURLOrLoginOrToken(optionSet, "--" + GET_WORKSPACE_FILE_INFO_ARG + " flag");

            WorkspaceFileRestDAOImpl workspaceFileDAO = new WorkspaceFileRestDAOImpl();

            workspaceFileDAO.setRestURL((String) optionSet.valueOf(URL_ARG));

            List<WorkspaceFile> wsFiles = workspaceFileDAO
                    .getWorkspaceFilesById((String) optionSet.valueOf(GET_WORKSPACE_FILE_INFO_ARG), null);

            if (wsFiles != null) {
                ObjectMapper om = new ObjectMapper();
                ObjectWriter ow = om.writerWithDefaultPrettyPrinter();
                System.out.print("[");
                boolean first = true;
                for (WorkspaceFile wsf : wsFiles) {
                    if (first == false) {
                        System.out.println(",");
                    } else {
                        first = false;
                    }
                    System.out.print(ow.writeValueAsString(wsf));
                }
                System.out.println("]");
            } else {
                System.err.println("[]");
            }
            System.exit(0);
        }

        if (optionSet.has(UPLOAD_FILE_ARG)) {
            addNewWorkspaceFile(optionSet, true, UPLOAD_FILE_ARG);
            System.exit(0);
        }

        if (optionSet.has(UPLOAD_WF_ARG)) {

            Long parentWfId = null;

            String postURL = null;
            if (optionSet.has(URL_ARG)) {
                postURL = (String) optionSet.valueOf(URL_ARG);
                failIfOptionSetMissingLoginOrToken(optionSet,
                        "--" + UPLOAD_WF_ARG + " and --" + URL_ARG + " flag");
            }

            File workflowFile = (File) optionSet.valueOf(UPLOAD_WF_ARG);
            Workflow w = getWorkflowFromFile(workflowFile);
            if (w != null) {

                if (optionSet.has(OWNER_ARG)) {
                    w.setOwner((String) optionSet.valueOf(OWNER_ARG));
                }

                ObjectMapper om = new ObjectMapper();
                if (parentWfId != null) {
                    w.setId(parentWfId);
                }
                if (postURL == null) {
                    System.out.println("\n--- JSON Representation of Workflow ---");
                    ObjectWriter ow = om.writerWithDefaultPrettyPrinter();
                    System.out.println(ow.writeValueAsString(w));
                    System.out.flush();
                    System.out.println("---------------------------------------");

                } else {
                    postURL = new StringBuilder().append(postURL).append(Constants.SLASH)
                            .append(Constants.REST_PATH).append(Constants.SLASH)
                            .append(Constants.WORKFLOWS_PATH).toString();

                    ClientConfig cc = new DefaultClientConfig();
                    cc.getClasses().add(StringProvider.class);
                    cc.getClasses().add(MultiPartWriter.class);
                    Client client = Client.create(cc);

                    client.setFollowRedirects(true);
                    WebResource resource = client.resource(postURL);
                    String workflowAsJson = om.writeValueAsString(w);

                    User u = getUserFromOptionSet(optionSet);
                    client.addFilter(new HTTPBasicAuthFilter(u.getLogin(), u.getToken()));
                    MultivaluedMap queryParams = multivaluedMapFactory.getMultivaluedMap(u);

                    String response = resource.queryParams(queryParams).type(MediaType.APPLICATION_JSON_TYPE)
                            .entity(workflowAsJson).post(String.class);
                    Workflow workflowRes = om.readValue(response, Workflow.class);
                    ObjectWriter ow = om.writerWithDefaultPrettyPrinter();

                    if (workflowRes.getWorkflowFileUploadURL() == null) {
                        throw new Exception(
                                "No upload url found for workflow!!!" + ow.writeValueAsString(workflowRes));
                    }

                    uploadWorkflowFile(workflowRes, workflowFile);
                }
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        System.err.println("Caught Exception: " + ex.getMessage());

        System.exit(2);
    }

    System.exit(0);
}

From source file:com.netcrest.pado.tools.pado.PadoShell.java

/**
 * @param args// w  w  w . j  a  v  a  2s .c  o m
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    PadoShell padoShell = new PadoShell(args);
    if (padoShell.isInteractiveMode()) {
        padoShell.initSignals();
        padoShell.go();
    } else {
        padoShell.setShowTime(false);
        if (padoShell.inputCommands != null) {
            StringBuffer buffer = new StringBuffer(padoShell.inputCommands.length * 10);
            for (String value : padoShell.inputCommands) {
                buffer.append(value + " ");
            }
            String parsedCommands[] = buffer.toString().split(";");
            for (String command : parsedCommands) {
                padoShell.runCommand(command, false);
            }
        }
        if (padoShell.scriptFilePath != null) {
            File file = new File(padoShell.scriptFilePath);
            if (file.exists() == false) {
                printlnError(padoShell.scriptFilePath + ": File does not exist.");
                System.exit(-1);
            }
            padoShell.runScript(file);
        }
        padoShell.waitForBackgroundToComplete();
        SharedCache.getSharedCache().disconnect();
        System.exit(0);
    }
}

From source file:br.com.riselabs.cotonet.Main.java

/**
 * @param args//from  ww w .  j a  v  a  2 s .  c  o  m
 * @throws EmptyContentException
 * @throws IOException
 * @throws NullPointerException
 * @throws InvalidNumberOfTagsException
 */
public static void main(String[] args) {

    CommandLineParser parser = new DefaultParser();
    Options options = new Options();

    options.addOption(Option.builder("c").longOpt("chunkBased").desc(
            "c - build a conflict chunk-based network with the developers that in fact conflits with each other."
                    + " Additionally to the c argument the user should provide a path. This path should have"
                    + " a file containig the repository's URL of the target systems.")
            .hasArg().build());

    options.addOption(Option.builder("cf").longOpt("chunkBasedFullGraph")
            .desc("cf - like c, build a conflict chunk-based network adding all developers involved in "
                    + "identified chunk conflicts. Additionally to the cf argument the user should provide a path. "
                    + "This path should have a file containig the repository's URL of the target systems.")
            .hasArg().build());

    options.addOption(Option.builder("f").longOpt("fileBase").desc(
            " f - build a conflict file-based network. In other others all developers that contribute to some"
                    + " conflict at file level should be part of this network. This network is based on network provides "
                    + "by cf, adding edges between developers of different chunks. Additionally to the f argument the"
                    + " user should provide a path. This path should have afile containig the repository's URL of "
                    + "the target systems.")
            .hasArg().build());
    /*
     * options.addOption( Option.builder("rw").longOpt("rewrite-aux").
     * desc("Rewrite auxilary files (e.g., *.conf, *.sh) " + "_WITHOUT_ " +
     * "the recreation of the merge scenarios based tags.").hasArg(false).
     * build());
     * 
     * options.addOption( Option.builder("rwt").longOpt("rewrite-tagfile").
     * desc("Rewrite auxilary files (e.g., *.conf, *.sh) " + "_INCLUDING_ "
     * + "the recreation of the merge scenarios based tags.").hasArg(false).
     * build());
     */
    options.addOption("h", "help", false, "Print this help page");

    File reposListFile = null;
    Boolean skipCloneAndNetworks = false;
    try {
        CommandLine cmd = parser.parse(options, args);
        // user is looking for help
        if (cmd.hasOption("h")) {
            new HelpFormatter().printHelp("java ", options);
            System.exit(0);
        }

        /* "c", "cf", and "f" are the three available options
        * "c" builds the chunk-based network with developers that contribute to the conflict
        * "cf" builds the chunk-based network with developers that contribute to the conflict and developers
        * that are part of the chunk, but don't contribute to the conflict
        * "f" builds the file-based network with developers that contribute to the chunk into a target file
        */
        else if (cmd.hasOption("c") || cmd.hasOption("cf") || cmd.hasOption("f")) {

            String urlsFilePath = null;
            NetworkType type;
            if (cmd.hasOption("c")) {
                urlsFilePath = cmd.getOptionValue("c");
                type = NetworkType.CHUNK_BASED;
            } else if (cmd.hasOption("cf")) {
                urlsFilePath = cmd.getOptionValue("cf");
                type = NetworkType.CHUNK_BASED_FULL;
            } else {
                urlsFilePath = cmd.getOptionValue("f");
                type = NetworkType.FILE_BASED;
            }

            System.out.println(urlsFilePath);

            reposListFile = new File(urlsFilePath);

            // Ends execution if file not found.
            if (!reposListFile.exists()) {
                System.out.println("COTONET ended without retrive any repository.\n\n"
                        + "The file containig the repository's URL of the target systems was not found. "
                        + "Check wether the file \"" + urlsFilePath + "\" exists.");
                System.exit(1);
            }

            skipCloneAndNetworks = (cmd.hasOption("rw") || cmd.hasOption("rwt")) ? true : false;

            MainThread m = new MainThread(type, reposListFile, skipCloneAndNetworks);
            m.start();
            m.join();
            Logger.log("COTONET finished. Files rewritten.");

        } else {
            System.out.println("COTONET ended without retrive any repository.\n\n"
                    + "You should use 'h' if you are looking for help. Otherwise,"
                    + " the 'l' or 'fc' option is mandatory.");
            System.exit(1);

        }

    } catch (ParseException e) {
        new HelpFormatter().printHelp("java ", options);
    } catch (Exception e) {
        Logger.log(e.getMessage());
    }
}

From source file:de.prozesskraft.pramp.parts.PrampPartUi1.java

/**
 * @param args// w w  w .  ja  v  a 2s .c om
 */
public static void main(String[] args) {
    /*----------------------------
      get options from ini-file
    ----------------------------*/
    File inifile = new java.io.File(
            WhereAmI.getInstallDirectoryAbsolutePath(PrampPartUi1.class) + "/" + "../etc/pramp-gui.ini");

    if (inifile.exists()) {
        try {
            ini = new Ini(inifile);
        } catch (InvalidFileFormatException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    } else {
        System.err.println("ini file does not exist: " + inifile.getAbsolutePath());
        System.exit(1);
    }

    /*----------------------------
      create boolean options
    ----------------------------*/
    Option help = new Option("help", "print this message");
    Option v = new Option("v", "prints version and build-date");
    /*----------------------------
      create argument options
    ----------------------------*/
    Option dbfile = OptionBuilder.withArgName("dbfile").hasArg().withDescription("[optional] dbfile")
            //            .isRequired()
            .create("dbfile");
    /*----------------------------
      create options object
    ----------------------------*/
    Options options = new Options();

    options.addOption(help);
    options.addOption(v);
    options.addOption(dbfile);

    /*----------------------------
      create the parser
    ----------------------------*/
    CommandLineParser parser = new GnuParser();
    try {
        // parse the command line arguments
        line = parser.parse(options, args);
    } catch (Exception exp) {
        // oops, something went wrong
        System.err.println("Parsing failed. Reason: " + exp.getMessage());
    }

    /*----------------------------
      usage/help
    ----------------------------*/
    if (line.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        //         formatter.printHelp("checkin --version [% version %]", options);
        formatter.printHelp("pramp-gui", options);
        System.exit(0);
    }

    if (line.hasOption("v")) {
        System.out.println("author:  alexander.vogel@caegroup.de");
        System.out.println("version: [% version %]");
        System.out.println("date:    [% date %]");
        System.exit(0);
    }

    /*----------------------------
      die lizenz ueberpruefen und ggf abbrechen
    ----------------------------*/

    // check for valid license
    ArrayList<String> allPortAtHost = new ArrayList<String>();
    allPortAtHost.add(ini.get("license-server", "license-server-1"));
    allPortAtHost.add(ini.get("license-server", "license-server-2"));
    allPortAtHost.add(ini.get("license-server", "license-server-3"));

    MyLicense lic = new MyLicense(allPortAtHost, "1", "user-edition", "0.1");

    // lizenz-logging ausgeben
    for (String actLine : (ArrayList<String>) lic.getLog()) {
        System.err.println(actLine);
    }

    // abbruch, wenn lizenz nicht valide
    if (!lic.isValid()) {
        System.exit(1);
    }

    // gui
    final Display display = new Display();

    Realm.runWithDefault(SWTObservables.getRealm(display), new Runnable() {
        public void run() {
            try {
                shell = new Shell(display);
                shell.setText("pramp " + "[% version %]");

                // set an icon
                if (this.getClass().getResourceAsStream("/logoSymbol50Transp.png") != null) {
                    shell.setImage(
                            new Image(display, this.getClass().getResourceAsStream("/logoSymbol50Transp.png")));
                } else if ((new java.io.File("logoSymbol50Transp.png")).exists()) {
                    shell.setImage(new Image(display, "logoSymbol50Transp.png"));
                }

                shell.setLayout(new FillLayout());
                shell.setSize(1000, 780);
                Composite composite = new Composite(shell, SWT.NO_FOCUS);
                GridLayout gl_composite = new GridLayout(2, false);
                gl_composite.marginWidth = 0;
                gl_composite.marginHeight = 0;
                new PrampPartUi1(composite);

                try {
                    shell.open();

                    while (!shell.isDisposed()) {
                        if (!display.readAndDispatch()) {
                            display.sleep();
                        }
                    }

                } finally {
                    if (!shell.isDisposed()) {
                        shell.dispose();
                    }
                }

            } finally {
                display.dispose();
            }
        }
    });
    System.exit(0);
}

From source file:de.uniwue.info2.main.CommandLineInterpreter.java

@SuppressWarnings("static-access")
public static void main(String[] args) {

    /*-------------------------------------------------------- */
    /*---------------SETTING TARGET LANGUAGE------------------ */
    /*-------------------------------------------------------- */
    LanguageFactory languageFactory = new LanguageFactory();

    CommandLine line = null;//  w ww.  j av a 2 s  .c  o  m
    CommandLineParser parser = new BasicParser();
    Options options = new Options();
    // options to display in the help page
    Options options_short = new Options();

    // add help option
    Option help_option = new Option(HELP_OPTION_SHORT, HELP_OPTION, false, HELP_DESCRIPTION);
    options.addOption(help_option);
    options_short.addOption(help_option);
    // add extended help option
    Option help2_option = new Option(HELP2_OPTION_SHORT, HELP2_OPTION, false, HELP2_DESCRIPTION);
    options.addOption(help2_option);
    options_short.addOption(help2_option);
    // add optional operations option
    options.addOption(new Option(OPTIONAL_OPTION_SHORT, OPTIONAL_OPTION, false, OPTIONAL_DESCRIPTION));
    options.addOption(new Option(BIG_ENDIAN_OPTION_SHORT, BIG_ENDIAN_OPTION, false, BIG_ENDIAN_DESCRIPTION));
    options.addOption(
            new Option(LITTLE_ENDIAN_OPTION_SHORT, LITTLE_ENDIAN_OPTION, false, LITTLE_ENDIAN_DESCRIPTION));
    // add optional operations config option
    options.addOption(OptionBuilder.withLongOpt(OPTIONAL_FUNCTIONS_CONFIG_OPTION)
            .withArgName(OPTIONAL_FUNCTIONS_CONFIG_ARGUMENT)
            .withDescription(OPTIONAL_FUNCTIONS_CONFIG_DESCRIPTION).hasArg()
            .create(OPTIONAL_FUNCTIONS_CONFIG_SHORT));
    // add dsl option
    Option dsl_option = OptionBuilder.withLongOpt(DSL_OPTION).withArgName(DSL_ARGUMENT)
            .withDescription(DSL_DESCRIPTION).hasArg().isRequired().create(DSL_OPTION_SHORT);
    options.addOption(dsl_option);
    options_short.addOption(dsl_option);
    // add output-folder option
    Option output_option = OptionBuilder.withLongOpt(OUTPUT_OPTION).isRequired().withArgName(OUTPUT_ARGUMENT)
            .withDescription(OUTPUT_DESCRIPTION).hasArg().create(OUTPUT_OPTION_SHORT);
    options.addOption(output_option);
    options_short.addOption(output_option);

    // count possible language-specifications
    short optionCounter = 1;

    // get all possible language-specifications from language-factory and iterate through them
    List<LanguageSpecification> lSpecs = languageFactory.getAvailableLanguageSpecifications_();

    for (LanguageSpecification lSpec : lSpecs) {
        // get all possible unit-specifications for current language and iterate through them
        List<UnitTestLibrarySpecification> uSpecs = languageFactory
                .getAvailableUnitTestLibraries_(lSpec.getOptionName());
        String languageDescriptionAll = LANGUAGE_SPECIFICATION + lSpec.getLanguageName();
        String languageCounter = "s" + INDEX.format(optionCounter++);

        for (UnitTestLibrarySpecification uSpec : uSpecs) {
            // get all possible arithmetic-library-specifications for current language and iterate through
            // them
            List<ArithmeticLibrarySpecification> aSpecs = languageFactory
                    .getAvailableArithmeticLibraries_(lSpec.getOptionName());
            for (ArithmeticLibrarySpecification aSpec : aSpecs) {
                String languageDescription = "Generate unit-test for " + lSpec.getLanguageName() + "\n*["
                        + uSpec.getLibraryName() + " - " + uSpec.getVersion() + "]\n*[" + aSpec.getLibraryName()
                        + " - " + aSpec.getVersion() + "]";

                // if there is more than one option, generate suitable option-names and add them all to
                // commandline options
                if (uSpecs.size() > 1 || aSpecs.size() > 1) {
                    options.addOption(OptionBuilder
                            .withLongOpt(lSpec.getOptionName() + "_" + uSpec.getOptionName() + "_"
                                    + aSpec.getOptionName())
                            .withDescription(languageDescription).hasArg(false)
                            .create("s" + INDEX.format(optionCounter++)));
                } else {
                    // if there is only one option, use language-name as option-name
                    languageDescriptionAll = languageDescription;
                }
            }
            // add specifications to options
            options.addOption(OptionBuilder.withLongOpt(lSpec.getOptionName())
                    .withDescription(languageDescriptionAll).hasArg(false).create(languageCounter));
        }
    }

    /*-------------------------------------------------------- */
    /*-------------------PARSE USER INPUT--------------------- */
    /*-------------------------------------------------------- */
    try {
        // manual search for help-arguments
        for (String arg : args) {
            arg = arg.trim().replace("-", "");
            if (arg.equals(HELP_OPTION_SHORT) || arg.equals(HELP_OPTION)) {
                printHelp(options_short);
                return;
            }
            if (arg.equals(HELP2_OPTION_SHORT) || arg.equals(HELP2_OPTION)) {
                printExtendedHelp(options);
                return;
            }
        }

        // parse arguments   
        line = parser.parse(options, args);

        File dsl_file = null;
        File output_folder = null;
        File optional_config = null;
        Properties optional_operations = null;
        Boolean optional = false;
        Boolean little_endian = null;
        ArrayList<String> optional_exceptions = new ArrayList<String>();

        // if help-option found print help
        if (line.hasOption(HELP2_OPTION_SHORT) || args.length == 0) {
            printExtendedHelp(options);
            return;
        }

        // if help-option found print help
        if (line.hasOption(HELP_OPTION_SHORT) || args.length == 0) {
            System.out.println("\n");
            printHelp(options_short);
            return;
        }

        if (line.hasOption(OPTIONAL_OPTION_SHORT)) {
            optional = true;
        }

        if (line.hasOption(LITTLE_ENDIAN_OPTION)) {
            little_endian = true;
        }

        if (line.hasOption(BIG_ENDIAN_OPTION)) {
            little_endian = false;
        }

        // if dsl-option found, check if file exists and is readable
        // print help if error occurs
        if (line.hasOption(DSL_OPTION_SHORT)) {
            dsl_file = new File(line.getOptionValue(DSL_OPTION_SHORT));
            if (!dsl_file.exists()) {
                System.err.println("\n" + SEPERATOR + "\n" + "ERROR - DSL-file doesn't exist:\n" + dsl_file
                        + "\n" + SEPERATOR + "\n");
                printHelp(options_short);
                return;
            } else if (dsl_file.isDirectory()) {
                System.err.println("\n" + SEPERATOR + "\n" + "ERROR - DSL-file is a directory:\n" + dsl_file
                        + "\n" + SEPERATOR + "\n");
                printHelp(options_short);
                return;
            } else if (!dsl_file.canRead()) {
                System.err.println("\n" + SEPERATOR + "\n" + "ERROR - Need read-permission for DSL-file:\n"
                        + dsl_file + "\n" + SEPERATOR + "\n");
                printHelp(options_short);
                return;
            }
        }

        // if output-option found, check if folder exists and if write-permission was granted
        // print help if error occurs
        if (line.hasOption(OUTPUT_OPTION_SHORT)) {
            output_folder = new File(line.getOptionValue(OUTPUT_OPTION_SHORT));
            if (!output_folder.exists()) {
                System.err.println("\n" + SEPERATOR + "\n" + "ERROR - Output-folder doesn't exist:\n"
                        + output_folder + "\n" + SEPERATOR + "\n");
                printHelp(options_short);
                return;
            } else if (!output_folder.isDirectory()) {
                System.err.println("\n" + SEPERATOR + "\n" + "ERROR - Output-folder is not a directory:\n"
                        + output_folder + "\n" + SEPERATOR + "\n");
                printHelp(options_short);
                return;
            } else if (!output_folder.canWrite() || !output_folder.canRead()) {
                System.err.println("\n" + SEPERATOR + "\n" + "ERROR - Missing permissions for output-folder:\n"
                        + output_folder + "\n" + SEPERATOR + "\n");
                printHelp(options_short);
                return;
            }
        }

        if (line.hasOption(OPTIONAL_FUNCTIONS_CONFIG_SHORT)) {
            optional_config = new File(line.getOptionValue(OPTIONAL_FUNCTIONS_CONFIG_OPTION));
            if (!dsl_file.exists()) {
                System.err.println("\n" + SEPERATOR + "\n" + "ERROR - config-file doesn't exist:\n" + dsl_file
                        + "\n" + SEPERATOR + "\n");
                printExtendedHelp(options);
                return;
            } else if (dsl_file.isDirectory()) {
                System.err.println("\n" + SEPERATOR + "\n" + "ERROR - config-file is a directory:\n" + dsl_file
                        + "\n" + SEPERATOR + "\n");
                printExtendedHelp(options);
                return;
            } else if (!dsl_file.canRead()) {
                System.err.println("\n" + SEPERATOR + "\n" + "ERROR - Need read-permission for config-file:\n"
                        + dsl_file + "\n" + SEPERATOR + "\n");
                printExtendedHelp(options);
                return;
            }
        }

        if (optional_config != null) {
            optional_operations = new Properties();
            BufferedInputStream stream = new BufferedInputStream(new FileInputStream(optional_config));
            optional_operations.load(stream);
            stream.close();
            String optional_prop = optional_operations.getProperty("GENERATE_OPTIONAL");
            if (optional_prop != null) {
                if (optional_prop.trim().toLowerCase().equals("true")) {
                    optional = true;
                } else if (optional_prop.trim().toLowerCase().equals("false")) {
                    optional = false;
                } else if (!optional_prop.trim().isEmpty()) {
                    System.err.println("\n" + SEPERATOR + "\n"
                            + "ERROR - Syntax incorrect in config-file:\nUse \"true\" or \"false\" for \"GENERATE_OPTIONAL\"\n"
                            + SEPERATOR + "\n");
                    printExtendedHelp(options);
                    return;
                }
            }
            String exceptions = optional_operations.getProperty("EXCLUSIONS");
            if (exceptions != null) {
                for (String exc : optional_operations.getProperty("EXCLUSIONS").split(";")) {
                    optional_exceptions.add(exc.trim());
                }
            }
        }

        /*-------------------------------------------------------- */
        /*-------------------START GENERATING--------------------- */
        /*-------------------------------------------------------- */

        // instantiate generator for unit-tests
        TestcaseGenerator mainGenerator = new TestcaseGenerator(dsl_file, output_folder);

        boolean overrideDefaultSpecs = false;

        // check if user input contains a language-specifications
        // if user specified language, set overrideDefaultSpecs to true, so that only given specifications
        // are used
        for (int i = 1; i <= optionCounter; i++) {
            String opt = "s" + INDEX.format(i);
            if (line.hasOption(opt)) {
                LanguageSpecification targetSpecification = languageFactory
                        .getLanguageSpecification(options.getOption(opt).getLongOpt());
                String output = (GENERATING_DIALOG + targetSpecification.getLanguageName());

                // finally generate unit-test for current language-specification
                boolean successful = mainGenerator.generateUnitTest(targetSpecification, optional,
                        optional_exceptions, little_endian);

                if (successful) {
                    System.out.println(output + "\n--> Successfully generated.");
                } else {
                    System.err.println(output + "\n--> ERROR - see logfile");
                }
                overrideDefaultSpecs = true;
            }
        }

        // skip, if user already defined one language-specification
        // if user did not define language-specification, generate unit-tests for all
        // possible language-specifications (default)
        if (!overrideDefaultSpecs) {
            for (int i = 0; i < lSpecs.size(); i++) {
                LanguageSpecification specification = languageFactory
                        .getLanguageSpecification(lSpecs.get(i).getOptionName());

                String output = INDEX.format(i + 1) + " - " + GENERATING_DIALOG
                        + specification.getLanguageName();

                // finally generate unit-test for current language-specification
                boolean successful = mainGenerator.generateUnitTest(specification, optional,
                        optional_exceptions, little_endian);

                if (successful) {
                    System.out.println(output + "\n--> Successfully generated.");
                } else {
                    System.err.println(output + "\n--> ERROR - see logfile");
                }
            }
        }

    } catch (ParseException | IOException p) {
        System.err.println("\n" + SEPERATOR + "\n" + "ERROR - WRONG ARGUMENTS:\n" + p.getMessage() + "\n"
                + SEPERATOR + "\n");
        printHelp(options_short);
        System.out.println("\n");
    }
}

From source file:com.cyclopsgroup.waterview.jelly.JellyScriptsRunner.java

/**
 * Main entry to run a script//ww  w.  j av  a  2  s  . c  o  m
 *
 * @param args Script paths
 * @throws Exception Throw it out
 */
public static final void main(String[] args) throws Exception {
    List scripts = new ArrayList();
    for (int i = 0; i < args.length; i++) {
        String path = args[i];
        File file = new File(path);
        if (file.isFile()) {
            scripts.add(file.toURL());
        } else {
            Enumeration enu = JellyScriptsRunner.class.getClassLoader().getResources(path);
            CollectionUtils.addAll(scripts, enu);
        }
    }
    if (scripts.isEmpty()) {
        System.out.println("No script to run, return!");
        return;
    }

    String basedir = new File("").getAbsolutePath();
    Properties initProperties = new Properties(System.getProperties());
    initProperties.setProperty("basedir", basedir);
    initProperties.setProperty("plexus.home", basedir);

    WaterviewPlexusContainer container = new WaterviewPlexusContainer();
    for (Iterator j = initProperties.keySet().iterator(); j.hasNext();) {
        String initPropertyName = (String) j.next();
        container.addContextValue(initPropertyName, initProperties.get(initPropertyName));
    }

    container.addContextValue(Waterview.INIT_PROPERTIES, initProperties);
    container.initialize();
    container.start();

    JellyEngine je = (JellyEngine) container.lookup(JellyEngine.ROLE);
    JellyContext jc = new JellyContext(je.getGlobalContext());
    XMLOutput output = XMLOutput.createXMLOutput(System.out);
    for (Iterator i = scripts.iterator(); i.hasNext();) {
        URL script = (URL) i.next();
        System.out.print("Running script " + script);
        ExtendedProperties ep = new ExtendedProperties();
        ep.putAll(initProperties);
        ep.load(script.openStream());
        for (Iterator j = ep.getKeys("script"); j.hasNext();) {
            String name = (String) j.next();
            if (name.endsWith(".file")) {
                File file = new File(ep.getString(name));
                if (file.exists()) {
                    System.out.println("Runner jelly file " + file);
                    jc.runScript(file, output);
                }
            } else if (name.endsWith(".resource")) {
                Enumeration k = JellyScriptsRunner.class.getClassLoader().getResources(ep.getString(name));
                while (j != null && k.hasMoreElements()) {
                    URL s = (URL) k.nextElement();
                    System.out.println("Running jelly script " + s);
                    jc.runScript(s, output);
                }
            }
        }
        //jc.runScript( script, XMLOutput.createDummyXMLOutput() );
        System.out.println("... Done!");
    }
    container.dispose();
}

From source file:com.peewah.distribuidosfinal.EntryPoint.java

public static void main(String[] args) {
    //1. Conexin con la base de datos
    String dbUrl = "jdbc:postgresql://localhost:5432/distribuidosfinal";
    try {/* w  w  w . jav  a 2  s. c  o m*/
        connectionSource = new JdbcConnectionSource(dbUrl);
        ((JdbcConnectionSource) connectionSource).setUsername("csacanam");
        ((JdbcConnectionSource) connectionSource).setPassword("12345678");
    } catch (SQLException ex) {
        System.out.println("Error en la conexin a la base de datos");
    }

    // 2. Data Acces Object (DAO) pattern
    usuarioDao = null;
    sistemaOperativoDao = null;
    maquinaVirtualDao = null;
    maquinaAppDao = null;
    appDao = null;
    cookbookDao = null;
    cookbookAppDao = null;
    nodoDao = null;

    if (connectionSource != null) {
        try {
            usuarioDao = DaoManager.createDao(connectionSource, Usuario.class);
            sistemaOperativoDao = DaoManager.createDao(connectionSource, SistemaOperativo.class);
            maquinaVirtualDao = DaoManager.createDao(connectionSource, MaquinaVirtual.class);
            maquinaAppDao = DaoManager.createDao(connectionSource, MaquinaApp.class);
            appDao = DaoManager.createDao(connectionSource, App.class);
            cookbookDao = DaoManager.createDao(connectionSource, Cookbook.class);
            cookbookAppDao = DaoManager.createDao(connectionSource, CookbookApp.class);
            nodoDao = DaoManager.createDao(connectionSource, Nodo.class);

        } catch (SQLException ex) {
            System.out.println("Error en la creacin del DAO");
            System.err.println(ex.getMessage());
        }
    }

    // 3. Crear tabla Usuario si no existe
    try {
        TableUtils.createTableIfNotExists(connectionSource, Usuario.class);
        TableUtils.createTableIfNotExists(connectionSource, SistemaOperativo.class);
        TableUtils.createTableIfNotExists(connectionSource, MaquinaVirtual.class);
        TableUtils.createTableIfNotExists(connectionSource, App.class);
        TableUtils.createTableIfNotExists(connectionSource, MaquinaApp.class);
        TableUtils.createTableIfNotExists(connectionSource, Cookbook.class);
        TableUtils.createTableIfNotExists(connectionSource, CookbookApp.class);
        TableUtils.createTableIfNotExists(connectionSource, Nodo.class);

    } catch (SQLException ex) {
        System.out.println("Error creando las tablas");
    }

    //4. Asignacin de puerto
    ProcessBuilder process = new ProcessBuilder();
    Integer puerto;
    if (process.environment().get("PORT") != null) {
        puerto = Integer.parseInt(process.environment().get("PORT"));
    } else {
        puerto = 8080;
    }
    spark.SparkBase.port(puerto);

    //5. Habilitar Cross-origin resource sharing (CORS)
    options("/*", (Request rqst, Response rspns) -> {
        String accessControlRequestHeaders = rqst.headers("Access-Control-Request-Headers");
        if (accessControlRequestHeaders != null) {
            rspns.header("Access-Control-Allow-Headers", accessControlRequestHeaders);
        }

        String accessControlRequestMethod = rqst.headers("Access-Control-Request-Method");
        if (accessControlRequestMethod != null) {
            rspns.header("Access-Control-Allow-Methods", accessControlRequestMethod);
        }
        return "OK";
    });

    before((Request rqst, Response rspns) -> {
        rspns.header("Access-Control-Allow-Origin", "*");
    });

    after((Request rqst, Response rspns) -> {
        rspns.type("application/json");
    });

    //6. Web services
    //Crear usuario
    post("/new-user", (Request rqst, Response rspns) -> {
        //Obtener datos como parmetros
        String nombre = rqst.queryParams("name");
        String username = rqst.queryParams("username");
        String password = rqst.queryParams("password");

        //Validar si no hay datos vacos
        if (nombre != null && !nombre.equals("") && username != null && !username.equals("") && password != null
                && !password.equals("")) {
            //Crear objeto usuario
            Usuario usuario = new Usuario();
            usuario.setNombre(nombre);
            usuario.setPassword(password);
            usuario.setUsername(username);

            //Crear objeto en base de datos
            try {
                usuarioDao.create(usuario);

                //Crear carpeta
                File file = new File("/tmp/" + username);
                if (!file.exists()) {
                    boolean success = file.mkdir();
                    if (!success) {
                        System.out.println("La carpeta no pudo ser creada");
                    }
                }

            } catch (SQLException ex) {
                System.out.println("Error creando el usuario");
                return false;
            }

        } else {
            System.out.println("No debes dejar campos vacos");
            return false;
        }

        System.out.println("Usuario creado");
        return true;
    });

    //Autenticar usuario
    post("/auth-user", (Request rqst, Response rspns) -> {
        //Obtener datos como parmetros
        String username = rqst.queryParams("username");
        String password = rqst.queryParams("password");

        //Validar si no hay datos vacos
        if (username != null && !username.equals("") && password != null && !password.equals("")) {

            //Validar la dupla usuario-password
            try {
                Usuario usuario = usuarioDao.queryForId(username);
                if (usuario != null && usuario.getPassword().equals(password)) {
                    return true;
                }

            } catch (SQLException ex) {
            }

        }

        return false;

    });

    //Listar sistemas operativos disponibles
    get("/list-so", (Request rqst, Response rspns) -> {
        List<SistemaOperativo> sistemasOperativos = new ArrayList<>();
        try {
            sistemasOperativos = sistemaOperativoDao.queryForAll();
        } catch (SQLException ex) {
            System.out.println("Error listando los sistemas operativos");
        }

        return sistemasOperativos;
    }, new JsonTransformer());

    //Crear mquina virtual
    post("/create-machine", (Request rqst, Response rspns) -> {
        try {
            //Obtener parmetros
            String username = rqst.queryParams("username");
            String nombreMaquina = rqst.queryParams("nombreMaquina");
            String nombreSO = rqst.queryParams("nombreSO");

            Usuario user = usuarioDao.queryForId(username);
            SistemaOperativo so = sistemaOperativoDao.queryForId(nombreSO);

            if (user != null && so != null) {
                //Crear mquina virtual
                MaquinaVirtual maquinaVirtual = new MaquinaVirtual();
                maquinaVirtual.setNombre(nombreMaquina);
                maquinaVirtual.setSistemaOperativo(sistemaOperativoDao.queryForId(nombreSO));
                maquinaVirtual.setUsername(usuarioDao.queryForId(username));

                maquinaVirtualDao.create(maquinaVirtual);

                //Crear carpeta
                String path = "/tmp/" + username + "/" + nombreMaquina;
                File file = new File(path);
                if (!file.exists()) {
                    boolean success = file.mkdir();

                    if (!success) {
                        System.out.println("No se pudo crear la carpeta para la mquina");
                    } else {

                        //Crear Vagrantfile
                        try (Writer writer = new BufferedWriter(
                                new OutputStreamWriter(new FileOutputStream(path + "/Vagrantfile"), "UTF-8"))) {
                            writer.write("VAGRANTFILE_API_VERSION = \"2\"\n");
                            writer.write("Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|\n");
                            writer.write("\n");
                            writer.write("end\n");
                        }

                    }
                }

                return true;
            } else {
                return false;
            }

        } catch (SQLException ex) {
            System.out.println("Error creando la mquina virtual");
            return false;
        }
    });

    //Eliminar usuario y sus mquinas virtuales asociadas
    post("/delete-user", (Request rqst, Response rspns) -> {
        String userLogged = rqst.queryParams("usernameLogged");
        String nombreUsuario = rqst.queryParams("usernameToDelete");

        if (userLogged != null && !userLogged.equals("") && nombreUsuario != null && !userLogged.equals("")
                && userLogged.equals("admin")) {
            try {
                Usuario user = usuarioDao.queryForId(nombreUsuario);

                if (user != null) {
                    //Eliminar mquinas virtuales del usuario
                    Collection<MaquinaVirtual> maquinasUsuario = user.getMaquinasVirtuales();
                    for (MaquinaVirtual maquina : maquinasUsuario) {
                        //Eliminar apps de las mquinas virtuales del usuario
                        QueryBuilder<MaquinaApp, String> queryBuilder = maquinaAppDao.queryBuilder();
                        queryBuilder.where().eq(MaquinaApp.MACHINE_FIELD, maquina.getId());
                        PreparedQuery<MaquinaApp> preparedQuery = queryBuilder.prepare();

                        Collection<MaquinaApp> maquinasApps = maquinaAppDao.query(preparedQuery);
                        maquinaAppDao.delete(maquinasApps);

                        //Eliminar la mquina virtual
                        maquinaVirtualDao.delete(maquina);
                    }

                    //Eliminar usuario
                    usuarioDao.delete(user);

                    //Eliminar carpeta del usuario
                    FileUtils.deleteDirectory(new File("/tmp/" + nombreUsuario));

                    return true;
                } else {
                    return false;
                }

            } catch (SQLException ex) {
                System.out.println("Error eliminando el usuario");
                return false;
            }

        } else {
            System.out.println("No tiene permisos para realizar esta accin");
            return false;
        }
    });

    //Listar mquinas virtuales de un usuario
    get("/list-machines", (Request rqst, Response rspns) -> {
        String username = rqst.queryParams("username");
        return listMachines(username);
    }, new JsonTransformer());

    //Listar usuarios
    get("/list-users", (Request rqst, Response rspns) -> {
        String username = rqst.queryParams("usernameLogged");

        if (username.equals("admin")) {
            List<Usuario> usuarios = new ArrayList<>();
            try {
                usuarios = usuarioDao.queryForAll();
            } catch (SQLException ex) {
                System.out.println("Error listando los usuarios");
            }

            return usuarios;
        } else {
            System.out.println("No tiene permisos para realizar esta accin");
            return "No tiene permisos para realizar esta accin";
        }
    }, new JsonTransformer());

    // Agregar nodo a una mquina virtual
    post("/add-node", (Request rqst, Response rspns) -> {
        String nombreNodo = rqst.queryParams("nombreNodo");
        String ipPrivada = rqst.queryParams("ipPrivada");
        String ipPublica = rqst.queryParams("ipPublica");
        String mascaraRed = rqst.queryParams("mascaraRed");
        String cantidadMemoria = rqst.queryParams("cantidadMemoria");
        String cantidadCPU = rqst.queryParams("cantidadCPU");
        String interfazPuente = rqst.queryParams("interfazPuente");
        String parametrosJSON = rqst.queryParams("parametrosJSON");
        String nombreMaquina = rqst.queryParams("nombreMaquina");
        String userLogged = rqst.queryParams("userLogged");

        Usuario user = usuarioDao.queryForId(userLogged);

        if (user != null) {
            //Buscar mquina
            QueryBuilder<MaquinaVirtual, Integer> queryBuilder = maquinaVirtualDao.queryBuilder();
            queryBuilder.where().eq(MaquinaVirtual.USERNAME_FIELD, userLogged);
            queryBuilder.where().eq(MaquinaVirtual.NOMBRE_FIELD, nombreMaquina);
            PreparedQuery<MaquinaVirtual> preparedQuery = queryBuilder.prepare();
            List<MaquinaVirtual> maquinasUser = maquinaVirtualDao.query(preparedQuery);

            //Existe la mquina
            if (maquinasUser.size() > 0 && maquinasUser.get(0).getNombre().equals(nombreMaquina)) {
                //Crear nodo
                Nodo nodo = new Nodo();
                nodo.setNombre(nombreNodo);
                nodo.setCantidadCPU(cantidadCPU);
                nodo.setCantidadMemoria(cantidadMemoria);
                nodo.setInterfazPuente(interfazPuente);
                nodo.setIpPrivada(ipPrivada);
                nodo.setIpPublica(ipPublica);
                nodo.setMascaraRed(mascaraRed);
                nodo.setParametrosJSON(parametrosJSON);
                nodo.setMaquinaVirtual(maquinasUser.get(0));
                nodoDao.create(nodo);

                //Crear nodo en Vagrantfile
                insertarNodoEnVagrantFile("/tmp/" + userLogged + "/" + nombreMaquina, nodo);

                return true;

            }
        }

        return false;

    });

    //Listar apps para un SO
    get("/list-apps", (Request rqst, Response rspns) -> {
        String nameSO = rqst.queryParams("nombreSO");

        SistemaOperativo buscado = sistemaOperativoDao.queryForId(nameSO);

        if (buscado != null) {

            QueryBuilder<App, String> queryBuilder = appDao.queryBuilder();
            queryBuilder.where().eq(App.SO_FIELD, buscado.getNombre());
            PreparedQuery<App> preparedQuery = queryBuilder.prepare();

            Collection<App> aplicaciones = appDao.query(preparedQuery);

            return aplicaciones;
        } else {
            return "El SO buscado no existe";
        }

    }, new JsonTransformer());

    //Listar apps para una maquina virtual
    get("/list-app-installed", (Request rqst, Response rspns) -> {
        String userLogged = rqst.queryParams("userLogged");
        String machineName = rqst.queryParams("nombreMaquina");

        List<MaquinaApp> maquinaApp;
        List<App> apps = new ArrayList<>();

        //Buscar si el usuario loggeado existe
        Usuario buscado;
        MaquinaVirtual buscada = null;
        try {
            buscado = usuarioDao.queryForId(userLogged);

            if (buscado != null) {
                //Lista de maquinas virtuales del usuario
                Collection<MaquinaVirtual> maquinasVirtuales = listMachines(userLogged);

                //Revisar si la maquina virtual buscada pertenece al usuario loggeado
                for (MaquinaVirtual maquina : maquinasVirtuales) {
                    if (maquina.getNombre().equals(machineName)) {
                        buscada = maquina;
                        break;
                    }
                }

                if (buscada != null) {
                    //Obtener la lista de aplicaciones de la maquina virtual
                    QueryBuilder<MaquinaApp, String> queryBuilderN = maquinaAppDao.queryBuilder();
                    queryBuilderN.where().eq(MaquinaApp.MACHINE_FIELD, buscada.getId());
                    PreparedQuery<MaquinaApp> preparedQueryN = queryBuilderN.prepare();

                    maquinaApp = maquinaAppDao.query(preparedQueryN);

                    if (maquinaApp.size() > 0) {
                        for (MaquinaApp m : maquinaApp) {
                            apps.add(m.getApp());
                        }
                    }

                } else {
                    System.out.println("La maquina no existe para el usuario buscado");
                }
            } else {
                System.out.println("El usuario loggeado no existe");
            }

        } catch (SQLException ex) {
            System.out.println("Error listando las apps instaladas");
        }
        return apps;

    }, new JsonTransformer());

    //Listar nodos de una maquina virtual
    get("/list-node", (Request rqst, Response rspns) -> {
        String userLogged = rqst.queryParams("userLogged");
        String nombreMaquina = rqst.queryParams("nombreMaquina");

        //Inicializar la lista de nodos que se va a retornar
        Collection<Nodo> nodos = new ArrayList<>();

        //Validar que no hayan campos vacios
        if (userLogged != null && !userLogged.equals("") && nombreMaquina != null
                && !nombreMaquina.equals("")) {
            //Buscar el usuario loggeado
            Usuario user = usuarioDao.queryForId(userLogged);

            //Verificar que el usuario existe
            if (user != null) {
                //Obtener las maquinas virtuales del usuario
                List<MaquinaVirtual> maquinasVirtuales = listMachines(userLogged);

                for (MaquinaVirtual m : maquinasVirtuales) {
                    if (m.getNombre().equals(nombreMaquina)) {
                        nodos = m.getNodos();
                    }
                }

            } else {
                System.out.println("El usuario loggeado no existe");
            }
        } else {
            System.out.println("No pueden haber parametros vacios");
        }

        return nodos;
    }, new JsonTransformer());

    //Eliminar maquina virtual y aplicaciones asociadas
    post("/delete-vm", (Request rqst, Response rspns) -> {
        String usernameLogged = rqst.queryParams("usernameLogged");
        String nombreMaquina = rqst.queryParams("nombreMaquina");

        MaquinaVirtual buscada = null;
        List<MaquinaApp> maquinaApp;

        //Verificar que los parametros recibidos no son null
        if (usernameLogged != null && !usernameLogged.equals("") && nombreMaquina != null
                && !nombreMaquina.equals("")) {

            Usuario user = usuarioDao.queryForId(usernameLogged);

            if (user != null) {
                //Obtener las maquinas virtuales del usuario
                List<MaquinaVirtual> maquinasVirtuales = listMachines(usernameLogged);

                //Buscar la maquina virtual a eliminar dentro de las maquinas del usuario
                for (MaquinaVirtual m : maquinasVirtuales) {
                    if (m.getNombre().equals(nombreMaquina)) {
                        buscada = m;
                        break;
                    }
                }

                //Verificar que la maquina buscada pertenece al usuario en cuestion
                if (buscada != null) {
                    //Obtener la lista de aplicaciones de la maquina virtual
                    QueryBuilder<MaquinaApp, String> queryBuilder = maquinaAppDao.queryBuilder();
                    queryBuilder.where().eq(MaquinaApp.MACHINE_FIELD, buscada.getId());
                    PreparedQuery<MaquinaApp> preparedQuery = queryBuilder.prepare();

                    maquinaApp = maquinaAppDao.query(preparedQuery);

                    if (maquinaApp.size() > 0) {
                        //Eliminar las aplicaciones 
                        for (MaquinaApp i : maquinaApp) {
                            maquinaAppDao.delete(i);
                        }

                    } else {
                        System.out.println("No existen aplicaciones para la maquina virtual en cuestion");
                    }

                    //Eliminar mquina virtual
                    maquinaVirtualDao.delete(buscada);

                    //Eliminar carpeta de la maquina virtual
                    FileUtils.deleteDirectory(new File("/tmp/" + usernameLogged + "/" + nombreMaquina));
                    return true;

                }
            } else {
                System.out.println("EL usuario loggeado no existe");
            }

        } else {
            System.out.println("No pueden haber campos vacios");
        }

        return false;
    });

    //Correr mquina virtual
    post("/run-vm", (Request rqst, Response rspns) -> {

        String username = rqst.queryParams("userLogged");
        String nombreMaquina = rqst.queryParams("nombreMaquina");

        MaquinaVirtual maquinaBuscada = null;

        if (username != null && nombreMaquina != null && !nombreMaquina.equals("")
                && !nombreMaquina.equals("")) {
            Usuario user = usuarioDao.queryForId(username);

            if (user != null) {
                //Listar mquinas virtuales del usuario
                List<MaquinaVirtual> maquinasVirtuales = listMachines(username);

                for (MaquinaVirtual maquina : maquinasVirtuales) {
                    if (maquina.getNombre().equals(nombreMaquina)) {
                        maquinaBuscada = maquina;
                        break;
                    }
                }

                if (maquinaBuscada != null) {
                    try {
                        //Comando para ejecutar el comando vagrant up en el shell 
                        ProcessBuilder pb = new ProcessBuilder("vagrant up");
                        Process p;
                        String path = "/tmp/" + username + "/" + nombreMaquina;
                        File file = new File(path);

                        //Validar si es un directorio
                        if (file.exists() && file.isDirectory()) {
                            pb.directory(file);
                            p = pb.start();
                            return true;
                        }

                    } catch (IOException ex) {
                    }
                }

            }

        }

        return false;
    });

    //Destruir mquina virtual
    post("/destroy-vm", (Request rqst, Response rspns) -> {

        String username = rqst.queryParams("userLogged");
        String nombreMaquina = rqst.queryParams("nombreMaquina");

        MaquinaVirtual maquinaBuscada = null;

        if (username != null && nombreMaquina != null && !nombreMaquina.equals("")
                && !nombreMaquina.equals("")) {
            Usuario user = usuarioDao.queryForId(username);

            if (user != null) {
                //Listar mquinas virtuales del usuario
                List<MaquinaVirtual> maquinasVirtuales = listMachines(username);

                for (MaquinaVirtual maquina : maquinasVirtuales) {
                    if (maquina.getNombre().equals(nombreMaquina)) {
                        maquinaBuscada = maquina;
                        break;
                    }
                }

                if (maquinaBuscada != null) {
                    try {
                        //Comando para ejecutar el comando vagrant up en el shell 
                        ProcessBuilder pb = new ProcessBuilder("vagrant destroy -f");
                        Process p;
                        String path = "/tmp/" + username + "/" + nombreMaquina;
                        File file = new File(path);

                        //Validar si es un directorio
                        if (file.exists() && file.isDirectory()) {
                            pb.directory(file);
                            p = pb.start();
                            return true;
                        }

                    } catch (IOException ex) {
                    }
                }

            }

        }

        return false;
    });

    //Reanudar mquina virtual
    post("/resume-vm", (Request rqst, Response rspns) -> {

        String username = rqst.queryParams("userLogged");
        String nombreMaquina = rqst.queryParams("nombreMaquina");

        MaquinaVirtual maquinaBuscada = null;

        if (username != null && nombreMaquina != null && !nombreMaquina.equals("")
                && !nombreMaquina.equals("")) {
            Usuario user = usuarioDao.queryForId(username);

            if (user != null) {
                //Listar mquinas virtuales del usuario
                List<MaquinaVirtual> maquinasVirtuales = listMachines(username);

                for (MaquinaVirtual maquina : maquinasVirtuales) {
                    if (maquina.getNombre().equals(nombreMaquina)) {
                        maquinaBuscada = maquina;
                        break;
                    }
                }

                if (maquinaBuscada != null) {
                    try {
                        //Comando para ejecutar el comando vagrant up en el shell 
                        ProcessBuilder pb = new ProcessBuilder("vagrant resume");
                        Process p;
                        String path = "/tmp/" + username + "/" + nombreMaquina;
                        File file = new File(path);

                        //Validar si es un directorio
                        if (file.exists() && file.isDirectory()) {
                            pb.directory(file);
                            p = pb.start();
                            return true;
                        }

                    } catch (IOException ex) {
                    }
                }

            }

        }

        return false;
    });

    //Asociar app a una mquina virtual
    post("/associate-app", (Request rqst, Response rspns) -> {
        String username = rqst.queryParams("username");
        String nombreMaquina = rqst.queryParams("nombreMaquina");
        String nombreApp = rqst.queryParams("nombreApp");

        Usuario user = usuarioDao.queryForId(username);

        if (user != null) {
            //Verificar si el usuario tiene la mquina
            List<MaquinaVirtual> maquinas = listMachines(username);

            MaquinaVirtual buscada = null;

            for (MaquinaVirtual maquina : maquinas) {
                if (maquina.getNombre().equals(nombreMaquina)) {
                    buscada = maquina;
                    break;
                }
            }

            if (buscada != null) {
                App app = appDao.queryForId(nombreApp);

                //Verificar si la app existe y si est para el mismo sistema operativo que tiene la mquina
                if (app != null && app.getSistemaOperativo().getNombre()
                        .equals(buscada.getSistemaOperativo().getNombre())) {
                    //Agregar a la base de datos
                    MaquinaApp maquinaApp = new MaquinaApp(buscada, app);
                    maquinaAppDao.create(maquinaApp);

                    //Crear registro en el Vagrantfile
                    String path = "/tmp/" + username + "/" + nombreMaquina;
                    insertarCookbooksANodos(new ArrayList(buscada.getNodos()), app, path);

                    return true;
                } else {
                    System.out.println("La app no existe");
                }
            } else {
                System.out.println("No se encontr la mquina en la lista del usuario");
            }
        } else {
            System.out.println("El usuario no existe");
        }

        return false;

    });

    //Listar todas las aplicaciones
    get("/list-apps-all", (Request rqst, Response rspns) -> {
        return appDao.queryForAll();
    }, new JsonTransformer());

    // Cargar datos de prueba
    get("/add-testdata", (Request rqst, Response rspns) -> {
        try {
            if (connectionSource != null) {
                TableUtils.createTableIfNotExists(connectionSource, Usuario.class);
                TableUtils.createTableIfNotExists(connectionSource, SistemaOperativo.class);
                TableUtils.createTableIfNotExists(connectionSource, MaquinaVirtual.class);
                TableUtils.createTableIfNotExists(connectionSource, App.class);
                TableUtils.createTableIfNotExists(connectionSource, MaquinaApp.class);
                TableUtils.createTableIfNotExists(connectionSource, Cookbook.class);
                TableUtils.createTableIfNotExists(connectionSource, CookbookApp.class);
                TableUtils.createTableIfNotExists(connectionSource, Nodo.class);
            }
            testData();
        } catch (SQLException ex) {
            return "Error agregando informacin de prueba";
        }

        return "OK";
    });

    //Eliminar datos de prueba
    get("/delete-testdata", (Request rqst, Response rspns) -> {
        try {
            TableUtils.dropTable(connectionSource, Usuario.class, true);
            TableUtils.dropTable(connectionSource, MaquinaVirtual.class, true);
            TableUtils.dropTable(connectionSource, SistemaOperativo.class, true);
            TableUtils.dropTable(connectionSource, App.class, true);
            TableUtils.dropTable(connectionSource, Cookbook.class, true);
            TableUtils.dropTable(connectionSource, MaquinaApp.class, true);
            TableUtils.dropTable(connectionSource, CookbookApp.class, true);
            TableUtils.dropTable(connectionSource, Nodo.class, true);
        } catch (SQLException ex) {
            return "Error eliminando la informacin";
        }

        return "OK";
    });

}

From source file:de.huberlin.cuneiform.main.Main.java

public static void main(String[] args)
        throws ParseException, IOException, NotDerivableException, InterruptedException, JSONException {

    GnuParser gnuParser;//from  ww w .j  ava2  s. co m
    CommandLine cmdline;
    Options opt;
    String value;
    int platform;
    File outputDir;
    String[] fileList;
    StringBuffer buf;
    String line;
    String dagid;
    File logFile;

    opt = new Options();

    opt.addOption("p", "platform", true, "The platform to perform the Cuneiform script's interpretation. "
            + "Possible platforms are: 'dot', 'local', and 'debug'. Default is 'local'.");

    opt.addOption("d", "directory", true,
            "The output directory, to put the interpretation intermediate and output result as well as the default location to store the log.");

    opt.addOption("c", "clean", false,
            "If set, the execution engine ignores all cached results and starts a clean workflow run.");

    opt.addOption("r", "runid", true,
            "If set, a custom id is set for this workflow run. By default a UUID string is used.");

    opt.addOption("f", "file", true,
            "Override the default location of the log file and use the specified filename instead. If the platform is 'dot', this option sets the name of the output dot-file.");

    opt.addOption("h", "help", false, "Print help text.");

    gnuParser = new GnuParser();
    cmdline = gnuParser.parse(opt, args);

    if (cmdline.hasOption("help")) {

        System.out.println("CUNEIFORM - A Functional Workflow Language\n" + LABEL_VERSION);
        new HelpFormatter().printHelp("java -jar cuneiform.jar [OPTION]*", opt);

        return;
    }

    if (cmdline.hasOption("platform")) {

        value = cmdline.getOptionValue("platform");

        if (value.equals("dot"))
            platform = PLATFORM_DOT;
        else if (value.equals("local"))
            platform = PLATFORM_LOCAL;
        else if (value.equals("debug"))
            platform = PLATFORM_DEBUG;
        else
            throw new RuntimeException("Specified platform '" + value + "' not recognized.");

    } else
        platform = PLATFORM_LOCAL;

    if (cmdline.hasOption('d')) {

        value = cmdline.getOptionValue('d');
    } else
        value = "build";

    outputDir = new File(value);

    if (outputDir.exists()) {

        if (!outputDir.isDirectory())
            throw new IOException(
                    "Output directory '" + outputDir.getAbsolutePath() + "' exists but is not a directory.");

        else if (cmdline.hasOption('c')) {

            FileUtils.deleteDirectory(outputDir);

            if (!outputDir.mkdirs())
                throw new IOException(
                        "Could not create output directory '" + outputDir.getAbsolutePath() + "'");
        }
    } else if (!outputDir.mkdirs())
        throw new IOException("Could not create output directory '" + outputDir.getAbsolutePath() + "'");

    if (cmdline.hasOption('r'))
        dagid = cmdline.getOptionValue('r');
    else
        dagid = UUID.randomUUID().toString();

    if (cmdline.hasOption('f'))
        logFile = new File(cmdline.getOptionValue('f'));
    else
        logFile = null;

    fileList = cmdline.getArgs();
    buf = new StringBuffer();
    if (fileList.length == 0) {

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {

            while ((line = reader.readLine()) != null)
                buf.append(line).append('\n');
        }

        switch (platform) {

        case PLATFORM_DOT:
            createDot(buf.toString(), outputDir, logFile);
            break;
        case PLATFORM_LOCAL:
            runLocal(buf.toString(), outputDir, logFile, dagid);
            break;
        case PLATFORM_DEBUG:
            runDebug(buf.toString(), outputDir, logFile, dagid);
            break;
        default:
            throw new RuntimeException("Platform not recognized.");
        }
    } else

        switch (platform) {

        case PLATFORM_DOT:
            createDot(fileList, outputDir, logFile);
            break;
        case PLATFORM_LOCAL:
            runLocal(fileList, outputDir, logFile, dagid);
            break;
        case PLATFORM_DEBUG:
            runDebug(fileList, outputDir, logFile, dagid);
            break;
        default:
            throw new RuntimeException("Platform not recognized.");
        }

}

From source file:edu.harvard.iq.dataverse.ingest.IngestServiceBean.java

public static void main(String[] args) {

    String file = args[0];/*from   w ww .  j a  v  a  2 s.  c o  m*/
    String type = args[1];

    if (file == null || type == null || "".equals(file) || "".equals(type)) {
        System.err.println("Usage: java edu.harvard.iq.dataverse.ingest.IngestServiceBean <file> <type>.");
        System.exit(1);
    }

    BufferedInputStream fileInputStream = null;

    try {
        fileInputStream = new BufferedInputStream(new FileInputStream(new File(file)));
    } catch (FileNotFoundException notfoundEx) {
        fileInputStream = null;
    }

    if (fileInputStream == null) {
        System.err.println("Could not open file " + file + ".");
        System.exit(1);
    }

    TabularDataFileReader ingestPlugin = getTabDataReaderByMimeType(type);

    if (ingestPlugin == null) {
        System.err.println("Could not locate an ingest plugin for type " + type + ".");
        System.exit(1);
    }

    TabularDataIngest tabDataIngest = null;

    try {
        tabDataIngest = ingestPlugin.read(fileInputStream, null);
    } catch (IOException ingestEx) {
        System.err.println("Caught an exception trying to ingest file " + file + ".");
        System.exit(1);
    }

    try {
        if (tabDataIngest != null) {
            File tabFile = tabDataIngest.getTabDelimitedFile();

            if (tabDataIngest.getDataTable() != null && tabFile != null && tabFile.exists()) {

                String tabFilename = FileUtil.replaceExtension(file, "tab");

                Files.copy(Paths.get(tabFile.getAbsolutePath()), Paths.get(tabFilename),
                        StandardCopyOption.REPLACE_EXISTING);

                DataTable dataTable = tabDataIngest.getDataTable();

                System.out.println("NVARS: " + dataTable.getVarQuantity());
                System.out.println("NOBS: " + dataTable.getCaseQuantity());
                System.out.println("UNF: " + dataTable.getUnf());

                for (int i = 0; i < dataTable.getVarQuantity(); i++) {
                    String vartype = "";

                    if (dataTable.getDataVariables().get(i).isIntervalContinuous()) {
                        vartype = "numeric-continuous";
                    } else {
                        if (dataTable.getDataVariables().get(i).isTypeNumeric()) {
                            vartype = "numeric-discrete";
                        } else {
                            vartype = "character";
                        }
                    }

                    System.out.print("VAR" + i + " ");
                    System.out.print(dataTable.getDataVariables().get(i).getName() + " ");
                    System.out.print(vartype + " ");
                    System.out.print(dataTable.getDataVariables().get(i).getUnf());
                    System.out.println();

                }

            } else {
                System.err.println("Ingest failed to produce tab file or data table for file " + file + ".");
                System.exit(1);
            }
        } else {
            System.err.println("Ingest resulted in a null tabDataIngest object for file " + file + ".");
            System.exit(1);
        }
    } catch (IOException ex) {
        System.err.println("Caught an exception trying to save ingested data for file " + file + ".");
        System.exit(1);
    }

}

From source file:de.prozesskraft.pradar.parts.PradarPartUi3.java

/**
 * @param args/* www  .  j  a v  a  2  s . com*/
 */
public static void main(String[] args) {
    /*----------------------------
      get options from ini-file
    ----------------------------*/
    File inifile = new java.io.File(
            WhereAmI.getInstallDirectoryAbsolutePath(PradarPartUi3.class) + "/" + "../etc/pradar-gui.ini");

    if (inifile.exists()) {
        try {
            ini = new Ini(inifile);
        } catch (InvalidFileFormatException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    } else {
        System.err.println("ini file does not exist: " + inifile.getAbsolutePath());
        System.exit(1);
    }

    /*----------------------------
      create boolean options
    ----------------------------*/
    Option help = new Option("help", "print this message");
    Option v = new Option("v", "prints version and build-date");
    /*----------------------------
      create argument options
    ----------------------------*/
    Option dbfile = OptionBuilder.withArgName("dbfile").hasArg().withDescription("[optional] dbfile")
            //            .isRequired()
            .create("dbfile");
    /*----------------------------
      create options object
    ----------------------------*/
    Options options = new Options();

    options.addOption(help);
    options.addOption(v);
    options.addOption(dbfile);

    /*----------------------------
      create the parser
    ----------------------------*/
    CommandLineParser parser = new GnuParser();
    try {
        // parse the command line arguments
        line = parser.parse(options, args);
    } catch (Exception exp) {
        // oops, something went wrong
        System.err.println("Parsing failed. Reason: " + exp.getMessage());
    }

    /*----------------------------
      usage/help
    ----------------------------*/
    if (line.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        //         formatter.printHelp("checkin --version [% version %]", options);
        formatter.printHelp("pradar-gui", options);
        System.exit(0);
    }

    if (line.hasOption("v")) {
        System.out.println("author:  alexander.vogel@caegroup.de");
        System.out.println("version: [% version %]");
        System.out.println("date:    [% date %]");
        System.exit(0);
    }

    /*----------------------------
      die lizenz ueberpruefen und ggf abbrechen
    ----------------------------*/

    // check for valid license
    ArrayList<String> allPortAtHost = new ArrayList<String>();
    allPortAtHost.add(ini.get("license-server", "license-server-1"));
    allPortAtHost.add(ini.get("license-server", "license-server-2"));
    allPortAtHost.add(ini.get("license-server", "license-server-3"));

    MyLicense lic = new MyLicense(allPortAtHost, "1", "user-edition", "0.1");

    // lizenz-logging ausgeben
    for (String actLine : (ArrayList<String>) lic.getLog()) {
        System.err.println(actLine);
    }

    // abbruch, wenn lizenz nicht valide
    if (!lic.isValid()) {
        System.exit(1);
    }

    /*----------------------------
      other things
    ----------------------------*/

    // gui
    final Display display = new Display();

    Realm.runWithDefault(SWTObservables.getRealm(display), new Runnable() {
        public void run() {
            try {
                Shell shell = new Shell(display);
                shell.setText("pradar " + "[% version %]");

                // set an icon
                if (this.getClass().getResourceAsStream("/logoSymbol50Transp.png") != null) {
                    shell.setImage(
                            new Image(display, this.getClass().getResourceAsStream("/logoSymbol50Transp.png")));
                } else if ((new java.io.File("logoSymbol50Transp.png")).exists()) {
                    shell.setImage(new Image(display, "logoSymbol50Transp.png"));
                }

                shell.setLayout(new FillLayout());
                //               shell.setSize(1500, 1000);
                shell.setMaximized(true);
                Composite composite = new Composite(shell, SWT.NO_FOCUS);
                GridLayout gl_composite = new GridLayout(2, false);
                gl_composite.marginWidth = 0;
                gl_composite.marginHeight = 0;
                new PradarPartUi3(composite);

                try {
                    shell.open();

                    while (!shell.isDisposed()) {
                        if (!display.readAndDispatch()) {
                            display.sleep();
                        }
                    }

                } finally {
                    if (!shell.isDisposed()) {
                        shell.dispose();
                    }
                }

            } finally {
                display.dispose();
            }
        }
    });
    System.exit(0);
}