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:edu.usf.cutr.siri.SiriParserJacksonExample.java

/**
 * Takes in a path to a JSON or XML file, parses the contents into a Siri object, 
 * and prints out the contents of the Siri object.
 * // w w w .  j a v a2 s  .c om
 * @param args path to the JSON or XML file located on disk
 */
public static void main(String[] args) {

    if (args[0] == null) {
        System.out.println("Proper Usage is: java JacksonSiriParserExample path-to-siri-file-to-parse");
        System.exit(0);
    }

    try {

        //Siri object we're going to instantiate based on JSON or XML data
        Siri siri = null;

        //Get example JSON or XML from file
        File file = new File(args[0]);

        System.out.println("Input file = " + file.getAbsolutePath());

        /*
         * Alternately, instead of passing in a File, a String encoded in JSON or XML can be
         * passed into Jackson for parsing.  Uncomment the below line to read the 
         * JSON or XML into the String.
         */
        //String inputExample = readFile(file);   

        String extension = FilenameUtils.getExtension(args[0]);

        if (extension.equalsIgnoreCase("json")) {
            System.out.println("Parsing JSON...");
            ObjectMapper mapper = null;

            try {
                mapper = (ObjectMapper) SiriUtils.readFromCache(SiriUtils.OBJECT_MAPPER);
            } catch (Exception e) {
                System.out.println("Error reading from cache: " + e);
            }

            if (mapper == null) {
                // instantiate ObjectMapper like normal if cache read failed
                mapper = new ObjectMapper();

                //Jackson 2.0 configuration settings
                mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
                mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
                mapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
                mapper.configure(DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY, true);
                mapper.configure(DeserializationFeature.READ_ENUMS_USING_TO_STRING, true);

                //Tell Jackson to expect the JSON in PascalCase, instead of camelCase
                mapper.setPropertyNamingStrategy(new PropertyNamingStrategy.PascalCaseStrategy());
            }

            //Deserialize the JSON from the file into the Siri object
            siri = mapper.readValue(file, Siri.class);

            /*
             * Alternately, you can also deserialize the JSON from a String into the Siri object.
             * Uncomment the below line to parsing the JSON from a String instead of the File.
             */
            //siri = mapper.readValue(inputExample, Siri.class);

            //Write the ObjectMapper to the cache, to speed up parsing for the next execution
            SiriUtils.forceCacheWrite(mapper);

        }

        if (extension.equalsIgnoreCase("xml")) {
            System.out.println("Parsing XML...");
            //Use Aalto StAX implementation explicitly            
            XmlFactory f = new XmlFactory(new InputFactoryImpl(), new OutputFactoryImpl());

            JacksonXmlModule module = new JacksonXmlModule();

            /**
             * Tell Jackson that Lists are using "unwrapped" style (i.e., 
             * there is no wrapper element for list). This fixes the error
             * "com.fasterxml.jackson.databind.JsonMappingException: Can not
             * >> instantiate value of type [simple type, class >>
             * uk.org.siri.siri.VehicleMonitoringDelivery] from JSON String;
             * no >> single-String constructor/factory method (through
             * reference chain: >>
             * uk.org.siri.siri.Siri["ServiceDelivery"]->
             * uk.org.siri.siri.ServiceDel >>
             * ivery["VehicleMonitoringDelivery"])"
             * 
             * NOTE - This requires Jackson v2.1
             */
            module.setDefaultUseWrapper(false);

            /**
             * Handles "xml:lang" attribute, which is used in SIRI
             * NaturalLanguage String, and looks like: <Description
             * xml:lang="EN">b/d 1:00pm until f/n. loc al and express buses
             * run w/delays & detours. POTUS visit in MANH. Allow additional
             * travel time Details at www.mta.info</Description>
             * 
             * Passing "Value" (to match expected name in XML to map,
             * considering naming strategy) will make things work. This is
             * since JAXB uses pseudo-property name of "value" for XML Text
             * segments, whereas Jackson by default uses "" (to avoid name
             * collisions).
             * 
             * NOTE - This requires Jackson v2.1
             * 
             * NOTE - This still requires a CustomPascalCaseStrategy to
             * work. Please see the CustomPascalCaseStrategy in this app
             * that is used below.
             */
            module.setXMLTextElementName("Value");

            XmlMapper xmlMapper = null;

            try {
                xmlMapper = (XmlMapper) SiriUtils.readFromCache(SiriUtils.XML_MAPPER);
            } catch (Exception e) {
                System.out.println("Error reading from cache: " + e);
            }

            if (xmlMapper == null) {
                xmlMapper = new XmlMapper(f, module);

                xmlMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
                xmlMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
                xmlMapper.configure(DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY, true);
                xmlMapper.configure(DeserializationFeature.READ_ENUMS_USING_TO_STRING, true);

                /**
                 * Tell Jackson to expect the XML in PascalCase, instead of camelCase
                 * NOTE:  We need the CustomPascalStrategy here to handle XML 
                 * namespace attributes such as xml:lang.  See the comments in 
                 * CustomPascalStrategy for details.
                 */
                xmlMapper.setPropertyNamingStrategy(new CustomPascalCaseStrategy());
            }

            //Parse the SIRI XML response            
            siri = xmlMapper.readValue(file, Siri.class);

            //Write the XmlMapper to the cache, to speed up parsing for the next execution
            SiriUtils.forceCacheWrite(xmlMapper);
        }

        //If we successfully retrieved and parsed JSON or XML, print the contents
        if (siri != null) {
            SiriUtils.printContents(siri);
        }

    } catch (IOException e) {
        System.err.println("Error reading or parsing input file: " + e);
    }

}

From source file:com.linkedin.python.importer.ImporterCLI.java

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

    Options options = createOptions();//from w  w  w.j a v  a  2 s  .c o  m

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

    if (line.hasOption("quite")) {
        Logger root = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
        root.setLevel(Level.WARN);
    }

    final File repoPath = new File(line.getOptionValue("repo"));
    final DependencySubstitution replacements = new DependencySubstitution(buildSubstitutionMap(line));

    repoPath.mkdirs();

    if (!repoPath.exists() || !repoPath.isDirectory()) {
        throw new RuntimeException(
                "Unable to continue, " + repoPath.getAbsolutePath() + " does not exist, or is not a directory");
    }

    for (String dependency : line.getArgList()) {
        new DependencyDownloader(dependency, repoPath, replacements).download();
    }

    logger.info("Execution Finished!");
}

From source file:com.moss.appsnap.server.AppSnapServer.java

public static void main(String[] args) throws Exception {
    System.setProperty("org.mortbay.log.class", Slf4jLog.class.getName());

    File log4jConfigFile = new File("log4j.xml");

    if (log4jConfigFile.exists()) {
        DOMConfigurator.configureAndWatch(log4jConfigFile.getAbsolutePath(), 1000);
    } else {//from   w ww  .  j  a  va  2s  . c o m
        BasicConfigurator.configure();
        Logger.getRootLogger().setLevel(Level.INFO);
    }

    ServerConfiguration config;

    JAXBContext context = JAXBContext.newInstance(ServerConfiguration.class, VeracityId.class);
    JAXBHelper helper = new JAXBHelper(context);

    Logger log = Logger.getLogger(AppSnapServer.class);

    File[] configPaths = new File[] { new File("settings.xml"),
            new File(new File(System.getProperty("user.home")), ".appsnap-server.xml"),
            new File("/etc/appsnap-server.xml") };

    File configFile = null;

    for (File next : configPaths) {
        if (next.exists()) {
            configFile = next;
        }
    }

    if (configFile == null) {

        log.warn("No config file found.");

        for (int x = configPaths.length - 1; x >= 0; x--) {
            File next = configPaths[x];
            log.warn("Attempting to create default config file at " + next.getAbsolutePath());
            ServerConfiguration defaults = new ServerConfiguration();
            defaults.idProofRecipie(
                    new PasswordProofRecipie(new SimpleId("mr-admin-dude"), "my-super-secret-password"));
            try {
                helper.writeToFile(helper.writeToXmlString(defaults), next);
                log.warn("done");
                break;
            } catch (Exception e) {
                log.warn("Error writing file: " + e.getMessage(), e);
            }
        }
        System.exit(1);
        return;
    } else {
        log.info("Reading configuration from " + configFile.getAbsolutePath());
        config = helper.readFromFile(configFile);
    }

    ProxyFactory proxyFactory = new ProxyFactory(new HessianProxyProvider());
    try {
        new AppSnapServer(config, proxyFactory);
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("Unexpected Error.  Shutting Down.");
        System.exit(1);
    }
}

From source file:com.github.fritaly.graphml4j.samples.GradleDependenciesWithGroups.java

public static void main(String[] args) throws Exception {
    if (args.length != 1) {
        System.out//from w w w .j  a v a2  s.c o m
                .println(String.format("%s <output-file>", GradleDependenciesWithGroups.class.getSimpleName()));
        System.exit(1);
    }

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

    System.out.println("Writing GraphML file to " + file.getAbsolutePath() + " ...");

    FileWriter fileWriter = null;
    GraphMLWriter graphWriter = null;
    Reader reader = null;
    LineNumberReader lineReader = null;

    try {
        fileWriter = new FileWriter(file);
        graphWriter = new GraphMLWriter(fileWriter);

        // Customize the rendering of nodes
        final NodeStyle nodeStyle = graphWriter.getNodeStyle();
        nodeStyle.setWidth(250.0f);
        nodeStyle.setHeight(50.0f);

        graphWriter.setNodeStyle(nodeStyle);

        // The dependency graph has been generated by Gradle with the
        // command "gradle dependencies". The output of this command has
        // been saved to a text file which will be parsed to rebuild the
        // dependency graph
        reader = new InputStreamReader(
                GradleDependenciesWithGroups.class.getResourceAsStream("gradle-dependencies.txt"));
        lineReader = new LineNumberReader(reader);

        String line = null;

        // Stack containing the artifacts per depth inside the dependency
        // graph (the topmost dependency is the first one in the stack)
        final Stack<Artifact> stack = new Stack<Artifact>();

        final Map<String, Set<Artifact>> artifactsByGroup = new HashMap<String, Set<Artifact>>();

        // List of parent/child relationships between artifacts
        final List<Relationship> relationships = new ArrayList<Relationship>();

        while ((line = lineReader.readLine()) != null) {
            // Determine the depth of the current dependency inside the
            // graph. The depth can be inferred from the indentation used by
            // Gradle. Each level of depth adds 5 more characters of
            // indentation
            final int initialLength = line.length();

            // Remove the strings used by Gradle to indent dependencies
            line = StringUtils.replace(line, "+--- ", "");
            line = StringUtils.replace(line, "|    ", "");
            line = StringUtils.replace(line, "\\--- ", "");
            line = StringUtils.replace(line, "     ", "");

            // The depth can easily be inferred now
            final int depth = (initialLength - line.length()) / 5;

            // Remove unnecessary artifacts
            while (depth <= stack.size()) {
                stack.pop();
            }

            // Create an artifact from the dependency (group, artifact,
            // version) tuple
            final Artifact artifact = createArtifact(line);

            stack.push(artifact);

            if (stack.size() > 1) {
                // Store the artifact and its parent
                relationships.add(new Relationship(stack.get(stack.size() - 2), artifact));
            }

            if (!artifactsByGroup.containsKey(artifact.group)) {
                artifactsByGroup.put(artifact.group, new HashSet<Artifact>());
            }

            artifactsByGroup.get(artifact.group).add(artifact);
        }

        // Open the graph
        graphWriter.graph();

        final Map<Artifact, String> nodeIdsByArtifact = new HashMap<Artifact, String>();

        // Loop over the groups and generate the associated nodes
        for (String group : artifactsByGroup.keySet()) {
            graphWriter.group(group, true);

            for (Artifact artifact : artifactsByGroup.get(group)) {
                final String nodeId = graphWriter.node(artifact.getLabel());

                nodeIdsByArtifact.put(artifact, nodeId);
            }

            graphWriter.closeGroup();
        }

        // Generate the edges
        for (Relationship relationship : relationships) {
            final String parentId = nodeIdsByArtifact.get(relationship.parent);
            final String childId = nodeIdsByArtifact.get(relationship.child);

            graphWriter.edge(parentId, childId);
        }

        // Close the graph
        graphWriter.closeGraph();

        System.out.println("Done");
    } finally {
        // Calling GraphMLWriter.close() is necessary to dispose the underlying resources
        graphWriter.close();
        fileWriter.close();
        lineReader.close();
        reader.close();
    }
}

From source file:com.github.fritaly.graphml4j.samples.GradleDependenciesWithGroupsAndBuffering.java

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

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

    System.out.println("Writing GraphML file to " + file.getAbsolutePath() + " ...");

    FileWriter fileWriter = null;
    Reader reader = null;
    LineNumberReader lineReader = null;

    try {
        fileWriter = new FileWriter(file);

        final com.github.fritaly.graphml4j.datastructure.Graph graph = new Graph();

        // The dependency graph has been generated by Gradle with the
        // command "gradle dependencies". The output of this command has
        // been saved to a text file which will be parsed to rebuild the
        // dependency graph
        reader = new InputStreamReader(
                GradleDependenciesWithGroupsAndBuffering.class.getResourceAsStream("gradle-dependencies.txt"));
        lineReader = new LineNumberReader(reader);

        String line = null;

        // Stack containing the nodes per depth inside the dependency graph
        // (the topmost dependency is the first one in the stack)
        final Stack<Node> parentNodes = new Stack<Node>();

        while ((line = lineReader.readLine()) != null) {
            // Determine the depth of the current dependency inside the
            // graph. The depth can be inferred from the indentation used by
            // Gradle. Each level of depth adds 5 more characters of
            // indentation
            final int initialLength = line.length();

            // Remove the strings used by Gradle to indent dependencies
            line = StringUtils.replace(line, "+--- ", "");
            line = StringUtils.replace(line, "|    ", "");
            line = StringUtils.replace(line, "\\--- ", "");
            line = StringUtils.replace(line, "     ", "");

            // The depth can easily be inferred now
            final int depth = (initialLength - line.length()) / 5;

            // Remove unnecessary node ids
            while (depth <= parentNodes.size()) {
                parentNodes.pop();
            }

            final Artifact artifact = createArtifact(line);

            Node node = graph.getNodeByData(artifact);

            // Has this dependency already been added to the graph ?
            if (node == null) {
                // No, add the node
                node = graph.addNode(artifact);
            }

            parentNodes.push(node);

            if (parentNodes.size() > 1) {
                // Generate an edge between the current node and its parent
                graph.addEdge("Depends on", parentNodes.get(parentNodes.size() - 2), node);
            }
        }

        // Create the groups after creating the nodes & edges
        for (Node node : graph.getNodes()) {
            final Artifact artifact = (Artifact) node.getData();

            final String groupId = artifact.group;

            Node groupNode = graph.getNodeByData(groupId);

            if (groupNode == null) {
                groupNode = graph.addNode(groupId);
            }

            // add the node to the group
            node.setParent(groupNode);
        }

        graph.toGraphML(fileWriter, new Renderer() {

            @Override
            public String getNodeLabel(Node node) {
                return node.isGroup() ? node.getData().toString() : ((Artifact) node.getData()).getLabel();
            }

            @Override
            public boolean isGroupOpen(Node node) {
                return true;
            }

            @Override
            public NodeStyle getNodeStyle(Node node) {
                // Customize the rendering of nodes
                final NodeStyle nodeStyle = new NodeStyle();
                nodeStyle.setWidth(250.0f);

                return nodeStyle;
            }

            @Override
            public GroupStyles getGroupStyles(Node node) {
                return new GroupStyles();
            }

            @Override
            public EdgeStyle getEdgeStyle(Edge edge) {
                return new EdgeStyle();
            }
        });

        System.out.println("Done");
    } finally {
        // Calling GraphMLWriter.close() is necessary to dispose the underlying resources
        fileWriter.close();
        lineReader.close();
        reader.close();
    }
}

From source file:com.github.lucapino.sheetmaker.PreviewJFrame.java

public static void main(String[] args) {
    System.setProperty("awt.useSystemAAFontSettings", "on");
    System.setProperty("swing.aatext", "true");
    SwingUtilities.invokeLater(new Runnable() {

        @Override/*from w  w w  .jav  a 2s  . c om*/
        public void run() {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                File tmpFolder = new File("/tmp/images");
                tmpFolder.mkdir();

                String coverPath = tmpFolder.getAbsolutePath().replaceAll("\\\\", "/") + "/cover.jpg";
                String backdropPath = tmpFolder.getAbsolutePath().replaceAll("\\\\", "/") + "/backdrop.jpg";
                String fanart1Path = tmpFolder.getAbsolutePath().replaceAll("\\\\", "/") + "/fanart1.jpg";
                String fanart2Path = tmpFolder.getAbsolutePath().replaceAll("\\\\", "/") + "/fanart2.jpg";
                String fanart3Path = tmpFolder.getAbsolutePath().replaceAll("\\\\", "/") + "/fanart3.jpg";

                PreviewJFrame frame = new PreviewJFrame();
                logger.info("Creating parser...");
                InfoRetriever parser = new MediaInfoRetriever();
                MovieInfo movieInfo = parser.getMovieInfo("/media/tagliani/Elements/Film/JackRyan.mkv");
                logger.info("Retrieving movie file info...");
                logger.info("Creating dataretriever...");
                DataRetriever retriever = new DataRetrieverImpl();
                logger.info("Retrieving movie data...");
                Movie movie = retriever.retrieveMovieFromImdbID("tt1205537", "IT");
                logger.info("Retrieving backdrops and fanart...");
                List<Artwork> images = movie.getBackdrops();
                // background
                logger.info("Saving backdrop...");
                IOUtils.copyLarge(new URL(images.get(0).getImageURL()).openStream(),
                        new FileOutputStream(backdropPath));
                for (int i = 1; i < 4; i++) {
                    // fanart1
                    // fanart2
                    // fanart3
                    String imageURL = images.get(i).getImageURL();
                    logger.info("Saving fanart{}...", i);
                    IOUtils.copyLarge(new URL(imageURL).openStream(),
                            new FileOutputStream(tmpFolder.getAbsolutePath() + "/fanart" + i + ".jpg"));
                }
                // cover
                logger.info("Retrieving cover...");
                Artwork cover = movie.getPosters().get(0);
                String imageURL = cover.getImageURL();
                logger.info("Saving cover...");
                IOUtils.copyLarge(new URL(imageURL).openStream(), new FileOutputStream(coverPath));

                Map<String, String> tokenMap = TemplateFilter.createTokenMap(movie, movieInfo, null);

                logger.info("Creating renderer...");
                JavaTemplateRenderer renderer = new JavaTemplateRenderer();
                JPanel imagePanel = null;
                try {
                    logger.info("Rendering image...");
                    imagePanel = renderer.renderTemplate(
                            this.getClass().getResource("/templates/simplicity/template.xml"), tokenMap,
                            backdropPath, fanart1Path, fanart2Path, fanart3Path, coverPath);
                    logger.info("Adding image to frame...");
                    frame.add(imagePanel);

                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                imagePanel.setPreferredSize(new Dimension(imagePanel.getWidth(), imagePanel.getHeight()));
                frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
                frame.setVisible(true);
                frame.pack();
                logger.info("Creating image for save...");
                BufferedImage imageTosave = ScreenImage.createImage(imagePanel);
                logger.info("Saving image...");
                ScreenImage.writeImage(imageTosave, "/tmp/images/final.png");
                logger.info("Image saved...");
            } catch (Exception ex) {
                logger.error("Error: ", ex);
            }
        }

    });

}

From source file:eu.fbk.dkm.sectionextractor.WikipediaBirthDeathDateExtractor.java

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

    CommandLineWithLogger commandLineWithLogger = new CommandLineWithLogger();
    commandLineWithLogger.addOption(OptionBuilder.withArgName("file").hasArg()
            .withDescription("wikipedia xml dump file").isRequired().withLongOpt("wikipedia-dump").create("d"));
    commandLineWithLogger.addOption(OptionBuilder.withArgName("dir").hasArg().withDescription("output file")
            .isRequired().withLongOpt("output-file").create("o"));

    commandLineWithLogger.addOption(OptionBuilder.withArgName("int").hasArg()
            .withDescription(//from  w w  w .j  a  va2s  .com
                    "number of threads (default " + AbstractWikipediaXmlDumpParser.DEFAULT_THREADS_NUMBER + ")")
            .withLongOpt("num-threads").create("t"));
    commandLineWithLogger.addOption(OptionBuilder.withArgName("int").hasArg()
            .withDescription("number of pages to process (default all)").withLongOpt("num-pages").create("p"));
    commandLineWithLogger.addOption(OptionBuilder.withArgName("int").hasArg()
            .withDescription("receive notification every n pages (default "
                    + AbstractWikipediaExtractor.DEFAULT_NOTIFICATION_POINT + ")")
            .withLongOpt("notification-point").create("b"));

    CommandLine commandLine = null;
    try {
        commandLine = commandLineWithLogger.getCommandLine(args);
        PropertyConfigurator.configure(commandLineWithLogger.getLoggerProps());
    } catch (Exception e) {
        System.exit(1);
    }

    int numThreads = Integer.parseInt(commandLine.getOptionValue("num-threads",
            Integer.toString(AbstractWikipediaXmlDumpParser.DEFAULT_THREADS_NUMBER)));
    int numPages = Integer.parseInt(commandLine.getOptionValue("num-pages",
            Integer.toString(AbstractWikipediaExtractor.DEFAULT_NUM_PAGES)));
    int notificationPoint = Integer.parseInt(commandLine.getOptionValue("notification-point",
            Integer.toString(AbstractWikipediaExtractor.DEFAULT_NOTIFICATION_POINT)));

    File outputFile = new File(commandLine.getOptionValue("output-file"));
    ExtractorParameters extractorParameters = new ExtractorParameters(
            commandLine.getOptionValue("wikipedia-dump"), outputFile.getAbsolutePath());

    WikipediaExtractor wikipediaPageParser = new WikipediaBirthDeathDateExtractor(numThreads, numPages,
            extractorParameters.getLocale(), outputFile);
    wikipediaPageParser.setNotificationPoint(notificationPoint);
    wikipediaPageParser.start(extractorParameters);

    logger.info("extraction ended " + new Date());

}

From source file:at.co.malli.relpm.RelPM.java

/**
 * @param args the command line arguments
 *//*from   w w  w.  jav  a2s .c om*/
public static void main(String[] args) {
    //<editor-fold defaultstate="collapsed" desc=" Create config & log directory ">
    String userHome = System.getProperty("user.home");
    File relPm = new File(userHome + "/.RelPM");
    if (!relPm.exists()) {
        boolean worked = relPm.mkdir();
        if (!worked) {
            ExceptionDisplayer.showErrorMessage(new Exception("Could not create directory "
                    + relPm.getAbsolutePath() + " to store user-settings and logs"));
            System.exit(-1);
        }
    }
    File userConfig = new File(relPm.getAbsolutePath() + "/RelPM-userconfig.xml"); //should be created...
    if (!userConfig.exists()) {
        try {
            URL resource = RelPM.class.getResource("/at/co/malli/relpm/RelPM-defaults.xml");
            FileUtils.copyURLToFile(resource, userConfig);
        } catch (IOException ex) {
            ExceptionDisplayer.showErrorMessage(new Exception("Could not copy default config. Reason:\n"
                    + ex.getClass().getName() + ": " + ex.getMessage()));
            System.exit(-1);
        }
    }
    if (!userConfig.canWrite() || !userConfig.canRead()) {
        ExceptionDisplayer.showErrorMessage(new Exception(
                "Can not read or write " + userConfig.getAbsolutePath() + "to store user-settings"));
        System.exit(-1);
    }
    if (System.getProperty("os.name").toLowerCase().contains("win")) {
        Path relPmPath = Paths.get(relPm.toURI());
        try {
            Files.setAttribute(relPmPath, "dos:hidden", true);
        } catch (IOException ex) {
            ExceptionDisplayer.showErrorMessage(new Exception("Could not set " + relPm.getAbsolutePath()
                    + " hidden. " + "Reason:\n" + ex.getClass().getName() + ": " + ex.getMessage()));
            System.exit(-1);
        }
    }
    //</editor-fold>

    logger.trace("Environment setup sucessfull");

    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code ">
    try {
        String wantedLookAndFeel = SettingsProvider.getInstance().getString("gui.lookAndFeel");
        UIManager.LookAndFeelInfo[] installed = UIManager.getInstalledLookAndFeels();
        boolean found = false;
        for (UIManager.LookAndFeelInfo info : installed) {
            if (info.getClassName().equals(wantedLookAndFeel))
                found = true;
        }
        if (found)
            UIManager.setLookAndFeel(wantedLookAndFeel);
        else
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (ClassNotFoundException ex) {
        logger.error(ex.getMessage());
        ExceptionDisplayer.showErrorMessage(ex);
    } catch (InstantiationException ex) {
        logger.error(ex.getMessage());
        ExceptionDisplayer.showErrorMessage(ex);
    } catch (IllegalAccessException ex) {
        logger.error(ex.getMessage());
        ExceptionDisplayer.showErrorMessage(ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        logger.error(ex.getMessage());
        ExceptionDisplayer.showErrorMessage(ex);
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc=" Add GUI start to awt EventQue ">
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new MainGUI().setVisible(true);
        }
    });
    //</editor-fold>
}

From source file:com.jdom.word.playdough.model.gamepack.GamePackFileGenerator.java

/**
 * Usage: java GamePackFileGenerator <input file> <output directory>
 * /*from ww w .  j  a  v  a 2s.c om*/
 * @param args
 * @throws IOException
 */
public static void main(String[] args) throws IOException {
    File dictionaryFile = new File(args[0]);

    // Validate arguments first
    if (!dictionaryFile.isFile()) {
        throw new IllegalArgumentException("The specified file does not seem to be a valid file ["
                + dictionaryFile.getAbsolutePath() + "]!");
    }

    File outputDir = new File(args[1]);
    if (!outputDir.isDirectory()) {
        throw new IllegalArgumentException("The specified directory does not seem to be a valid directory ["
                + outputDir.getAbsolutePath() + "]!");
    }

    Set<String> words = GamePackFileGenerator.readWordsFromDictionaryFile(dictionaryFile);

    GamePackFileGenerator generator = new GamePackFileGenerator(words);
    List<Properties> properties = generator.generateGamePacks(20);

    for (int i = 0; i < properties.size(); i++) {
        Properties current = properties.get(i);
        File outputFile = new File(outputDir, i + ".properties");
        PropertiesUtil.writePropertiesFile(current, outputFile);
    }
}

From source file:mase.MaseEvolve.java

public static void main(String[] args) throws Exception {
    File outDir = getOutDir(args);
    boolean force = Arrays.asList(args).contains(FORCE);
    if (!outDir.exists()) {
        outDir.mkdirs();//from  w w w .  j  a v  a2s  .  c o m
    } else if (!force) {
        System.out.println("Folder already exists: " + outDir.getAbsolutePath() + ". Waiting 5 sec.");
        try {
            Thread.sleep(5000);
        } catch (InterruptedException ex) {
        }
    }

    // Get config file
    Map<String, String> pars = readParams(args);

    // Copy config to outdir
    try {
        File rawConfig = writeConfig(args, pars, outDir, false);
        File destiny = new File(outDir, DEFAULT_CONFIG);
        destiny.delete();
        FileUtils.moveFile(rawConfig, new File(outDir, DEFAULT_CONFIG));
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    // JBOT INTEGRATION: copy jbot config file to the outdir
    // Does nothing when jbot is not used
    if (pars.containsKey("problem.jbot-config")) {
        File jbot = new File(pars.get("problem.jbot-config"));
        FileUtils.copyFile(jbot, new File(outDir, jbot.getName()));
    }

    // Write config to system temp file
    File config = writeConfig(args, pars, outDir, true);
    // Launch
    launchExperiment(config);
}