Example usage for java.io File getName

List of usage examples for java.io File getName

Introduction

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

Prototype

public String getName() 

Source Link

Document

Returns the name of the file or directory denoted by this abstract pathname.

Usage

From source file:io.apicurio.studio.tools.release.ReleaseTool.java

/**
 * Main method./*from  w  ww .j a  v  a  2  s.  c om*/
 * @param args
 */
public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption("n", "release-name", true, "The name of the new release.");
    options.addOption("p", "prerelease", false, "Indicate that this is a pre-release.");
    options.addOption("t", "release-tag", true, "The tag name of the new release.");
    options.addOption("o", "previous-tag", true, "The tag name of the previous release.");
    options.addOption("g", "github-pat", true, "The GitHub PAT (for authentication/authorization).");
    options.addOption("a", "artifact", true, "The binary release artifact (full path).");
    options.addOption("d", "output-directory", true, "Where to store output file(s).");

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

    if (!cmd.hasOption("n") || !cmd.hasOption("t") || !cmd.hasOption("o") || !cmd.hasOption("g")
            || !cmd.hasOption("a")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("release-studio", options);
        System.exit(1);
    }

    // Arguments (command line)
    String releaseName = cmd.getOptionValue("n");
    boolean isPrerelease = cmd.hasOption("p");
    String releaseTag = cmd.getOptionValue("t");
    String oldReleaseTag = cmd.getOptionValue("o");
    String githubPAT = cmd.getOptionValue("g");
    String artifact = cmd.getOptionValue("a");
    File outputDir = new File("");
    if (cmd.hasOption("d")) {
        outputDir = new File(cmd.getOptionValue("d"));
        if (!outputDir.exists()) {
            outputDir.mkdirs();
        }
    }

    File releaseArtifactFile = new File(artifact);
    File releaseArtifactSigFile = new File(artifact + ".asc");

    String releaseArtifact = releaseArtifactFile.getName();
    String releaseArtifactSig = releaseArtifactSigFile.getName();

    if (!releaseArtifactFile.isFile()) {
        System.err.println("Missing file: " + releaseArtifactFile.getAbsolutePath());
        System.exit(1);
    }
    if (!releaseArtifactSigFile.isFile()) {
        System.err.println("Missing file: " + releaseArtifactSigFile.getAbsolutePath());
        System.exit(1);
    }

    System.out.println("=========================================");
    System.out.println("Creating Release: " + releaseTag);
    System.out.println("Previous Release: " + oldReleaseTag);
    System.out.println("            Name: " + releaseName);
    System.out.println("        Artifact: " + releaseArtifact);
    System.out.println("     Pre-Release: " + isPrerelease);
    System.out.println("=========================================");

    String releaseNotes = "";

    // Step #1 - Generate Release Notes
    //   * Grab info about the previous release (extract publish date)
    //   * Query all Issues for ones closed since that date
    //   * Generate Release Notes from the resulting Issues
    try {
        System.out.println("Getting info about release " + oldReleaseTag);
        HttpResponse<JsonNode> response = Unirest
                .get("https://api.github.com/repos/apicurio/apicurio-studio/releases/tags/v" + oldReleaseTag)
                .header("Accept", "application/json").header("Authorization", "token " + githubPAT).asJson();
        if (response.getStatus() != 200) {
            throw new Exception("Failed to get old release info: " + response.getStatusText());
        }
        JsonNode body = response.getBody();
        String publishedDate = body.getObject().getString("published_at");
        if (publishedDate == null) {
            throw new Exception("Could not find Published Date for previous release " + oldReleaseTag);
        }
        System.out.println("Release " + oldReleaseTag + " was published on " + publishedDate);

        List<JSONObject> issues = getIssuesForRelease(publishedDate, githubPAT);
        System.out.println("Found " + issues.size() + " issues closed in release " + releaseTag);
        System.out.println("Generating Release Notes");

        releaseNotes = generateReleaseNotes(releaseName, releaseTag, issues);
        System.out.println("------------ Release Notes --------------");
        System.out.println(releaseNotes);
        System.out.println("-----------------------------------------");
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }

    String assetUploadUrl = null;

    // Step #2 - Create a GitHub Release
    try {
        System.out.println("\nCreating GitHub Release " + releaseTag);
        JSONObject body = new JSONObject();
        body.put("tag_name", "v" + releaseTag);
        body.put("name", releaseName);
        body.put("body", releaseNotes);
        body.put("prerelease", isPrerelease);

        HttpResponse<JsonNode> response = Unirest
                .post("https://api.github.com/repos/apicurio/apicurio-studio/releases")
                .header("Accept", "application/json").header("Content-Type", "application/json")
                .header("Authorization", "token " + githubPAT).body(body).asJson();
        if (response.getStatus() != 201) {
            throw new Exception("Failed to create release in GitHub: " + response.getStatusText());
        }

        assetUploadUrl = response.getBody().getObject().getString("upload_url");
        if (assetUploadUrl == null || assetUploadUrl.trim().isEmpty()) {
            throw new Exception("Failed to get Asset Upload URL for newly created release!");
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }

    // Step #3 - Upload Release Artifact (zip file)
    System.out.println("\nUploading Quickstart Artifact: " + releaseArtifact);
    try {
        String artifactUploadUrl = createUploadUrl(assetUploadUrl, releaseArtifact);
        byte[] artifactData = loadArtifactData(releaseArtifactFile);
        System.out.println("Uploading artifact asset: " + artifactUploadUrl);
        HttpResponse<JsonNode> response = Unirest.post(artifactUploadUrl).header("Accept", "application/json")
                .header("Content-Type", "application/zip").header("Authorization", "token " + githubPAT)
                .body(artifactData).asJson();
        if (response.getStatus() != 201) {
            throw new Exception("Failed to upload asset: " + releaseArtifact,
                    new Exception(response.getStatus() + "::" + response.getStatusText()));
        }

        Thread.sleep(1000);

        artifactUploadUrl = createUploadUrl(assetUploadUrl, releaseArtifactSig);
        artifactData = loadArtifactData(releaseArtifactSigFile);
        System.out.println("Uploading artifact asset: " + artifactUploadUrl);
        response = Unirest.post(artifactUploadUrl).header("Accept", "application/json")
                .header("Content-Type", "text/plain").header("Authorization", "token " + githubPAT)
                .body(artifactData).asJson();
        if (response.getStatus() != 201) {
            throw new Exception("Failed to upload asset: " + releaseArtifactSig,
                    new Exception(response.getStatus() + "::" + response.getStatusText()));
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }

    Thread.sleep(1000);

    // Step #4 - Download Latest Release JSON for inclusion in the project web site
    try {
        System.out.println("Getting info about the release.");
        HttpResponse<JsonNode> response = Unirest
                .get("https://api.github.com/repos/apicurio/apicurio-studio/releases/latest")
                .header("Accept", "application/json").asJson();
        if (response.getStatus() != 200) {
            throw new Exception("Failed to get release info: " + response.getStatusText());
        }
        JsonNode body = response.getBody();
        String publishedDate = body.getObject().getString("published_at");
        if (publishedDate == null) {
            throw new Exception("Could not find Published Date for release.");
        }
        String fname = publishedDate.replace(':', '-');
        File outFile = new File(outputDir, fname + ".json");

        System.out.println("Writing latest release info to: " + outFile.getAbsolutePath());

        String output = body.getObject().toString(4);
        try (FileOutputStream fos = new FileOutputStream(outFile)) {
            fos.write(output.getBytes("UTF-8"));
            fos.flush();
        }

        System.out.println("Release info successfully written.");
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }

    System.out.println("=========================================");
    System.out.println("All Done!");
    System.out.println("=========================================");
}

From source file:de.tudarmstadt.ukp.experiments.argumentation.convincingness.sampling.Step4MTurkOutputCollector.java

@SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception {
    String inputDirWithArgumentPairs = args[0];

    File[] resultFiles;//  ww w .  j a  v a2s . c o m

    if (args[1].contains("*")) {
        File path = new File(args[1]);
        File directory = path.getParentFile();
        String regex = path.getName().replaceAll("\\*", "");

        List<File> files = new ArrayList<>(FileUtils.listFiles(directory, new String[] { regex }, false));
        resultFiles = new File[files.size()];
        for (int i = 0; i < files.size(); i++) {
            resultFiles[i] = files.get(i);
        }
    } else {
        // result file is a comma-separated list of CSV files from MTurk
        String[] split = args[1].split(",");
        resultFiles = new File[split.length];
        for (int i = 0; i < split.length; i++) {
            resultFiles[i] = new File(split[i]);
        }
    }

    File outputDir = new File(args[2]);

    if (!outputDir.exists()) {
        if (!outputDir.mkdirs()) {
            throw new IOException("Cannot create directory " + outputDir);
        }
    }

    // error if output folder not empty to prevent any confusion by mixing files
    if (!FileUtils.listFiles(outputDir, null, false).isEmpty()) {
        throw new IllegalArgumentException("Output dir " + outputDir + " is not empty");
    }

    // collected assignments with empty reason for rejections
    Set<String> assignmentsWithEmptyReason = new HashSet<>();

    // parse with first line as header
    MTurkOutputReader mTurkOutputReader = new MTurkOutputReader(resultFiles);

    Collection<File> files = FileUtils.listFiles(new File(inputDirWithArgumentPairs), new String[] { "xml" },
            false);

    if (files.isEmpty()) {
        throw new IOException("No xml files found in " + inputDirWithArgumentPairs);
    }

    // statistics: how many hits with how many assignments ; hit ID / assignments
    Map<String, Map<String, Integer>> assignmentsPerHits = new HashMap<>();

    // collect accept/reject statistics
    for (Map<String, String> record : mTurkOutputReader) {
        boolean wasRejected = "Rejected".equals(record.get("assignmentstatus"));
        String hitID = record.get("hitid");
        String hitTypeId = record.get("hittypeid");

        if (!wasRejected) {
            // update statistics
            if (!assignmentsPerHits.containsKey(hitTypeId)) {
                assignmentsPerHits.put(hitTypeId, new HashMap<String, Integer>());
            }

            if (!assignmentsPerHits.get(hitTypeId).containsKey(hitID)) {
                assignmentsPerHits.get(hitTypeId).put(hitID, 0);
            }

            assignmentsPerHits.get(hitTypeId).put(hitID, assignmentsPerHits.get(hitTypeId).get(hitID) + 1);
        }
    }

    // statistics: how many hits with how many assignments ; hit ID / assignments
    Map<String, Integer> approvedAssignmentsPerHit = new HashMap<>();
    Map<String, Integer> rejectedAssignmentsPerHit = new HashMap<>();

    // collect accept/reject statistics
    for (Map<String, String> record : mTurkOutputReader) {
        boolean approved = "Approved".equals(record.get("assignmentstatus"));
        boolean rejected = "Rejected".equals(record.get("assignmentstatus"));
        String hitID = record.get("hitid");

        if (approved) {
            // update statistics
            if (!approvedAssignmentsPerHit.containsKey(hitID)) {
                approvedAssignmentsPerHit.put(hitID, 0);
            }

            approvedAssignmentsPerHit.put(hitID, approvedAssignmentsPerHit.get(hitID) + 1);
        } else if (rejected) {
            // update statistics
            if (!rejectedAssignmentsPerHit.containsKey(hitID)) {
                rejectedAssignmentsPerHit.put(hitID, 0);
            }

            rejectedAssignmentsPerHit.put(hitID, rejectedAssignmentsPerHit.get(hitID) + 1);
        } else {
            throw new IllegalStateException(
                    "Unknown state: " + record.get("assignmentstatus") + " HITID: " + hitID);
        }
    }

    //        System.out.println("Approved: " + approvedAssignmentsPerHit);
    //        System.out.println("Rejected: " + rejectedAssignmentsPerHit);

    System.out.println("Approved (values): " + new HashSet<>(approvedAssignmentsPerHit.values()));
    System.out.println("Rejected (values): " + new HashSet<>(rejectedAssignmentsPerHit.values()));
    // rejection statistics
    int totalRejected = 0;
    for (Map.Entry<String, Integer> rejectionEntry : rejectedAssignmentsPerHit.entrySet()) {
        totalRejected += rejectionEntry.getValue();
    }

    System.out.println("Total rejections: " + totalRejected);

    /*
    // generate .success files for adding more annotations
    for (File resultFile : resultFiles) {
    String hitTypeID = mTurkOutputReader.getHitTypeIdForFile().get(resultFile);
            
    // assignments for that hittypeid (= file)
    Map<String, Integer> assignments = assignmentsPerHits.get(hitTypeID);
            
    prepareUpdateHITsFiles(assignments, hitTypeID, resultFile);
    }
    */

    int totalSavedPairs = 0;

    // load all previously prepared argument pairs
    for (File file : files) {
        List<ArgumentPair> argumentPairs = (List<ArgumentPair>) XStreamTools.getXStream().fromXML(file);

        List<AnnotatedArgumentPair> annotatedArgumentPairs = new ArrayList<>();

        for (ArgumentPair argumentPair : argumentPairs) {
            AnnotatedArgumentPair annotatedArgumentPair = new AnnotatedArgumentPair(argumentPair);

            // is there such an answer?
            String key = "Answer." + argumentPair.getId();

            // iterate only if there is such column to save time
            if (mTurkOutputReader.getColumnNames().contains(key)) {
                // now find the results
                for (Map<String, String> record : mTurkOutputReader) {
                    if (record.containsKey(key)) {
                        // extract the values
                        AnnotatedArgumentPair.MTurkAssignment assignment = new AnnotatedArgumentPair.MTurkAssignment();

                        boolean wasRejected = "Rejected".equals(record.get("assignmentstatus"));

                        // only non-rejected (if required)
                        if (!wasRejected) {
                            String hitID = record.get("hitid");
                            String workerID = record.get("workerid");
                            String assignmentId = record.get("assignmentid");
                            try {
                                assignment.setAssignmentAcceptTime(
                                        DATE_FORMAT.parse(record.get("assignmentaccepttime")));
                                assignment.setAssignmentSubmitTime(
                                        DATE_FORMAT.parse(record.get("assignmentsubmittime")));
                                assignment.setHitComment(record.get("Answer.feedback"));
                                assignment.setHitID(hitID);
                                assignment.setTurkID(workerID);
                                assignment.setAssignmentId(assignmentId);

                                // and answer specific fields
                                String valueRaw = record.get(key);

                                // so far the label has had format aXXX_aYYY_a1, aXXX_aYYY_a2, or aXXX_aYYY_equal
                                // strip now only true label
                                String label = valueRaw.split("_")[2];

                                assignment.setValue(label);
                                String reason = record.get(key + "_reason");

                                // missing reason
                                if (reason == null) {
                                    assignmentsWithEmptyReason.add(assignmentId);
                                } else {
                                    assignment.setReason(reason);

                                    // get worker's stance
                                    String stanceRaw = record.get(key + "_stance");
                                    if (stanceRaw != null) {
                                        // parse stance
                                        String stance = stanceRaw.split("_stance_")[1];
                                        assignment.setWorkerStance(stance);
                                    }

                                    // we take maximal 5 assignments
                                    Collections.sort(annotatedArgumentPair.mTurkAssignments,
                                            new Comparator<AnnotatedArgumentPair.MTurkAssignment>() {
                                                @Override
                                                public int compare(AnnotatedArgumentPair.MTurkAssignment o1,
                                                        AnnotatedArgumentPair.MTurkAssignment o2) {
                                                    return o1.getAssignmentAcceptTime()
                                                            .compareTo(o2.getAssignmentAcceptTime());
                                                }
                                            });

                                    if (annotatedArgumentPair.mTurkAssignments
                                            .size() < MAXIMUM_ASSIGNMENTS_PER_HIT) {
                                        annotatedArgumentPair.mTurkAssignments.add(assignment);
                                    }
                                }
                            } catch (IllegalArgumentException | NullPointerException ex) {
                                System.err.println("Malformed annotations for HIT " + hitID + ", worker "
                                        + workerID + ", assignment " + assignmentId + "; " + ex.getMessage()
                                        + ", full record: " + record);
                            }
                        }
                    }
                }
            }

            // and if there are some annotations, add it to the result set
            if (!annotatedArgumentPair.mTurkAssignments.isEmpty()) {
                annotatedArgumentPairs.add(annotatedArgumentPair);
            }
        }

        if (!annotatedArgumentPairs.isEmpty()) {
            File outputFile = new File(outputDir, file.getName());
            XStreamTools.toXML(annotatedArgumentPairs, outputFile);

            System.out.println("Saved " + annotatedArgumentPairs.size() + " annotated pairs to " + outputFile);
            totalSavedPairs += annotatedArgumentPairs.size();
        }
    }

    System.out.println("Total saved " + totalSavedPairs + " pairs");

    // print assignments with empty reasons
    if (!assignmentsWithEmptyReason.isEmpty()) {
        System.out.println(
                "== Assignments with empty reason:\nassignmentIdToReject\tassignmentIdToRejectComment");
        for (String assignmentId : assignmentsWithEmptyReason) {
            System.out.println(
                    assignmentId + "\t\"Dear worker, you did not fill the required field with a reason.\"");
        }
    }

}

From source file:gash.router.app.DemoApp.java

/**
 * sample application (client) use of our messaging service
 *
 * @param args//  w w  w. j av  a 2  s.com
 */
public static void main(String[] args) {
    if (args.length == 0) {
        System.out.println("usage:  <ip address> <port no>");
        System.exit(1);
    }
    String ipAddress = args[0];
    int port = Integer.parseInt(args[1]);
    Scanner s = new Scanner(System.in);
    boolean isExit = false;
    try {
        MessageClient mc = new MessageClient(ipAddress, port);
        DemoApp da = new DemoApp(mc);
        int choice = 0;

        while (true) {
            System.out.println(
                    "Enter your option \n1. WRITE a file. \n2. READ a file. \n3. Update a File. \n4. Delete a File\n 5 Ping(Global)\n 6 Exit");
            choice = s.nextInt();
            switch (choice) {
            case 1: {
                System.out.println("Enter the full pathname of the file to be written ");
                String currFileName = s.next();
                File file = new File(currFileName);
                if (file.exists()) {
                    ArrayList<ByteString> chunkedFile = da.divideFileChunks(file);
                    String name = file.getName();
                    int i = 0;
                    String requestId = SupportMessageGenerator.generateRequestID();
                    for (ByteString string : chunkedFile) {
                        mc.saveFile(name, string, chunkedFile.size(), i++, requestId);
                    }
                } else {
                    throw new FileNotFoundException("File does not exist in this path ");
                }
            }
                break;
            case 2: {
                System.out.println("Enter the file name to be read : ");
                String currFileName = s.next();
                da.sendReadTasks(currFileName);
                //Thread.sleep(1000 * 100);
            }
                break;
            case 3: {
                System.out.println("Enter the full pathname of the file to be updated");
                String currFileName = s.next();
                File file = new File(currFileName);
                if (file.exists()) {
                    ArrayList<ByteString> chunkedFile = da.divideFileChunks(file);
                    String name = file.getName();
                    int i = 0;
                    String requestId = SupportMessageGenerator.generateRequestID();
                    for (ByteString string : chunkedFile) {
                        mc.updateFile(name, string, chunkedFile.size(), i++, requestId);
                    }
                    //Thread.sleep(10 * 1000);
                } else {
                    throw new FileNotFoundException("File does not exist in this path ");
                }
            }
                break;

            case 4:
                System.out.println("Enter the file name to be deleted : ");
                String currFileName = s.next();
                mc.deleteFile(currFileName);
                //Thread.sleep(1000 * 100);
                break;
            case 5:
                da.ping(1);
                break;
            case 6:
                isExit = true;
                break;
            default:
                break;
            }
            if (isExit)
                break;
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        CommConnection.getInstance().release();
        if (s != null)
            s.close();
    }
}

From source file:mujava.cli.genmutes.java

public static void main(String[] args) throws Exception {
    // System.out.println("test");
    genmutesCom jct = new genmutesCom();
    String[] argv = { "-all", "-debug", "Flower" }; // development use, when release,
    // comment out this line
    JCommander jCommander = new JCommander(jct, args);

    // check session name
    if (jct.getParameters().size() > 1) {
        Util.Error("Has more parameters than needed.");
        return;//from   w w  w . java2s.  co  m
    }

    // set session name
    String sessionName = jct.getParameters().get(0);

    muJavaHomePath = Util.loadConfig();
    // check if debug mode
    if (jct.isDebug()) {
        Util.debug = true;
    }

    // get all existing session name
    File folder = new File(muJavaHomePath);
    // check if the config file has defined the correct folder
    if (!folder.isDirectory()) {
        Util.Error("ERROR: cannot locate the folder specified in mujava.config");
        return;
    }
    File[] listOfFiles = folder.listFiles();
    // null checking
    // check the specified folder has files or not
    if (listOfFiles == null) {
        Util.Error("ERROR: no files in the muJava home folder: " + muJavaHomePath);
        return;
    }
    List<String> fileNameList = new ArrayList<>();
    for (File file : listOfFiles) {
        fileNameList.add(file.getName());
    }

    // check if session is already created.
    if (!fileNameList.contains(sessionName)) {
        Util.Error("Session does not exist.");
        return;

    }

    // get all files in the session
    String[] file_list = new String[1];
    // if(jct.getD())
    // {
    File sessionFolder = new File(muJavaHomePath + "/" + sessionName + "/src");
    File[] listOfFilesInSession = sessionFolder.listFiles();
    file_list = new String[listOfFilesInSession.length];
    for (int i = 0; i < listOfFilesInSession.length; i++) {
        file_list[i] = listOfFilesInSession[i].getName();
    }

    // get all mutation operators selected
    HashMap<String, List<String>> ops = new HashMap<String, List<String>>(); // used
    // for
    // add
    // random
    // percentage
    // and
    // maximum

    String[] paras = new String[] { "1", "0" };
    if (jct.getAll()) // all is selected, add all operators
    {

        // if all is selected, all mutation operators are added
        ops.put("AORB", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("AORS", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("AOIU", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("AOIS", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("AODU", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("AODS", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("ROR", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("COR", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("COD", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("COI", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("SOR", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("LOR", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("LOI", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("LOD", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("ASRS", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("SDL", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("ODL", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("VDL", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("CDL", new ArrayList<String>(Arrays.asList(paras)));
        // ops.put("SDL", jct.getAll());

    } else { // if not all, add selected ops to the list
        if (jct.getAORB()) {
            ops.put("AORB", new ArrayList<String>(Arrays.asList(paras)));
        }
        if (jct.getAORS()) {
            ops.put("AORS", new ArrayList<String>(Arrays.asList(paras)));
        }
        if (jct.getAOIU()) {
            ops.put("AOIU", new ArrayList<String>(Arrays.asList(paras)));
        }
        if (jct.getAOIS()) {
            ops.put("AOIS", new ArrayList<String>(Arrays.asList(paras)));
        }
        if (jct.getAODU()) {
            ops.put("AODU", new ArrayList<String>(Arrays.asList(paras)));
        }
        if (jct.getAODS()) {
            ops.put("AODS", new ArrayList<String>(Arrays.asList(paras)));
        }
        if (jct.getROR()) {
            ops.put("ROR", new ArrayList<String>(Arrays.asList(paras)));
        }
        if (jct.getCOR()) {
            ops.put("COR", new ArrayList<String>(Arrays.asList(paras)));
        }
        if (jct.getCOD()) {
            ops.put("COD", new ArrayList<String>(Arrays.asList(paras)));
        }
        if (jct.getCOI()) {
            ops.put("COI", new ArrayList<String>(Arrays.asList(paras)));
        }
        if (jct.getSOR()) {
            ops.put("SOR", new ArrayList<String>(Arrays.asList(paras)));
        }
        if (jct.getLOR()) {
            ops.put("LOR", new ArrayList<String>(Arrays.asList(paras)));
        }
        if (jct.getLOI()) {
            ops.put("LOI", new ArrayList<String>(Arrays.asList(paras)));
        }
        if (jct.getLOD()) {
            ops.put("LOD", new ArrayList<String>(Arrays.asList(paras)));
        }
        if (jct.getASRS()) {
            ops.put("ASRS", new ArrayList<String>(Arrays.asList(paras)));
        }
        if (jct.getSDL()) {
            ops.put("SDL", new ArrayList<String>(Arrays.asList(paras)));
        }
        if (jct.getVDL()) {
            ops.put("VDL", new ArrayList<String>(Arrays.asList(paras)));
        }
        if (jct.getODL()) {
            ops.put("ODL", new ArrayList<String>(Arrays.asList(paras)));
        }
        if (jct.getCDL()) {
            ops.put("CDL", new ArrayList<String>(Arrays.asList(paras)));
        }
    }

    // add default option "all"
    if (ops.size() == 0) {
        ops.put("AORB", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("AORS", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("AOIU", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("AOIS", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("AODU", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("AODS", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("ROR", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("COR", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("COD", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("COI", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("SOR", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("LOR", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("LOI", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("LOD", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("ASRS", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("SDL", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("ODL", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("VDL", new ArrayList<String>(Arrays.asList(paras)));
        ops.put("CDL", new ArrayList<String>(Arrays.asList(paras)));
    }

    // String[] tradional_ops = ops.toArray(new String[0]);
    // set system
    setJMutationStructureAndSession(sessionName);
    // MutationSystem.setJMutationStructureAndSession(sessionName);
    MutationSystem.recordInheritanceRelation();
    // generate mutants
    generateMutants(file_list, ops);

    //System.exit(0);
}

From source file:Inmemantlr.java

public static void main(String[] args) {
    LOGGER.info("Inmemantlr tool");

    HelpFormatter hformatter = new HelpFormatter();

    Options options = new Options();

    // Binary arguments
    options.addOption("h", "print this message");

    Option grmr = Option.builder().longOpt("grmrfiles").hasArgs().desc("comma-separated list of ANTLR files")
            .required(true).argName("grmrfiles").type(String.class).valueSeparator(',').build();

    Option infiles = Option.builder().longOpt("infiles").hasArgs()
            .desc("comma-separated list of files to parse").required(true).argName("infiles").type(String.class)
            .valueSeparator(',').build();

    Option utilfiles = Option.builder().longOpt("utilfiles").hasArgs()
            .desc("comma-separated list of utility files to be added for " + "compilation").required(false)
            .argName("utilfiles").type(String.class).valueSeparator(',').build();

    Option odir = Option.builder().longOpt("outdir")
            .desc("output directory in which the dot files will be " + "created").required(false).hasArg(true)
            .argName("outdir").type(String.class).build();

    options.addOption(infiles);//from  www .ja  v  a2  s.  c  om
    options.addOption(grmr);
    options.addOption(utilfiles);
    options.addOption(odir);

    CommandLineParser parser = new DefaultParser();

    CommandLine cmd = null;

    try {
        cmd = parser.parse(options, args);
        if (cmd.hasOption('h')) {
            hformatter.printHelp("java -jar inmemantlr.jar", options);
            System.exit(0);
        }
    } catch (ParseException e) {
        hformatter.printHelp("java -jar inmemantlr.jar", options);
        LOGGER.error(e.getMessage());
        System.exit(-1);
    }

    // input files
    Set<File> ins = getFilesForOption(cmd, "infiles");
    // grammar files
    Set<File> gs = getFilesForOption(cmd, "grmrfiles");
    // utility files
    Set<File> uf = getFilesForOption(cmd, "utilfiles");
    // output dir
    Set<File> od = getFilesForOption(cmd, "outdir");

    if (od.size() > 1) {
        LOGGER.error("output directories must be less than or equal to 1");
        System.exit(-1);
    }

    if (ins.size() <= 0) {
        LOGGER.error("no input files were specified");
        System.exit(-1);
    }

    if (gs.size() <= 0) {
        LOGGER.error("no grammar files were specified");
        System.exit(-1);
    }

    LOGGER.info("create generic parser");
    GenericParser gp = null;
    try {
        gp = new GenericParser(gs.toArray(new File[gs.size()]));
    } catch (FileNotFoundException e) {
        LOGGER.error(e.getMessage());
        System.exit(-1);
    }

    if (!uf.isEmpty()) {
        try {
            gp.addUtilityJavaFiles(uf.toArray(new String[uf.size()]));
        } catch (FileNotFoundException e) {
            LOGGER.error(e.getMessage());
            System.exit(-1);
        }
    }

    LOGGER.info("create and add parse tree listener");
    DefaultTreeListener dt = new DefaultTreeListener();
    gp.setListener(dt);

    LOGGER.info("compile generic parser");
    try {
        gp.compile();
    } catch (CompilationException e) {
        LOGGER.error("cannot compile generic parser: {}", e.getMessage());
        System.exit(-1);
    }

    String fpfx = "";
    for (File of : od) {
        if (!of.exists() || !of.isDirectory()) {
            LOGGER.error("output directory does not exist or is not a " + "directory");
            System.exit(-1);
        }
        fpfx = of.getAbsolutePath();
    }

    Ast ast;
    for (File f : ins) {
        try {
            gp.parse(f);
        } catch (IllegalWorkflowException | FileNotFoundException e) {
            LOGGER.error(e.getMessage());
            System.exit(-1);
        }
        ast = dt.getAst();

        if (!fpfx.isEmpty()) {
            String of = fpfx + "/" + FilenameUtils.removeExtension(f.getName()) + ".dot";

            LOGGER.info("write file {}", of);

            try {
                FileUtils.writeStringToFile(new File(of), ast.toDot(), "UTF-8");
            } catch (IOException e) {
                LOGGER.error(e.getMessage());
                System.exit(-1);
            }
        } else {
            LOGGER.info("Tree for {} \n {}", f.getName(), ast.toDot());
        }
    }

    System.exit(0);
}

From source file:com.recomdata.transmart.data.export.util.SftpClient.java

public static void main(String[] args) {
    //File outputFile = new File("./latestGet.log");
    try {//w w w .  j a  va2  s  . c  o m
        SftpClient sftpClient = new SftpClient("factbookdev", "SvcCOPSSH",
                "C:/Users/smunikuntla/Downloads/SaiMunikuntla12.ppk", "22", "");
        sftpClient.putFile(new File("C:/Users/smunikuntla/Downloads/camelinaction-src.zip"));
        //sftpClient.getFile("server1.log", outputFile);

        File jobZipFile = null;
        File tempFile = null;

        /*StringTokenizer st = new StringTokenizer("ftp://SvcCOPSSH:@factbookdev:22/camelinaction-src.zip", "/");
        String token = null;
        while (st.hasMoreTokens()) {
           token = st.nextToken();
        }*/
        tempFile = new File("ftp://SvcCOPSSH:@factbookdev:22/camelinaction-src.zip");
        jobZipFile = new File(tempFile.getName());

        sftpClient.getFile("camelinaction-src.zip", jobZipFile);

        sftpClient.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:net.itransformers.idiscover.core.DiscoveryManager.java

public static void main(String[] args) throws Exception, IllegalAccessException, JAXBException {
    Map<String, String> params = CmdLineParser.parseCmdLine(args);
    if (params == null) {
        printUsage("mibDir");
        return;//from  w  w w  .  j  a v  a  2 s  . c  om
    }
    final String fileName = params.get("-f");
    if (fileName == null) {
        printUsage("fileName");
        return;
    }
    File file = new File(fileName);

    DiscoveryManager manager = createDiscoveryManager(file.getParentFile(), file.getName(), "network", true);

    String mode = params.get("-d");
    if (mode == null) {
        //Set default snmpDiscovery mode to discover network!!!
        mode = "network";
    }

    Map<String, String> resourceSelectionParams = new HashMap<String, String>();
    resourceSelectionParams.put("protocol", "SNMP");
    ResourceType snmp = manager.discoveryResource.returnResourceByParam(resourceSelectionParams);

    Map<String, String> snmpConnParams = new HashMap<String, String>();
    snmpConnParams = manager.discoveryResource.getParamMap(snmp, "snmp");

    String host = params.get("-h");
    IPv4Address initialIPaddress = new IPv4Address(host, null);
    snmpConnParams.put("status", "initial");
    String mibDir = params.get("-m");
    snmpConnParams.put("mibDir", mibDir);

    snmpConnParams.get("port");
    Resource resource = new Resource(initialIPaddress, null, Integer.parseInt(snmpConnParams.get("port")),
            snmpConnParams);

    if (resource == null)
        ;

    String[] discoveryTypes = new String[] { "PHYSICAL", "NEXT_HOP", "OSPF", "ISIS", "BGP", "RIP", "ADDITIONAL",
            "IPV6" };

    //        DiscovererFactory.init(new SimulSnmpWalker(resource, new File("logs.log")));
    //        DiscovererFactory.init();
    //        Discoverer discoverer = new SnmpWalker(resource);
    NetworkType network = manager.discoverNetwork(resource, mode, discoveryTypes);

    for (DiscoveredDeviceData data : network.getDiscoveredDevice()) {
        System.out.println(data.getName() + "\n");
        for (ObjectType object : data.getObject()) {
            for (ObjectType innterObject : object.getObject()) {
                System.out.println(innterObject.getObjectType());
            }
        }

    }
    //        List<DiscoveredDeviceData> discoveredDeviceDatas = network.getDiscoveredDevice();
    //        for (DiscoveredDeviceData discoveredDeviceData : discoveredDeviceDatas) {
    //            discoveredDeviceData.getName();
    //            ParametersType parameters = discoveredDeviceData.getParameters();
    //            List<ParameterType> paras =   parameters.getParameter();
    //            for (ParameterType para : paras) {
    //
    //            }
    //
    //        }

}

From source file:it.univpm.deit.semedia.musicuri.utils.experimental.LambdaCalculator.java

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

    //*****************************************************************************
    //*************************   F I L E   I N P U T   ***************************
    //*****************************************************************************

    if ((args.length == 1) && (new File(args[0]).exists())) {
        // get the file's canonical path
        File givenHandle = new File(args[0]);
        String queryAudioCanonicalPath = givenHandle.getCanonicalPath();
        System.out.println("Input: " + queryAudioCanonicalPath);

        //PerformanceStatistic tempStat;
        SummaryStatistics lambdaSummary = SummaryStatistics.newInstance();

        if (givenHandle.isDirectory()) {

            File[] list = givenHandle.listFiles();
            if (list.length == 0) {
                System.out.println("Directory is empty");
                return;
            } else {
                ArrayList allStats = new ArrayList();
                File currentFile;
                for (int i = 0; i < list.length; i++) {
                    currentFile = list[i];
                    try {
                        if (Toolset.isSupportedAudioFile(currentFile)) {
                            System.out.println("\nCalculating optimal lambda : " + currentFile.getName());
                            lambdaSummary.addValue(getBestLambda(new MusicURIQuery(currentFile)));
                        }/*from w  ww  .  j a  v a  2  s . c o  m*/
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                //               System.out.println("\n\nStatistics for Test Case: " + queryAudioCanonicalPath);
                //               mergeStatistics(allStats);
            }
        }
        if (givenHandle.isFile()) {
            if (Toolset.isSupportedAudioFile(givenHandle)) {
                //               tempStat = getBestLambda (new MusicURIQuery(givenHandle));
                //               if (tempStat!=null)
                //               {
                //                  //tempStat.printStatistics();
                //                  ArrayList allStats = new ArrayList();
                //                  allStats.add(tempStat);
                //                  mergeStatistics(allStats);
                //               }
                //               else 
                //                  System.out.println("Error in identification ");
            }
        }

    } //end if
    else {
        System.err.println("LambdaCalculator");
        System.err.println("Usage: java tester.LambdaCalculator {directory}");
    }

}

From source file:ca.uqac.info.monitor.BeepBeepMonitor.java

public static void main(String[] args) {
    int verbosity = 1, slowdown = 0, tcp_port = 0;
    boolean show_stats = false, to_stdout = false;
    String trace_filename = "", pipe_filename = "", event_name = "message";
    final MonitorFactory mf = new MonitorFactory();

    // In case we open a socket
    ServerSocket m_serverSocket = null;
    Socket m_connection = null;//from  ww w  .  j a v  a2s.  co m

    // Parse command line arguments
    Options options = setupOptions();
    CommandLine c_line = setupCommandLine(args, options);
    assert c_line != null;
    if (c_line.hasOption("verbosity")) {
        verbosity = Integer.parseInt(c_line.getOptionValue("verbosity"));
    }
    if (verbosity > 0) {
        showHeader();
    }
    if (c_line.hasOption("version")) {
        System.err.println("(C) 2008-2013 Sylvain Hall et al., Universit du Qubec  Chicoutimi");
        System.err.println("This program comes with ABSOLUTELY NO WARRANTY.");
        System.err.println("This is a free software, and you are welcome to redistribute it");
        System.err.println("under certain conditions. See the file COPYING for details.\n");
        System.exit(ERR_OK);
    }
    if (c_line.hasOption("h")) {
        showUsage(options);
        System.exit(ERR_OK);
    }
    if (c_line.hasOption("version")) {
        System.exit(ERR_OK);
    }
    if (c_line.hasOption("slowdown")) {
        slowdown = Integer.parseInt(c_line.getOptionValue("slowdown"));
        if (verbosity > 0)
            System.err.println("Slowdown factor: " + slowdown + " ms");
    }
    if (c_line.hasOption("stats")) {
        show_stats = true;
    }
    if (c_line.hasOption("csv")) {
        // Will output data in CSV format to stdout
        to_stdout = true;
    }
    if (c_line.hasOption("eventname")) {
        // Set event name
        event_name = c_line.getOptionValue("eventname");
    }
    if (c_line.hasOption("t")) {
        // Read events from a trace
        trace_filename = c_line.getOptionValue("t");
    }
    if (c_line.hasOption("p")) {
        // Read events from a pipe
        pipe_filename = c_line.getOptionValue("p");
    }
    if (c_line.hasOption("k")) {
        // Read events from a TCP port
        tcp_port = Integer.parseInt(c_line.getOptionValue("k"));
    }
    if (!trace_filename.isEmpty() && !pipe_filename.isEmpty()) {
        System.err.println("ERROR: you must specify at most one of trace file or named pipe");
        showUsage(options);
        System.exit(ERR_ARGUMENTS);
    }
    @SuppressWarnings("unchecked")
    List<String> remaining_args = c_line.getArgList();
    if (remaining_args.isEmpty()) {
        System.err.println("ERROR: no input formula specified");
        showUsage(options);
        System.exit(ERR_ARGUMENTS);
    }
    // Instantiate the event notifier
    boolean notify = (verbosity > 0);
    EventNotifier en = new EventNotifier(notify);
    en.m_slowdown = slowdown;
    en.m_csvToStdout = to_stdout;
    // Create one monitor for each input file and add it to the notifier 
    for (String formula_filename : remaining_args) {
        try {
            String formula_contents = FileReadWrite.readFile(formula_filename);
            Operator op = Operator.parseFromString(formula_contents);
            op.accept(mf);
            Monitor mon = mf.getMonitor();
            Map<String, String> metadata = getMetadata(formula_contents);
            metadata.put("Filename", formula_filename);
            en.addMonitor(mon, metadata);
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(ERR_IO);
        } catch (Operator.ParseException e) {
            System.err.println("Error parsing input formula");
            System.exit(ERR_PARSE);
        }
    }

    // Read trace and iterate
    // Opens file
    PipeReader pr = null;
    try {
        if (!pipe_filename.isEmpty()) {
            // We tell the pipe reader we read a pipe
            File f = new File(pipe_filename);
            if (verbosity > 0)
                System.err.println("Reading from pipe named " + f.getName());
            pr = new PipeReader(new FileInputStream(f), en, false);
        } else if (!trace_filename.isEmpty()) {
            // We tell the pipe reader we read a regular file
            File f = new File(trace_filename);
            if (verbosity > 0)
                System.err.println("Reading from file " + f.getName());
            pr = new PipeReader(new FileInputStream(f), en, true);
        } else if (tcp_port > 0) {
            // We tell the pipe reader we read from a socket
            if (verbosity > 0)
                System.err.println("Reading from TCP port " + tcp_port);
            m_serverSocket = new ServerSocket(tcp_port);
            m_connection = m_serverSocket.accept();
            pr = new PipeReader(m_connection.getInputStream(), en, false);
        } else {
            // We tell the pipe reader we read from standard input
            if (verbosity > 0)
                System.err.println("Reading from standard input");
            pr = new PipeReader(System.in, en, false);
        }
    } catch (FileNotFoundException ex) {
        // We print both trace and pipe since one of them must be empty
        System.err.println("ERROR: file not found " + trace_filename + pipe_filename);
        System.exit(ERR_IO);
    } catch (IOException e) {
        // Caused by socket error
        e.printStackTrace();
        System.exit(ERR_IO);
    }
    pr.setSeparator("<" + event_name + ">", "</" + event_name + ">");

    // Check parameters for the event notifier
    if (c_line.hasOption("no-trigger")) {
        en.m_notifyOnVerdict = false;
    } else {
        en.m_notifyOnVerdict = true;
    }
    if (c_line.hasOption("mirror")) {
        en.m_mirrorEventsOnStdout = true;
    }

    // Start event notifier
    en.reset();
    Thread th = new Thread(pr);
    long clock_start = System.nanoTime();
    th.start();
    try {
        th.join(); // Wait for thread to finish
    } catch (InterruptedException e1) {
        // Thread is finished
    }
    if (tcp_port > 0 && m_serverSocket != null) {
        // We opened a socket; now we close it
        try {
            m_serverSocket.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    long clock_end = System.nanoTime();
    int ret_code = pr.getReturnCode();
    switch (ret_code) {
    case PipeReader.ERR_EOF:
        if (verbosity > 0)
            System.err.println("\nEnd of file reached");
        break;
    case PipeReader.ERR_EOT:
        if (verbosity > 0)
            System.err.println("\nEOT received on pipe: closing");
        break;
    case PipeReader.ERR_OK:
        // Do nothing
        break;
    default:
        // An error
        System.err.println("Runtime error");
        System.exit(ERR_RUNTIME);
        break;
    }
    if (show_stats) {
        if (verbosity > 0) {
            System.out.println("Messages:   " + en.m_numEvents);
            System.out.println("Time:       " + (int) (en.m_totalTime / 1000000f) + " ms");
            System.out.println("Clock time: " + (int) ((clock_end - clock_start) / 1000000f) + " ms");
            System.out.println("Max heap:   " + (int) (en.heapSize / 1048576f) + " MB");
        } else {
            // If stats are asked but verbosity = 0, only show time value
            // (both monitor and wall clock) 
            System.out.print((int) (en.m_totalTime / 1000000f));
            System.out.print(",");
            System.out.print((int) ((clock_end - clock_start) / 1000000f));
        }
    }
    System.exit(ERR_OK);
}

From source file:edu.msu.cme.rdp.alignment.errorcheck.CompareErrorType.java

public static void main(String[] args) throws IOException {
    Options options = new Options();
    options.addOption("s", "stem", true, "Output stem (default <query_nucl.fasta>)");

    final SeqReader queryReader;
    final List<Sequence> refSeqList;
    final PrintStream alignOutStream;
    final CompareErrorType errorProcessor;
    Sequence seq;//from w ww . jav  a2s . co  m
    Map<String, PAObject> matchMap = new HashMap();

    try {
        CommandLine line = new PosixParser().parse(options, args);

        String stem;

        args = line.getArgs();
        if (args.length != 2 && args.length != 3) {
            throw new Exception("Unexpected number of arguments");
        }

        File refFile = new File(args[0]);
        File queryFile = new File(args[1]);

        if (line.hasOption("stem")) {
            stem = line.getOptionValue("stem");
        } else {
            stem = queryFile.getName();
        }

        File alignOutFile = new File(stem + "_alignments.txt");
        File mismatchOutFile = new File(stem + "_mismatches.txt");
        File indelOutFile = new File(stem + "_indels.txt");
        File qualOutFile = null;

        refSeqList = SequenceReader.readFully(refFile);
        if (args.length == 3) {
            queryReader = new QSeqReader(queryFile, new File(args[2]));
        } else {
            queryReader = new SequenceReader(queryFile);
        }

        seq = queryReader.readNextSequence();
        if (seq instanceof QSequence) {
            qualOutFile = new File(stem + "_qual.txt");
        }

        errorProcessor = new CompareErrorType(mismatchOutFile, indelOutFile, qualOutFile);
        alignOutStream = new PrintStream(alignOutFile);

        System.err.println("Starting CompareErrorType");
        System.err.println("*  Time:              " + new Date());
        System.err.println("*  Reference File:    " + refFile);
        System.err.println("*  Query File:        " + queryFile);
        if (args.length == 3) {
            System.err.println("*  Qual File:         " + args[2]);
        }
        System.err.println("*  Query format:      " + queryReader.getFormat());
        System.err.println("*  Alignment Output:  " + alignOutFile);
        System.err.println("*  Mismatches Output: " + mismatchOutFile);
        System.err.println("*  Alignment Output:  " + indelOutFile);
        if (qualOutFile != null) {
            System.err.println("*  Quality Output:    " + qualOutFile);
        }

    } catch (Exception e) {
        new HelpFormatter().printHelp(
                "CompareErrorType [options] <ref_nucl> (<query_nucl> | <query_nucl.fasta> <query_nucl.qual>)",
                options);
        System.err.println("ERROR: " + e.getMessage());
        throw new RuntimeException(e);
        //System.exit(1);
        //return;
    }

    //ScoringMatrix scoringMatrix = ScoringMatrix.getDefaultNuclMatrix();
    // use a simple scoring function, match score 0, mismatch -1, gap opening -1, gap extension -1.
    ScoringMatrix scoringMatrix = new ScoringMatrix(
            ScoringMatrix.class.getResourceAsStream("/data/simple_scoringmatrix.txt"), -1, -1);

    do {
        try {
            PairwiseAlignment bestResult = null;
            Sequence bestSeq = null;
            boolean bestReversed = false;
            String querySeqStr = seq.getSeqString().toLowerCase();
            String reversedQuery = IUBUtilities.reverseComplement(querySeqStr);
            PAObject bestMatch = null;

            //checking if sequence has been seen before
            if (matchMap.containsKey(seq.getSeqString())) {
                bestMatch = matchMap.get(seq.getSeqString());
            } else {
                for (Sequence refSeq : refSeqList) {
                    String refSeqStr = refSeq.getSeqString().toLowerCase();
                    PairwiseAlignment result = PairwiseAligner.align(refSeqStr, querySeqStr, scoringMatrix,
                            AlignmentMode.global);
                    PairwiseAlignment reversedResult = PairwiseAligner.align(refSeqStr,
                            IUBUtilities.reverseComplement(querySeqStr), scoringMatrix, AlignmentMode.global);

                    PairwiseAlignment currBest = (result.getScore() > reversedResult.getScore()) ? result
                            : reversedResult;

                    if (bestResult == null || currBest.getScore() > bestResult.getScore()) {
                        bestResult = currBest;
                        bestSeq = refSeq;
                        if (currBest == reversedResult) {
                            bestReversed = true;
                        } else {
                            bestReversed = false;
                        }

                    }

                    //Since this is a new sequence, make a new PAObject to put into the map to compare against later
                    bestMatch = new PAObject(bestResult, bestReversed, bestSeq);
                    matchMap.put(seq.getSeqString(), bestMatch);
                }
            }
            int refStart = bestMatch.getPA().getStarti();
            int refEnd = bestMatch.getPA().getEndi();
            bestSeq = bestMatch.getRefSeq();
            bestReversed = bestMatch.getReversed();
            bestResult = bestMatch.getPA();

            //output information
            alignOutStream.println(">\t" + seq.getSeqName() + "\t" + bestSeq.getSeqName() + "\t"
                    + seq.getSeqString().length() + "\t" + refStart + "\t" + refEnd + "\t"
                    + bestResult.getScore() + "\t" + ((bestReversed) ? "\treversed" : ""));
            alignOutStream.println(bestResult.getAlignedSeqj() + "\n");
            alignOutStream.println(bestResult.getAlignedSeqi() + "\n");

            //seqi is reference seq, seqj is the refseq
            errorProcessor.processSequence(seq, bestResult.getAlignedSeqj(), bestSeq.getSeqName(),
                    bestResult.getAlignedSeqi(), refStart, bestReversed);

        } catch (Exception e) {
            throw new RuntimeException("Failed while processing seq " + seq.getSeqName(), e);
        }
    } while ((seq = queryReader.readNextSequence()) != null);
    queryReader.close();
    alignOutStream.close();
    errorProcessor.close();
}