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:de.tudarmstadt.ukp.experiments.dip.wp1.documents.Step6HITPreparator.java

public static void main(String[] args) throws Exception {
    // input dir - list of xml query containers
    // step5-linguistic-annotation/
    System.err.println("Starting step 6 HIT Preparation");

    File inputDir = new File(args[0]);

    // output dir
    File outputDir = new File(args[1]);
    if (outputDir.exists()) {
        outputDir.delete();//w  w  w  .  ja v a2s .c o  m
    }
    outputDir.mkdir();

    List<String> queries = new ArrayList<>();

    // iterate over query containers
    int countClueWeb = 0;
    int countSentence = 0;
    for (File f : FileUtils.listFiles(inputDir, new String[] { "xml" }, false)) {
        QueryResultContainer queryResultContainer = QueryResultContainer
                .fromXML(FileUtils.readFileToString(f, "utf-8"));
        if (queries.contains(f.getName()) || queries.size() == 0) {
            // groups contain only non-empty documents
            Map<Integer, List<QueryResultContainer.SingleRankedResult>> groups = new HashMap<>();

            // split to groups according to number of sentences
            for (QueryResultContainer.SingleRankedResult rankedResult : queryResultContainer.rankedResults) {
                if (rankedResult.originalXmi != null) {
                    byte[] bytes = new BASE64Decoder()
                            .decodeBuffer(new ByteArrayInputStream(rankedResult.originalXmi.getBytes()));
                    JCas jCas = JCasFactory.createJCas();
                    XmiCasDeserializer.deserialize(new ByteArrayInputStream(bytes), jCas.getCas());

                    Collection<Sentence> sentences = JCasUtil.select(jCas, Sentence.class);

                    int groupId = sentences.size() / 40;
                    if (rankedResult.originalXmi == null) {
                        System.err.println("Empty document: " + rankedResult.clueWebID);
                    } else {
                        if (!groups.containsKey(groupId)) {
                            groups.put(groupId, new ArrayList<>());

                        }
                    }
                    //handle it
                    groups.get(groupId).add(rankedResult);
                    countClueWeb++;
                }
            }

            for (Map.Entry<Integer, List<QueryResultContainer.SingleRankedResult>> entry : groups.entrySet()) {
                Integer groupId = entry.getKey();
                List<QueryResultContainer.SingleRankedResult> rankedResults = entry.getValue();

                // make sure the results are sorted
                // DEBUG
                //                for (QueryResultContainer.SingleRankedResult r : rankedResults) {
                //                    System.out.print(r.rank + "\t");
                //                }

                Collections.sort(rankedResults, (o1, o2) -> o1.rank.compareTo(o2.rank));

                // iterate over results for one query and group
                for (int i = 0; i < rankedResults.size() && i < TOP_RESULTS_PER_GROUP; i++) {
                    QueryResultContainer.SingleRankedResult rankedResult = rankedResults.get(i);

                    QueryResultContainer.SingleRankedResult r = rankedResults.get(i);
                    int rank = r.rank;
                    MustacheFactory mf = new DefaultMustacheFactory();
                    Mustache mustache = mf.compile("template/template.html");
                    String queryId = queryResultContainer.qID;
                    String query = queryResultContainer.query;
                    // make the first letter uppercase
                    query = query.substring(0, 1).toUpperCase() + query.substring(1);

                    List<String> relevantInformationExamples = queryResultContainer.relevantInformationExamples;
                    List<String> irrelevantInformationExamples = queryResultContainer.irrelevantInformationExamples;
                    byte[] bytes = new BASE64Decoder()
                            .decodeBuffer(new ByteArrayInputStream(rankedResult.originalXmi.getBytes()));

                    JCas jCas = JCasFactory.createJCas();
                    XmiCasDeserializer.deserialize(new ByteArrayInputStream(bytes), jCas.getCas());

                    List<generators.Sentence> sentences = new ArrayList<>();
                    List<Integer> paragraphs = new ArrayList<>();
                    paragraphs.add(0);

                    for (WebParagraph webParagraph : JCasUtil.select(jCas, WebParagraph.class)) {
                        for (Sentence s : JCasUtil.selectCovered(Sentence.class, webParagraph)) {

                            String sentenceBegin = String.valueOf(s.getBegin());
                            generators.Sentence sentence = new generators.Sentence(s.getCoveredText(),
                                    sentenceBegin);
                            sentences.add(sentence);
                            countSentence++;
                        }
                        int SentenceID = paragraphs.get(paragraphs.size() - 1);
                        if (sentences.size() > 120)
                            while (SentenceID < sentences.size()) {
                                if (!paragraphs.contains(SentenceID))
                                    paragraphs.add(SentenceID);
                                SentenceID = SentenceID + 120;
                            }
                        paragraphs.add(sentences.size());

                    }
                    System.err.println("Output dir: " + outputDir);
                    int startID = 0;
                    int endID;

                    for (int j = 0; j < paragraphs.size(); j++) {

                        endID = paragraphs.get(j);
                        int sentLength = endID - startID;
                        if (sentLength > 120 || j == paragraphs.size() - 1) {
                            if (sentLength > 120) {

                                endID = paragraphs.get(j - 1);
                                j--;
                            }
                            sentLength = endID - startID;
                            if (sentLength <= 40)
                                groupId = 40;
                            else if (sentLength <= 80 && sentLength > 40)
                                groupId = 80;
                            else if (sentLength > 80)
                                groupId = 120;

                            File folder = new File(outputDir + "/" + groupId);
                            if (!folder.exists()) {
                                System.err.println("creating directory: " + outputDir + "/" + groupId);
                                boolean result = false;

                                try {
                                    folder.mkdir();
                                    result = true;
                                } catch (SecurityException se) {
                                    //handle it
                                }
                                if (result) {
                                    System.out.println("DIR created");
                                }
                            }

                            String newHtmlFile = folder.getAbsolutePath() + "/" + f.getName() + "_"
                                    + rankedResult.clueWebID + "_" + sentLength + ".html";
                            System.err.println("Printing a file: " + newHtmlFile);
                            File newHTML = new File(newHtmlFile);
                            int t = 0;
                            while (newHTML.exists()) {
                                newHTML = new File(folder.getAbsolutePath() + "/" + f.getName() + "_"
                                        + rankedResult.clueWebID + "_" + sentLength + "." + t + ".html");
                                t++;
                            }
                            mustache.execute(new PrintWriter(new FileWriter(newHTML)),
                                    new generators(query, relevantInformationExamples,
                                            irrelevantInformationExamples, sentences.subList(startID, endID),
                                            queryId, rank))
                                    .flush();
                            startID = endID;
                        }
                    }
                }
            }

        }
    }
    System.out.println("Printed " + countClueWeb + " documents with " + countSentence + " sentences");
}

From source file:me.timothy.ddd.DrunkDuckDispatch.java

License:asdf

public static void main(String[] args) throws LWJGLException {
    try {// w w  w. j ava 2 s  . c  o m
        float defaultDisplayWidth = SizeScaleSystem.EXPECTED_WIDTH / 2;
        float defaultDisplayHeight = SizeScaleSystem.EXPECTED_HEIGHT / 2;
        boolean fullscreen = false, defaultDisplay = !fullscreen;
        File resolutionInfo = new File("graphics.json");

        if (resolutionInfo.exists()) {
            try (FileReader fr = new FileReader(resolutionInfo)) {
                JSONObject obj = (JSONObject) new JSONParser().parse(fr);
                Set<?> keys = obj.keySet();
                for (Object o : keys) {
                    if (o instanceof String) {
                        String key = (String) o;
                        switch (key.toLowerCase()) {
                        case "width":
                            defaultDisplayWidth = JSONCompatible.getFloat(obj, key);
                            break;
                        case "height":
                            defaultDisplayHeight = JSONCompatible.getFloat(obj, key);
                            break;
                        case "fullscreen":
                            fullscreen = JSONCompatible.getBoolean(obj, key);
                            defaultDisplay = !fullscreen;
                            break;
                        }
                    }
                }
            } catch (IOException | ParseException e) {
                e.printStackTrace();
            }
            float expHeight = defaultDisplayWidth
                    * (SizeScaleSystem.EXPECTED_HEIGHT / SizeScaleSystem.EXPECTED_WIDTH);
            float expWidth = defaultDisplayHeight
                    * (SizeScaleSystem.EXPECTED_WIDTH / SizeScaleSystem.EXPECTED_HEIGHT);
            if (Math.round(defaultDisplayWidth) != Math.round(expWidth)) {
                if (defaultDisplayHeight < expHeight) {
                    System.err.printf("%f x %f is an invalid resolution; adjusting to %f x %f\n",
                            defaultDisplayWidth, defaultDisplayHeight, defaultDisplayWidth, expHeight);
                    defaultDisplayHeight = expHeight;
                } else {
                    System.err.printf("%f x %f is an invalid resolution; adjusting to %f x %f\n",
                            defaultDisplayWidth, defaultDisplayHeight, expWidth, defaultDisplayHeight);
                    defaultDisplayWidth = expWidth;
                }
            }
        }
        File dir = null;
        String os = getOS();
        if (os.equals("windows")) {
            dir = new File(System.getenv("APPDATA"), "timgames/");
        } else {
            dir = new File(System.getProperty("user.home"), ".timgames/");
        }
        File lwjglDir = new File(dir, "lwjgl-2.9.1/");
        Resources.init();
        Resources.downloadIfNotExists(lwjglDir, "lwjgl-2.9.1.zip", "http://umad-barnyard.com/lwjgl-2.9.1.zip",
                "Necessary LWJGL natives couldn't be found, I can attempt "
                        + "to download it, but I make no promises",
                "Unfortunately I was unable to download it, so I'll open up the "
                        + "link to the official download. Make sure you get LWJGL version 2.9.1, "
                        + "and you put it at " + dir.getAbsolutePath() + "/lwjgl-2.9.1.zip",
                new Runnable() {

                    @Override
                    public void run() {
                        if (!Desktop.isDesktopSupported()) {
                            JOptionPane.showMessageDialog(null,
                                    "I couldn't " + "even do that! Download it manually and try again");
                            return;
                        }

                        try {
                            Desktop.getDesktop().browse(new URI("http://www.lwjgl.org/download.php"));
                        } catch (IOException | URISyntaxException e) {
                            JOptionPane.showMessageDialog(null,
                                    "Oh cmon.. Address is http://www.lwjgl.org/download.php, good luck");
                            System.exit(1);
                        }
                    }

                }, 5843626);

        Resources.extractIfNotFound(lwjglDir, "lwjgl-2.9.1.zip", "lwjgl-2.9.1");
        System.setProperty("org.lwjgl.librarypath",
                new File(dir, "lwjgl-2.9.1/lwjgl-2.9.1/native/" + os).getAbsolutePath()); // deal w/ it
        System.setProperty("net.java.games.input.librarypath", System.getProperty("org.lwjgl.librarypath"));

        Resources.downloadIfNotExists("entities.json", "http://umad-barnyard.com/ddd/entities.json", 16142);
        Resources.downloadIfNotExists("map.binary", "http://umad-barnyard.com/ddd/map.binary", 16142);
        Resources.downloadIfNotExists("victory.txt", "http://umad-barnyard.com/ddd/victory.txt", 168);
        Resources.downloadIfNotExists("failure.txt", "http://umad-barnyard.com/ddd/failure.txt", 321);
        File resFolder = new File("resources/");
        if (!resFolder.exists() && !new File("player-still.png").exists()) {
            Resources.downloadIfNotExists("resources.zip", "http://umad-barnyard.com/ddd/resources.zip", 54484);
            Resources.extractIfNotFound(new File("."), "resources.zip", "player-still.png");
            new File("resources.zip").delete();
        }
        File soundFolder = new File("sounds/");
        if (!soundFolder.exists()) {
            soundFolder.mkdirs();
            Resources.downloadIfNotExists("sounds/sounds.zip", "http://umad-barnyard.com/ddd/sounds.zip",
                    1984977);
            Resources.extractIfNotFound(soundFolder, "sounds.zip", "asdfasdffadasdf");
            new File(soundFolder, "sounds.zip").delete();
        }
        AppGameContainer appgc;
        ddd = new DrunkDuckDispatch();
        appgc = new AppGameContainer(ddd);
        appgc.setTargetFrameRate(60);
        appgc.setShowFPS(false);
        appgc.setAlwaysRender(true);
        if (fullscreen) {
            DisplayMode[] modes = Display.getAvailableDisplayModes();
            DisplayMode current, best = null;
            float ratio = 0f;
            for (int i = 0; i < modes.length; i++) {
                current = modes[i];
                float rX = (float) current.getWidth() / SizeScaleSystem.EXPECTED_WIDTH;
                float rY = (float) current.getHeight() / SizeScaleSystem.EXPECTED_HEIGHT;
                System.out.println(current.getWidth() + "x" + current.getHeight() + " -> " + rX + "x" + rY);
                if (rX == rY && rX > ratio) {
                    best = current;
                    ratio = rX;
                }
            }
            if (best == null) {
                System.out.println("Failed to find an appropriately scaled resolution, using default display");
                defaultDisplay = true;
            } else {
                appgc.setDisplayMode(best.getWidth(), best.getHeight(), true);
                SizeScaleSystem.setRealHeight(best.getHeight());
                SizeScaleSystem.setRealWidth(best.getWidth());
                System.out.println("I choose " + best.getWidth() + "x" + best.getHeight());
            }
        }

        if (defaultDisplay) {
            SizeScaleSystem.setRealWidth(Math.round(defaultDisplayWidth));
            SizeScaleSystem.setRealHeight(Math.round(defaultDisplayHeight));
            appgc.setDisplayMode(Math.round(defaultDisplayWidth), Math.round(defaultDisplayHeight), false);
        }
        ddd.logger.info(
                "SizeScaleSystem: " + SizeScaleSystem.getRealWidth() + "x" + SizeScaleSystem.getRealHeight());
        appgc.start();
    } catch (SlickException ex) {
        LogManager.getLogger(DrunkDuckDispatch.class.getSimpleName()).catching(Level.ERROR, ex);
    }
}

From source file:com.mmounirou.spotirss.SpotiRss.java

/**
 * @param args/*from   w  ww.jav a2 s.  co  m*/
 * @throws IOException 
 * @throws ClassNotFoundException 
 * @throws IllegalAccessException 
 * @throws InstantiationException 
 * @throws SpotifyClientException 
 * @throws ChartRssException 
 * @throws SpotifyException 
 */
public static void main(String[] args) throws IOException, InstantiationException, IllegalAccessException,
        ClassNotFoundException, SpotifyClientException {
    if (args.length == 0) {
        System.err.println("usage : java -jar spotiboard.jar <charts-folder>");
        return;
    }

    Properties connProperties = new Properties();
    InputStream inStream = SpotiRss.class.getResourceAsStream("/spotify-server.properties");
    try {
        connProperties.load(inStream);
    } finally {
        IOUtils.closeQuietly(inStream);
    }

    String host = connProperties.getProperty("host");
    int port = Integer.parseInt(connProperties.getProperty("port"));
    String user = connProperties.getProperty("user");

    final SpotifyClient spotifyClient = new SpotifyClient(host, port, user);
    final Map<String, Playlist> playlistsByTitle = getPlaylistsByTitle(spotifyClient);

    final File outputDir = new File(args[0]);
    outputDir.mkdirs();
    TrackCache cache = new TrackCache();
    try {

        for (String strProvider : PROVIDERS) {
            String providerClassName = EntryToTrackConverter.class.getPackage().getName() + "."
                    + StringUtils.capitalize(strProvider);
            final EntryToTrackConverter converter = (EntryToTrackConverter) SpotiRss.class.getClassLoader()
                    .loadClass(providerClassName).newInstance();
            Iterable<String> chartsRss = getCharts(strProvider);
            final File resultDir = new File(outputDir, strProvider);
            resultDir.mkdir();

            final SpotifyHrefQuery hrefQuery = new SpotifyHrefQuery(cache);
            Iterable<String> results = FluentIterable.from(chartsRss).transform(new Function<String, String>() {

                @Override
                @Nullable
                public String apply(@Nullable String chartRss) {

                    try {

                        long begin = System.currentTimeMillis();
                        ChartRss bilboardChartRss = ChartRss.getInstance(chartRss, converter);
                        Map<Track, String> trackHrefs = hrefQuery.getTrackHrefs(bilboardChartRss.getSongs());

                        String strTitle = bilboardChartRss.getTitle();
                        File resultFile = new File(resultDir, strTitle);
                        List<String> lines = Lists.newLinkedList(FluentIterable.from(trackHrefs.keySet())
                                .transform(Functions.toStringFunction()));
                        lines.addAll(trackHrefs.values());
                        FileUtils.writeLines(resultFile, Charsets.UTF_8.displayName(), lines);

                        Playlist playlist = playlistsByTitle.get(strTitle);
                        if (playlist != null) {
                            playlist.getTracks().clear();
                            playlist.getTracks().addAll(trackHrefs.values());
                            spotifyClient.patch(playlist);
                            LOGGER.info(String.format("%s chart exported patched", strTitle));
                        }

                        LOGGER.info(String.format("%s chart exported in %s in %d s", strTitle,
                                resultFile.getAbsolutePath(),
                                (int) TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - begin)));

                    } catch (Exception e) {
                        LOGGER.error(String.format("fail to export %s charts", chartRss), e);
                    }

                    return "";
                }
            });

            // consume iterables
            Iterables.size(results);

        }

    } finally {
        cache.close();
    }

}

From source file:com.servoy.extensions.plugins.http.HttpProvider.java

public static void main(String[] args) throws Exception {
    if (args.length != 3) {
        System.out.println("Use: ContentFetcher mainurl contenturl destdir"); //$NON-NLS-1$
        System.out.println(/*from  www.ja  v a2s.  com*/
                "Example: ContentFetcher http://site.com http://site.com/dir[0-2]/image_A[001-040].jpg c:/temp"); //$NON-NLS-1$
        System.out.println(
                "Result: accessing http://site.com for cookie, reading http://site.com/dir1/image_A004.jpg writing c:/temp/dir_1_image_A004.jpg"); //$NON-NLS-1$
    } else {
        String url = args[1];
        String destdir = args[2];

        List parts = new ArrayList();
        int dir_from = 0;
        int dir_to = 0;
        int dir_fill = 0;
        int from = 0;
        int to = 0;
        int fill = 0;

        StringTokenizer tk = new StringTokenizer(url, "[]", true); //$NON-NLS-1$
        boolean hasDir = (tk.countTokens() > 5);
        boolean inDir = hasDir;
        System.out.println("hasDir " + hasDir); //$NON-NLS-1$
        boolean inTag = false;
        while (tk.hasMoreTokens()) {
            String token = tk.nextToken();
            if (token.equals("[")) //$NON-NLS-1$
            {
                inTag = true;
                continue;
            }
            if (token.equals("]")) //$NON-NLS-1$
            {
                inTag = false;
                if (inDir)
                    inDir = false;
                continue;
            }
            if (inTag) {
                int idx = token.indexOf('-');
                String s_from = token.substring(0, idx);
                int a_from = new Integer(s_from).intValue();
                int a_fill = s_from.length();
                int a_to = new Integer(token.substring(idx + 1)).intValue();
                if (inDir) {
                    dir_from = a_from;
                    dir_to = a_to;
                    dir_fill = a_fill;
                } else {
                    from = a_from;
                    to = a_to;
                    fill = a_fill;
                }
            } else {
                parts.add(token);
            }
        }

        DefaultHttpClient client = new DefaultHttpClient();
        client.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
        HttpGet main = new HttpGet(args[0]);
        HttpResponse res = client.execute(main);
        ;
        int main_rs = res.getStatusLine().getStatusCode();
        if (main_rs != 200) {
            System.out.println("main page retrieval failed " + main_rs); //$NON-NLS-1$
            return;
        }

        for (int d = dir_from; d <= dir_to; d++) {
            String dir_number = "" + d; //$NON-NLS-1$
            if (dir_fill > 1) {
                dir_number = "000000" + d; //$NON-NLS-1$
                int dir_digits = (int) (Math.log(fill) / Math.log(10));
                System.out.println("dir_digits " + dir_digits); //$NON-NLS-1$
                dir_number = dir_number.substring(dir_number.length() - (dir_fill - dir_digits),
                        dir_number.length());
            }
            for (int i = from; i <= to; i++) {
                try {
                    String number = "" + i; //$NON-NLS-1$
                    if (fill > 1) {
                        number = "000000" + i; //$NON-NLS-1$
                        int digits = (int) (Math.log(fill) / Math.log(10));
                        System.out.println("digits " + digits); //$NON-NLS-1$
                        number = number.substring(number.length() - (fill - digits), number.length());
                    }
                    int part = 0;
                    StringBuffer surl = new StringBuffer((String) parts.get(part++));
                    if (hasDir) {
                        surl.append(dir_number);
                        surl.append(parts.get(part++));
                    }
                    surl.append(number);
                    surl.append(parts.get(part++));
                    System.out.println("reading url " + surl); //$NON-NLS-1$

                    int indx = surl.toString().lastIndexOf('/');
                    StringBuffer sfile = new StringBuffer(destdir);
                    sfile.append("\\"); //$NON-NLS-1$
                    if (hasDir) {
                        sfile.append("dir_"); //$NON-NLS-1$
                        sfile.append(dir_number);
                        sfile.append("_"); //$NON-NLS-1$
                    }
                    sfile.append(surl.toString().substring(indx + 1));
                    File file = new File(sfile.toString());
                    if (file.exists()) {
                        file = new File("" + System.currentTimeMillis() + sfile.toString());
                    }
                    System.out.println("write file " + file.getAbsolutePath()); //$NON-NLS-1$

                    //                  URL iurl = createURLFromString(surl.toString());
                    HttpGet get = new HttpGet(surl.toString());

                    HttpResponse response = client.execute(get);
                    int result = response.getStatusLine().getStatusCode();
                    System.out.println("page http result " + result); //$NON-NLS-1$
                    if (result == 200) {
                        InputStream is = response.getEntity().getContent();
                        FileOutputStream fos = new FileOutputStream(file);
                        Utils.streamCopy(is, fos);
                        fos.close();
                    }
                } catch (Exception e) {
                    System.err.println(e);
                }
            }
        }
    }
}

From source file:io.apiman.tools.i18n.TemplateScanner.java

public static void main(String[] args) throws IOException {
    if (args == null || args.length != 1) {
        System.out.println("Template directory not provided (no path provided).");
        System.exit(1);//w w w.  ja  v  a  2 s  . c  om
    }
    File templateDir = new File(args[0]);
    if (!templateDir.isDirectory()) {
        System.out.println("Template directory not provided (provided path is not a directory).");
        System.exit(1);
    }

    if (!new File(templateDir, "dash.html").isFile()) {
        System.out.println("Template directory not provided (dash.html not found).");
        System.exit(1);
    }

    File outputDir = new File(templateDir, "../../../../../../tools/i18n/target");
    if (!outputDir.isDirectory()) {
        System.out.println("Output directory not found: " + outputDir);
        System.exit(1);
    }
    File outputFile = new File(outputDir, "scanner-messages.properties");
    if (outputFile.isFile() && !outputFile.delete()) {
        System.out.println("Couldn't delete the old messages.properties: " + outputFile);
        System.exit(1);
    }

    System.out.println("Starting scan.");
    System.out.println("Scanning template directory: " + templateDir.getAbsolutePath());

    String[] extensions = { "html", "include" };
    Collection<File> files = FileUtils.listFiles(templateDir, extensions, true);

    TreeMap<String, String> strings = new TreeMap<>();

    for (File file : files) {
        System.out.println("\tScanning file: " + file);
        scanFile(file, strings);
    }

    outputMessages(strings, outputFile);

    System.out.println("Scan complete.  Scanned " + files.size() + " files and discovered " + strings.size()
            + " translation strings.");
}

From source file:org.yardstickframework.report.jfreechart.JFreeChartGraphPlotter.java

/**
 * @param cmdArgs Arguments./*from w  w w  . j  a  va  2s . co m*/
 */
public static void main(String[] cmdArgs) {
    try {
        JFreeChartGraphPlotterArguments args = new JFreeChartGraphPlotterArguments();

        JCommander jCommander = jcommander(cmdArgs, args, "<graph-plotter>");

        if (args.help()) {
            jCommander.usage();

            return;
        }

        if (args.inputFolders().isEmpty()) {
            errorHelp("Input folders are not defined.");

            return;
        }

        List<String> inFoldersAsString = args.inputFolders();

        List<File> inFolders = new ArrayList<>(inFoldersAsString.size());

        for (String folderAsString : inFoldersAsString)
            inFolders.add(new File(folderAsString).getAbsoluteFile());

        for (File inFolder : inFolders) {
            if (!inFolder.exists()) {
                errorHelp("Folder does not exist: " + inFolder.getAbsolutePath());

                return;
            }
        }

        List<List<List<File>>> benchFolders = new ArrayList<>();

        for (File inFolder : inFolders) {
            File[] dirs0 = inFolder.listFiles();

            if (dirs0 == null || dirs0.length == 0)
                continue;

            List<File> dirs = new ArrayList<>(Arrays.asList(dirs0));

            Collections.sort(dirs, FILE_NAME_COMP);

            boolean multipleDrivers = false;

            for (File f : dirs) {
                if (f.isFile() && MULTIPLE_DRIVERS_MARKER_FILE.equals(f.getName())) {
                    multipleDrivers = true;

                    break;
                }
            }

            List<List<File>> mulDrvFiles = new ArrayList<>();

            if (multipleDrivers) {
                for (File f : dirs) {
                    List<File> files = getFiles(f);

                    if (files != null)
                        mulDrvFiles.add(files);
                }
            } else {
                List<File> files = getFiles(inFolder);

                if (files != null)
                    mulDrvFiles.add(files);
            }

            benchFolders.add(mergeMultipleDriverLists(mulDrvFiles));
        }

        if (benchFolders.isEmpty()) {
            errorHelp("Input folders are empty or have invalid structure: " + inFoldersAsString);

            return;
        }

        String outputFolder = outputFolder(inFolders);

        JFreeChartGenerationMode mode = args.generationMode();

        if (mode == COMPOUND)
            processCompoundMode(outputFolder, benchFolders, args);
        else if (mode == COMPARISON)
            processComparisonMode(outputFolder, benchFolders, args);
        else if (mode == STANDARD)
            processStandardMode(benchFolders, args);
        else
            errorHelp("Unknown generation mode: " + args.generationMode());
    } catch (ParameterException e) {
        errorHelp("Invalid parameter.", e);
    } catch (Exception e) {
        errorHelp("Failed to execute graph generator.", e);
    }
}

From source file:org.ala.spatial.web.services.DownloadController.java

public static void main(String[] args) {

    // maxent - 1323641423144
    // aloc   - 1323844048457

    String pid = "1323844048457";

    try {// www  .  jav a  2s.c om
        File dir = sfindFile(pid);

        if (dir != null) {
            //System.out.println("Found session data: " + dir.getAbsolutePath());
            //return "Found session data: " + dir.getAbsolutePath();

            String parentName = "ALA_";
            String parentPath = dir.getParent().substring(dir.getParent().lastIndexOf("/") + 1);

            String zipfile = dir.getParent() + "/" + pid + ".zip";

            if ("maxent".equals(parentPath)) {
                fixMaxentFiles(pid, dir);
                Zipper.zipDirectory(dir.getParent() + "/temp/" + pid, zipfile);
            } else if ("layers".equals(parentPath) || "aloc".equals(parentPath)) {
                fixAlocFiles(pid, dir);
                Zipper.zipDirectory(dir.getParent() + "/temp/" + pid, zipfile);
            } else {
                Zipper.zipDirectory(dir.getAbsolutePath(), zipfile);
            }

            System.out.println(
                    "Found " + dir.getName() + " in " + dir.getParent() + " and zipped at: " + zipfile);
            //return "Found " + dir.getName() + " in " + dir.getParent() + " and zipped at: " + zipfile;

            if ("maxent".equals(parentPath)) {
                parentName = "ALA_Prediction_";
            } else if ("sampling".equals(parentPath)) {
                parentName = "ALA_Species_Samples_";
            } else if ("layers".equals(parentPath) || "aloc".equals(parentPath)) {
                parentName = "ALA_Classification_";
            } else if ("gdm".equals(parentPath)) {
                parentName = "ALA_GDM_";
            } else if ("filtering".equals(parentPath)) {
                parentName = "ALA_EnvFilter_";
            } else if ("sitesbyspecies".equals(parentPath)) {
                parentName = "ALA_SitesBySpecies_";
            }

            File file = new File(zipfile);

            System.out.println("File generated: " + file.getAbsolutePath());

        } else {
            System.out.println("Could not find session data");
            //return "Could not find session data";
        }
    } catch (Exception e) {
        e.printStackTrace(System.out);
    }
}

From source file:com.trsst.Command.java

public static void main(String[] argv) {

    // during alpha period: expire after one week
    Date builtOn = Common.getBuildDate();
    if (builtOn != null) {
        long weekMillis = 1000 * 60 * 60 * 24 * 7;
        Date expiry = new Date(builtOn.getTime() + weekMillis);
        if (new Date().after(expiry)) {
            System.err.println("Build expired on: " + expiry);
            System.err.println("Please obtain a more recent build for testing.");
            System.exit(1);//from  w  ww .  j a va  2s  .co m
        } else {
            System.err.println("Build will expire on: " + expiry);
        }
    }

    // experimental tor support
    boolean wantsTor = false;
    for (String s : argv) {
        if ("--tor".equals(s)) {
            wantsTor = true;
            break;
        }
    }
    if (wantsTor && !HAS_TOR) {
        try {
            log.info("Attempting to connect to tor network...");
            Security.addProvider(new BouncyCastleProvider());
            JvmGlobalUtil.init();
            NetLayer netLayer = NetFactory.getInstance().getNetLayerById(NetLayerIDs.TOR);
            JvmGlobalUtil.setNetLayerAndNetAddressNameService(netLayer, true);
            log.info("Connected to tor network");
            HAS_TOR = true;
        } catch (Throwable t) {
            log.error("Could not connect to tor: exiting", t);
            System.exit(1);
        }
    }

    // if unspecified, default relay to home.trsst.com
    if (System.getProperty("com.trsst.server.relays") == null) {
        System.setProperty("com.trsst.server.relays", "https://home.trsst.com/feed");
    }

    // default to user-friendlier file names
    String home = System.getProperty("user.home", ".");
    if (System.getProperty("com.trsst.client.storage") == null) {
        File client = new File(home, "Trsst Accounts");
        System.setProperty("com.trsst.client.storage", client.getAbsolutePath());
    }
    if (System.getProperty("com.trsst.server.storage") == null) {
        File server = new File(home, "Trsst System Cache");
        System.setProperty("com.trsst.server.storage", server.getAbsolutePath());
    }
    // TODO: try to detect if launching from external volume like a flash
    // drive and store on the local flash drive instead

    Console console = System.console();
    int result;
    try {
        if (console == null && argv.length == 0) {
            argv = new String[] { "serve", "--gui" };
        }
        result = new Command().doBegin(argv, System.out, System.in);

        // task queue prevents exit unless stopped
        if (TrsstAdapter.TASK_QUEUE != null) {
            TrsstAdapter.TASK_QUEUE.cancel();
        }
    } catch (Throwable t) {
        result = 1; // "general catchall error code"
        log.error("Unexpected error, exiting.", t);
    }

    // if error
    if (result != 0) {
        // force exit
        System.exit(result);
    }
}

From source file:de.prozesskraft.pkraft.PkraftPartUi1.java

/**
 * @param args/*from  w  w  w .  jav a2  s.c om*/
 */
public static void main(String[] args) {

    /*----------------------------
      get options from ini-file
    ----------------------------*/
    File inifile = new java.io.File(
            WhereAmI.getInstallDirectoryAbsolutePath(PkraftPartUi1.class) + "/" + "../etc/pkraft-gui.ini");

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

    /*----------------------------
      create boolean options
    ----------------------------*/
    Option help = new Option("help", "print this message");
    Option v = new Option("v", "prints version and build-date");
    /*----------------------------
      create argument options
    ----------------------------*/

    /*----------------------------
      create options object
    ----------------------------*/
    Options options = new Options();

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

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

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

    if (line.hasOption("v")) {
        System.err.println("author:  [% email %]");
        System.err.println("version: [% version %]");
        System.err.println("date:    [% date %]");
        System.exit(0);
    }

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

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

    // muss final sein - wird sonst beim installieren mit maven angemeckert (nicht so aus eclipse heraus)
    final MyLicense lic = new MyLicense(allPortAtHost, "1", "user-edition", "0.1");

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

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

    /*----------------------------
      other things
    ----------------------------*/
    // gui
    final Display display = new Display();

    Realm.runWithDefault(SWTObservables.getRealm(display), new Runnable() {
        public void run() {
            try {
                // SPLASHSCREEN

                //                final Image image = new Image(display, 300, 300);
                Image image = null;

                // set an image. die 2 versionen sind dazu da um von eclipse aus und in der installierten version zu funktionieren
                if (this.getClass().getResourceAsStream("/logo_beschnitten_transparent_small.png") != null) {
                    image = new Image(display,
                            this.getClass().getResourceAsStream("/logo_beschnitten_transparent_small.png"));
                } else if ((new java.io.File("logo_beschnitten_transparent_small.png")).exists()) {
                    image = new Image(display, "logo_beschnitten_transparent_small.png");
                }

                final Shell splash = new Shell(SWT.ON_TOP);
                splash.setLayout(new GridLayout(1, false));
                splash.setSize(300, 300);
                splash.setBackground(new Color(display, 255, 255, 255)); // Weiss

                Label labelImage = new Label(splash, SWT.NONE);
                labelImage.setImage(image);
                //                labelImage.setLayout(new GridLayout(1, false));
                GridData gd_labelImage = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1);
                gd_labelImage.widthHint = 300;
                gd_labelImage.minimumWidth = 300;
                //               gd_labelImage.minimumHeight = 10;
                labelImage.setLayoutData(gd_labelImage);

                Label labelZeile1 = new Label(splash, SWT.NONE | SWT.BORDER | SWT.CENTER);
                String text = "version [% version %]";
                text += "\nlicense status: " + lic.getLicense().getValidationStatus();

                switch (lic.getLicense().getValidationStatus()) {
                case LICENSE_VALID:

                    text += "\nlicensee: " + lic.getLicense().getLicenseText().getUserEMail();
                    text += "\nexpires in: "
                            + lic.getLicense().getLicenseText().getLicenseExpireDaysRemaining(null)
                            + " day(s).";
                    break;
                case LICENSE_INVALID:
                    break;
                default:
                    text += "\nno valid license found";
                }
                text += "\nsupport: support@prozesskraft.de";

                Button buttonOk = new Button(splash, SWT.NONE);
                GridData gd_buttonOk = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1);
                gd_buttonOk.widthHint = 62;
                buttonOk.setLayoutData(gd_buttonOk);
                buttonOk.setText("Ok");
                buttonOk.addSelectionListener(new SelectionAdapter() {
                    public void widgetSelected(SelectionEvent event) {
                        splash.close();
                    }
                });

                labelZeile1.setText(text);
                //                labelImage.setLayout(new GridLayout(1, false));
                GridData gd_labelZeile1 = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1);
                gd_labelZeile1.horizontalAlignment = SWT.CENTER;
                gd_labelZeile1.widthHint = 300;
                gd_labelZeile1.minimumWidth = 300;
                //               gd_labelImage.minimumHeight = 10;
                labelZeile1.setLayoutData(gd_labelZeile1);

                splash.pack();
                Rectangle splashRect = splash.getBounds();
                Rectangle displayRect = display.getBounds();
                int x = (displayRect.width - splashRect.width) / 2;
                int y = (displayRect.height - splashRect.height) / 2;
                splash.setLocation(x, y);
                splash.open();

                // DAS HAUPTFENSTER

                Shell shell = new Shell(display);
                //               shell.setSize(1200, 800);
                shell.setMaximized(true);
                shell.setText("pkraft " + "v[% version %]");

                // set an icon. die 2 versionen sind dazu da um von eclipse aus und in der installierten version zu funktionieren
                if (this.getClass().getResourceAsStream("/logoSymbol50Transp.png") != null) {
                    shell.setImage(
                            new Image(display, this.getClass().getResourceAsStream("/logoSymbol50Transp.png")));
                } else if ((new java.io.File("logoSymbol50Transp.png")).exists()) {
                    shell.setImage(new Image(display, "logoSymbol50Transp.png"));
                }

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

                try {
                    shell.open();

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

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

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

}

From source file:androidimporter.AndroidImporter.java

public static void main(String[] args) throws ParseException {
    //"/usr/local/apache-ant/bin/ant"
    String antPath = System.getProperty("ANT_PATH", System.getenv("ANT_PATH"));
    if (antPath == null || !new File(antPath).exists()) {
        throw new RuntimeException("Cannot find ant at " + antPath
                + ".  Please specify location to ant via the ANT_PATH environment variable or java system property.");
    }/*from   www.ja v a  2s.  c o m*/

    Options opts = new Options()
            .addOption("i", "android-resource-dir", true, "Android project res directory path")
            .addOption("o", "cn1-project-dir", true, "Path to the CN1 output project directory.")
            .addOption("r", "cn1-resource-file", false,
                    "Path to CN1 output .res file.  Defaults to theme.res in project dir")
            .addOption("p", "package", true, "Java package to place GUI forms in.")
            .addOption("h", "help", false, "Usage instructions");

    CommandLineParser parser = new DefaultParser();

    CommandLine line = parser.parse(opts, args);

    if (line.hasOption("help")) {
        showHelp(opts);
        System.exit(0);
    }
    args = line.getArgs();

    if (args.length < 1) {
        System.out.println("No command provided.");
        showHelp(opts);
        System.exit(0);
    }

    switch (args[0]) {
    case "import-project": {

        if (!line.hasOption("android-resource-dir") || !line.hasOption("cn1-project-dir")
                || !line.hasOption("package")) {
            System.out.println("Please provide android-resource-dir, package, and cn1-project-dir options");
            showHelp(opts);
            System.exit(1);
        }
        File resDir = findResDir(new File(line.getOptionValue("android-resource-dir")));
        if (resDir == null || !resDir.isDirectory()) {
            System.out.println("Failed to find android resource directory from provided value");
            showHelp(opts);
            System.exit(1);
        }

        File projDir = new File(line.getOptionValue("cn1-project-dir"));
        File resFile = new File(projDir, "src" + File.separator + "theme.res");
        if (line.hasOption("cn1-resource-file")) {
            resFile = new File(line.getOptionValue("cn1-resource-file"));
        }

        JavaSEPort.setShowEDTViolationStacks(false);
        JavaSEPort.setShowEDTWarnings(false);
        JFrame frm = new JFrame("Placeholder");
        frm.setVisible(false);
        Display.init(frm.getContentPane());
        JavaSEPort.setBaseResourceDir(resFile.getParentFile());
        try {
            System.out.println("About to import project at " + resDir.getAbsolutePath());
            System.out.println("Codename One Output Project: " + projDir.getAbsolutePath());
            System.out.println("Resource file: " + resFile.getAbsolutePath());
            System.out.println("Java Package: " + line.getOptionValue("package"));
            AndroidProjectImporter.importProject(resDir, projDir, resFile, line.getOptionValue("package"));
            Runtime.getRuntime().exec(new String[] { antPath, "init" }, new String[] {},
                    resFile.getParentFile().getParentFile());
            //runAnt(new File(resFile.getParentFile().getParentFile(), "build.xml"), "init");
            System.exit(0);
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            System.exit(0);
        }
        break;
    }

    default:
        System.out.println("Unknown command " + args[0]);
        showHelp(opts);
        break;

    }

}