Example usage for java.net URI URI

List of usage examples for java.net URI URI

Introduction

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

Prototype

public URI(String str) throws URISyntaxException 

Source Link

Document

Constructs a URI by parsing the given string.

Usage

From source file:org.eclipse.lyo.client.oslc.samples.RTCFormSample.java

/**
 * Login to the RTC server and perform some OSLC actions
 * @param args/*from  w  w  w.  j  a va  2 s  .  com*/
 * @throws ParseException 
 */
public static void main(String[] args) throws ParseException {

    Options options = new Options();

    options.addOption("url", true, "url");
    options.addOption("user", true, "user ID");
    options.addOption("password", true, "password");
    options.addOption("project", true, "project area");

    CommandLineParser cliParser = new GnuParser();

    //Parse the command line
    CommandLine cmd = cliParser.parse(options, args);

    if (!validateOptions(cmd)) {
        logger.severe(
                "Syntax:  java <class_name> -url https://<server>:port/<context>/ -user <user> -password <password> -project \"<project_area>\"");
        logger.severe(
                "Example: java RTCFormSample -url https://exmple.com:9443/ccm -user ADMIN -password ADMIN -project \"JKE Banking (Change Management)\"");
        return;
    }

    String webContextUrl = cmd.getOptionValue("url");
    String user = cmd.getOptionValue("user");
    String passwd = cmd.getOptionValue("password");
    String projectArea = cmd.getOptionValue("project");

    try {

        //STEP 1: Initialize a Jazz rootservices helper and indicate we're looking for the ChangeManagement catalog
        //RTC contains a service provider for CM and SCM, so we need to indicate our interest in CM
        JazzRootServicesHelper helper = new JazzRootServicesHelper(webContextUrl, OSLCConstants.OSLC_CM_V2);

        //STEP 2: Create a new Form Auth client with the supplied user/password
        JazzFormAuthClient client = helper.initFormClient(user, passwd);

        //STEP 3: Login in to Jazz Server
        if (client.formLogin() == HttpStatus.SC_OK) {

            //STEP 4: Get the URL of the OSLC ChangeManagement catalog
            String catalogUrl = helper.getCatalogUrl();

            //STEP 5: Find the OSLC Service Provider for the project area we want to work with
            String serviceProviderUrl = client.lookupServiceProviderUrl(catalogUrl, projectArea);

            //STEP 6: Get the Query Capabilities URL so that we can run some OSLC queries
            String queryCapability = client.lookupQueryCapability(serviceProviderUrl, OSLCConstants.OSLC_CM_V2,
                    OSLCConstants.CM_CHANGE_REQUEST_TYPE);

            //SCENARIO A: Run a query for all open ChangeRequests with OSLC paging of 10 items per
            //page turned on and list the members of the result
            OslcQueryParameters queryParams = new OslcQueryParameters();
            queryParams.setWhere("oslc_cm:closed=false");
            queryParams.setSelect("dcterms:identifier,dcterms:title,oslc_cm:status");
            OslcQuery query = new OslcQuery(client, queryCapability, 10, queryParams);

            OslcQueryResult result = query.submit();

            boolean processAsJavaObjects = true;
            processPagedQueryResults(result, client, processAsJavaObjects);

            System.out.println("\n------------------------------\n");

            //SCENARIO B:  Run a query for a specific ChangeRequest selecting only certain 
            //attributes and then print it as raw XML.  Change the dcterms:identifier below to match a 
            //real workitem in your RTC project area
            OslcQueryParameters queryParams2 = new OslcQueryParameters();
            queryParams2.setWhere("dcterms:identifier=\"10\"");
            queryParams2.setSelect(
                    "dcterms:identifier,dcterms:title,dcterms:creator,dcterms:created,oslc_cm:status");
            OslcQuery query2 = new OslcQuery(client, queryCapability, queryParams2);

            OslcQueryResult result2 = query2.submit();
            ClientResponse rawResponse = result2.getRawResponse();
            processRawResponse(rawResponse);
            rawResponse.consumeContent();

            //SCENARIO C:  RTC Workitem creation and update
            ChangeRequest changeRequest = new ChangeRequest();
            changeRequest.setTitle("Implement accessibility in Pet Store application");
            changeRequest.setDescription(
                    "Image elements must provide a description in the 'alt' attribute for consumption by screen readers.");
            changeRequest.addTestedByTestCase(new Link(new URI("http://qmprovider/testcase/1"),
                    "Accessibility verification using a screen reader"));
            changeRequest.addDctermsType("task");

            //Get the Creation Factory URL for change requests so that we can create one
            String changeRequestCreation = client.lookupCreationFactory(serviceProviderUrl,
                    OSLCConstants.OSLC_CM_V2, changeRequest.getRdfTypes()[0].toString());

            //Create the change request
            ClientResponse creationResponse = client.createResource(changeRequestCreation, changeRequest,
                    OslcMediaType.APPLICATION_RDF_XML, OslcMediaType.APPLICATION_RDF_XML);
            String changeRequestLocation = creationResponse.getHeaders().getFirst(HttpHeaders.LOCATION);
            creationResponse.consumeContent();
            System.out.println("Change Request created a location " + changeRequestLocation);

            //Get the change request from the service provider and update its title property 
            changeRequest = client.getResource(changeRequestLocation, OslcMediaType.APPLICATION_RDF_XML)
                    .getEntity(ChangeRequest.class);
            changeRequest.setTitle(changeRequest.getTitle() + " (updated)");

            //Create a partial update URL so that only the title will be updated.
            //Assuming (for readability) that the change request URL does not already contain a '?'
            String updateUrl = changeRequest.getAbout() + "?oslc.properties=dcterms:title";

            //Update the change request at the service provider
            ClientResponse updateResponse = client.updateResource(updateUrl, changeRequest,
                    OslcMediaType.APPLICATION_RDF_XML, OslcMediaType.APPLICATION_RDF_XML);

            updateResponse.consumeContent();

        }
    } catch (RootServicesException re) {
        logger.log(Level.SEVERE,
                "Unable to access the Jazz rootservices document at: " + webContextUrl + "/rootservices", re);
    } catch (Exception e) {
        logger.log(Level.SEVERE, e.getMessage(), e);
    }

}

From source file:com.jrodeo.queue.messageset.provider.TestHttpClient5.java

public static void main(String[] args) throws Exception {
    if (args.length < 2) {
        System.out.println("Usage: <target URI> <no of requests> <concurrent connections>");
        System.exit(-1);/*from   w w w.  j a  va2  s  .c  om*/
    }
    URI targetURI = new URI(args[0]);
    int n = Integer.parseInt(args[1]);
    int c = 1;
    if (args.length > 2) {
        c = Integer.parseInt(args[2]);
    }

    TestHttpClient5 test = new TestHttpClient5();
    test.init();

    try {
        long startTime = System.currentTimeMillis();
        Stats stats = test.get(targetURI, n, c);
        long finishTime = System.currentTimeMillis();

        Stats.printStats(targetURI, startTime, finishTime, stats);
    } finally {
        test.shutdown();
    }
}

From source file:com.jrodeo.queue.messageset.provider.TestHttpClient4.java

public static void main(String[] args) throws Exception {
    if (args.length < 2) {
        System.out.println("Usage: <target URI> <no of requests> <concurrent connections>");
        System.exit(-1);/*  w w w .jav a  2 s . co m*/
    }
    URI targetURI = new URI(args[0]);
    int n = Integer.parseInt(args[1]);
    int c = 1;
    if (args.length > 2) {
        c = Integer.parseInt(args[2]);
    }

    TestHttpClient4 test = new TestHttpClient4();
    test.init();

    List<MessageSetRow> rows = new ArrayList<MessageSetRow>();
    for (int i = 0; i < 45; i++) {
        MessageSetRow msr = new MessageSetRow();
        msr.setI(i);
        msr.setData("this is a message row " + i);
        rows.add(msr);
    }
    MessageSet ms = new MessageSet();
    ms.setRows(rows);

    ObjectMapper mapper = new ObjectMapper();
    byte[] payload = mapper.writeValueAsBytes(ms);

    System.out.println("payload size to server: " + payload.length);

    try {
        long startTime = System.currentTimeMillis();
        // Stats stats = test.get(targetURI, n, c);
        Stats stats = test.post(targetURI, payload, n, c);
        long finishTime = System.currentTimeMillis();

        Stats.printStats(targetURI, startTime, finishTime, stats);
    } finally {
        test.shutdown();
    }
}

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);

    /**/*from ww  w  .j  a va 2 s.  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:ezbake.azkaban.manager.ProjectManager.java

public static void main(String[] args) throws Exception {
    System.out.println("Attempting to delete project: " + args[0]);
    final URI azkabanUri = new URI("https://az01:8443");
    final ProjectManager manager = new ProjectManager(azkabanUri, args[1], args[2]);
    System.out.println("Removed project #" + manager.removeProject(args[0]));
}

From source file:org.eclipse.lyo.client.oslc.samples.DoorsOauthSample.java

/**
 * Login to the DWA server and perform some OSLC actions
 * @param args/*from   www . ja v  a  2 s  .c  o  m*/
 * @throws ParseException 
 */
public static void main(String[] args) throws ParseException {

    Options options = new Options();

    options.addOption("url", true, "url");
    options.addOption("user", true, "user ID");
    options.addOption("password", true, "password");
    options.addOption("project", true, "project area");

    CommandLineParser cliParser = new GnuParser();

    //Parse the command line
    CommandLine cmd = cliParser.parse(options, args);

    if (!validateOptions(cmd)) {
        logger.severe(
                "Syntax:  java <class_name> -url https://<server>:port/<context>/ -user <user> -password <password> -project \"<project_area>\"");
        logger.severe(
                "Example: java DoorsOauthSample -url https://exmple.com:9443/dwa -user ADMIN -password ADMIN -project \"JKE Banking (Requirements Management)\"");
        return;
    }

    String webContextUrl = cmd.getOptionValue("url");
    String user = cmd.getOptionValue("user");
    String passwd = cmd.getOptionValue("password");
    String projectArea = cmd.getOptionValue("project");

    try {

        //STEP 1: Initialize a Jazz rootservices helper and indicate we're looking for the RequirementManagement catalog
        // The root services for DOORs is found at /public level
        JazzRootServicesHelper helper = new JazzRootServicesHelper(webContextUrl + "/public",
                OSLCConstants.OSLC_RM_V2);

        //STEP 2: Create a new OSLC OAuth capable client, the parameter of following call should be provided
        // by the system administrator of the DOORs Web Access server
        OslcOAuthClient client = helper.initOAuthClient("1234567890", "123");

        if (client != null) {

            //STEP 3: Try to access the context URL to trigger the OAuth dance and login
            try {
                client.getResource(webContextUrl, OSLCConstants.CT_RDF);
            } catch (OAuthRedirectException oauthE) {
                validateTokens(client,
                        oauthE.getRedirectURL() + "?oauth_token=" + oauthE.getAccessor().requestToken, user,
                        passwd, webContextUrl + "/j_acegi_security_check");
                // Try to access again
                ClientResponse response = client.getResource(webContextUrl, OSLCConstants.CT_RDF);
                response.getEntity(InputStream.class).close();
            }

            //STEP 4: Get the URL of the OSLC catalog
            String catalogUrl = helper.getCatalogUrl();

            //STEP 5: Find the OSLC Service Provider for the project area we want to work with
            String serviceProviderUrl = lookupServiceProviderUrl(catalogUrl, "Services for " + projectArea,
                    client);

            //STEP 6: Get the Query Capabilities URL so that we can run some OSLC queries
            String queryCapability = client.lookupQueryCapability(serviceProviderUrl, OSLCConstants.OSLC_RM_V2,
                    OSLCConstants.RM_REQUIREMENT_TYPE);

            //STEP 7: Get the Creation Factory URL for default Requirements so that we can create one
            Requirement requirement = new Requirement();
            String requirementFactory = client.lookupCreationFactory(serviceProviderUrl,
                    OSLCConstants.OSLC_RM_V2, requirement.getRdfTypes()[0].toString());

            //STEP 8 Get the default Requirement Type URL
            ResourceShape reqInstanceShape = RmUtil.lookupRequirementsInstanceShapes(serviceProviderUrl,
                    OSLCConstants.OSLC_RM_V2, requirement.getRdfTypes()[0].toString(), client,
                    "Resource shape for a requirement in the " + projectArea);

            if ((reqInstanceShape != null) && (requirementFactory != null)) {
                //STEP 9: Create a Requirement
                requirement.setInstanceShape(reqInstanceShape.getAbout());
                // Add a link
                requirement.addImplementedBy(
                        new Link(new URI("http://google.com"), "Link created by an Eclipse Lyo user"));
                requirement.setDescription("Created By EclipseLyo");

                // Add the PrimaryText
                String primaryText = "My Eclipse Lyo CREATED Primary Text";
                Element obj = RmUtil.convertStringToHTML(primaryText);
                requirement.getExtendedProperties().put(RmConstants.PROPERTY_PRIMARY_TEXT, obj);

                //Create the Requirement
                ClientResponse creationResponse = client.createResource(requirementFactory, requirement,
                        OslcMediaType.APPLICATION_RDF_XML, OslcMediaType.APPLICATION_RDF_XML);
                String req01URL = creationResponse.getHeaders().getFirst(HttpHeaders.LOCATION);

                creationResponse.consumeContent();
            }

            //STEP 10: Query of changed values
            OslcQueryParameters queryParams = new OslcQueryParameters();
            queryParams.setPrefix("oslc_rm=<http://open-services.net/ns/rm#>");
            queryParams.setWhere("oslc_rm:implementedBy=<http://google.com>");
            OslcQuery query = new OslcQuery(client, queryCapability, 10, queryParams);
            OslcQueryResult result = query.submit();
            boolean processAsJavaObjects = false;
            int resultsSize = result.getMembersUrls().length;
            processPagedQueryResults(result, client, processAsJavaObjects);
            System.out.println("\n------------------------------\n");
            System.out.println("Number of Results for query 1 = " + resultsSize + "\n");

            //STEP 11: Now get the artifact with identifier = 9 
            queryParams = new OslcQueryParameters();
            queryParams.setPrefix("dcterms=<http://purl.org/dc/terms/>");
            queryParams.setWhere("dcterms:identifier=9");
            query = new OslcQuery(client, queryCapability, 10, queryParams);
            result = query.submit();
            String requirementURL = null;
            // Get the URL of returned requirement
            if (result != null) {
                String[] returnedURLS = result.getMembersUrls();
                if ((returnedURLS != null) && (returnedURLS.length > 0)) {
                    requirementURL = returnedURLS[0];
                }
            }

            // STEP 12 If requirement found, lets get it an modify
            if (requirementURL != null) {
                // Get the requirement
                ClientResponse getResponse = client.getResource(requirementURL,
                        OslcMediaType.APPLICATION_RDF_XML);
                requirement = getResponse.getEntity(Requirement.class);
                // Get the eTAG, we need it to update
                String etag = getResponse.getHeaders().getFirst(OSLCConstants.ETAG);
                getResponse.consumeContent();

                // Following code is needed to workaround an issue in DWA that exposes the Heading inf as encoded XML
                {
                    // Get the type for "Object Heading"
                    org.eclipse.lyo.oslc4j.core.model.Property[] properties = reqInstanceShape.getProperties();
                    String attrDef = null;
                    for (org.eclipse.lyo.oslc4j.core.model.Property property : properties) {
                        if (property.getTitle().equalsIgnoreCase("Object Heading")) {
                            attrDef = property.getPropertyDefinition().toString();
                        }
                    }
                    if (attrDef != null) {
                        String url = attrDef.substring(0, attrDef.lastIndexOf("/") + 1);
                        String name = attrDef.substring(attrDef.lastIndexOf("/") + 1);
                        // QName attr12Name = new QName("https://slot12.gdl.mex.ibm.com:8443/dwa/rm/urn:rational::1-514b30b9627b2a31-M-00000062/types/", "attrDef-12");
                        QName attr12Name = new QName(url, name);
                        String attr12 = (String) requirement.getExtendedProperties().get(attr12Name);
                        attr12 = removeXMLEscape(attr12);
                        Element objattr12 = RmUtil.convertStringToHTML(attr12);
                        requirement.getExtendedProperties().put(attr12Name, objattr12);
                    }
                }

                // Change the Primary text
                String primaryText = "My Eclipse Lyo CHANGED Primary Text";
                // Put in the proper object ( Element for XML Strings )
                Element obj = RmUtil.convertStringToHTML(primaryText);
                requirement.getExtendedProperties().put(RmConstants.PROPERTY_PRIMARY_TEXT, obj);

                // Add a couple of links 
                requirement.addImplementedBy(new Link(new URI("http://google.com"), "ImplementedBy example"));
                requirement.addElaboratedBy(new Link(new URI("http://terra.com.mx"), "ElaboratedBy example"));
                // Update the requirement with the proper etag 
                ClientResponse updateResponse = client.updateResource(requirementURL, requirement,
                        OslcMediaType.APPLICATION_RDF_XML, OslcMediaType.APPLICATION_RDF_XML, etag);

                updateResponse.consumeContent();
            }

        }
    } catch (RootServicesException re) {
        logger.log(Level.SEVERE,
                "Unable to access the Jazz rootservices document at: " + webContextUrl + "/public/rootservices",
                re);
    } catch (Exception e) {
        logger.log(Level.SEVERE, e.getMessage(), e);
    }

}

From source file:org.eclipse.lyo.client.oslc.samples.RRCFormSample.java

/**
 * Login to the RRC server and perform some OSLC actions
 * @param args/*  w  w  w  . j a  va  2  s.  c om*/
 * @throws ParseException 
 */
public static void main(String[] args) throws ParseException {

    Options options = new Options();

    options.addOption("url", true, "url");
    options.addOption("user", true, "user ID");
    options.addOption("password", true, "password");
    options.addOption("project", true, "project area");

    CommandLineParser cliParser = new GnuParser();

    //Parse the command line
    CommandLine cmd = cliParser.parse(options, args);

    if (!validateOptions(cmd)) {
        logger.severe(
                "Syntax:  java <class_name> -url https://<server>:port/<context>/ -user <user> -password <password> -project \"<project_area>\"");
        logger.severe(
                "Example: java RRCFormSample -url https://exmple.com:9443/rm -user ADMIN -password ADMIN -project \"JKE Banking (Requirements Management)\"");
        return;
    }

    String webContextUrl = cmd.getOptionValue("url");
    String user = cmd.getOptionValue("user");
    String passwd = cmd.getOptionValue("password");
    String projectArea = cmd.getOptionValue("project");

    try {

        //STEP 1: Initialize a Jazz rootservices helper and indicate we're looking for the RequirementManagement catalog
        JazzRootServicesHelper helper = new JazzRootServicesHelper(webContextUrl, OSLCConstants.OSLC_RM_V2);

        //STEP 2: Create a new Form Auth client with the supplied user/password
        //RRC is a fronting server, so need to use the initForm() signature which allows passing of an authentication URL.
        //For RRC, use the JTS for the authorization URL

        //This is a bit of a hack for readability.  It is assuming RRC is at context /rm.  Could use a regex or UriBuilder instead.
        String authUrl = webContextUrl.replaceFirst("/rm", "/jts");
        JazzFormAuthClient client = helper.initFormClient(user, passwd, authUrl);

        //STEP 3: Login in to Jazz Server
        if (client.formLogin() == HttpStatus.SC_OK) {

            //STEP 4: Get the URL of the OSLC ChangeManagement catalog
            String catalogUrl = helper.getCatalogUrl();

            //STEP 5: Find the OSLC Service Provider for the project area we want to work with
            String serviceProviderUrl = client.lookupServiceProviderUrl(catalogUrl, projectArea);

            //STEP 6: Get the Query Capabilities URL so that we can run some OSLC queries
            String queryCapability = client.lookupQueryCapability(serviceProviderUrl, OSLCConstants.OSLC_RM_V2,
                    OSLCConstants.RM_REQUIREMENT_TYPE);
            //STEP 7: Create base requirements
            //Get the Creation Factory URL for change requests so that we can create one
            Requirement requirement = new Requirement();
            String requirementFactory = client.lookupCreationFactory(serviceProviderUrl,
                    OSLCConstants.OSLC_RM_V2, requirement.getRdfTypes()[0].toString());

            //Get Feature Requirement Type URL
            ResourceShape featureInstanceShape = RmUtil.lookupRequirementsInstanceShapes(serviceProviderUrl,
                    OSLCConstants.OSLC_RM_V2, requirement.getRdfTypes()[0].toString(), client, "Feature");

            URI rootFolder = null;
            //Get Collection Type URL
            RequirementCollection collection = new RequirementCollection();
            ResourceShape collectionInstanceShape = RmUtil.lookupRequirementsInstanceShapes(serviceProviderUrl,
                    OSLCConstants.OSLC_RM_V2, collection.getRdfTypes()[0].toString(), client,
                    "Personal Collection");

            String req01URL = null;
            String req02URL = null;
            String req03URL = null;
            String req04URL = null;
            String reqcoll01URL = null;

            String primaryText = null;
            if ((featureInstanceShape != null) && (requirementFactory != null)) {

                // Create REQ01
                requirement.setInstanceShape(featureInstanceShape.getAbout());
                requirement.setTitle("Req01");

                // Decorate the PrimaryText
                primaryText = "My Primary Text";
                org.w3c.dom.Element obj = RmUtil.convertStringToHTML(primaryText);
                requirement.getExtendedProperties().put(RmConstants.PROPERTY_PRIMARY_TEXT, obj);

                requirement.setDescription("Created By EclipseLyo");
                requirement.addImplementedBy(new Link(new URI("http://google.com"), "Link in REQ01"));
                //Create the change request
                ClientResponse creationResponse = client.createResource(requirementFactory, requirement,
                        OslcMediaType.APPLICATION_RDF_XML, OslcMediaType.APPLICATION_RDF_XML);
                req01URL = creationResponse.getHeaders().getFirst(HttpHeaders.LOCATION);
                creationResponse.consumeContent();

                // Create REQ02   
                requirement = new Requirement();
                requirement.setInstanceShape(featureInstanceShape.getAbout());
                requirement.setTitle("Req02");
                requirement.setDescription("Created By EclipseLyo");
                requirement.addValidatedBy(new Link(new URI("http://bancomer.com"), "Link in REQ02"));
                //Create the change request
                creationResponse = client.createResource(requirementFactory, requirement,
                        OslcMediaType.APPLICATION_RDF_XML, OslcMediaType.APPLICATION_RDF_XML);

                req02URL = creationResponse.getHeaders().getFirst(HttpHeaders.LOCATION);
                creationResponse.consumeContent();

                // Create REQ03   
                requirement = new Requirement();
                requirement.setInstanceShape(featureInstanceShape.getAbout());
                requirement.setTitle("Req03");
                requirement.setDescription("Created By EclipseLyo");
                requirement.addValidatedBy(new Link(new URI("http://outlook.com"), "Link in REQ03"));
                //Create the change request
                creationResponse = client.createResource(requirementFactory, requirement,
                        OslcMediaType.APPLICATION_RDF_XML, OslcMediaType.APPLICATION_RDF_XML);
                req03URL = creationResponse.getHeaders().getFirst(HttpHeaders.LOCATION);
                creationResponse.consumeContent();

                // Create REQ04   
                requirement = new Requirement();
                requirement.setInstanceShape(featureInstanceShape.getAbout());
                requirement.setTitle("Req04");
                requirement.setDescription("Created By EclipseLyo");

                //Create the Requirement
                creationResponse = client.createResource(requirementFactory, requirement,
                        OslcMediaType.APPLICATION_RDF_XML, OslcMediaType.APPLICATION_RDF_XML);
                req04URL = creationResponse.getHeaders().getFirst(HttpHeaders.LOCATION);
                creationResponse.consumeContent();

                // Now create a collection 
                // Create REQ04   
                collection = new RequirementCollection();

                collection.addUses(new URI(req03URL));
                collection.addUses(new URI(req04URL));

                collection.setInstanceShape(collectionInstanceShape.getAbout());
                collection.setTitle("Collection01");
                collection.setDescription("Created By EclipseLyo");
                //Create the change request
                creationResponse = client.createResource(requirementFactory, collection,
                        OslcMediaType.APPLICATION_RDF_XML, OslcMediaType.APPLICATION_RDF_XML);
                reqcoll01URL = creationResponse.getHeaders().getFirst(HttpHeaders.LOCATION);
                creationResponse.consumeContent();

            }

            // Check that everything was properly created
            if (req01URL == null || req02URL == null || req03URL == null || req04URL == null
                    || reqcoll01URL == null) {
                throw new Exception("Failed to create an artifact");
            }

            // GET the root folder based on First requirement created
            ClientResponse getResponse = client.getResource(req01URL, OslcMediaType.APPLICATION_RDF_XML);
            requirement = getResponse.getEntity(Requirement.class);
            String etag1 = getResponse.getHeaders().getFirst(OSLCConstants.ETAG);
            // May not be needed getResponse.consumeContent();
            //Save the URI of the root folder in order to used it easily 
            rootFolder = (URI) requirement.getExtendedProperties().get(RmConstants.PROPERTY_PARENT_FOLDER);

            String changedPrimaryText = (String) requirement.getExtendedProperties()
                    .get(RmConstants.PROPERTY_PRIMARY_TEXT);
            if (changedPrimaryText == null) {
                // Check with the workaround
                changedPrimaryText = (String) requirement.getExtendedProperties()
                        .get(PROPERTY_PRIMARY_TEXT_WORKAROUND);
            }

            if ((changedPrimaryText != null) && (!changedPrimaryText.contains(primaryText))) {
                logger.log(Level.SEVERE, "Error getting primary Text");
            }

            //QUERIES
            // SCENARIO 01  Do a query for type= Requirements
            OslcQueryParameters queryParams = new OslcQueryParameters();
            queryParams.setPrefix("rdf=<http://www.w3.org/1999/02/22-rdf-syntax-ns#>");
            queryParams.setWhere("rdf:type=<http://open-services.net/ns/rm#Requirement>");
            OslcQuery query = new OslcQuery(client, queryCapability, 10, queryParams);
            OslcQueryResult result = query.submit();
            boolean processAsJavaObjects = false;
            int resultsSize = result.getMembersUrls().length;
            processPagedQueryResults(result, client, processAsJavaObjects);
            System.out.println("\n------------------------------\n");
            System.out.println("Number of Results for SCENARIO 01 = " + resultsSize + "\n");

            // SCENARIO 02    Do a query for type= Requirements and for it folder container = rootFolder
            queryParams = new OslcQueryParameters();
            queryParams.setPrefix(
                    "nav=<http://com.ibm.rdm/navigation#>,rdf=<http://www.w3.org/1999/02/22-rdf-syntax-ns#>");
            queryParams.setWhere("rdf:type=<http://open-services.net/ns/rm#Requirement> and nav:parent=<"
                    + rootFolder + ">");
            query = new OslcQuery(client, queryCapability, 10, queryParams);
            result = query.submit();
            processAsJavaObjects = false;
            resultsSize = result.getMembersUrls().length;
            processPagedQueryResults(result, client, processAsJavaObjects);
            System.out.println("\n------------------------------\n");
            System.out.println("Number of Results for SCENARIO 02 = " + resultsSize + "\n");

            // SCENARIO 03   Do a query for title
            queryParams = new OslcQueryParameters();
            queryParams.setPrefix("dcterms=<http://purl.org/dc/terms/>");
            queryParams.setWhere("dcterms:title=\"Req04\"");
            query = new OslcQuery(client, queryCapability, 10, queryParams);
            result = query.submit();
            resultsSize = result.getMembersUrls().length;
            processAsJavaObjects = false;
            processPagedQueryResults(result, client, processAsJavaObjects);
            System.out.println("\n------------------------------\n");
            System.out.println("Number of Results for SCENARIO 03 = " + resultsSize + "\n");

            // SCENARIO 04   Do a query for the link that is implemented
            queryParams = new OslcQueryParameters();
            queryParams.setPrefix("oslc_rm=<http://open-services.net/ns/rm#>");
            queryParams.setWhere("oslc_rm:implementedBy=<http://google.com>");
            query = new OslcQuery(client, queryCapability, 10, queryParams);
            result = query.submit();
            resultsSize = result.getMembersUrls().length;
            processAsJavaObjects = false;
            processPagedQueryResults(result, client, processAsJavaObjects);
            System.out.println("\n------------------------------\n");
            System.out.println("Number of Results for SCENARIO 04 = " + resultsSize + "\n");

            // SCENARIO 05   Do a query for the links that is validated 
            queryParams = new OslcQueryParameters();
            queryParams.setPrefix("oslc_rm=<http://open-services.net/ns/rm#>");
            queryParams.setWhere("oslc_rm:validatedBy in [<http://bancomer.com>,<http://outlook.com>]");
            query = new OslcQuery(client, queryCapability, 10, queryParams);
            result = query.submit();
            resultsSize = result.getMembersUrls().length;
            processAsJavaObjects = false;
            processPagedQueryResults(result, client, processAsJavaObjects);
            System.out.println("\n------------------------------\n");
            System.out.println("Number of Results for SCENARIO 05 = " + resultsSize + "\n");

            // SCENARIO 06 Do a query for it container folder and for the link that is implemented
            queryParams = new OslcQueryParameters();
            queryParams.setPrefix(
                    "nav=<http://com.ibm.rdm/navigation#>,oslc_rm=<http://open-services.net/ns/rm#>");
            queryParams
                    .setWhere("nav:parent=<" + rootFolder + "> and oslc_rm:validatedBy=<http://bancomer.com>");
            query = new OslcQuery(client, queryCapability, 10, queryParams);
            result = query.submit();
            resultsSize = result.getMembersUrls().length;
            processAsJavaObjects = false;
            processPagedQueryResults(result, client, processAsJavaObjects);
            System.out.println("\n------------------------------\n");
            System.out.println("Number of Results for SCENARIO 06 = " + resultsSize + "\n");

            // GET resources from req03 in order edit its values
            getResponse = client.getResource(req03URL, OslcMediaType.APPLICATION_RDF_XML);
            requirement = getResponse.getEntity(Requirement.class);
            // Get the eTAG, we need it to update
            String etag = getResponse.getHeaders().getFirst(OSLCConstants.ETAG);
            getResponse.consumeContent();
            requirement.setTitle("My new Title");
            requirement.addImplementedBy(
                    new Link(new URI("http://google.com"), "Link created by an Eclipse Lyo user"));

            // Update the requirement with the proper etag 
            ClientResponse updateResponse = client.updateResource(req03URL, requirement,
                    OslcMediaType.APPLICATION_RDF_XML, OslcMediaType.APPLICATION_RDF_XML, etag);

            updateResponse.consumeContent();

            /*Do a query in order to see if the requirement have changed*/
            // SCENARIO 07 Do a query for the new title just changed
            queryParams = new OslcQueryParameters();
            queryParams.setPrefix("dcterms=<http://purl.org/dc/terms/>");
            queryParams.setWhere("dcterms:title=\"My new Title\"");
            query = new OslcQuery(client, queryCapability, 10, queryParams);
            result = query.submit();
            resultsSize = result.getMembersUrls().length;
            processAsJavaObjects = false;
            processPagedQueryResults(result, client, processAsJavaObjects);
            System.out.println("\n------------------------------\n");
            System.out.println("Number of Results for SCENARIO 07 = " + resultsSize + "\n");

            // SCENARIO 08   Do a query for implementedBy links
            queryParams = new OslcQueryParameters();
            queryParams.setPrefix("oslc_rm=<http://open-services.net/ns/rm#>");
            queryParams.setWhere("oslc_rm:implementedBy=<http://google.com>");
            query = new OslcQuery(client, queryCapability, 10, queryParams);
            result = query.submit();
            resultsSize = result.getMembersUrls().length;
            processAsJavaObjects = false;
            processPagedQueryResults(result, client, processAsJavaObjects);
            System.out.println("\n------------------------------\n");
            System.out.println("Number of Results for SCENARIO 08 = " + resultsSize + "\n");

        }
    } catch (RootServicesException re) {
        logger.log(Level.SEVERE,
                "Unable to access the Jazz rootservices document at: " + webContextUrl + "/rootservices", re);
    } catch (Exception e) {
        logger.log(Level.SEVERE, e.getMessage(), e);
    }

}

From source file:org.asamk.signal.Main.java

public static void main(String[] args) {
    // Workaround for BKS truststore
    Security.insertProviderAt(new org.bouncycastle.jce.provider.BouncyCastleProvider(), 1);

    Namespace ns = parseArgs(args);
    if (ns == null) {
        System.exit(1);//from  ww w  . jav  a 2 s .  co  m
    }

    final String username = ns.getString("username");
    Manager m;
    Signal ts;
    DBusConnection dBusConn = null;
    try {
        if (ns.getBoolean("dbus") || ns.getBoolean("dbus_system")) {
            try {
                m = null;
                int busType;
                if (ns.getBoolean("dbus_system")) {
                    busType = DBusConnection.SYSTEM;
                } else {
                    busType = DBusConnection.SESSION;
                }
                dBusConn = DBusConnection.getConnection(busType);
                ts = (Signal) dBusConn.getRemoteObject(SIGNAL_BUSNAME, SIGNAL_OBJECTPATH, Signal.class);
            } catch (DBusException e) {
                e.printStackTrace();
                if (dBusConn != null) {
                    dBusConn.disconnect();
                }
                System.exit(3);
                return;
            }
        } else {
            String settingsPath = ns.getString("config");
            if (TextUtils.isEmpty(settingsPath)) {
                settingsPath = System.getProperty("user.home") + "/.config/signal";
                if (!new File(settingsPath).exists()) {
                    String legacySettingsPath = System.getProperty("user.home") + "/.config/textsecure";
                    if (new File(legacySettingsPath).exists()) {
                        settingsPath = legacySettingsPath;
                    }
                }
            }

            m = new Manager(username, settingsPath);
            ts = m;
            if (m.userExists()) {
                try {
                    m.load();
                } catch (Exception e) {
                    System.err
                            .println("Error loading state file \"" + m.getFileName() + "\": " + e.getMessage());
                    System.exit(2);
                    return;
                }
            }
        }

        switch (ns.getString("command")) {
        case "register":
            if (dBusConn != null) {
                System.err.println("register is not yet implemented via dbus");
                System.exit(1);
            }
            if (!m.userHasKeys()) {
                m.createNewIdentity();
            }
            try {
                m.register(ns.getBoolean("voice"));
            } catch (IOException e) {
                System.err.println("Request verify error: " + e.getMessage());
                System.exit(3);
            }
            break;
        case "verify":
            if (dBusConn != null) {
                System.err.println("verify is not yet implemented via dbus");
                System.exit(1);
            }
            if (!m.userHasKeys()) {
                System.err.println("User has no keys, first call register.");
                System.exit(1);
            }
            if (m.isRegistered()) {
                System.err.println("User registration is already verified");
                System.exit(1);
            }
            try {
                m.verifyAccount(ns.getString("verificationCode"));
            } catch (IOException e) {
                System.err.println("Verify error: " + e.getMessage());
                System.exit(3);
            }
            break;
        case "link":
            if (dBusConn != null) {
                System.err.println("link is not yet implemented via dbus");
                System.exit(1);
            }

            // When linking, username is null and we always have to create keys
            m.createNewIdentity();

            String deviceName = ns.getString("name");
            if (deviceName == null) {
                deviceName = "cli";
            }
            try {
                System.out.println(m.getDeviceLinkUri());
                m.finishDeviceLink(deviceName);
                System.out.println("Associated with: " + m.getUsername());
            } catch (TimeoutException e) {
                System.err.println("Link request timed out, please try again.");
                System.exit(3);
            } catch (IOException e) {
                System.err.println("Link request error: " + e.getMessage());
                System.exit(3);
            } catch (InvalidKeyException e) {
                e.printStackTrace();
                System.exit(3);
            } catch (UserAlreadyExists e) {
                System.err.println("The user " + e.getUsername() + " already exists\nDelete \""
                        + e.getFileName() + "\" before trying again.");
                System.exit(3);
            }
            break;
        case "addDevice":
            if (dBusConn != null) {
                System.err.println("link is not yet implemented via dbus");
                System.exit(1);
            }
            if (!m.isRegistered()) {
                System.err.println("User is not registered.");
                System.exit(1);
            }
            try {
                m.addDeviceLink(new URI(ns.getString("uri")));
            } catch (IOException e) {
                e.printStackTrace();
                System.exit(3);
            } catch (InvalidKeyException e) {
                e.printStackTrace();
                System.exit(2);
            } catch (URISyntaxException e) {
                e.printStackTrace();
                System.exit(2);
            }
            break;
        case "listDevices":
            if (dBusConn != null) {
                System.err.println("listDevices is not yet implemented via dbus");
                System.exit(1);
            }
            if (!m.isRegistered()) {
                System.err.println("User is not registered.");
                System.exit(1);
            }
            try {
                List<DeviceInfo> devices = m.getLinkedDevices();
                for (DeviceInfo d : devices) {
                    System.out.println("Device " + d.getId()
                            + (d.getId() == m.getDeviceId() ? " (this device)" : "") + ":");
                    System.out.println(" Name: " + d.getName());
                    System.out.println(" Created: " + d.getCreated());
                    System.out.println(" Last seen: " + d.getLastSeen());
                }
            } catch (IOException e) {
                e.printStackTrace();
                System.exit(3);
            }
            break;
        case "removeDevice":
            if (dBusConn != null) {
                System.err.println("removeDevice is not yet implemented via dbus");
                System.exit(1);
            }
            if (!m.isRegistered()) {
                System.err.println("User is not registered.");
                System.exit(1);
            }
            try {
                int deviceId = ns.getInt("deviceId");
                m.removeLinkedDevices(deviceId);
            } catch (IOException e) {
                e.printStackTrace();
                System.exit(3);
            }
            break;
        case "send":
            if (dBusConn == null && !m.isRegistered()) {
                System.err.println("User is not registered.");
                System.exit(1);
            }

            if (ns.getBoolean("endsession")) {
                if (ns.getList("recipient") == null) {
                    System.err.println("No recipients given");
                    System.err.println("Aborting sending.");
                    System.exit(1);
                }
                try {
                    ts.sendEndSessionMessage(ns.<String>getList("recipient"));
                } catch (IOException e) {
                    handleIOException(e);
                } catch (EncapsulatedExceptions e) {
                    handleEncapsulatedExceptions(e);
                } catch (AssertionError e) {
                    handleAssertionError(e);
                } catch (DBusExecutionException e) {
                    handleDBusExecutionException(e);
                } catch (UntrustedIdentityException e) {
                    e.printStackTrace();
                }
            } else {
                String messageText = ns.getString("message");
                if (messageText == null) {
                    try {
                        messageText = IOUtils.toString(System.in);
                    } catch (IOException e) {
                        System.err.println("Failed to read message from stdin: " + e.getMessage());
                        System.err.println("Aborting sending.");
                        System.exit(1);
                    }
                }

                try {
                    List<String> attachments = ns.getList("attachment");
                    if (attachments == null) {
                        attachments = new ArrayList<>();
                    }
                    if (ns.getString("group") != null) {
                        byte[] groupId = decodeGroupId(ns.getString("group"));
                        ts.sendGroupMessage(messageText, attachments, groupId);
                    } else {
                        ts.sendMessage(messageText, attachments, ns.<String>getList("recipient"));
                    }
                } catch (IOException e) {
                    handleIOException(e);
                } catch (EncapsulatedExceptions e) {
                    handleEncapsulatedExceptions(e);
                } catch (AssertionError e) {
                    handleAssertionError(e);
                } catch (GroupNotFoundException e) {
                    handleGroupNotFoundException(e);
                } catch (AttachmentInvalidException e) {
                    System.err.println("Failed to add attachment: " + e.getMessage());
                    System.err.println("Aborting sending.");
                    System.exit(1);
                } catch (DBusExecutionException e) {
                    handleDBusExecutionException(e);
                } catch (UntrustedIdentityException e) {
                    e.printStackTrace();
                }
            }

            break;
        case "receive":
            if (dBusConn != null) {
                try {
                    dBusConn.addSigHandler(Signal.MessageReceived.class,
                            new DBusSigHandler<Signal.MessageReceived>() {
                                @Override
                                public void handle(Signal.MessageReceived s) {
                                    System.out
                                            .print(String.format("Envelope from: %s\nTimestamp: %d\nBody: %s\n",
                                                    s.getSender(), s.getTimestamp(), s.getMessage()));
                                    if (s.getGroupId().length > 0) {
                                        System.out.println("Group info:");
                                        System.out.println("  Id: " + Base64.encodeBytes(s.getGroupId()));
                                    }
                                    if (s.getAttachments().size() > 0) {
                                        System.out.println("Attachments: ");
                                        for (String attachment : s.getAttachments()) {
                                            System.out.println("-  Stored plaintext in: " + attachment);
                                        }
                                    }
                                    System.out.println();
                                }
                            });
                } catch (DBusException e) {
                    e.printStackTrace();
                }
                while (true) {
                    try {
                        Thread.sleep(10000);
                    } catch (InterruptedException e) {
                        System.exit(0);
                    }
                }
            }
            if (!m.isRegistered()) {
                System.err.println("User is not registered.");
                System.exit(1);
            }
            int timeout = 60;
            if (ns.getInt("timeout") != null) {
                timeout = ns.getInt("timeout");
            }
            boolean returnOnTimeout = true;
            if (timeout < 0) {
                returnOnTimeout = false;
                timeout = 3600;
            }
            try {

                for (int i = 0; i < 10; i++) {
                    System.out.println("Numero di threads: " + Thread.activeCount());
                    m.receiveMessages(timeout, returnOnTimeout, new ReceiveMessageHandler(m));
                }

            } catch (IOException e) {
                System.err.println("Error while receiving messages: " + e.getMessage());
                System.exit(3);
            } catch (AssertionError e) {
                handleAssertionError(e);
            }
            break;
        case "quitGroup":
            if (dBusConn != null) {
                System.err.println("quitGroup is not yet implemented via dbus");
                System.exit(1);
            }
            if (!m.isRegistered()) {
                System.err.println("User is not registered.");
                System.exit(1);
            }

            try {
                m.sendQuitGroupMessage(decodeGroupId(ns.getString("group")));
            } catch (IOException e) {
                handleIOException(e);
            } catch (EncapsulatedExceptions e) {
                handleEncapsulatedExceptions(e);
            } catch (AssertionError e) {
                handleAssertionError(e);
            } catch (GroupNotFoundException e) {
                handleGroupNotFoundException(e);
            } catch (UntrustedIdentityException e) {
                e.printStackTrace();
            }

            break;
        case "updateGroup":
            if (dBusConn != null) {
                System.err.println("updateGroup is not yet implemented via dbus");
                System.exit(1);
            }
            if (!m.isRegistered()) {
                System.err.println("User is not registered.");
                System.exit(1);
            }

            try {
                byte[] groupId = null;
                if (ns.getString("group") != null) {
                    groupId = decodeGroupId(ns.getString("group"));
                }
                byte[] newGroupId = m.sendUpdateGroupMessage(groupId, ns.getString("name"),
                        ns.<String>getList("member"), ns.getString("avatar"));
                if (groupId == null) {
                    System.out.println("Creating new group \"" + Base64.encodeBytes(newGroupId) + "\" ");
                }
            } catch (IOException e) {
                handleIOException(e);
            } catch (AttachmentInvalidException e) {
                System.err.println("Failed to add avatar attachment for group\": " + e.getMessage());
                System.err.println("Aborting sending.");
                System.exit(1);
            } catch (GroupNotFoundException e) {
                handleGroupNotFoundException(e);
            } catch (EncapsulatedExceptions e) {
                handleEncapsulatedExceptions(e);
            } catch (UntrustedIdentityException e) {
                e.printStackTrace();
            }

            break;
        case "daemon":
            if (dBusConn != null) {
                System.err.println("Stop it.");
                System.exit(1);
            }
            if (!m.isRegistered()) {
                System.err.println("User is not registered.");
                System.exit(1);
            }
            DBusConnection conn = null;
            try {
                try {
                    int busType;
                    if (ns.getBoolean("system")) {
                        busType = DBusConnection.SYSTEM;
                    } else {
                        busType = DBusConnection.SESSION;
                    }
                    conn = DBusConnection.getConnection(busType);
                    conn.exportObject(SIGNAL_OBJECTPATH, m);
                    conn.requestBusName(SIGNAL_BUSNAME);
                } catch (DBusException e) {
                    e.printStackTrace();
                    System.exit(3);
                }
                try {
                    m.receiveMessages(3600, false, new DbusReceiveMessageHandler(m, conn));
                } catch (IOException e) {
                    System.err.println("Error while receiving messages: " + e.getMessage());
                    System.exit(3);
                } catch (AssertionError e) {
                    handleAssertionError(e);
                }
            } finally {
                if (conn != null) {
                    conn.disconnect();
                }
            }

            break;
        }
        System.exit(0);
    } finally {
        if (dBusConn != null) {
            dBusConn.disconnect();
        }
    }
}

From source file:de.interactive_instruments.ShapeChange.Target.FeatureCatalogue.XsltWriter.java

/**
 * Parameter identifiers have a leading "-". Parameter values are separated
 * from the parameter identifier via a single space.
 * <ul>// w  w w.jav  a  2s.  c o  m
 * <li>Parameter {@value #PARAM_xslTransformerFactory}: fully qualified name
 * of the XSLT processor implementation; NOTE: this parameter may not be
 * provided if the default implementation shall be used.</li>
 * <li>Parameter {@value #PARAM_hrefMappings}: list of key-value pairs
 * defining href mappings, structured using URL query syntax (i.e. using '='
 * to separate the key from the value, using '&' to separate pairs, and with
 * URL-encoded value (with UTF-8 character encoding); NOTE: this parameter
 * may not be provided if href mappings are not needed.</li>
 * <li>Parameter {@value #PARAM_transformationParameters}: list of key-value
 * pairs defining the transformation parameters, structured using URL query
 * syntax (i.e. using '=' to separate the key from the value, using '&' to
 * separate pairs, and with URL-encoded value (with UTF-8 character
 * encoding); NOTE: this parameter may not be provided if transformation
 * parameters are not needed.</li>
 * <li>Parameter {@value #PARAM_transformationSourcePath}: path to the
 * transformation source file (may be a relative path); NOTE: this is a
 * required parameter.</li>
 * <li>Parameter {@value #PARAM_xsltMainFileUri}: String representation of
 * the URI to the main XSLT file; NOTE: this is a required parameter.</li>
 * <li>Parameter {@value #PARAM_transformationTargetPath}: path to the
 * transformation target file (may be a relative path); NOTE: this is a
 * required parameter.</li>
 * </ul>
 */
public static void main(String[] args) {

    String xslTransformerFactory = null;
    String hrefMappingsString = null;
    String transformationParametersString = null;
    String transformationSourcePath = null;
    String xsltMainFileUriString = null;
    String transformationTargetPath = null;

    // identify parameters
    String arg = null;

    for (int i = 0; i < args.length; i++) {

        arg = args[i];

        if (arg.equals(PARAM_xslTransformerFactory)) {

            if (i + 1 == args.length || args[i + 1].startsWith("-")) {
                System.err.println("No value provided for invocation parameter " + PARAM_xslTransformerFactory);
                return;
            } else {
                xslTransformerFactory = args[i + 1];
                i++;
            }

        } else if (arg.equals(PARAM_hrefMappings)) {

            if (i + 1 == args.length || args[i + 1].startsWith("-")) {
                System.err.println("No value provided for invocation parameter " + PARAM_hrefMappings);
                return;
            } else {
                hrefMappingsString = args[i + 1];
                i++;
            }

        } else if (arg.equals(PARAM_transformationParameters)) {

            if (i + 1 == args.length || args[i + 1].startsWith("-")) {
                System.err.println(
                        "No value provided for invocation parameter " + PARAM_transformationParameters);
                return;
            } else {
                transformationParametersString = args[i + 1];
                i++;
            }

        } else if (arg.equals(PARAM_transformationSourcePath)) {

            if (i + 1 == args.length || args[i + 1].startsWith("-")) {
                System.err.println(
                        "No value provided for invocation parameter " + PARAM_transformationSourcePath);
                return;
            } else {
                transformationSourcePath = args[i + 1];
                i++;
            }

        } else if (arg.equals(PARAM_transformationTargetPath)) {

            if (i + 1 == args.length || args[i + 1].startsWith("-")) {
                System.err.println(
                        "No value provided for invocation parameter " + PARAM_transformationTargetPath);
                return;
            } else {
                transformationTargetPath = args[i + 1];
                i++;
            }

        } else if (arg.equals(PARAM_xsltMainFileUri)) {

            if (i + 1 == args.length || args[i + 1].startsWith("-")) {
                System.err.println("No value provided for invocation parameter " + PARAM_xsltMainFileUri);
                return;
            } else {
                xsltMainFileUriString = args[i + 1];
                i++;
            }
        }
    }

    try {

        // parse parameter values
        Map<String, URI> hrefMappings = new HashMap<String, URI>();

        List<NameValuePair> hrefMappingsList = URLEncodedUtils.parse(hrefMappingsString, ENCODING_CHARSET);
        for (NameValuePair nvp : hrefMappingsList) {

            hrefMappings.put(nvp.getName(), new URI(nvp.getValue()));
        }

        Map<String, String> transformationParameters = new HashMap<String, String>();

        List<NameValuePair> transParamList = URLEncodedUtils.parse(transformationParametersString,
                ENCODING_CHARSET);
        for (NameValuePair nvp : transParamList) {
            transformationParameters.put(nvp.getName(), nvp.getValue());
        }

        boolean invalidParameters = false;

        if (transformationSourcePath == null) {
            invalidParameters = true;
            System.err.println("Path to transformation source file was not provided.");
        }
        if (xsltMainFileUriString == null) {
            invalidParameters = true;
            System.err.println("Path to main XSLT file was not provided.");
        }
        if (transformationTargetPath == null) {
            invalidParameters = true;
            System.err.println("Path to transformation target file was not provided.");
        }

        if (!invalidParameters) {

            // set up and execute XSL transformation
            XsltWriter writer = new XsltWriter(xslTransformerFactory, hrefMappings, transformationParameters,
                    null);

            File transformationSource = new File(transformationSourcePath);
            URI xsltMainFileUri = new URI(xsltMainFileUriString);
            File transformationTarget = new File(transformationTargetPath);

            writer.xsltWrite(transformationSource, xsltMainFileUri, transformationTarget);
        }

    } catch (Exception e) {

        String m = e.getMessage();

        if (m != null) {
            System.err.println(m);
        } else {
            System.err.println("Exception occurred while processing the XSL transformation.");
        }
    }
}

From source file:com.jrodeo.remote.TestHttpCore.java

public static void main(String[] args) throws Exception {
    if (args.length < 2) {
        System.out.println("Usage: <target URI> <no of requests> <concurrent connections>");
        System.exit(-1);//from  w ww .j av  a2  s  .c  o m
    }
    URI targetURI = new URI(args[0]);
    int n = Integer.parseInt(args[1]);
    int c = 1;
    if (args.length > 2) {
        c = Integer.parseInt(args[2]);
    }

    TestHttpCore test = new TestHttpCore();
    test.init();
    try {
        long startTime = System.currentTimeMillis();
        Stats stats = test.get(targetURI, n, c);
        long finishTime = System.currentTimeMillis();

        Stats.printStats(targetURI, startTime, finishTime, stats);
    } finally {
        test.shutdown();
    }
}