Example usage for java.net URI toString

List of usage examples for java.net URI toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Returns the content of this URI as a string.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);//  w w  w.  j  a  v a  2 s.c o m

    factory.setExpandEntityReferences(false);

    Document doc = factory.newDocumentBuilder().parse(new File("filename"));
    Source source = new DOMSource(doc);

    URI uri = new File("infilename.xml").toURI();
    source.setSystemId(uri.toString());

    DefaultHandler handler = new MyHandler();
    SAXResult result = new SAXResult(handler);
    Transformer xformer = TransformerFactory.newInstance().newTransformer();
    xformer.transform(source, result);
}

From source file:Main.java

public static void main(String[] args) throws NullPointerException, URISyntaxException {
    URI uri = new URI("http://www.java2s.com");
    System.out.println("URI      : " + uri);
    System.out.println(uri.toString());
}

From source file:com.thed.zapi.cloud.sample.sampleJwtGenerator.java

/**
 * @param args/*from w  w  w  .ja  v  a 2 s. com*/
 * @author Created by swapna.vemula on 12-Dec-2016.
 * @throws URISyntaxException
 * @throws JobProgressException
 * @throws JSONException
 * @throws IOException 
 * @throws IllegalStateException 
 */
public static void main(String[] args) throws URISyntaxException, IllegalStateException, IOException {
    // Replace Zephyr BaseUrl with the <ZAPI_CLOUD_URL> shared with ZAPI Cloud Installation
    String zephyrBaseUrl = "<ZAPI_CLOUD_URL>";
    // zephyr accessKey , we can get from Addons >> zapi section
    String accessKey = "YjE2MjdjMGEtNzExNy0zYjY1LWFkMzQtNjcwMDM3IGFkbWluIGFkbWlu";
    // zephyr secretKey , we can get from Addons >> zapi section
    String secretKey = "qufnbimi96Ob2hq3ISF08yZ8nUvDRHmQwHGeGlk";
    // Jira UserName
    String userName = "admin";
    ZFJCloudRestClient client = ZFJCloudRestClient.restBuilder(zephyrBaseUrl, accessKey, secretKey, userName)
            .build();
    JwtGenerator jwtGenerator = client.getJwtGenerator();

    // API to which the JWT token has to be generated
    String createCycleUri = zephyrBaseUrl + "/public/rest/api/1.0/cycle?expand=&clonedCycleId=";

    URI uri = new URI(createCycleUri);
    int expirationInSec = 360;
    String jwt = jwtGenerator.generateJWT("GET", uri, expirationInSec);

    // Print the URL and JWT token to be used for making the REST call
    System.out.println("FINAL API : " + uri.toString());
    System.out.println("JWT Token : " + jwt);

}

From source file:org.mitre.mpf.rest.client.Main.java

public static void main(String[] args) throws RestClientException, IOException, InterruptedException {
    System.out.println("Starting rest-client!");

    //not necessary for localhost, but left if a proxy configuration is needed
    //System.setProperty("http.proxyHost","");
    //System.setProperty("http.proxyPort","");  

    String currentDirectory;/*from ww  w  .j a va  2 s  .c o m*/
    currentDirectory = System.getProperty("user.dir");
    System.out.println("Current working directory : " + currentDirectory);

    String username = "mpf";
    String password = "mpf123";
    byte[] encodedBytes = Base64.encodeBase64((username + ":" + password).getBytes());
    String base64 = new String(encodedBytes);
    System.out.println("encodedBytes " + base64);
    final String mpfAuth = "Basic " + base64;

    RequestInterceptor authorize = new RequestInterceptor() {
        @Override
        public void intercept(HttpRequestBase request) {
            request.addHeader("Authorization", mpfAuth /*credentials*/);
        }
    };

    //RestClient client = RestClient.builder().requestInterceptor(authorize).build();
    CustomRestClient client = (CustomRestClient) CustomRestClient.builder()
            .restClientClass(CustomRestClient.class).requestInterceptor(authorize).build();

    //getAvailableWorkPipelineNames
    String url = "http://localhost:8080/workflow-manager/rest/pipelines";
    Map<String, String> params = new HashMap<String, String>();
    List<String> availableWorkPipelines = client.get(url, params, new TypeReference<List<String>>() {
    });
    System.out.println("availableWorkPipelines size: " + availableWorkPipelines.size());
    System.out.println(Arrays.toString(availableWorkPipelines.toArray()));

    //processMedia        
    JobCreationRequest jobCreationRequest = new JobCreationRequest();
    URI uri = Paths.get(currentDirectory,
            "/trunk/workflow-manager/src/test/resources/samples/meds/aa/S001-01-t10_01.jpg").toUri();
    jobCreationRequest.getMedia().add(new JobCreationMediaData(uri.toString()));
    uri = Paths.get(currentDirectory,
            "/trunk/workflow-manager/src/test/resources/samples/meds/aa/S008-01-t10_01.jpg").toUri();
    jobCreationRequest.getMedia().add(new JobCreationMediaData(uri.toString()));
    jobCreationRequest.setExternalId("external id");

    //get first DLIB pipeline
    String firstDlibPipeline = availableWorkPipelines.stream()
            //.peek(pipepline -> System.out.println("will filter - " + pipepline))
            .filter(pipepline -> pipepline.startsWith("DLIB")).findFirst().get();

    System.out.println("found firstDlibPipeline: " + firstDlibPipeline);

    jobCreationRequest.setPipelineName(firstDlibPipeline); //grabbed from 'rest/pipelines' - see #1
    //two optional params
    jobCreationRequest.setBuildOutput(true);
    //jobCreationRequest.setPriority(priority); //will be set to 4 (default) if not set
    JobCreationResponse jobCreationResponse = client.customPostObject(
            "http://localhost:8080/workflow-manager/rest/jobs", jobCreationRequest, JobCreationResponse.class);
    System.out.println("jobCreationResponse job id: " + jobCreationResponse.getJobId());

    System.out.println("\n---Sleeping for 10 seconds to let the job process---\n");
    Thread.sleep(10000);

    //getJobStatus
    url = "http://localhost:8080/workflow-manager/rest/jobs"; // /status";
    params = new HashMap<String, String>();
    //OPTIONAL
    //params.put("v", "") - no versioning currently implemented         
    //id is now a path var - if not set, all job info will returned
    url = url + "/" + Long.toString(jobCreationResponse.getJobId());
    SingleJobInfo jobInfo = client.get(url, params, SingleJobInfo.class);
    System.out.println("jobInfo id: " + jobInfo.getJobId());

    //getSerializedOutput
    String jobIdToGetOutputStr = Long.toString(jobCreationResponse.getJobId());
    url = "http://localhost:8080/workflow-manager/rest/jobs/" + jobIdToGetOutputStr + "/output/detection";
    params = new HashMap<String, String>();
    //REQUIRED  - job id is now a path var and required for this endpoint
    String serializedOutput = client.getAsString(url, params);
    System.out.println("serializedOutput: " + serializedOutput);
}

From source file:com.thed.zapi.cloud.sample.CreateTestWithTestSteps.java

public static void main(String[] args) throws JSONException, URISyntaxException, ParseException, IOException {
    final String createTestUri = API_CREATE_TEST.replace("{SERVER}", jiraBaseURL);
    final String createTestStepUri = API_CREATE_TEST_STEP.replace("{SERVER}", zephyrBaseUrl);

    /**/* w  w  w. j  av a 2s . c o  m*/
     * Create Test Parameters, declare Create Test Issue fields Declare more
     * field objects if required
     */

    JSONObject projectObj = new JSONObject();
    projectObj.put("id", projectId); // Project ID where the Test to be
    // Created

    JSONObject issueTypeObj = new JSONObject();
    issueTypeObj.put("id", issueTypeId); // IssueType ID which is Test isse
    // type

    JSONObject assigneeObj = new JSONObject();
    assigneeObj.put("name", userName); // Username of the assignee

    JSONObject reporterObj = new JSONObject();
    reporterObj.put("name", userName); // Username of the Reporter

    String testSummary = "Sample Test case With Steps created through ZAPI Cloud"; // Test
    // Case
    // Summary/Name

    /**
     * Create JSON payload to POST Add more field objects if required
     * 
     * ***DONOT EDIT BELOW ***
     */

    JSONObject fieldsObj = new JSONObject();
    fieldsObj.put("project", projectObj);
    fieldsObj.put("summary", testSummary);
    fieldsObj.put("issuetype", issueTypeObj);
    fieldsObj.put("assignee", assigneeObj);
    fieldsObj.put("reporter", reporterObj);

    JSONObject createTestObj = new JSONObject();
    createTestObj.put("fields", fieldsObj);
    System.out.println(createTestObj.toString());
    byte[] bytesEncoded = Base64.encodeBase64((userName + ":" + password).getBytes());
    String authorizationHeader = "Basic " + new String(bytesEncoded);
    Header header = new BasicHeader(HttpHeaders.AUTHORIZATION, authorizationHeader);

    StringEntity createTestJSON = null;
    try {
        createTestJSON = new StringEntity(createTestObj.toString());
    } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
    }

    HttpResponse response = null;
    HttpClient restClient = new DefaultHttpClient();
    try {
        // System.out.println(issueSearchURL);
        HttpPost createTestReq = new HttpPost(createTestUri);
        createTestReq.addHeader(header);
        createTestReq.addHeader("Content-Type", "application/json");
        createTestReq.setEntity(createTestJSON);

        response = restClient.execute(createTestReq);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    String testId = null;
    int statusCode = response.getStatusLine().getStatusCode();
    // System.out.println(statusCode);
    HttpEntity entity1 = response.getEntity();
    if (statusCode >= 200 && statusCode < 300) {

        String string1 = null;
        try {
            string1 = EntityUtils.toString(entity1);
            System.out.println(string1);
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        JSONObject createTestResp = new JSONObject(string1);
        testId = createTestResp.getString("id");
        System.out.println("testId :" + testId);
    } else {

        try {
            String string = null;
            string = EntityUtils.toString(entity1);
            JSONObject executionResponseObj = new JSONObject(string);
            System.out.println(executionResponseObj.toString());
            throw new ClientProtocolException("Unexpected response status: " + statusCode);

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        }
    }

    /** Create test Steps ***/

    /**
     * Create Steps Replace the step,data,result values as required
     */

    JSONObject testStepJsonObj = new JSONObject();
    testStepJsonObj.put("step", "Sample Test Step");
    testStepJsonObj.put("data", "Sample Test Data");
    testStepJsonObj.put("result", "Sample Expected Result");

    /** DONOT EDIT FROM HERE ***/

    StringEntity createTestStepJSON = null;
    try {
        createTestStepJSON = new StringEntity(testStepJsonObj.toString());
    } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
    }
    String finalURL = createTestStepUri + testId + "?projectId=" + projectId;
    URI uri = new URI(finalURL);
    int expirationInSec = 360;
    JwtGenerator jwtGenerator = client.getJwtGenerator();
    String jwt = jwtGenerator.generateJWT("POST", uri, expirationInSec);
    System.out.println(uri.toString());
    System.out.println(jwt);

    HttpResponse responseTestStep = null;

    HttpPost addTestStepReq = new HttpPost(uri);
    addTestStepReq.addHeader("Content-Type", "application/json");
    addTestStepReq.addHeader("Authorization", jwt);
    addTestStepReq.addHeader("zapiAccessKey", accessKey);
    addTestStepReq.setEntity(createTestStepJSON);

    try {
        responseTestStep = restClient.execute(addTestStepReq);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    int testStepStatusCode = responseTestStep.getStatusLine().getStatusCode();
    System.out.println(testStepStatusCode);
    System.out.println(response.toString());

    if (statusCode >= 200 && statusCode < 300) {
        HttpEntity entity = responseTestStep.getEntity();
        String string = null;
        String stepId = null;
        try {
            string = EntityUtils.toString(entity);
            JSONObject testStepObj = new JSONObject(string);
            stepId = testStepObj.getString("id");
            System.out.println("stepId :" + stepId);
            System.out.println(testStepObj.toString());
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    } else {
        try {
            throw new ClientProtocolException("Unexpected response status: " + statusCode);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        }
    }

}

From source file:gr.iti.mklab.bubing.parser.ITIHTMLParser.java

public static void main(String arg[]) throws IllegalArgumentException, IOException, URISyntaxException,
        JSAPException, NoSuchAlgorithmException {

    final SimpleJSAP jsap = new SimpleJSAP(ITIHTMLParser.class.getName(),
            "Produce the digest of a page: the page is downloaded or passed as argument by specifying a file",
            new Parameter[] {
                    new UnflaggedOption("url", JSAP.STRING_PARSER, JSAP.REQUIRED, "The url of the page."),
                    new Switch("crossAuthorityDuplicates", 'c', "cross-authority-duplicates"),
                    new FlaggedOption("charBufferSize", JSAP.INTSIZE_PARSER, Integer.toString(CHAR_BUFFER_SIZE),
                            JSAP.NOT_REQUIRED, 'b', "buffer",
                            "The size of the parser character buffer (0 for dynamic sizing)."),
                    new FlaggedOption("file", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'f',
                            "file", "The page to be processed."),
                    new FlaggedOption("digester", JSAP.STRING_PARSER, "MD5", JSAP.NOT_REQUIRED, 'd', "digester",
                            "The digester to be used.") });

    JSAPResult jsapResult = jsap.parse(arg);
    if (jsap.messagePrinted())
        System.exit(1);/*from w w w  . ja  v  a2  s. com*/

    final String url = jsapResult.getString("url");
    final String digester = jsapResult.getString("digester");
    final boolean crossAuthorityDuplicates = jsapResult.userSpecified("crossAuthorityDuplicates");
    final int charBufferSize = jsapResult.getInt("charBufferSize");

    final ITIHTMLParser<Void> htmlParser = new ITIHTMLParser<Void>(BinaryParser.forName(digester),
            (TextProcessor<Void>) null, crossAuthorityDuplicates, charBufferSize);
    final SetLinkReceiver linkReceiver = new SetLinkReceiver();
    final byte[] digest;

    if (!jsapResult.userSpecified("file")) {
        final URI uri = new URI(url);
        final HttpGet request = new HttpGet(uri);
        request.setConfig(RequestConfig.custom().setRedirectsEnabled(false).build());
        digest = htmlParser.parse(uri, HttpClients.createDefault().execute(request), linkReceiver);
    } else {
        final String file = jsapResult.getString("file");
        String content = IOUtils.toString(new InputStreamReader(new FileInputStream(file)));
        digest = htmlParser.parse(BURL.parse(url), new StringHttpMessages.HttpResponse(content), linkReceiver);
    }

    System.out.println("DigestHexString: " + Hex.encodeHexString(digest));
    System.out.println("Links: " + linkReceiver.urls);

    Set<String> urlStrings = new ObjectOpenHashSet<String>();
    for (URI link : linkReceiver.urls)
        urlStrings.add(link.toString());
    if (urlStrings.size() != linkReceiver.urls.size())
        System.out.println(
                "There are " + linkReceiver.urls.size() + " URIs but " + urlStrings.size() + " strings");

}

From source file:UploadUrlGenerator.java

public static void main(String[] args) throws Exception {
    Options opts = new Options();

    opts.addOption(Option.builder().longOpt(ENDPOINT_OPTION).required().hasArg().argName("url")
            .desc("Sets the ECS S3 endpoint to use, e.g. https://ecs.company.com:9021").build());
    opts.addOption(Option.builder().longOpt(ACCESS_KEY_OPTION).required().hasArg().argName("access-key")
            .desc("Sets the Access Key (user) to sign the request").build());
    opts.addOption(Option.builder().longOpt(SECRET_KEY_OPTION).required().hasArg().argName("secret")
            .desc("Sets the secret key to sign the request").build());
    opts.addOption(Option.builder().longOpt(BUCKET_OPTION).required().hasArg().argName("bucket-name")
            .desc("The bucket containing the object").build());
    opts.addOption(Option.builder().longOpt(KEY_OPTION).required().hasArg().argName("object-key")
            .desc("The object name (key) to access with the URL").build());
    opts.addOption(Option.builder().longOpt(EXPIRES_OPTION).hasArg().argName("minutes")
            .desc("Minutes from local time to expire the request.  1 day = 1440, 1 week=10080, "
                    + "1 month (30 days)=43200, 1 year=525600.  Defaults to 1 hour (60).")
            .build());/* w  ww  .j a  v  a 2 s  .com*/
    opts.addOption(Option.builder().longOpt(VERB_OPTION).hasArg().argName("http-verb").type(HttpMethod.class)
            .desc("The HTTP verb that will be used with the URL (PUT, GET, etc).  Defaults to GET.").build());
    opts.addOption(Option.builder().longOpt(CONTENT_TYPE_OPTION).hasArg().argName("mimetype")
            .desc("Sets the Content-Type header (e.g. image/jpeg) that will be used with the request.  "
                    + "Must match exactly.  Defaults to application/octet-stream for PUT/POST and "
                    + "null for all others")
            .build());

    DefaultParser dp = new DefaultParser();

    CommandLine cmd = null;
    try {
        cmd = dp.parse(opts, args);
    } catch (ParseException e) {
        System.err.println("Error: " + e.getMessage());
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp("java -jar UploadUrlGenerator-xxx.jar", opts, true);
        System.exit(255);
    }

    URI endpoint = URI.create(cmd.getOptionValue(ENDPOINT_OPTION));
    String accessKey = cmd.getOptionValue(ACCESS_KEY_OPTION);
    String secretKey = cmd.getOptionValue(SECRET_KEY_OPTION);
    String bucket = cmd.getOptionValue(BUCKET_OPTION);
    String key = cmd.getOptionValue(KEY_OPTION);
    HttpMethod method = HttpMethod.GET;
    if (cmd.hasOption(VERB_OPTION)) {
        method = HttpMethod.valueOf(cmd.getOptionValue(VERB_OPTION).toUpperCase());
    }
    int expiresMinutes = 60;
    if (cmd.hasOption(EXPIRES_OPTION)) {
        expiresMinutes = Integer.parseInt(cmd.getOptionValue(EXPIRES_OPTION));
    }
    String contentType = null;
    if (method == HttpMethod.PUT || method == HttpMethod.POST) {
        contentType = "application/octet-stream";
    }

    if (cmd.hasOption(CONTENT_TYPE_OPTION)) {
        contentType = cmd.getOptionValue(CONTENT_TYPE_OPTION);
    }

    BasicAWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
    ClientConfiguration cc = new ClientConfiguration();
    // Force use of v2 Signer.  ECS does not support v4 signatures yet.
    cc.setSignerOverride("S3SignerType");
    AmazonS3Client s3 = new AmazonS3Client(credentials, cc);
    s3.setEndpoint(endpoint.toString());
    S3ClientOptions s3c = new S3ClientOptions();
    s3c.setPathStyleAccess(true);
    s3.setS3ClientOptions(s3c);

    // Sign the URL
    Calendar c = Calendar.getInstance();
    c.add(Calendar.MINUTE, expiresMinutes);
    GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(bucket, key).withExpiration(c.getTime())
            .withMethod(method);
    if (contentType != null) {
        req = req.withContentType(contentType);
    }
    URL u = s3.generatePresignedUrl(req);
    System.out.printf("URL: %s\n", u.toURI().toASCIIString());
    System.out.printf("HTTP Verb: %s\n", method);
    System.out.printf("Expires: %s\n", c.getTime());
    System.out.println("To Upload with curl:");

    StringBuilder sb = new StringBuilder();
    sb.append("curl ");

    if (method != HttpMethod.GET) {
        sb.append("-X ");
        sb.append(method.toString());
        sb.append(" ");
    }

    if (contentType != null) {
        sb.append("-H \"Content-Type: ");
        sb.append(contentType);
        sb.append("\" ");
    }

    if (method == HttpMethod.POST || method == HttpMethod.PUT) {
        sb.append("-T <filename> ");
    }

    sb.append("\"");
    sb.append(u.toURI().toASCIIString());
    sb.append("\"");

    System.out.println(sb.toString());

    System.exit(0);
}

From source file:edu.usc.goffish.gofs.tools.GoFSFormat.java

public static void main(String[] args) throws IOException {
    if (args.length < REQUIRED_ARGS) {
        PrintUsageAndQuit(null);/*from  w ww. ja  v  a 2 s  . c o m*/
    }

    if (args.length == 1 && args[0].equals("-help")) {
        PrintUsageAndQuit(null);
    }

    Path executableDirectory;
    try {
        executableDirectory = Paths
                .get(GoFSFormat.class.getProtectionDomain().getCodeSource().getLocation().toURI()).getParent();
    } catch (URISyntaxException e) {
        throw new RuntimeException("Unexpected error retrieving executable location", e);
    }
    Path configPath = executableDirectory.resolve(DEFAULT_CONFIG).normalize();

    boolean copyBinaries = false;

    // parse optional arguments
    int i = 0;
    OptArgLoop: for (i = 0; i < args.length - REQUIRED_ARGS; i++) {
        switch (args[i]) {
        case "-config":
            i++;

            try {
                configPath = Paths.get(args[i]);
            } catch (InvalidPathException e) {
                PrintUsageAndQuit("Config file - " + e.getMessage());
            }

            break;
        case "-copyBinaries":
            copyBinaries = true;
            break;
        default:
            break OptArgLoop;
        }
    }

    if (args.length - i < REQUIRED_ARGS) {
        PrintUsageAndQuit(null);
    }

    // finished parsing args
    if (i < args.length) {
        PrintUsageAndQuit("Unrecognized argument \"" + args[i] + "\"");
    }

    // parse config

    System.out.println("Parsing config...");

    PropertiesConfiguration config = new PropertiesConfiguration();
    config.setDelimiterParsingDisabled(true);
    try {
        config.load(Files.newInputStream(configPath));
    } catch (ConfigurationException e) {
        throw new IOException(e);
    }

    // retrieve data nodes
    ArrayList<URI> dataNodes;
    {
        String[] dataNodesArray = config.getStringArray(GOFS_DATANODES_KEY);
        if (dataNodesArray.length == 0) {
            throw new ConversionException("Config must contain key " + GOFS_DATANODES_KEY);
        }

        dataNodes = new ArrayList<>(dataNodesArray.length);

        if (dataNodesArray.length == 0) {
            throw new ConversionException("Config key " + GOFS_DATANODES_KEY
                    + " has invalid format - must define at least one data node");
        }

        try {
            for (String node : dataNodesArray) {
                URI dataNodeURI = new URI(node);

                if (!"file".equalsIgnoreCase(dataNodeURI.getScheme())) {
                    throw new ConversionException("config key " + GOFS_DATANODES_KEY + " value \"" + dataNodeURI
                            + "\" has invalid format - data node urls must have 'file' scheme");
                } else if (dataNodeURI.getPath() == null || dataNodeURI.getPath().isEmpty()) {
                    throw new ConversionException("config key " + GOFS_DATANODES_KEY + " value \"" + dataNodeURI
                            + "\" has invalid format - data node urls must have an absolute path specified");
                }

                // ensure uri ends with a slash, so we know it is a directory
                if (!dataNodeURI.getPath().endsWith("/")) {
                    dataNodeURI = dataNodeURI.resolve(dataNodeURI.getPath() + "/");
                }

                dataNodes.add(dataNodeURI);
            }
        } catch (URISyntaxException e) {
            throw new ConversionException(
                    "Config key " + GOFS_DATANODES_KEY + " has invalid format - " + e.getMessage());
        }
    }

    // validate serializer type
    Class<? extends ISliceSerializer> serializerType;
    {
        String serializerTypeName = config.getString(GOFS_SERIALIZER_KEY);
        if (serializerTypeName == null) {
            throw new ConversionException("Config must contain key " + GOFS_SERIALIZER_KEY);
        }

        try {
            serializerType = SliceSerializerProvider.loadSliceSerializerType(serializerTypeName);
        } catch (ReflectiveOperationException e) {
            throw new ConversionException(
                    "Config key " + GOFS_SERIALIZER_KEY + " has invalid format - " + e.getMessage());
        }
    }

    // retrieve name node
    IInternalNameNode nameNode;
    try {
        nameNode = NameNodeProvider.loadNameNodeFromConfig(config, GOFS_NAMENODE_TYPE_KEY,
                GOFS_NAMENODE_LOCATION_KEY);
    } catch (ReflectiveOperationException e) {
        throw new RuntimeException("Unable to load name node", e);
    }

    System.out.println("Contacting name node...");

    // validate name node
    if (!nameNode.isAvailable()) {
        throw new IOException("Name node at " + nameNode.getURI() + " is not available");
    }

    System.out.println("Contacting data nodes...");

    // validate data nodes
    for (URI dataNode : dataNodes) {
        // only attempt ssh if host exists
        if (dataNode.getHost() != null) {
            try {
                SSHHelper.SSH(dataNode, "true");
            } catch (IOException e) {
                throw new IOException("Data node at " + dataNode + " is not available", e);
            }
        }
    }

    // create temporary directory
    Path workingDir = Files.createTempDirectory("gofs_format");
    try {
        // create deploy directory
        Path deployDirectory = Files.createDirectory(workingDir.resolve(DATANODE_DIR_NAME));

        // create empty slice directory
        Files.createDirectory(deployDirectory.resolve(DataNode.DATANODE_SLICE_DIR));

        // copy binaries
        if (copyBinaries) {
            System.out.println("Copying binaries...");
            FileUtils.copyDirectory(executableDirectory.toFile(),
                    deployDirectory.resolve(executableDirectory.getFileName()).toFile());
        }

        // write config file
        Path dataNodeConfigFile = deployDirectory.resolve(DataNode.DATANODE_CONFIG);
        try {
            // create config for every data node and scp deploy folder into place
            for (URI dataNodeParent : dataNodes) {
                URI dataNode = dataNodeParent.resolve(DATANODE_DIR_NAME);

                PropertiesConfiguration datanode_config = new PropertiesConfiguration();
                datanode_config.setDelimiterParsingDisabled(true);
                datanode_config.setProperty(DataNode.DATANODE_INSTALLED_KEY, true);
                datanode_config.setProperty(DataNode.DATANODE_NAMENODE_TYPE_KEY,
                        config.getString(GOFS_NAMENODE_TYPE_KEY));
                datanode_config.setProperty(DataNode.DATANODE_NAMENODE_LOCATION_KEY,
                        config.getString(GOFS_NAMENODE_LOCATION_KEY));
                datanode_config.setProperty(DataNode.DATANODE_LOCALHOSTURI_KEY, dataNode.toString());

                try {
                    datanode_config.save(Files.newOutputStream(dataNodeConfigFile));
                } catch (ConfigurationException e) {
                    throw new IOException(e);
                }

                System.out.println("Formatting data node " + dataNode.toString() + "...");

                // scp everything into place on the data node
                SCPHelper.SCP(deployDirectory, dataNodeParent);

                // update name node
                nameNode.addDataNode(dataNode);
            }

            // update name node
            nameNode.setSerializer(serializerType);
        } catch (Exception e) {
            System.out.println(
                    "ERROR: data node formatting interrupted - name node and data nodes are in an inconsistent state and require clean up");
            throw e;
        }

        System.out.println("GoFS format complete");

    } finally {
        FileUtils.deleteQuietly(workingDir.toFile());
    }
}

From source file:Main.java

/**
 * Convert a Java URI to a String (Not Uri)
 * @param uri java.net.URI to convert// w  w  w .ja  v a  2  s  .  c  om
 * @return String
 */
public static String convertJavaUriToString(java.net.URI uri) {
    return uri.toString();
}

From source file:Main.java

public static void setURIAttribute(Element el, String attr, URI uri) {
    el.setAttribute(attr, uri.toString());
}