Example usage for java.io File getAbsolutePath

List of usage examples for java.io File getAbsolutePath

Introduction

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

Prototype

public String getAbsolutePath() 

Source Link

Document

Returns the absolute pathname string of this abstract pathname.

Usage

From source file:com.act.lcms.v2.MZCollisionCounter.java

public static void main(String[] args) throws Exception {
    CLIUtil cliUtil = new CLIUtil(MassChargeCalculator.class, HELP_MESSAGE, OPTION_BUILDERS);
    CommandLine cl = cliUtil.parseCommandLine(args);

    File inputFile = new File(cl.getOptionValue(OPTION_INPUT_INCHI_LIST));
    if (!inputFile.exists()) {
        cliUtil.failWithMessage("Input file at does not exist at %s", inputFile.getAbsolutePath());
    }/*from   w  w w  .  j  a v  a2  s  . c o  m*/

    List<MassChargeCalculator.MZSource> sources = new ArrayList<>();
    try (BufferedReader reader = new BufferedReader(new FileReader(inputFile))) {
        String line;
        while ((line = reader.readLine()) != null) {
            line = line.trim();
            sources.add(new MassChargeCalculator.MZSource(line));
            if (sources.size() % 1000 == 0) {
                LOGGER.info("Loaded %d sources from input file", sources.size());
            }
        }
    }

    Set<String> considerIons = Collections.emptySet();
    if (cl.hasOption(OPTION_ONLY_CONSIDER_IONS)) {
        List<String> ions = Arrays.asList(cl.getOptionValues(OPTION_ONLY_CONSIDER_IONS));
        LOGGER.info("Only considering ions for m/z calculation: %s", StringUtils.join(ions, ", "));
        considerIons = new HashSet<>(ions);
    }

    TSVWriter<String, Long> tsvWriter = new TSVWriter<>(Arrays.asList("collisions", "count"));
    tsvWriter.open(new File(cl.getOptionValue(OPTION_OUTPUT_FILE)));

    try {
        LOGGER.info("Loaded %d sources in total from input file", sources.size());

        MassChargeCalculator.MassChargeMap mzMap = MassChargeCalculator.makeMassChargeMap(sources,
                considerIons);

        if (!cl.hasOption(OPTION_COUNT_WINDOW_INTERSECTIONS)) {
            // Do an exact analysis of the m/z collisions if windowing is not specified.

            LOGGER.info("Computing precise collision histogram.");
            Iterable<Double> mzs = mzMap.ionMZIter();
            Map<Integer, Long> collisionHistogram = histogram(
                    StreamSupport.stream(mzs.spliterator(), false).map(mz -> { // See comment about Iterable below.
                        try {
                            return mzMap.ionMZToMZSources(mz).size();
                        } catch (NoSuchElementException e) {
                            LOGGER.error("Caught no such element exception for mz %f: %s", mz, e.getMessage());
                            throw e;
                        }
                    }));
            List<Integer> sortedCollisions = new ArrayList<>(collisionHistogram.keySet());
            Collections.sort(sortedCollisions);
            for (Integer collision : sortedCollisions) {
                tsvWriter.append(new HashMap<String, Long>() {
                    {
                        put("collisions", collision.longValue());
                        put("count", collisionHistogram.get(collision));
                    }
                });
            }
        } else {
            /* After some deliberation (thanks Gil!), the windowed variant of this calculation counts the number of
             * structures whose 0.01 Da m/z windows (for some set of ions) overlap with each other.
             *
             * For example, let's assume we have five total input structures, and are only searching for one ion.  Let's
             * also assume that three of those structures have m/z A and the remaining two have m/z B.  The windows might
             * look like this in the m/z domain:
             * |----A----|
             *        |----B----|
             * Because A represents three structures and overlaps with B, which represents two, we assign A a count of 5--
             * this is the number of structures we believe could fall into the range of A given our current peak calling
             * approach.  Similarly, B is assigned a count of 5, as the possibility for collision/confusion is symmetric.
             *
             * Note that this is an over-approximation of collisions, as we could more precisely only consider intersections
             * when the exact m/z of B falls within the window around A and vice versa.  However, because we have observed
             * cases where the MS sensor doesn't report structures at exactly the m/z we predict, we employ this weaker
             * definition of intersection to give a slightly pessimistic view of what confusions might be possible. */
            // Compute windows for every m/z.  We don't care about the original mz values since we just want the count.
            List<Double> mzs = mzMap.ionMZsSorted();

            final Double windowHalfWidth;
            if (cl.hasOption(OPTION_WINDOW_HALFWIDTH)) {
                // Don't use get with default for this option, as we want the exact FP value of the default tolerance.
                windowHalfWidth = Double.valueOf(cl.getOptionValue(OPTION_WINDOW_HALFWIDTH));
            } else {
                windowHalfWidth = DEFAULT_WINDOW_TOLERANCE;
            }

            /* Window = (lower bound, upper bound), counter of represented m/z's that collide with this window, and number
             * of representative structures (which will be used in counting collisions). */
            LinkedList<CollisionWindow> allWindows = new LinkedList<CollisionWindow>() {
                {
                    for (Double mz : mzs) {
                        // CPU for memory trade-off: don't re-compute the window bounds over and over and over and over and over.
                        try {
                            add(new CollisionWindow(mz, windowHalfWidth, mzMap.ionMZToMZSources(mz).size()));
                        } catch (NoSuchElementException e) {
                            LOGGER.error("Caught no such element exception for mz %f: %s", mz, e.getMessage());
                            throw e;
                        }
                    }
                }
            };

            // Sweep line time!  The window ranges are the interesting points.  We just accumulate overlap counts as we go.
            LinkedList<CollisionWindow> workingSet = new LinkedList<>();
            List<CollisionWindow> finished = new LinkedList<>();

            while (allWindows.size() > 0) {
                CollisionWindow thisWindow = allWindows.pop();
                // Remove any windows from the working set that don't overlap with the next window.
                while (workingSet.size() > 0 && workingSet.peekFirst().getMaxMZ() < thisWindow.getMinMZ()) {
                    finished.add(workingSet.pop());
                }

                for (CollisionWindow w : workingSet) {
                    /* Add the size of the new overlapping window's structure count to each of the windows in the working set,
                     * which represents the number of possible confused structures that fall within the overlapping region.
                     * We exclude the window itself as it should already have counted the colliding structures it represents. */
                    w.getAccumulator().add(thisWindow.getStructureCount());

                    /* Reciprocally, add the structure counts of all windows with which the current window overlaps to it. */
                    thisWindow.getAccumulator().add(w.getStructureCount());
                }

                // Now that accumulation is complete, we can safely add the current window.
                workingSet.add(thisWindow);
            }

            // All the interesting events are done, so drop the remaining windows into the finished set.
            finished.addAll(workingSet);

            Map<Long, Long> collisionHistogram = histogram(
                    finished.stream().map(w -> w.getAccumulator().longValue()));
            List<Long> sortedCollisions = new ArrayList<>(collisionHistogram.keySet());
            Collections.sort(sortedCollisions);
            for (Long collision : sortedCollisions) {
                tsvWriter.append(new HashMap<String, Long>() {
                    {
                        put("collisions", collision);
                        put("count", collisionHistogram.get(collision));
                    }
                });
            }
        }
    } finally {
        if (tsvWriter != null) {
            tsvWriter.close();
        }
    }
}

From source file:Snippet135.java

public static void main(String[] args) {
    final Display display = new Display();
    final Shell shell = new Shell(display);
    shell.setText("SWT and Swing/AWT Example");

    Listener exitListener = new Listener() {
        public void handleEvent(Event e) {
            MessageBox dialog = new MessageBox(shell, SWT.OK | SWT.CANCEL | SWT.ICON_QUESTION);
            dialog.setText("Question");
            dialog.setMessage("Exit?");
            if (e.type == SWT.Close)
                e.doit = false;//from  ww  w .  j ava2s. c  o m
            if (dialog.open() != SWT.OK)
                return;
            shell.dispose();
        }
    };
    Listener aboutListener = new Listener() {
        public void handleEvent(Event e) {
            final Shell s = new Shell(shell, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL);
            s.setText("About");
            GridLayout layout = new GridLayout(1, false);
            layout.verticalSpacing = 20;
            layout.marginHeight = layout.marginWidth = 10;
            s.setLayout(layout);
            Label label = new Label(s, SWT.NONE);
            label.setText("SWT and AWT Example.");
            Button button = new Button(s, SWT.PUSH);
            button.setText("OK");
            GridData data = new GridData();
            data.horizontalAlignment = GridData.CENTER;
            button.setLayoutData(data);
            button.addListener(SWT.Selection, new Listener() {
                public void handleEvent(Event event) {
                    s.dispose();
                }
            });
            s.pack();
            Rectangle parentBounds = shell.getBounds();
            Rectangle bounds = s.getBounds();
            int x = parentBounds.x + (parentBounds.width - bounds.width) / 2;
            int y = parentBounds.y + (parentBounds.height - bounds.height) / 2;
            s.setLocation(x, y);
            s.open();
            while (!s.isDisposed()) {
                if (!display.readAndDispatch())
                    display.sleep();
            }
        }
    };
    shell.addListener(SWT.Close, exitListener);
    Menu mb = new Menu(shell, SWT.BAR);
    MenuItem fileItem = new MenuItem(mb, SWT.CASCADE);
    fileItem.setText("&File");
    Menu fileMenu = new Menu(shell, SWT.DROP_DOWN);
    fileItem.setMenu(fileMenu);
    MenuItem exitItem = new MenuItem(fileMenu, SWT.PUSH);
    exitItem.setText("&Exit\tCtrl+X");
    exitItem.setAccelerator(SWT.CONTROL + 'X');
    exitItem.addListener(SWT.Selection, exitListener);
    MenuItem aboutItem = new MenuItem(fileMenu, SWT.PUSH);
    aboutItem.setText("&About\tCtrl+A");
    aboutItem.setAccelerator(SWT.CONTROL + 'A');
    aboutItem.addListener(SWT.Selection, aboutListener);
    shell.setMenuBar(mb);

    RGB color = shell.getBackground().getRGB();
    Label separator1 = new Label(shell, SWT.SEPARATOR | SWT.HORIZONTAL);
    Label locationLb = new Label(shell, SWT.NONE);
    locationLb.setText("Location:");
    Composite locationComp = new Composite(shell, SWT.EMBEDDED);
    ToolBar toolBar = new ToolBar(shell, SWT.FLAT);
    ToolItem exitToolItem = new ToolItem(toolBar, SWT.PUSH);
    exitToolItem.setText("&Exit");
    exitToolItem.addListener(SWT.Selection, exitListener);
    ToolItem aboutToolItem = new ToolItem(toolBar, SWT.PUSH);
    aboutToolItem.setText("&About");
    aboutToolItem.addListener(SWT.Selection, aboutListener);
    Label separator2 = new Label(shell, SWT.SEPARATOR | SWT.HORIZONTAL);
    final Composite comp = new Composite(shell, SWT.NONE);
    final Tree fileTree = new Tree(comp, SWT.SINGLE | SWT.BORDER);
    Sash sash = new Sash(comp, SWT.VERTICAL);
    Composite tableComp = new Composite(comp, SWT.EMBEDDED);
    Label separator3 = new Label(shell, SWT.SEPARATOR | SWT.HORIZONTAL);
    Composite statusComp = new Composite(shell, SWT.EMBEDDED);

    java.awt.Frame locationFrame = SWT_AWT.new_Frame(locationComp);
    final java.awt.TextField locationText = new java.awt.TextField();
    locationFrame.add(locationText);

    java.awt.Frame fileTableFrame = SWT_AWT.new_Frame(tableComp);
    java.awt.Panel panel = new java.awt.Panel(new java.awt.BorderLayout());
    fileTableFrame.add(panel);
    final JTable fileTable = new JTable(new FileTableModel(null));
    fileTable.setDoubleBuffered(true);
    fileTable.setShowGrid(false);
    fileTable.createDefaultColumnsFromModel();
    JScrollPane scrollPane = new JScrollPane(fileTable);
    panel.add(scrollPane);

    java.awt.Frame statusFrame = SWT_AWT.new_Frame(statusComp);
    statusFrame.setBackground(new java.awt.Color(color.red, color.green, color.blue));
    final java.awt.Label statusLabel = new java.awt.Label();
    statusFrame.add(statusLabel);
    statusLabel.setText("Select a file");

    sash.addListener(SWT.Selection, new Listener() {
        public void handleEvent(Event e) {
            if (e.detail == SWT.DRAG)
                return;
            GridData data = (GridData) fileTree.getLayoutData();
            Rectangle trim = fileTree.computeTrim(0, 0, 0, 0);
            data.widthHint = e.x - trim.width;
            comp.layout();
        }
    });

    File[] roots = File.listRoots();
    for (int i = 0; i < roots.length; i++) {
        File file = roots[i];
        TreeItem treeItem = new TreeItem(fileTree, SWT.NONE);
        treeItem.setText(file.getAbsolutePath());
        treeItem.setData(file);
        new TreeItem(treeItem, SWT.NONE);
    }
    fileTree.addListener(SWT.Expand, new Listener() {
        public void handleEvent(Event e) {
            TreeItem item = (TreeItem) e.item;
            if (item == null)
                return;
            if (item.getItemCount() == 1) {
                TreeItem firstItem = item.getItems()[0];
                if (firstItem.getData() != null)
                    return;
                firstItem.dispose();
            } else {
                return;
            }
            File root = (File) item.getData();
            File[] files = root.listFiles();
            if (files == null)
                return;
            for (int i = 0; i < files.length; i++) {
                File file = files[i];
                if (file.isDirectory()) {
                    TreeItem treeItem = new TreeItem(item, SWT.NONE);
                    treeItem.setText(file.getName());
                    treeItem.setData(file);
                    new TreeItem(treeItem, SWT.NONE);
                }
            }
        }
    });
    fileTree.addListener(SWT.Selection, new Listener() {
        public void handleEvent(Event e) {
            TreeItem item = (TreeItem) e.item;
            if (item == null)
                return;
            final File root = (File) item.getData();
            EventQueue.invokeLater(new Runnable() {
                public void run() {
                    statusLabel.setText(root.getAbsolutePath());
                    locationText.setText(root.getAbsolutePath());
                    fileTable.setModel(new FileTableModel(root.listFiles()));
                }
            });
        }
    });

    GridLayout layout = new GridLayout(4, false);
    layout.marginWidth = layout.marginHeight = 0;
    layout.horizontalSpacing = layout.verticalSpacing = 1;
    shell.setLayout(layout);
    GridData data;
    data = new GridData(GridData.FILL_HORIZONTAL);
    data.horizontalSpan = 4;
    separator1.setLayoutData(data);
    data = new GridData();
    data.horizontalSpan = 1;
    data.horizontalIndent = 10;
    locationLb.setLayoutData(data);
    data = new GridData(GridData.FILL_HORIZONTAL);
    data.horizontalSpan = 2;
    data.heightHint = locationText.getPreferredSize().height;
    locationComp.setLayoutData(data);
    data = new GridData(GridData.FILL_HORIZONTAL);
    data.horizontalSpan = 1;
    toolBar.setLayoutData(data);
    data = new GridData(GridData.FILL_HORIZONTAL);
    data.horizontalSpan = 4;
    separator2.setLayoutData(data);
    data = new GridData(GridData.FILL_BOTH);
    data.horizontalSpan = 4;
    comp.setLayoutData(data);
    data = new GridData(GridData.FILL_HORIZONTAL);
    data.horizontalSpan = 4;
    separator3.setLayoutData(data);
    data = new GridData(GridData.FILL_HORIZONTAL);
    data.horizontalSpan = 4;
    data.heightHint = statusLabel.getPreferredSize().height;
    statusComp.setLayoutData(data);

    layout = new GridLayout(3, false);
    layout.marginWidth = layout.marginHeight = 0;
    layout.horizontalSpacing = layout.verticalSpacing = 1;
    comp.setLayout(layout);
    data = new GridData(GridData.FILL_VERTICAL);
    data.widthHint = 200;
    fileTree.setLayoutData(data);
    data = new GridData(GridData.FILL_VERTICAL);
    sash.setLayoutData(data);
    data = new GridData(GridData.FILL_BOTH);
    tableComp.setLayoutData(data);

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

From source file:de.codesourcery.luaparser.LuaToJSON.java

public static void main(String[] args) throws Exception {
    args = new String[] { "/home/tgierke/apps/factorio/data/base/prototypes/entity/entities.lua" };

    for (String file : args) {
        System.out.println("Parsing LUA file " + file + " ...");
        final String json = new LuaToJSON().getJSON(new File(file));
        final File jsonFile = new File(file + ".json");
        System.out.println("Writing JSON file " + jsonFile.getAbsolutePath() + " ...");
        try (FileWriter writer = new FileWriter(jsonFile)) {
            writer.write(json);/*from w w w.j  av  a 2s  .  c om*/
        }
        JSONTokener tokener = new JSONTokener(json);
        try {
            JSONObject obj = LenientJSONParser.parse(tokener);
        } catch (Exception e) {
            final int errorOffset = getOffset(tokener);
            System.out.println("Error at offset " + errorOffset);
            System.out.println(toErrorString(json, errorOffset, "HERE: " + e.getMessage()));
            e.printStackTrace();
        }
    }
}

From source file:com.google.gwt.resources.converter.Css2Gss.java

public static void main(String... args) {

    Options options = Options.parseOrQuit(args);

    if (options.singleFile) {
        try {/*from   w  w  w.java2  s.com*/
            System.out.println(
                    convertFile(options.resource, options.simpleBooleanConditions, options.scopeFiles));
            System.exit(0);
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(-1);
        }
    }

    Collection<File> filesToConvert = FileUtils.listFiles(options.resource, new String[] { "css" },
            options.recurse);

    for (File cssFile : filesToConvert) {
        try {
            if (doesCorrespondingGssFileExists(cssFile)) {
                System.out.println(
                        "GSS file already exists - will not convert, file: " + cssFile.getAbsolutePath());
                continue;
            }
            String gss = convertFile(cssFile, options.simpleBooleanConditions, options.scopeFiles);
            writeGss(gss, cssFile);
            System.out.println("Converted " + cssFile.getAbsolutePath());
        } catch (Exception e) {
            System.err.println("Failed to convert " + cssFile.getAbsolutePath());
            e.printStackTrace();
        }
    }
}

From source file:de.uni_koblenz.jgralab.utilities.tgraphbrowser.TGraphBrowserServer.java

/**
 * Runs the server. Needed args: -w --workspace the workspace
 * //from w  w  w. j a v a2 s .  c om
 * @param args
 */
public static void main(String[] args) {
    CommandLine comLine = processCommandLineOptions(args);
    assert comLine != null;
    try {
        starttime = System.currentTimeMillis();
        String portnumber = comLine.getOptionValue("p");
        String workspacePath;

        if (comLine.hasOption("r")) {
            TwoDVisualizer.PRINT_ROLE_NAMES = true;
        }

        if (comLine.hasOption("w")) {
            workspacePath = comLine.getOptionValue("w");
        } else {
            File workspace = new File(System.getProperty("java.io.tmpdir") + File.separator + "tgraphbrowser");
            if (!workspace.exists()) {
                if (!workspace.mkdir()) {
                    logger.info("The temp folder " + workspace.getAbsolutePath() + " could not be created.");
                }
            }
            workspace = new File(workspace.getAbsoluteFile() + File.separator + "workspace");
            if (!workspace.exists()) {
                if (!workspace.mkdir()) {
                    logger.info(
                            "The default workspace " + workspace.getAbsolutePath() + " could not be created.");
                }
            }
            workspacePath = workspace.getAbsolutePath();
        }
        new TGraphBrowserServer(portnumber == null ? DEFAULT_PORT : Integer.parseInt(portnumber), workspacePath,
                comLine.getOptionValue("m"), comLine.getOptionValue("s")).start();
        if (comLine.getOptionValue("ic") != null) {
            TabularVisualizer.NUMBER_OF_INCIDENCES_PER_PAGE = Math
                    .max(Integer.parseInt(comLine.getOptionValue("ic")), 1);
        }
        if (comLine.hasOption("d")) {
            StateRepository.dot = comLine.getOptionValue("d");
        } else {
            System.out.println("The 2D-Visualization is disabled because parameter -d is not set.");
        }
        String timeout = comLine.getOptionValue("t");
        String checkIntervall = comLine.getOptionValue("i");
        new DeleteUnusedStates(timeout == null ? 600 : Integer.parseInt(timeout),
                checkIntervall == null ? 60 : Integer.parseInt(checkIntervall)).start();
        if (comLine.hasOption("td")) {
            TwoDVisualizer.SECONDS_TO_WAIT_FOR_DOT = Integer.parseInt(comLine.getOptionValue("td"));
        }
    } catch (IOException e) {
        System.out.println(e);
    }
}

From source file:DIA_Umpire_Quant.DIA_Umpire_ExtLibSearch.java

/**
 * @param args the command line arguments
 *///from   w  ww .  j  a v  a 2 s .com
public static void main(String[] args) throws FileNotFoundException, IOException, Exception {
    System.out.println(
            "=================================================================================================");
    System.out.println("DIA-Umpire targeted re-extraction analysis using external library (version: "
            + UmpireInfo.GetInstance().Version + ")");
    if (args.length != 1) {
        System.out.println(
                "command format error, the correct format should be: java -jar -Xmx10G DIA_Umpire_ExtLibSearch.jar diaumpire_module.params");
        return;
    }
    try {
        ConsoleLogger.SetConsoleLogger(Level.INFO);
        ConsoleLogger.SetFileLogger(Level.DEBUG,
                FilenameUtils.getFullPath(args[0]) + "diaumpire_extlibsearch.log");
    } catch (Exception e) {
    }

    Logger.getRootLogger().info("Version: " + UmpireInfo.GetInstance().Version);
    Logger.getRootLogger().info("Parameter file:" + args[0]);

    BufferedReader reader = new BufferedReader(new FileReader(args[0]));
    String line = "";
    String WorkFolder = "";
    int NoCPUs = 2;

    String ExternalLibPath = "";
    String ExternalLibDecoyTag = "DECOY";

    float ExtProbThreshold = 0.99f;
    float RTWindow_Ext = -1f;

    TandemParam tandemPara = new TandemParam(DBSearchParam.SearchInstrumentType.TOF5600);
    HashMap<String, File> AssignFiles = new HashMap<>();

    //<editor-fold defaultstate="collapsed" desc="Reading parameter file">
    while ((line = reader.readLine()) != null) {
        line = line.trim();
        Logger.getRootLogger().info(line);
        if (!"".equals(line) && !line.startsWith("#")) {
            //System.out.println(line);
            if (line.equals("==File list begin")) {
                do {
                    line = reader.readLine();
                    line = line.trim();
                    if (line.equals("==File list end")) {
                        continue;
                    } else if (!"".equals(line)) {
                        File newfile = new File(line);
                        if (newfile.exists()) {
                            AssignFiles.put(newfile.getAbsolutePath(), newfile);
                        } else {
                            Logger.getRootLogger().info("File: " + newfile + " does not exist.");
                        }
                    }
                } while (!line.equals("==File list end"));
            }
            if (line.split("=").length < 2) {
                continue;
            }
            String type = line.split("=")[0].trim();
            String value = line.split("=")[1].trim();
            switch (type) {

            case "Path": {
                WorkFolder = value;
                break;
            }
            case "path": {
                WorkFolder = value;
                break;
            }
            case "Thread": {
                NoCPUs = Integer.parseInt(value);
                break;
            }
            case "Fasta": {
                tandemPara.FastaPath = value;
                break;
            }
            case "DecoyPrefix": {
                if (!"".equals(value)) {
                    tandemPara.DecoyPrefix = value;
                }
                break;
            }
            case "ExternalLibPath": {
                ExternalLibPath = value;
                break;
            }
            case "ExtProbThreshold": {
                ExtProbThreshold = Float.parseFloat(value);
                break;
            }
            case "RTWindow_Ext": {
                RTWindow_Ext = Float.parseFloat(value);
                break;
            }
            case "ExternalLibDecoyTag": {
                ExternalLibDecoyTag = value;
                if (ExternalLibDecoyTag.endsWith("_")) {
                    ExternalLibDecoyTag = ExternalLibDecoyTag.substring(0, ExternalLibDecoyTag.length() - 1);
                }
                break;
            }
            }
        }
    }
    //</editor-fold>

    //Initialize PTM manager using compomics library
    PTMManager.GetInstance();

    //Check if the fasta file can be found
    if (!new File(tandemPara.FastaPath).exists()) {
        Logger.getRootLogger().info("Fasta file :" + tandemPara.FastaPath
                + " cannot be found, the process will be terminated, please check.");
        System.exit(1);
    }

    //Generate DIA file list
    ArrayList<DIAPack> FileList = new ArrayList<>();

    File folder = new File(WorkFolder);
    if (!folder.exists()) {
        Logger.getRootLogger().info("The path : " + WorkFolder + " cannot be found.");
        System.exit(1);
    }
    for (final File fileEntry : folder.listFiles()) {
        if (fileEntry.isFile()
                && (fileEntry.getAbsolutePath().toLowerCase().endsWith(".mzxml")
                        | fileEntry.getAbsolutePath().toLowerCase().endsWith(".mzml"))
                && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q1.mzxml")
                && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q2.mzxml")
                && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q3.mzxml")) {
            AssignFiles.put(fileEntry.getAbsolutePath(), fileEntry);
        }
        if (fileEntry.isDirectory()) {
            for (final File fileEntry2 : fileEntry.listFiles()) {
                if (fileEntry2.isFile()
                        && (fileEntry2.getAbsolutePath().toLowerCase().endsWith(".mzxml")
                                | fileEntry2.getAbsolutePath().toLowerCase().endsWith(".mzml"))
                        && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q1.mzxml")
                        && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q2.mzxml")
                        && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q3.mzxml")) {
                    AssignFiles.put(fileEntry2.getAbsolutePath(), fileEntry2);
                }
            }
        }
    }

    Logger.getRootLogger().info("No. of files assigned :" + AssignFiles.size());
    for (File fileEntry : AssignFiles.values()) {
        Logger.getRootLogger().info(fileEntry.getAbsolutePath());
    }

    for (File fileEntry : AssignFiles.values()) {
        String mzXMLFile = fileEntry.getAbsolutePath();
        if (mzXMLFile.toLowerCase().endsWith(".mzxml") | mzXMLFile.toLowerCase().endsWith(".mzml")) {
            DIAPack DiaFile = new DIAPack(mzXMLFile, NoCPUs);
            Logger.getRootLogger().info(
                    "=================================================================================================");
            Logger.getRootLogger().info("Processing " + mzXMLFile);
            if (!DiaFile.LoadDIASetting()) {
                Logger.getRootLogger().info("Loading DIA setting failed, job is incomplete");
                System.exit(1);
            }
            if (!DiaFile.LoadParams()) {
                Logger.getRootLogger().info("Loading parameters failed, job is incomplete");
                System.exit(1);
            }
            Logger.getRootLogger().info("Loading identification results " + mzXMLFile + "....");

            //If the serialization file for ID file existed
            if (DiaFile.ReadSerializedLCMSID()) {
                DiaFile.IDsummary.ReduceMemoryUsage();
                DiaFile.IDsummary.FastaPath = tandemPara.FastaPath;
                FileList.add(DiaFile);
            }
        }
    }

    //<editor-fold defaultstate="collapsed" desc="Targeted re-extraction using external library">

    //External library search

    Logger.getRootLogger().info("Targeted extraction using external library");

    //Read exteranl library
    FragmentLibManager ExlibManager = FragmentLibManager.ReadFragmentLibSerialization(WorkFolder,
            FilenameUtils.getBaseName(ExternalLibPath));
    if (ExlibManager == null) {
        ExlibManager = new FragmentLibManager(FilenameUtils.getBaseName(ExternalLibPath));

        //Import traML file
        ExlibManager.ImportFragLibByTraML(ExternalLibPath, ExternalLibDecoyTag);
        //Check if there are decoy spectra
        ExlibManager.CheckDecoys();
        //ExlibManager.ImportFragLibBySPTXT(ExternalLibPath);
        ExlibManager.WriteFragmentLibSerialization(WorkFolder);
    }
    Logger.getRootLogger()
            .info("No. of peptide ions in external lib:" + ExlibManager.PeptideFragmentLib.size());
    for (DIAPack diafile : FileList) {
        if (diafile.IDsummary == null) {
            diafile.ReadSerializedLCMSID();
        }
        //Generate RT mapping
        RTMappingExtLib RTmap = new RTMappingExtLib(diafile.IDsummary, ExlibManager, diafile.GetParameter());
        RTmap.GenerateModel();
        RTmap.GenerateMappedPepIon();

        diafile.BuildStructure();
        diafile.MS1FeatureMap.ReadPeakCluster();
        diafile.GenerateMassCalibrationRTMap();
        //Perform targeted re-extraction
        diafile.TargetedExtractionQuant(false, ExlibManager, ExtProbThreshold, RTWindow_Ext);
        diafile.MS1FeatureMap.ClearAllPeaks();
        diafile.IDsummary.ReduceMemoryUsage();
        //Remove target IDs below the defined probability threshold
        diafile.IDsummary.RemoveLowProbMappedIon(ExtProbThreshold);
        diafile.ExportID();
        diafile.ClearStructure();
        Logger.getRootLogger().info("Peptide ions: " + diafile.IDsummary.GetPepIonList().size()
                + " Mapped ions: " + diafile.IDsummary.GetMappedPepIonList().size());
    }

    //</editor-fold>

    Logger.getRootLogger().info("Job done");
    Logger.getRootLogger().info(
            "=================================================================================================");

}

From source file:com.github.fritaly.svngraph.SvnGraph.java

public static void main(String[] args) throws Exception {
    if (args.length != 2) {
        System.out.println(String.format("%s <input-file> <output-file>", SvnGraph.class.getSimpleName()));
        System.exit(1);/*from ww  w.  java 2s.c o m*/
    }

    final File input = new File(args[0]);

    if (!input.exists()) {
        throw new IllegalArgumentException(
                String.format("The given file '%s' doesn't exist", input.getAbsolutePath()));
    }

    final File output = new File(args[1]);

    final Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(input);

    final History history = new History(document);

    final Set<String> rootPaths = history.getRootPaths();

    System.out.println(rootPaths);

    for (String path : rootPaths) {
        System.out.println(path);
        System.out.println(history.getHistory(path).getRevisions());
        System.out.println();
    }

    int count = 0;

    FileWriter fileWriter = null;
    GraphMLWriter graphWriter = null;

    try {
        fileWriter = new FileWriter(output);

        graphWriter = new GraphMLWriter(fileWriter);

        final NodeStyle tagStyle = graphWriter.getNodeStyle();
        tagStyle.setFillColor(Color.WHITE);

        graphWriter.graph();

        // map associating node labels to their corresponding node id in the graph
        final Map<String, String> nodeIdsPerLabel = new TreeMap<>();

        // the node style associated to each branch
        final Map<String, NodeStyle> nodeStyles = new TreeMap<>();

        for (Revision revision : history.getSignificantRevisions()) {
            System.out.println(revision.getNumber() + " - " + revision.getMessage());

            // TODO Render also the deletion of branches
            // there should be only 1 significant update per revision (the one with action ADD)
            for (Update update : revision.getSignificantUpdates()) {
                if (update.isCopy()) {
                    // a merge is also considered a copy
                    final RevisionPath source = update.getCopySource();

                    System.out.println(String.format("  > %s %s from %s@%d", update.getAction(),
                            update.getPath(), source.getPath(), source.getRevision()));

                    final String sourceRoot = Utils.getRootName(source.getPath());

                    if (sourceRoot == null) {
                        // skip the revisions whose associated root is
                        // null (happens whether a branch was created
                        // outside the 'branches' directory for
                        // instance)
                        System.err.println(String.format("Skipped revision %d because of a null root",
                                source.getRevision()));
                        continue;
                    }

                    final String sourceLabel = computeNodeLabel(sourceRoot, source.getRevision());

                    // create a node for the source (path, revision)
                    final String sourceId;

                    if (nodeIdsPerLabel.containsKey(sourceLabel)) {
                        // retrieve the id of the existing node
                        sourceId = nodeIdsPerLabel.get(sourceLabel);
                    } else {
                        // create the new node
                        if (Utils.isTagPath(source.getPath())) {
                            graphWriter.setNodeStyle(tagStyle);
                        } else {
                            if (!nodeStyles.containsKey(sourceRoot)) {
                                final NodeStyle style = new NodeStyle();
                                style.setFillColor(randomColor());

                                nodeStyles.put(sourceRoot, style);
                            }

                            graphWriter.setNodeStyle(nodeStyles.get(sourceRoot));
                        }

                        sourceId = graphWriter.node(sourceLabel);

                        nodeIdsPerLabel.put(sourceLabel, sourceId);
                    }

                    // and another for the newly created directory
                    final String targetRoot = Utils.getRootName(update.getPath());

                    if (targetRoot == null) {
                        System.err.println(String.format("Skipped revision %d because of a null root",
                                revision.getNumber()));
                        continue;
                    }

                    final String targetLabel = computeNodeLabel(targetRoot, revision.getNumber());

                    if (Utils.isTagPath(update.getPath())) {
                        graphWriter.setNodeStyle(tagStyle);
                    } else {
                        if (!nodeStyles.containsKey(targetRoot)) {
                            final NodeStyle style = new NodeStyle();
                            style.setFillColor(randomColor());

                            nodeStyles.put(targetRoot, style);
                        }

                        graphWriter.setNodeStyle(nodeStyles.get(targetRoot));
                    }

                    final String targetId;

                    if (nodeIdsPerLabel.containsKey(targetLabel)) {
                        // retrieve the id of the existing node
                        targetId = nodeIdsPerLabel.get(targetLabel);
                    } else {
                        // create the new node
                        if (Utils.isTagPath(update.getPath())) {
                            graphWriter.setNodeStyle(tagStyle);
                        } else {
                            if (!nodeStyles.containsKey(targetRoot)) {
                                final NodeStyle style = new NodeStyle();
                                style.setFillColor(randomColor());

                                nodeStyles.put(targetRoot, style);
                            }

                            graphWriter.setNodeStyle(nodeStyles.get(targetRoot));
                        }

                        targetId = graphWriter.node(targetLabel);

                        nodeIdsPerLabel.put(targetLabel, targetId);
                    }

                    // create an edge between the 2 nodes
                    graphWriter.edge(sourceId, targetId);
                } else {
                    System.out.println(String.format("  > %s %s", update.getAction(), update.getPath()));
                }
            }

            System.out.println();

            count++;
        }

        // Dispatch the revisions per corresponding branch
        final Map<String, Set<Long>> revisionsPerBranch = new TreeMap<>();

        for (String nodeLabel : nodeIdsPerLabel.keySet()) {
            if (nodeLabel.contains("@")) {
                final String branchName = StringUtils.substringBefore(nodeLabel, "@");
                final long revision = Long.parseLong(StringUtils.substringAfter(nodeLabel, "@"));

                if (!revisionsPerBranch.containsKey(branchName)) {
                    revisionsPerBranch.put(branchName, new TreeSet<Long>());
                }

                revisionsPerBranch.get(branchName).add(revision);
            } else {
                throw new IllegalStateException(nodeLabel);
            }
        }

        // Recreate the missing edges between revisions from a same branch
        for (String branchName : revisionsPerBranch.keySet()) {
            final List<Long> branchRevisions = new ArrayList<>(revisionsPerBranch.get(branchName));

            for (int i = 0; i < branchRevisions.size() - 1; i++) {
                final String nodeLabel1 = String.format("%s@%d", branchName, branchRevisions.get(i));
                final String nodeLabel2 = String.format("%s@%d", branchName, branchRevisions.get(i + 1));

                graphWriter.edge(nodeIdsPerLabel.get(nodeLabel1), nodeIdsPerLabel.get(nodeLabel2));
            }
        }

        graphWriter.closeGraph();

        System.out.println(String.format("Found %d significant revisions", count));
    } finally {
        if (graphWriter != null) {
            graphWriter.close();
        }
        if (fileWriter != null) {
            fileWriter.close();
        }
    }

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

From source file:net.orzo.App.java

/**
 *
 *//*from w w w . j  a  v a2 s .c  o  m*/
public static void main(final String[] args) {
    final App app = new App();
    Logger log = null;
    CommandLine cmd;

    try {
        cmd = app.init(args);

        if (cmd.hasOption("h")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp(
                    "orzo [options] user_script [user_arg1 [user_arg2 [...]]]\n(to generate a template: orzo -t [file path])",
                    app.cliOptions);

        } else if (cmd.hasOption("v")) {
            System.out.printf("Orzo.js version %s\n", app.props.get("orzo.version"));

        } else if (cmd.hasOption("t")) {
            String templateSrc = new ResourceLoader().getResourceAsString("net/orzo/template1.js");

            File tplFile = new File(cmd.getOptionValue("t"));
            FileWriter tplWriter = new FileWriter(tplFile);
            tplWriter.write(templateSrc);
            tplWriter.close();

            File dtsFile = new File(
                    String.format("%s/orzojs.d.ts", new File(tplFile.getAbsolutePath()).getParent()));
            FileWriter dtsWriter = new FileWriter(dtsFile);
            String dtsSrc = new ResourceLoader().getResourceAsString("net/orzo/orzojs.d.ts");
            dtsWriter.write(dtsSrc);
            dtsWriter.close();

        } else if (cmd.hasOption("T")) {
            String templateSrc = new ResourceLoader().getResourceAsString("net/orzo/template1.js");
            System.out.println(templateSrc);

        } else {

            // Logger initialization
            if (cmd.hasOption("g")) {
                System.setProperty("logback.configurationFile", cmd.getOptionValue("g"));

            } else {
                System.setProperty("logback.configurationFile", "./logback.xml");
            }
            log = LoggerFactory.getLogger(App.class);
            if (cmd.hasOption("s")) { // Orzo.js as a REST and AMQP service
                FullServiceConfig conf = new Gson().fromJson(new FileReader(cmd.getOptionValue("s")),
                        FullServiceConfig.class);
                Injector injector = Guice.createInjector(new CoreModule(conf), new RestServletModule());
                HttpServer httpServer = new HttpServer(conf, new JerseyGuiceServletConfig(injector));
                app.services.add(httpServer);

                if (conf.getAmqpResponseConfig() != null) {
                    // response AMQP service must be initialized before receiving one
                    app.services.add(injector.getInstance(AmqpResponseConnection.class));
                }

                if (conf.getAmqpConfig() != null) {
                    app.services.add(injector.getInstance(AmqpConnection.class));
                    app.services.add(injector.getInstance(AmqpService.class));
                }

                if (conf.getRedisConf() != null) {
                    app.services.add(injector.getInstance(RedisStorage.class));
                }

                Runtime.getRuntime().addShutdownHook(new ShutdownHook(app));
                app.startServices();

            } else if (cmd.hasOption("d")) { // Demo mode
                final String scriptId = "demo";
                final SourceCode demoScript = SourceCode.fromResource(DEMO_SCRIPT);
                System.err.printf("Running demo script %s.", demoScript.getName());
                CmdConfig conf = new CmdConfig(scriptId, demoScript, null, cmd.getOptionValue("p", null));
                TaskManager tm = new TaskManager(conf);
                tm.startTaskSync(tm.registerTask(scriptId, new String[0]));

            } else if (cmd.getArgs().length > 0) { // Command line mode
                File userScriptFile = new File(cmd.getArgs()[0]);
                String optionalModulesPath = null;
                String[] inputValues;
                SourceCode userScript;

                // custom CommonJS modules path
                if (cmd.hasOption("m")) {
                    optionalModulesPath = cmd.getOptionValue("m");
                }

                if (cmd.getArgs().length > 0) {
                    inputValues = Arrays.copyOfRange(cmd.getArgs(), 1, cmd.getArgs().length);
                } else {
                    inputValues = new String[0];
                }

                userScript = SourceCode.fromFile(userScriptFile);
                CmdConfig conf = new CmdConfig(userScript.getName(), userScript, optionalModulesPath,
                        cmd.getOptionValue("p", null));
                TaskManager tm = new TaskManager(conf);
                String taskId = tm.registerTask(userScript.getName(), inputValues);
                tm.startTaskSync(taskId);
                if (tm.getTask(taskId).getStatus() == TaskStatus.ERROR) {
                    tm.getTask(taskId).getFirstError().getErrors().stream().forEach(System.err::println);
                }

            } else {
                System.err.println("Invalid parameters. Try -h for more information.");
                System.exit(1);
            }
        }

    } catch (Exception ex) {
        System.err.printf("Orzo.js crashed with error: %s\nSee the log for details.\n", ex.getMessage());
        if (log != null) {
            log.error(ex.getMessage(), ex);

        } else {
            ex.printStackTrace();
        }
    }
}

From source file:de.alpharogroup.scheduler.system.ApplicationJettyRunner.java

/**
 * The main method starts a jetty server with the rest services for the resource-bundle-data.
 *
 * @param args/*from   w w w  . ja va 2  s  .  com*/
 *            the arguments
 * @throws Exception
 *             the exception
 */
public static void main(final String[] args) throws Exception {
    final int sessionTimeout = 1800;// set timeout to 30min(60sec * 30min=1800sec)...
    final String projectname = getProjectName();
    final File projectDirectory = PathFinder.getProjectDirectory();
    final File webapp = PathFinder.getRelativePath(projectDirectory, projectname, "src", "main", "webapp");

    final String filterPath = "/*";

    final File logfile = new File(projectDirectory, "application.log");
    if (logfile.exists()) {
        try {
            DeleteFileExtensions.delete(logfile);
        } catch (final IOException e) {
            Logger.getRootLogger().error("logfile could not deleted.", e);
        }
    }
    // Add a file appender to the logger programatically
    LoggerExtensions.addFileAppender(Logger.getRootLogger(),
            LoggerExtensions.newFileAppender(logfile.getAbsolutePath()));

    final ServletContextHandler servletContextHandler = ServletContextHandlerFactory
            .getNewServletContextHandler(ServletContextHandlerConfiguration.builder()
                    .servletHolderConfiguration(ServletHolderConfiguration.builder()
                            .servletClass(CXFServlet.class).pathSpec(filterPath).build())
                    .contextPath("/").webapp(webapp).maxInactiveInterval(sessionTimeout).filterPath(filterPath)
                    .initParameter("contextConfigLocation", "classpath:application-context.xml").build());
    servletContextHandler.addEventListener(new ContextLoaderListener());
    final Jetty9RunConfiguration configuration = Jetty9RunConfiguration.builder()
            .servletContextHandler(servletContextHandler).httpPort(8080).httpsPort(8443).build();
    final Server server = new Server();
    Jetty9Runner.runServletContextHandler(server, configuration);

}

From source file:de.alpharogroup.message.system.ApplicationJettyRunner.java

/**
 * The main method starts a jetty server with the rest services for the resource-bundle-data.
 *
 * @param args/*from ww w  . ja v  a  2s .com*/
 *            the arguments
 * @throws Exception
 *             the exception
 */
public static void main(final String[] args) throws Exception {
    final int sessionTimeout = 1800;// set timeout to 30min(60sec *
    // 30min=1800sec)...
    final String projectname = getProjectName();
    final File projectDirectory = PathFinder.getProjectDirectory();
    final File webapp = PathFinder.getRelativePath(projectDirectory, projectname, "src", "main", "webapp");

    final String filterPath = "/*";

    final File logfile = new File(projectDirectory, "application.log");
    if (logfile.exists()) {
        try {
            DeleteFileExtensions.delete(logfile);
        } catch (final IOException e) {
            Logger.getRootLogger().error("logfile could not deleted.", e);
        }
    }
    // Add a file appender to the logger programatically
    LoggerExtensions.addFileAppender(Logger.getRootLogger(),
            LoggerExtensions.newFileAppender(logfile.getAbsolutePath()));

    final ServletContextHandler servletContextHandler = ServletContextHandlerFactory
            .getNewServletContextHandler(ServletContextHandlerConfiguration.builder()
                    .servletHolderConfiguration(ServletHolderConfiguration.builder()
                            .servletClass(CXFServlet.class).pathSpec(filterPath).build())
                    .contextPath("/").webapp(webapp).maxInactiveInterval(sessionTimeout).filterPath(filterPath)
                    .initParameter("contextConfigLocation", "classpath:application-context.xml").build());
    servletContextHandler.addEventListener(new ContextLoaderListener());
    final Jetty9RunConfiguration configuration = Jetty9RunConfiguration.builder()
            .servletContextHandler(servletContextHandler).httpPort(8080).httpsPort(8443).build();
    final Server server = new Server();
    Jetty9Runner.runServletContextHandler(server, configuration);

}