Example usage for java.net URI create

List of usage examples for java.net URI create

Introduction

In this page you can find the example usage for java.net URI create.

Prototype

public static URI create(String str) 

Source Link

Document

Creates a URI by parsing the given string.

Usage

From source file:org.apache.taverna.scufl2.wfdesc.WfdescAgent.java

public static void main(String[] args) throws Exception {
    URI baseURI;// w ww. j  a  v a  2 s .co m
    if (args.length > 0) {
        baseURI = URI.create(args[0]);
    } else {
        baseURI = DEFAULT_BASE;
    }

    new WfdescAgent(baseURI).annotateT2flows();

}

From source file:com.atlauncher.Bootstrap.java

public static void main(String[] args) {
    String json = null;/*  w  w  w.j a v  a  2  s .  c  om*/

    if (!Files.isDirectory(PATH)) {
        try {
            Files.createDirectories(PATH);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    try {
        json = IOUtils.toString(URI.create("http://download.nodecdn.net/containers/atl/v4/app.json"));
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(1);
    }

    Application application = GSON.fromJson(json, Application.class);

    Dependency currentDependency = null;

    if (Files.exists(PATH.resolve("nwjs.json"))) {
        try {
            currentDependency = GSON.fromJson(FileUtils.readFileToString(PATH.resolve("nwjs.json").toFile()),
                    Dependency.class);
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    for (Dependency dependency : application.getDependencies()) {
        if (dependency.shouldInstall() && !dependency.matches(currentDependency)) {
            if (Files.isDirectory(PATH.resolve("nwjs/"))) {
                try {
                    FileUtils.deleteDirectory(PATH.resolve("nwjs/").toFile());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            try {
                File zipFile = PATH.resolve("nwjs/temp.zip").toFile();
                FileUtils.copyURLToFile(dependency.getUrl(), zipFile);
                Utils.unzip(zipFile, PATH.resolve("nwjs/").toFile());
                FileUtils.forceDelete(zipFile);

                currentDependency = dependency;

                FileUtils.writeStringToFile(PATH.resolve("nwjs.json").toFile(), GSON.toJson(dependency));

                break;
            } catch (IOException e) {
                e.printStackTrace();
                System.exit(1);
            }
        }
    }

    App currentApp = null;

    if (Files.exists(PATH.resolve("app.json"))) {
        try {
            currentApp = GSON.fromJson(FileUtils.readFileToString(PATH.resolve("app.json").toFile()),
                    App.class);
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    if (!application.getApp().matches(currentApp)
            || (currentApp != null && !Files.exists(PATH.resolve(currentApp.getFilename())))) {
        if (currentApp != null && Files.exists(PATH.resolve(currentApp.getFilename()))) {
            try {
                FileUtils.forceDelete(PATH.resolve(currentApp.getFilename()).toFile());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        try {
            FileUtils.copyURLToFile(application.getApp().getUrl(),
                    PATH.resolve(application.getApp().getFilename()).toFile());

            currentApp = application.getApp();

            FileUtils.writeStringToFile(PATH.resolve("app.json").toFile(), GSON.toJson(application.getApp()));
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    if (currentDependency == null || currentApp == null) {
        System.exit(1);
    }

    List<String> arguments = new ArrayList<>();
    arguments.add(PATH.resolve("nwjs/").toAbsolutePath() + currentDependency.getStartup());
    arguments.add(currentApp.getFilename());
    ProcessBuilder processBuilder = new ProcessBuilder(arguments);
    processBuilder.directory(PATH.toFile());
    try {
        processBuilder.start();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.twitter.distributedlog.basic.MultiReader.java

public static void main(String[] args) throws Exception {
    if (2 != args.length) {
        System.out.println(HELP);
        return;/*from  w  ww . ja v a  2s .c  o m*/
    }

    String dlUriStr = args[0];
    final String streamList = args[1];

    URI uri = URI.create(dlUriStr);
    DistributedLogConfiguration conf = new DistributedLogConfiguration();
    DistributedLogNamespace namespace = DistributedLogNamespaceBuilder.newBuilder().conf(conf).uri(uri).build();

    String[] streamNameList = StringUtils.split(streamList, ',');
    DistributedLogManager[] managers = new DistributedLogManager[streamNameList.length];

    for (int i = 0; i < managers.length; i++) {
        String streamName = streamNameList[i];
        // open the dlm
        System.out.println("Opening log stream " + streamName);
        managers[i] = namespace.openLog(streamName);
    }

    final CountDownLatch keepAliveLatch = new CountDownLatch(1);

    for (DistributedLogManager dlm : managers) {
        final DistributedLogManager manager = dlm;
        dlm.getLastLogRecordAsync().addEventListener(new FutureEventListener<LogRecordWithDLSN>() {
            @Override
            public void onFailure(Throwable cause) {
                if (cause instanceof LogNotFoundException) {
                    System.err.println(
                            "Log stream " + manager.getStreamName() + " is not found. Please create it first.");
                    keepAliveLatch.countDown();
                } else if (cause instanceof LogEmptyException) {
                    System.err.println("Log stream " + manager.getStreamName() + " is empty.");
                    readLoop(manager, DLSN.InitialDLSN, keepAliveLatch);
                } else {
                    System.err.println("Encountered exception on process stream " + manager.getStreamName());
                    keepAliveLatch.countDown();
                }
            }

            @Override
            public void onSuccess(LogRecordWithDLSN record) {
                readLoop(manager, record.getDlsn(), keepAliveLatch);
            }
        });
    }
    keepAliveLatch.await();
    for (DistributedLogManager dlm : managers) {
        dlm.close();
    }
    namespace.close();
}

From source file:adapter.tdb.sync.clients.GetVocabularyOfMagicDrawAdapterAndPushToStore.java

public static void main(String[] args) {

    Thread thread = new Thread() {
        public void start() {

            URI vocabURI = URI.create("http://localhost:8080/oslc4jmagicdraw/services/sysml-rdfvocabulary");

            // create an empty RDF model
            Model model = ModelFactory.createDefaultModel();

            // use FileManager to read OSLC Resource Shape in RDF
            //            String inputFileName = "file:C:/Users/Axel/git/EcoreMetamodel2OSLCSpecification/EcoreMetamodel2OSLCSpecification/Resource Shapes/Block.rdf";
            //            String inputFileName = "file:C:/Users/Axel/git/ecore2oslc/EcoreMetamodel2OSLCSpecification/RDF Vocabulary/sysmlRDFVocabulary of OMG.rdf";
            //            InputStream in = FileManager.get().open(inputFileName);
            //            if (in == null) {
            //               throw new IllegalArgumentException("File: " + inputFileName
            //                     + " not found");
            //            }

            // create TDB dataset
            String directory = TriplestoreUtil.getTriplestoreLocation();
            Dataset dataset = TDBFactory.createDataset(directory);
            Model tdbModel = dataset.getDefaultModel();
            try {

                HttpGet httpget = new HttpGet(vocabURI);
                httpget.addHeader("accept", "application/rdf+xml");
                CloseableHttpClient httpClient = HttpClients.createDefault();
                HttpResponse response = httpClient.execute(httpget);
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    InputStream inputStream = entity.getContent();
                    model.read(inputStream, null);
                    tdbModel.add(model);
                }//from   w w w .j  a  v  a2s.  c om

            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            tdbModel.close();
            dataset.close();
        }
    };
    thread.start();
    try {
        thread.join();
        System.out.println("Vocabulary of OSLC MagicDraw SysML adapter added to triplestore");
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:com.github.sdbg.debug.core.internal.webkit.protocol.TestMain.java

/**
 * @param args//from ww  w.j  a  v a2s . c o m
 * @throws IOException
 * @throws InterruptedException
 * @throws JSONException
 */
public static void main(String[] args) throws IOException, InterruptedException {
    if (args.length != 1) {
        System.out.println("usage Main <port>");
        return;
    }

    int port = Integer.parseInt(args[0]);

    List<ChromiumTabInfo> tabs = ChromiumConnector.getAvailableTabs(port);

    //ChromiumConnector.getWebSocketURLFor(port, 1);
    URI uri = URI.create(tabs.get(0).getWebSocketDebuggerUrl());
    WebkitConnection connection = new WebkitConnection(uri);

    connection.addConnectionListener(new WebkitConnectionListener() {
        @Override
        public void connectionClosed(WebkitConnection connection) {
            System.out.println("connection closed");
        }
    });

    connection.connect();

    System.out.println("connection opened");

    // add a console listener
    connection.getConsole().addConsoleListener(new ConsoleListener() {
        @Override
        public void messageAdded(String message, String url, int line, List<CallFrame> stackTrace) {
            System.out.println("message added: " + message);
        }

        @Override
        public void messageRepeatCountUpdated(int count) {
            System.out.println("messageRepeatCountUpdated: " + count);
        }

        @Override
        public void messagesCleared() {
            System.out.println("messages cleared");
        }
    });

    // enable console events
    connection.getConsole().enable();

    // add a debugger listener
    connection.getDebugger().addDebuggerListener(new DebuggerListener() {
        @Override
        public void debuggerBreakpointResolved(WebkitBreakpoint breakpoint) {
            System.out.println("debuggerBreakpointResolved: " + breakpoint);
        }

        @Override
        public void debuggerGlobalObjectCleared() {
            System.out.println("debuggerGlobalObjectCleared");
        }

        @Override
        public void debuggerPaused(PausedReasonType reason, List<WebkitCallFrame> frames,
                WebkitRemoteObject exception) {
            System.out.println("debugger paused: " + reason);

            for (WebkitCallFrame frame : frames) {
                System.out.println("  " + frame);
            }
        }

        @Override
        public void debuggerResumed() {
            System.out.println("debugger resumed");
        }

        @Override
        public void debuggerScriptParsed(WebkitScript script) {
            System.out.println("debugger script: " + script);
        }
    });

    // enable debugger events
    connection.getDebugger().enable();

    // navigate to cheese.com
    connection.getPage().navigate("http://www.cheese.com");

    //Thread.sleep(2000);

    //connection.close();
}

From source file:net.tirasa.olingooauth2.Main.java

public static void main(final String[] args) throws Exception {
    final Properties oauth2Properties = new Properties();
    oauth2Properties.load(Main.class.getResourceAsStream("/oauth2.properties"));

    final AzureADOAuth2HttpClientFactory oauth2HCF = new AzureADOAuth2HttpClientFactory(
            oauth2Properties.getProperty("oauth2.authority"), oauth2Properties.getProperty("oauth2.clientId"),
            oauth2Properties.getProperty("oauth2.redirectURI"),
            oauth2Properties.getProperty("oauth2.resourceURI"),
            new UsernamePasswordCredentials(oauth2Properties.getProperty("oauth2.username"),
                    oauth2Properties.getProperty("oauth2.password")));

    final ODataClient client = ODataClientFactory.getEdmEnabledV4("https://outlook.office365.com/ews/odata");
    client.getConfiguration().setHttpClientFactory(oauth2HCF);

    final ODataEntitySetRequest<ODataEntitySet> messages = client.getRetrieveRequestFactory()
            .getEntitySetRequest(/*from  w  w  w .  j  a  va 2  s.  c o m*/
                    URI.create("https://outlook.office365.com/ews/odata/Me/Folders('Inbox')/Messages"));
    for (ODataEntity message : messages.execute().getBody().getEntities()) {
        System.out.println("Message: " + message.getId());
    }
}

From source file:com.jeffy.hdfs.compression.FileCompressor.java

/**
 * @param args/*  ww w.  j  av a 2  s .  c o  m*/
 * ??????
 * ????
 * @throws IOException 
 */
public static void main(String[] args) throws IOException {
    Configuration conf = new Configuration();
    //??
    CompressionCodecFactory factory = new CompressionCodecFactory(conf);
    // For example for the 'GzipCodec' codec class name the alias are 'gzip' and 'gzipcodec'.
    CompressionCodec codec = factory.getCodecByName(args[0]);
    if (codec == null) {//???
        System.err.println("Comperssion codec not found for " + args[0]);
        System.exit(1);
    }
    String ext = codec.getDefaultExtension();
    Compressor compressor = null;
    try {
        //?CodecPool?Compressor
        compressor = CodecPool.getCompressor(codec);
        for (int i = 1; i < args.length; i++) {
            String filename = args[i] + ext;
            System.out.println("Compression the file " + filename);
            try (FileSystem outFs = FileSystem.get(URI.create(filename), conf);
                    FileSystem inFs = FileSystem.get(URI.create(args[i]), conf);
                    InputStream in = inFs.open(new Path(args[i]))) {//
                //Compressor?
                CompressionOutputStream out = codec.createOutputStream(outFs.create(new Path(filename)),
                        compressor);
                //?????
                IOUtils.copy(in, out);
                out.finish();//?finish()?flush()???
                compressor.reset(); //???????java.io.IOException: write beyond end of stream
            }
        }
    } finally {//?Compressor??
        CodecPool.returnCompressor(compressor);
    }
}

From source file:cf.service.integration.FunctionalTest.java

public static void main(String[] args) throws Exception {
    final CfTokens cfTokens = new CfTokens();
    final CfTokens.CfToken target = cfTokens.getCurrentTargetToken();

    if (target == null) {
        System.err.println("It appears you haven't logged into a Cloud Foundry instance with cf.");
        return;/*from w  ww  .j  a v a  2  s . co  m*/
    }
    if (target.getVersion() == null || target.getVersion() != 2) {
        System.err.println("You must target a v2 Cloud Controller using cf.");
        return;
    }
    if (target.getSpaceGuid() == null) {
        System.err.println("You must select a space to use using cf.");
        return;
    }

    LOGGER.info("Using Cloud Controller at: {}", target.getTarget());

    final String label = "testService" + ThreadLocalRandom.current().nextInt();
    final String provider = "core";
    final URI url = URI.create("http://" + localIp(target.getTarget()) + ":" + serverPort);
    final String description = "A service used for testing the service framework.";
    final String version = "0.1";

    final String servicePlan = "ServicePlan";
    final String servicePlanDescription = "Finest service... ever.";

    final String authToken = "SsshhhThisIsASecret";
    final CloudController cloudControllerClient = new DefaultCloudController(new DefaultHttpClient(),
            target.getTarget());
    try (final SimpleHttpServer server = new SimpleHttpServer(new InetSocketAddress(serverPort))) {

        final UUID serviceGuid = cloudControllerClient.createService(target.getToken(),
                new Service(label, provider, url, description, version, null, true, null));
        LOGGER.debug("Created service with guid: {}", serviceGuid);

        final TestProvisioner provisioner = new TestProvisioner();
        new NettyBrokerServer(server, provisioner, authToken);

        try {
            final UUID servicePlanGuid = cloudControllerClient.createServicePlan(target.getToken(),
                    new ServicePlan(servicePlan, servicePlanDescription, serviceGuid, true, null));
            LOGGER.debug("Created service plan with guid: {}", serviceGuid);

            final UUID authTokenGuid = cloudControllerClient.createAuthToken(target.getToken(),
                    new ServiceAuthToken(label, provider, authToken));
            LOGGER.debug("Created service token with guid: {}", authTokenGuid);
            try {
                final String instanceName = "myservice";
                final UUID serviceInstanceGuid = cloudControllerClient.createServiceInstance(target.getToken(),
                        instanceName, servicePlanGuid, target.getSpaceGuid());
                int instanceId = -1;
                try {
                    assertEquals(1, provisioner.getCreateInvocationCount());
                    instanceId = provisioner.getLastCreateId();
                } finally {
                    cloudControllerClient.deleteServiceInstance(target.getToken(), serviceInstanceGuid);
                    assertEquals(provisioner.getDeleteInvocationCount(), 1);
                    assertEquals(provisioner.getLastDeleteId(), instanceId);
                }
            } finally {
                cloudControllerClient.deleteServiceAuthToken(target.getToken(), authTokenGuid);
            }
        } finally {
            cloudControllerClient.deleteService(target.getToken(), serviceGuid);
        }
    }

    // TODO: Create service pointing to test gateway
    // TODO: Create service instance and validate

}

From source file:it.anyplace.sync.webclient.Main.java

public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption("C", "set-config", true, "set config file for s-client");
    options.addOption("h", "help", false, "print help");
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(options, args);

    if (cmd.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("s-client", options);
        return;//from www  . j  av  a  2s .c  o m
    }

    File configFile = cmd.hasOption("C") ? new File(cmd.getOptionValue("C"))
            : new File(System.getProperty("user.home"), ".s-client.properties");
    logger.info("using config file = {}", configFile);
    try (ConfigurationService configuration = ConfigurationService.newLoader().loadFrom(configFile)) {
        FileUtils.cleanDirectory(configuration.getTemp());
        KeystoreHandler.newLoader().loadAndStore(configuration);
        logger.debug("{}", configuration.getStorageInfo().dumpAvailableSpace());
        try (HttpService httpService = new HttpService(configuration)) {
            httpService.start();
            if (Desktop.isDesktopSupported()) {
                Desktop.getDesktop().browse(
                        URI.create("http://localhost:" + httpService.getPort() + "/web/webclient.html"));
            }
            httpService.join();
        }
    }
}

From source file:org.wso2.msf4j.example.SampleClient.java

public static void main(String[] args) throws IOException {
    HttpEntity messageEntity = createMessageForComplexForm();
    // Uncomment the required message body based on the method that want to be used
    //HttpEntity messageEntity = createMessageForMultipleFiles();
    //HttpEntity messageEntity = createMessageForSimpleFormStreaming();

    String serverUrl = "http://localhost:8080/formService/complexForm";
    // Uncomment the required service url based on the method that want to be used
    //String serverUrl = "http://localhost:8080/formService/multipleFiles";
    //String serverUrl = "http://localhost:8080/formService/simpleFormStreaming";

    URL url = URI.create(serverUrl).toURL();
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);//from   ww w  .jav a  2  s  .c  om
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", messageEntity.getContentType().getValue());
    try (OutputStream out = connection.getOutputStream()) {
        messageEntity.writeTo(out);
    }

    InputStream inputStream = connection.getInputStream();
    String response = StreamUtil.asString(inputStream);
    IOUtils.closeQuietly(inputStream);
    connection.disconnect();
    System.out.println(response);

}