Example usage for java.io File toURI

List of usage examples for java.io File toURI

Introduction

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

Prototype

public URI toURI() 

Source Link

Document

Constructs a file: URI that represents this abstract pathname.

Usage

From source file:MyClass.java

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

    URL[] urls = null;// w  ww . jav a2s  . co m

    File dir = new File(System.getProperty("user.dir") + File.separator + "dir" + File.separator);
    URL url = dir.toURI().toURL();
    urls = new URL[] { url };

    ClassLoader cl = new URLClassLoader(urls);

    Class cls = cl.loadClass("MyClass");

    MyClass myObj = (MyClass) cls.newInstance();

}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Robot robot = new Robot();
    Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
    BufferedImage image = robot.createScreenCapture(new Rectangle(d));
    BufferedImage sub = image.getSubimage(0, 0, 400, 400);
    File f = new File("SubImage.png");
    ImageIO.write(sub, "png", f);
    final ImageIcon im = new ImageIcon(f.toURI().toURL());

    Runnable r = new Runnable() {

        @Override//from   www.  j  av  a  2s. c om
        public void run() {
            JOptionPane.showMessageDialog(null, new JLabel(im));
        }
    };
    SwingUtilities.invokeLater(r);
}

From source file:demo.wssec.client.Client.java

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

    if (args.length == 0) {
        System.out.println("please specify wsdl");
        System.exit(1);//from w  w w .  ja va2s  .  c o m
    }

    URL wsdlURL;
    File wsdlFile = new File(args[0]);
    if (wsdlFile.exists()) {
        wsdlURL = wsdlFile.toURI().toURL();
    } else {
        wsdlURL = new URL(args[0]);
    }

    SpringBusFactory bf = new SpringBusFactory();
    URL busFile = new ClassPathResource("wssec-client.xml").getURL();

    Bus bus = bf.createBus(busFile.toString());
    SpringBusFactory.setDefaultBus(bus);
    SpringBusFactory.setThreadDefaultBus(bus);

    Service service = Service.create(wsdlURL, SERVICE_NAME);
    Greeter port = service.getPort(PORT_NAME, Greeter.class);

    System.out.println("Invoking greetMe...");
    try {
        String resp = port.greetMe(System.getProperty("user.name"));
        System.out.println("Server responded with: " + resp);
        System.out.println();

    } catch (Exception e) {
        System.out.println("Invocation failed with the following: " + e.getCause());
        System.out.println();
    }

    System.exit(0);
}

From source file:net.itransformers.idiscover.v2.core.Main.java

public static void main(String[] args) throws MalformedURLException {
    logger.debug("iDiscover v2. gearing up");
    Map<String, String> params = CmdLineParser.parseCmdLine(args);
    //        String connectionDetailsFileName = params.get("-f");
    //        if (connectionDetailsFileName == null) {
    //            printUsage("fileName"); return;
    //        }// w  w  w  .java  2 s  .com
    String depthCmdArg = params.get("-d");
    //        if (depthCmdArg == null) {
    //            printUsage("depth"); return;
    //        }
    String projectPath = params.get("-p");

    if (projectPath == null) {
        File cwd = new File(".");
        System.out.println("Project path is not specified. Will use current dir: " + cwd.getAbsolutePath());
        projectPath = cwd.getAbsolutePath();
    }

    File workingDir = new File(projectPath);
    if (!workingDir.exists()) {
        System.out.println("Invalid project path!");
        return;
    }
    System.out.println("Loading beans!!");

    File conDetails = new File(projectPath, "iDiscover/conf/txt/connection-details.txt");

    File generic = new File(projectPath, "iDiscover/conf/xml/generic.xml");
    String genericContextPath = generic.toURI().toURL().toString();

    File snmpDiscovery = new File(projectPath, "iDiscover/conf/xml/snmpNetworkDiscovery.xml");
    String snmpDiscoveryContextPath = snmpDiscovery.toURI().toURL().toString();

    File connectionsDetails = new File(projectPath, "iDiscover/conf/xml/connectionsDetails.xml");
    String connectionsDetailsContextPath = connectionsDetails.toURI().toURL().toString();

    DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
    BeanDefinition beanDefinition = BeanDefinitionBuilder.rootBeanDefinition(String.class)
            .addConstructorArgValue(projectPath).getBeanDefinition();

    String labelDirName = autolabel(projectPath);

    BeanDefinition beanDefinition2 = BeanDefinitionBuilder.rootBeanDefinition(String.class)
            .addConstructorArgValue(labelDirName).getBeanDefinition();

    beanFactory.registerBeanDefinition("projectPath", beanDefinition);

    beanFactory.registerBeanDefinition("labelDirName", beanDefinition2);

    GenericApplicationContext cmdArgCxt = new GenericApplicationContext(beanFactory);
    // Must call refresh to initialize context
    cmdArgCxt.refresh();

    String[] paths = new String[] { genericContextPath, snmpDiscoveryContextPath,
            connectionsDetailsContextPath };
    //        ,project.getAbsolutePath()+project.getAbsolutePath()+File.separator+"iDiscover/conf/xml/snmpNetworkDiscovery.xml", project.getAbsolutePath()+File.separator+"iDiscover/src/main/resources/connectionsDetails.xml"
    FileSystemXmlApplicationContext applicationContext = new FileSystemXmlApplicationContext(paths, cmdArgCxt);
    //        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(workingDir+File.separator+"iDiscover/conf/xml/generic.xml",workingDir+File.separator+"/iDiscover/conf/xml/snmpNetworkDiscovery.xml","connectionsDetails.xml");
    // NetworkDiscoverer discoverer = fileApplicationContext.getBean("bgpPeeringMapDiscovery", NetworkDiscoverer.class);
    //NetworkDiscoverer discoverer = fileApplicationContext.getBean("floodLightNodeDiscoverer", NetworkDiscoverer.class);
    NetworkDiscoverer discoverer = applicationContext.getBean("snmpDiscovery", NetworkDiscoverer.class);
    LinkedHashMap<String, ConnectionDetails> connectionList = (LinkedHashMap) applicationContext
            .getBean("connectionList", conDetails);
    int depth = (Integer) applicationContext.getBean("discoveryDepth",
            depthCmdArg == null ? "-1" : depthCmdArg);
    NetworkDiscoveryResult result = discoverer
            .discoverNetwork(new ArrayList<ConnectionDetails>(connectionList.values()), depth);
    if (result != null) {
        for (String s : result.getNodes().keySet()) {
            System.out.println("\nNode: " + s);

        }
    }

    //
}

From source file:com.athena.peacock.agent.Starter.java

/**
 * <pre>//from   w  w  w . ja  va2s.  c  o  m
 * 
 * </pre>
 * @param args
 */
@SuppressWarnings("resource")
public static void main(String[] args) {

    int rand = (int) (Math.random() * 100) % 50;
    System.setProperty("random.seconds", Integer.toString(rand));

    String configFile = null;

    try {
        configFile = PropertyUtil.getProperty(PeacockConstant.CONFIG_FILE_KEY);
    } catch (Exception e) {
        // nothing to do.
    } finally {
        if (StringUtils.isEmpty(configFile)) {
            configFile = "/peacock/agent/config/agent.conf";
        }
    }

    /**
     * ${peacock.agent.config.file.name} ?? load  ? ??   ? ?  ? .
     */
    String errorMsg = "\n\"" + configFile + "\" file does not exist or cannot read.\n" + "Please check \""
            + configFile + "\" file exists and can read.";

    Assert.isTrue(AgentConfigUtil.exception == null, errorMsg);
    Assert.notNull(AgentConfigUtil.getConfig(PeacockConstant.SERVER_IP), "ServerIP cannot be empty.");
    Assert.notNull(AgentConfigUtil.getConfig(PeacockConstant.SERVER_PORT), "ServerPort cannot be empty.");

    /**
     * Agent ID ??  ${peacock.agent.agent.file.name} ?   ?, 
     *  ?? ?   Agent ID ? ?? .
     */
    String agentFile = null;
    String agentId = null;

    try {
        agentFile = PropertyUtil.getProperty(PeacockConstant.AGENT_ID_FILE_KEY);
    } catch (Exception e) {
        // nothing to do.
    } finally {
        if (StringUtils.isEmpty(agentFile)) {
            agentFile = "/peacock/agent/.agent";
        }
    }

    File file = new File(agentFile);
    boolean isNew = false;

    if (file.exists()) {
        try {
            agentId = IOUtils.toString(file.toURI());

            // ? ? agent ID  agent ID? ? 36? ?   ?.
            if (StringUtils.isEmpty(agentId) || agentId.length() != 36) {
                throw new IOException();
            }
        } catch (IOException e) {
            logger.error(agentFile + " file cannot read or saved invalid agent ID.", e);

            agentId = PeacockAgentIDGenerator.generateId();
            isNew = true;
        }
    } else {
        agentId = PeacockAgentIDGenerator.generateId();
        isNew = true;
    }

    if (isNew) {
        logger.info("New Agent-ID({}) be generated.", agentId);

        try {
            file.setWritable(true);
            OutputStreamWriter output = new OutputStreamWriter(new FileOutputStream(file));
            output.write(agentId);
            file.setReadOnly();
            IOUtils.closeQuietly(output);
        } catch (UnsupportedEncodingException e) {
            logger.error("UnsupportedEncodingException has occurred : ", e);
        } catch (FileNotFoundException e) {
            logger.error("FileNotFoundException has occurred : ", e);
        } catch (IOException e) {
            logger.error("IOException has occurred : ", e);
        }
    }

    // Spring Application Context Loading
    logger.debug("Starting application context...");
    AbstractApplicationContext applicationContext = new ClassPathXmlApplicationContext(
            "classpath:spring/context-*.xml");
    applicationContext.registerShutdownHook();
}

From source file:fi.jasoft.plugin.LibSassCompiler.java

public static void main(String[] args) throws Exception {
    File inputFile = new File(args[0]);
    File outputFile = new File(args[1]);
    if (!outputFile.exists()) {
        outputFile.createNewFile();// w  w w.  j av a 2s  . co  m
    }

    File sourceMapFile = new File(args[1] + ".map");
    if (!sourceMapFile.exists()) {
        sourceMapFile.createNewFile();
    }

    File unpackedThemes = new File(args[2]);
    File unpackedInputFile = Paths
            .get(unpackedThemes.getCanonicalPath(), inputFile.getParentFile().getName(), inputFile.getName())
            .toFile();

    Compiler compiler = new Compiler();
    Options options = new Options();

    try {
        Output output = compiler.compileFile(unpackedInputFile.toURI(), outputFile.toURI(), options);
        FileUtils.write(outputFile, output.getCss(), StandardCharsets.UTF_8.name());
        FileUtils.write(sourceMapFile, output.getSourceMap(), StandardCharsets.UTF_8.name());
    } catch (CompilationException e) {
        outputFile.delete();
        sourceMapFile.delete();
        throw e;
    }
}

From source file:at.ac.ait.ubicity.fileloader.FileLoader.java

/**
 * //from   ww  w.j a v  a  2  s.  c o m
 * This method is here for demo purposes only. It is not part of the required functionality for this class. 
 * 
 * 
 * @param args arg 0 = file, arg #1 = keyspace, arg #2 = server host name, arg #3 = batch size, arg #4 = number of time units to wait, arg #5 = time unit ( minute, second, hour,.. ) 
 * ( For now, tacitly assume we are on the default Cassandra 9160 port ). Clustering is not yet supported.
 */
public final static void main(String[] args) throws Exception {
    if (!(args.length == 6)) {
        usage();
        System.exit(1);
    }

    try {
        final File _f = new File(args[0]);

        URI uri = _f.toURI();
        String keySpaceName = args[1];
        final String host = args[2];
        final int batchSize = Integer.parseInt(args[3]);
        final int timeUnitCount = Integer.parseInt(args[4]);
        Delay timeUnit = timeUnitsFromCmdLine(args[5].toUpperCase());
        if (timeUnit == null)
            timeUnit = Delay.SECOND;
        long millisToWait = timeUnitCount * timeUnit.getMilliSeconds();
        useCache = true;
        while (true) {
            try {
                invigilate(uri, keySpaceName, host, batchSize, millisToWait);
                Thread.sleep(millisToWait);
            } catch (InterruptedException | Error any) {
                Thread.interrupted();
            } finally {

            }
        }
    } catch (Exception e) {
        logger.log(Level.SEVERE, e.toString());
    }
}

From source file:httpsdemo.client.Client.java

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

    File clientKeystore = new File("certs/clientKeystore.jks");
    File truststore = new File("certs/commonTruststore.jks");

    // Send HTTP GET request to query customer info - using portable HttpClient method
    Protocol authhttps = new Protocol("https", new AuthSSLProtocolSocketFactory(clientKeystore.toURI().toURL(),
            "password", truststore.toURI().toURL(), "password"), 9000);
    Protocol.registerProtocol("https", authhttps);

    System.out.println("Sending HTTPS GET request to query customer info");
    HttpClient httpclient = new HttpClient();
    GetMethod httpget = new GetMethod(BASE_SERVICE_URL + "/123");
    httpget.addRequestHeader("Accept", "text/xml");

    // If Basic Authentication required could use: 
    /*/* w w w  . ja  va2  s.c  o  m*/
    String authorizationHeader = "Basic " 
       + org.apache.cxf.common.util.Base64Utility.encode("username:password".getBytes());
    httpget.addRequestHeader("Authorization", authorizationHeader);
    */
    try {
        httpclient.executeMethod(httpget);
        System.out.println(httpget.getResponseBodyAsString());
    } finally {
        httpget.releaseConnection();
    }

    /*
     *  Send HTTP PUT request to update customer info, using CXF WebClient method
     *  Note: if need to use basic authentication, use the WebClient.create(baseAddress,
     *  username,password,configFile) variant, where configFile can be null if you're
     *  not using certificates.
     */
    System.out.println("Sending HTTPS PUT to update customer name");
    WebClient wc = WebClient.create(BASE_SERVICE_URL, CLIENT_CONFIG_FILE);
    Customer customer = new Customer();
    customer.setId(123);
    customer.setName("Mary");
    Response resp = wc.put(customer);

    /*
     *  Send HTTP POST request to add customer, using JAXRSClientProxy
     *  Note: if need to use basic authentication, use the JAXRSClientFactory.create(baseAddress,
     *  username,password,configFile) variant, where configFile can be null if you're
     *  not using certificates.
     */
    System.out.println("\n");
    System.out.println("Sending HTTPS POST request to add customer");
    CustomerService proxy = JAXRSClientFactory.create(BASE_SERVICE_URL, CustomerService.class,
            CLIENT_CONFIG_FILE);
    customer = new Customer();
    customer.setName("Jack");
    resp = wc.post(customer);

    System.out.println("\n");
    System.exit(0);
}

From source file:com.ctriposs.rest4j.tools.data.FilterSchemaGenerator.java

public static void main(String[] args) {
    final CommandLineParser parser = new GnuParser();
    CommandLine cl = null;//from  w ww .ja va  2  s.  com
    try {
        cl = parser.parse(_options, args);
    } catch (ParseException e) {
        _log.error("Invalid arguments: " + e.getMessage());
        reportInvalidArguments();
    }

    final String[] directoryArgs = cl.getArgs();
    if (directoryArgs.length != 2) {
        reportInvalidArguments();
    }

    final File sourceDirectory = new File(directoryArgs[0]);
    if (!sourceDirectory.exists()) {
        _log.error(sourceDirectory.getPath() + " does not exist");
        System.exit(1);
    }
    if (!sourceDirectory.isDirectory()) {
        _log.error(sourceDirectory.getPath() + " is not a directory");
        System.exit(1);
    }
    final URI sourceDirectoryURI = sourceDirectory.toURI();

    final File outputDirectory = new File(directoryArgs[1]);
    if (outputDirectory.exists() && !sourceDirectory.isDirectory()) {
        _log.error(outputDirectory.getPath() + " is not a directory");
        System.exit(1);
    }

    final boolean isAvroMode = cl.hasOption('a');
    final String predicateExpression = cl.getOptionValue('e');
    final Predicate predicate = PredicateExpressionParser.parse(predicateExpression);

    final Collection<File> sourceFiles = FileUtil.listFiles(sourceDirectory, null);
    int exitCode = 0;
    for (File sourceFile : sourceFiles) {
        try {
            final ValidationOptions val = new ValidationOptions();
            val.setAvroUnionMode(isAvroMode);

            final SchemaParser schemaParser = new SchemaParser();
            schemaParser.setValidationOptions(val);

            schemaParser.parse(new FileInputStream(sourceFile));
            if (schemaParser.hasError()) {
                _log.error("Error parsing " + sourceFile.getPath() + ": "
                        + schemaParser.errorMessageBuilder().toString());
                exitCode = 1;
                continue;
            }

            final DataSchema originalSchema = schemaParser.topLevelDataSchemas().get(0);
            if (!(originalSchema instanceof NamedDataSchema)) {
                _log.error(sourceFile.getPath() + " does not contain valid NamedDataSchema");
                exitCode = 1;
                continue;
            }

            final SchemaParser filterParser = new SchemaParser();
            filterParser.setValidationOptions(val);

            final NamedDataSchema filteredSchema = Filters.removeByPredicate((NamedDataSchema) originalSchema,
                    predicate, filterParser);
            if (filterParser.hasError()) {
                _log.error("Error applying predicate: " + filterParser.errorMessageBuilder().toString());
                exitCode = 1;
                continue;
            }

            final String relativePath = sourceDirectoryURI.relativize(sourceFile.toURI()).getPath();
            final String outputFilePath = outputDirectory.getPath() + File.separator + relativePath;
            final File outputFile = new File(outputFilePath);
            final File outputFileParent = outputFile.getParentFile();
            outputFileParent.mkdirs();
            if (!outputFileParent.exists()) {
                _log.error("Unable to write filtered schema to " + outputFileParent.getPath());
                exitCode = 1;
                continue;
            }

            FileOutputStream fout = new FileOutputStream(outputFile);
            fout.write(filteredSchema.toString().getBytes(RestConstants.DEFAULT_CHARSET));
            fout.close();
        } catch (IOException e) {
            _log.error(e.getMessage());
            exitCode = 1;
        }
    }

    System.exit(exitCode);
}

From source file:com.linkedin.restli.tools.data.FilterSchemaGenerator.java

public static void main(String[] args) {
    CommandLine cl = null;//w w  w  .j a  va  2  s .  c o m
    try {
        final CommandLineParser parser = new GnuParser();
        cl = parser.parse(_options, args);
    } catch (ParseException e) {
        _log.error("Invalid arguments: " + e.getMessage());
        reportInvalidArguments();
    }

    final String[] directoryArgs = cl.getArgs();
    if (directoryArgs.length != 2) {
        reportInvalidArguments();
    }

    final File sourceDirectory = new File(directoryArgs[0]);
    if (!sourceDirectory.exists()) {
        _log.error(sourceDirectory.getPath() + " does not exist");
        System.exit(1);
    }
    if (!sourceDirectory.isDirectory()) {
        _log.error(sourceDirectory.getPath() + " is not a directory");
        System.exit(1);
    }
    final URI sourceDirectoryURI = sourceDirectory.toURI();

    final File outputDirectory = new File(directoryArgs[1]);
    if (outputDirectory.exists() && !sourceDirectory.isDirectory()) {
        _log.error(outputDirectory.getPath() + " is not a directory");
        System.exit(1);
    }

    final boolean isAvroMode = cl.hasOption('a');
    final String predicateExpression = cl.getOptionValue('e');
    final Predicate predicate = PredicateExpressionParser.parse(predicateExpression);

    final Collection<File> sourceFiles = FileUtil.listFiles(sourceDirectory, null);
    int exitCode = 0;
    for (File sourceFile : sourceFiles) {
        try {
            final ValidationOptions val = new ValidationOptions();
            val.setAvroUnionMode(isAvroMode);

            final SchemaParser schemaParser = new SchemaParser();
            schemaParser.setValidationOptions(val);

            schemaParser.parse(new FileInputStream(sourceFile));
            if (schemaParser.hasError()) {
                _log.error("Error parsing " + sourceFile.getPath() + ": " + schemaParser.errorMessageBuilder());
                exitCode = 1;
                continue;
            }

            final DataSchema originalSchema = schemaParser.topLevelDataSchemas().get(0);
            if (!(originalSchema instanceof NamedDataSchema)) {
                _log.error(sourceFile.getPath() + " does not contain valid NamedDataSchema");
                exitCode = 1;
                continue;
            }

            final SchemaParser filterParser = new SchemaParser();
            filterParser.setValidationOptions(val);

            final NamedDataSchema filteredSchema = Filters.removeByPredicate((NamedDataSchema) originalSchema,
                    predicate, filterParser);
            if (filterParser.hasError()) {
                _log.error("Error applying predicate: " + filterParser.errorMessageBuilder());
                exitCode = 1;
                continue;
            }

            final String relativePath = sourceDirectoryURI.relativize(sourceFile.toURI()).getPath();
            final String outputFilePath = outputDirectory.getPath() + File.separator + relativePath;
            final File outputFile = new File(outputFilePath);
            final File outputFileParent = outputFile.getParentFile();
            outputFileParent.mkdirs();
            if (!outputFileParent.exists()) {
                _log.error("Unable to write filtered schema to " + outputFileParent.getPath());
                exitCode = 1;
                continue;
            }

            FileOutputStream fout = new FileOutputStream(outputFile);
            String schemaJson = SchemaToJsonEncoder.schemaToJson(filteredSchema, JsonBuilder.Pretty.INDENTED);
            fout.write(schemaJson.getBytes(RestConstants.DEFAULT_CHARSET));
            fout.close();
        } catch (IOException e) {
            _log.error(e.getMessage());
            exitCode = 1;
        }
    }

    System.exit(exitCode);
}