List of usage examples for java.net URI URI
public URI(String str) throws URISyntaxException
From source file:edu.stanford.junction.extra.Encryption.java
public static void main(String[] args) { try {/*from w w w . j a v a2 s .c o m*/ SwitchboardConfig config = new XMPPSwitchboardConfig("prpl.stanford.edu"); JunctionMaker jm = JunctionMaker.getInstance(config); JunctionActor rec = new JunctionActor("Recevier") { @Override public void onMessageReceived(MessageHeader header, JSONObject message) { System.out.println("rec got " + message.toString()); } @Override public List<JunctionExtra> getInitialExtras() { List<JunctionExtra> e = super.getInitialExtras(); e.add(new Encryption()); return e; } @Override public void onActivityCreate() { System.out.println("Receiver created"); } }; JunctionActor send = new JunctionActor("Sender") { @Override public void onMessageReceived(MessageHeader header, JSONObject message) { System.out.println("send got " + message.toString()); } @Override public void onActivityJoin() { try { JSONObject message = new JSONObject("{\"msg\":\"hello!! encrypted!\"}"); sendMessageToSession(message); message = new JSONObject("{\"msg\":\"hello!! encrypted!\"}"); sendMessageToSession(message); message = new JSONObject("{\"msg\":\"hello!! encrypted!\"}"); sendMessageToSession(message); message = new JSONObject("{\"msg\":\"Keep the cryptotimes rollin!\",\"more\":\"mannnn\"}"); sendMessageToSession(message); message = new JSONObject("{\"msg\":\"Keep the cryptotimes rollin!\",\"more\":\"mannnn\"}"); sendMessageToSession(message); } catch (Exception e) { } } @Override public List<JunctionExtra> getInitialExtras() { List<JunctionExtra> e = super.getInitialExtras(); e.add(new Encryption()); return e; } @Override public void onActivityCreate() { System.out.println("Sender created"); } }; ActivityScript myScript = new ActivityScript(); myScript.setActivityID("edu.stanford.junction.cryptdemo"); myScript.setFriendlyName("CryptDemo"); myScript.setSessionID("cryptosess"); URI mySession = new URI("junction://prpl.stanford.edu/cryptosess?skey=XPVisDpGE82GYc8nCcgj%2FQ%3D%3D"); jm.newJunction(mySession, rec); //jm.newJunction(myScript, rec); URI invite = rec.getJunction().getInvitationURI(); System.out.println("created invitation " + invite); jm.newJunction(invite, send); synchronized (send) { send.wait(); } } catch (Exception e) { e.printStackTrace(); } }
From source file:eu.planets_project.services.utils.DigitalObjectUtils.java
/** * These cases: <br/>//from ww w. j a v a 2 s . c o m * - A compound DO, zip as Content, with MD outside the zip, pointing into * it via Title. This is to pass between services.<br/> * - A zip file containing CDO, MD inside the zip, pointing to the binaries * via the Title. This is an pure file 'IP', in effect.<br/> * - A compound DO, pulled from such a CDO zip file, with inputstreams for * content. Okay, two formats, different contexts and packing/unpacking * options.<br/> * - (CDO[zip] or CDO) i.e. If no Content, look up to root and unpack?<br/> * - DOIP - a special ZIP file containing CDOs. <br/> * Operations:<br/> * - Packing one or more CDOs into a DOIP, optionally embedding referenced * resources. (Value) resources always to be embedded.<br/> * - Unpacking a DOIP and getting N CDOs out, optionally embedding binaries, * using ZipInputStreams, or unpacking into Files?<br/> * TODO Should DO use URI internally got Content.reference, to allow * relative resolution? */ public static void main(String args[]) { try { URI uri = new URI("FAQ.html"); System.out.println("Got " + uri); System.out.println("Got " + uri.isAbsolute()); uri = new URI("http://localhost/FAQ.html"); System.out.println("Got " + uri); System.out.println("Got " + uri.isAbsolute()); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.athena.dolly.websocket.client.test.WebSocketClient.java
public static void main(String[] args) throws Exception { URI uri;// ww w .j av a 2 s . c o m if (args.length > 0) { uri = new URI(args[0]); } else { uri = new URI("ws://localhost:7700/websocket"); } WebSocketClient client = new WebSocketClient(uri); client.initialize(); File directory = new File("C:/Private"); Collection<File> files = FileUtils.listFiles(directory, TrueFileFilter.TRUE, TrueFileFilter.TRUE); for (Iterator<File> iterator = files.iterator(); iterator.hasNext();) { File file = (File) iterator.next(); client.sendFile(file); } //client.sendFile(new File("C:/Temp/netty-master.zip")); client.shutdown(); }
From source file:cn.jumper.study.http.ClientFormLogin.java
public static void main(String[] args) throws Exception { BasicCookieStore cookieStore = new BasicCookieStore(); CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build(); HttpHost proxy = new HttpHost("192.168.10.3", 8080, "http"); RequestConfig config = RequestConfig.custom().setProxy(proxy).build(); try {//from w ww . j av a2 s .com HttpGet httpget = new HttpGet("http://www.ksf-food.com/admin/Login.asp"); httpget.setConfig(config); CloseableHttpResponse response1 = httpclient.execute(httpget); try { HttpEntity entity = response1.getEntity(); System.out.println("Login form get: " + response1.getStatusLine()); EntityUtils.consume(entity); System.out.println("Initial set of cookies:"); List<Cookie> cookies = cookieStore.getCookies(); if (cookies.isEmpty()) { System.out.println("None"); } else { for (int i = 0; i < cookies.size(); i++) { System.out.println("- " + cookies.get(i).toString()); } } } finally { response1.close(); } String code = ""; try { HttpUriRequest httpgetCode = RequestBuilder.get() .setUri("http://www.ksf-food.com/admin/inc/checkcode.asp").setConfig(config).build(); /* * HttpGet httpgetCode = new HttpGet( * "http://www.qufuev.com/admin/inc/checkcode.asp"); * httpgetCode.setConfig(config); */ System.out.println("Executing request " + httpgetCode.getRequestLine()); System.out.println("========================================================"); System.out.println("==httpget header =="); for (Header header : httpgetCode.getAllHeaders()) { System.out.println(header.getName() + ":" + header.getValue()); } System.out.println("==httpget header =="); ResponseHandler<String> responseHandler = new ResponseHandler<String>() { public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException { int status = response.getStatusLine().getStatusCode(); if (status >= 200 && status < 300) { HttpEntity entity = response.getEntity(); System.out.println("==respons header =="); for (Header header : response.getAllHeaders()) { System.out.println(header.getName() + ":" + header.getValue()); } System.out.println("==respons header =="); String fileName = System.currentTimeMillis() + ""; DataOutputStream dataOutputStream = new DataOutputStream( new FileOutputStream("d://test//e3//" + fileName + ".jpg")); dataOutputStream.write(EntityUtils.toByteArray(entity)); dataOutputStream.close(); return ImageTest.getAllOcr("d://test//e3//" + fileName + ".jpg"); } else { throw new ClientProtocolException("Unexpected response status: " + status); } } }; code = httpclient.execute(httpgetCode, responseHandler); System.out.println("ClientFormLogin.main()-CheckCode:" + code); System.out.println("----------------------------------------"); } catch (IOException e) { e.printStackTrace(); } HttpUriRequest login = RequestBuilder.post() .setUri(new URI("http://www.ksf-food.com/admin/Admin_ChkLogin.asp")) .addParameter("UserName", "username").addParameter("Password", "password") .addParameter("CheckCode", code).setConfig(config).build(); System.out.println("========================================================"); System.out.println("==httpget header =="); for (Header header : login.getAllHeaders()) { System.out.println(header.getName() + ":" + header.getValue()); } CloseableHttpResponse response2 = httpclient.execute(login); try { HttpEntity entity = response2.getEntity(); System.out.println("Login form post: " + response2.getStatusLine()); // EntityUtils.consume(entity); System.out.println("ClientFormLogin.main():\\n" + EntityUtils.toString(entity, "GBK")); System.out.println("Post logon cookies:"); List<Cookie> cookies = cookieStore.getCookies(); if (cookies.isEmpty()) { System.out.println("None"); } else { for (int i = 0; i < cookies.size(); i++) { System.out.println("- " + cookies.get(i).toString()); } } } finally { response2.close(); } } finally { httpclient.close(); } }
From source file:me.timothy.ddd.DrunkDuckDispatch.java
License:asdf
public static void main(String[] args) throws LWJGLException { try {/*from w w w .j a v a 2 s . c om*/ float defaultDisplayWidth = SizeScaleSystem.EXPECTED_WIDTH / 2; float defaultDisplayHeight = SizeScaleSystem.EXPECTED_HEIGHT / 2; boolean fullscreen = false, defaultDisplay = !fullscreen; File resolutionInfo = new File("graphics.json"); if (resolutionInfo.exists()) { try (FileReader fr = new FileReader(resolutionInfo)) { JSONObject obj = (JSONObject) new JSONParser().parse(fr); Set<?> keys = obj.keySet(); for (Object o : keys) { if (o instanceof String) { String key = (String) o; switch (key.toLowerCase()) { case "width": defaultDisplayWidth = JSONCompatible.getFloat(obj, key); break; case "height": defaultDisplayHeight = JSONCompatible.getFloat(obj, key); break; case "fullscreen": fullscreen = JSONCompatible.getBoolean(obj, key); defaultDisplay = !fullscreen; break; } } } } catch (IOException | ParseException e) { e.printStackTrace(); } float expHeight = defaultDisplayWidth * (SizeScaleSystem.EXPECTED_HEIGHT / SizeScaleSystem.EXPECTED_WIDTH); float expWidth = defaultDisplayHeight * (SizeScaleSystem.EXPECTED_WIDTH / SizeScaleSystem.EXPECTED_HEIGHT); if (Math.round(defaultDisplayWidth) != Math.round(expWidth)) { if (defaultDisplayHeight < expHeight) { System.err.printf("%f x %f is an invalid resolution; adjusting to %f x %f\n", defaultDisplayWidth, defaultDisplayHeight, defaultDisplayWidth, expHeight); defaultDisplayHeight = expHeight; } else { System.err.printf("%f x %f is an invalid resolution; adjusting to %f x %f\n", defaultDisplayWidth, defaultDisplayHeight, expWidth, defaultDisplayHeight); defaultDisplayWidth = expWidth; } } } File dir = null; String os = getOS(); if (os.equals("windows")) { dir = new File(System.getenv("APPDATA"), "timgames/"); } else { dir = new File(System.getProperty("user.home"), ".timgames/"); } File lwjglDir = new File(dir, "lwjgl-2.9.1/"); Resources.init(); Resources.downloadIfNotExists(lwjglDir, "lwjgl-2.9.1.zip", "http://umad-barnyard.com/lwjgl-2.9.1.zip", "Necessary LWJGL natives couldn't be found, I can attempt " + "to download it, but I make no promises", "Unfortunately I was unable to download it, so I'll open up the " + "link to the official download. Make sure you get LWJGL version 2.9.1, " + "and you put it at " + dir.getAbsolutePath() + "/lwjgl-2.9.1.zip", new Runnable() { @Override public void run() { if (!Desktop.isDesktopSupported()) { JOptionPane.showMessageDialog(null, "I couldn't " + "even do that! Download it manually and try again"); return; } try { Desktop.getDesktop().browse(new URI("http://www.lwjgl.org/download.php")); } catch (IOException | URISyntaxException e) { JOptionPane.showMessageDialog(null, "Oh cmon.. Address is http://www.lwjgl.org/download.php, good luck"); System.exit(1); } } }, 5843626); Resources.extractIfNotFound(lwjglDir, "lwjgl-2.9.1.zip", "lwjgl-2.9.1"); System.setProperty("org.lwjgl.librarypath", new File(dir, "lwjgl-2.9.1/lwjgl-2.9.1/native/" + os).getAbsolutePath()); // deal w/ it System.setProperty("net.java.games.input.librarypath", System.getProperty("org.lwjgl.librarypath")); Resources.downloadIfNotExists("entities.json", "http://umad-barnyard.com/ddd/entities.json", 16142); Resources.downloadIfNotExists("map.binary", "http://umad-barnyard.com/ddd/map.binary", 16142); Resources.downloadIfNotExists("victory.txt", "http://umad-barnyard.com/ddd/victory.txt", 168); Resources.downloadIfNotExists("failure.txt", "http://umad-barnyard.com/ddd/failure.txt", 321); File resFolder = new File("resources/"); if (!resFolder.exists() && !new File("player-still.png").exists()) { Resources.downloadIfNotExists("resources.zip", "http://umad-barnyard.com/ddd/resources.zip", 54484); Resources.extractIfNotFound(new File("."), "resources.zip", "player-still.png"); new File("resources.zip").delete(); } File soundFolder = new File("sounds/"); if (!soundFolder.exists()) { soundFolder.mkdirs(); Resources.downloadIfNotExists("sounds/sounds.zip", "http://umad-barnyard.com/ddd/sounds.zip", 1984977); Resources.extractIfNotFound(soundFolder, "sounds.zip", "asdfasdffadasdf"); new File(soundFolder, "sounds.zip").delete(); } AppGameContainer appgc; ddd = new DrunkDuckDispatch(); appgc = new AppGameContainer(ddd); appgc.setTargetFrameRate(60); appgc.setShowFPS(false); appgc.setAlwaysRender(true); if (fullscreen) { DisplayMode[] modes = Display.getAvailableDisplayModes(); DisplayMode current, best = null; float ratio = 0f; for (int i = 0; i < modes.length; i++) { current = modes[i]; float rX = (float) current.getWidth() / SizeScaleSystem.EXPECTED_WIDTH; float rY = (float) current.getHeight() / SizeScaleSystem.EXPECTED_HEIGHT; System.out.println(current.getWidth() + "x" + current.getHeight() + " -> " + rX + "x" + rY); if (rX == rY && rX > ratio) { best = current; ratio = rX; } } if (best == null) { System.out.println("Failed to find an appropriately scaled resolution, using default display"); defaultDisplay = true; } else { appgc.setDisplayMode(best.getWidth(), best.getHeight(), true); SizeScaleSystem.setRealHeight(best.getHeight()); SizeScaleSystem.setRealWidth(best.getWidth()); System.out.println("I choose " + best.getWidth() + "x" + best.getHeight()); } } if (defaultDisplay) { SizeScaleSystem.setRealWidth(Math.round(defaultDisplayWidth)); SizeScaleSystem.setRealHeight(Math.round(defaultDisplayHeight)); appgc.setDisplayMode(Math.round(defaultDisplayWidth), Math.round(defaultDisplayHeight), false); } ddd.logger.info( "SizeScaleSystem: " + SizeScaleSystem.getRealWidth() + "x" + SizeScaleSystem.getRealHeight()); appgc.start(); } catch (SlickException ex) { LogManager.getLogger(DrunkDuckDispatch.class.getSimpleName()).catching(Level.ERROR, ex); } }
From source file:ezbake.azkaban.manager.ExecutionManager.java
public static void main(String[] args) throws Exception { final OptionsBean optionsBean = new OptionsBean(); final CmdLineParser parser = new CmdLineParser(optionsBean); try {/*from w ww. ja v a 2 s .c o m*/ parser.parseArgument(args); final ExecutionResult result = new ExecutionManager(new URI(optionsBean.endPoint), optionsBean.username, optionsBean.password).executeFlow(optionsBean.name, optionsBean.flow); if (result.hasError()) { System.err.println(result.getError()); } else { System.out.println(result.getMessage()); } } catch (CmdLineException e) { System.err.println(e.getMessage()); parser.printUsage(System.err); } }
From source file:fr.cls.atoll.motu.processor.wps.StringList.java
/** * ./*from www. jav a 2 s.c o m*/ * * @param args */ public static void main(String[] args) { try { Organizer.initProxyLogin(); } catch (MotuException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { URI uri = new URI("sftp://C:/home/data"); System.out.println(uri.getScheme()); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } // String serverURL = "http://localhost:8080/atoll-motuservlet/services"; // // try { // WPSInfo wpsInfo = WPSFactory.getWpsInfo(serverURL); // } catch (MotuException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // StatusModeType test = StatusModeType.DONE; // test.toString(); // StatusModeType.valueOf("DONE"); // Enum.valueOf(StatusModeType.class, "DONE"); // boolean b = StatusModeType.class.isEnum(); // testCreateObject(); // testComplexOutputWPSResponse(); // AnnotatedElement annotatedElement = StatusType.class; // System.out.println(annotatedElement.getAnnotations().toString()); // for (Annotation annotation : annotatedElement.getAnnotations()) { // System.out.println(annotation.toString()); // System.out.println(annotation.annotationType().toString()); // // } // // XmlType xmlType = annotatedElement.getAnnotation(XmlType.class); // System.out.println(xmlType.propOrder().toString()); // for (String annotation : xmlType.propOrder()) { // System.out.println(annotation); // // } // // // testArrayToEnum(xmlType.propOrder()); // Collection<String> tt = new ArrayList<String>(); // tt.add("qsdfsdf"); // // System.out.println(tt.getClass()); // System.out.println(tt.getClass().getGenericSuperclass()); // ParameterizedType pt = (ParameterizedType) tt.getClass().getGenericSuperclass(); // System.out.println(pt.getActualTypeArguments()[0]); // System.out.println(pt.getOwnerType()); // System.out.println(pt.getRawType()); // System.out.println(tt.getClass().getTypeParameters()[0].getName()); // System.out.println(tt.getClass().getTypeParameters()[0].getGenericDeclaration()); // System.out.println(tt.getClass().getComponentType()); // // // Object o = tt.iterator().next(); // System.out.println(o.getClass()); // Type type = StringList.class.getGenericSuperclass(); // System.out.println(type); // java.util.ArrayList<java.lang.String> // pt = (ParameterizedType) type; // System.out.println(pt.getActualTypeArguments()[0]); // System.setProperty("proxyHost", "proxy.cls.fr"); // adresse IP // System.setProperty("proxyPort", "8080"); // System.setProperty("socksProxyHost", "proxy.cls.fr"); // System.setProperty("socksProxyPort", "1080"); // Authenticator.setDefault(new MyAuthenticator()); // testBuildWPS(); // testBuildChainWPS(); // testBuildAndRunChainWPS(); // testUnmarshallWPS(); // for (ErrorType c: ErrorType.values()) { // if (c.toString().equalsIgnoreCase("system")) { // System.out.println(c.toString()); // } // } // testBodyPost(); // testUTF8EncodeDecode(); // TestWPS test = new TestWPS(); // // TestWPS.GetObjectId id = test.new GetObjectId();j // System.out.println(id.hashCode()); // TestWPS.GetObjectId id2 = test.new GetObjectId(); // System.out.println(id2.hashCode()); // // TestWPS.GetObjectId id3 = id; // System.out.println(id3.hashCode()); // // String abc = new String("Australia"); // System.out.println("Hash code for String object: " + abc.hashCode()); // String abc2 = new String("Australia"); // System.out.println("Hash code for String object: " + abc2.hashCode()); // // // try { // // Generate a DES key // KeyGenerator keyGen = KeyGenerator.getInstance("DES"); // SecretKey key = keyGen.generateKey(); // System.out.println(key.hashCode()); // // Get the bytes of the key // byte[] keyBytes = key.getEncoded(); // int numBytes = keyBytes.length; // String string = new String(keyBytes); // System.out.println(string); // // // // Generate a Blowfish key // keyGen = KeyGenerator.getInstance("Blowfish"); // key = keyGen.generateKey(); // System.out.println(key.hashCode()); // // // Generate a triple DES key // keyGen = KeyGenerator.getInstance("DESede"); // key = keyGen.generateKey(); // System.out.println(key.hashCode()); // } catch (java.security.NoSuchAlgorithmException e) { // } getDescribeProcess(); // testPackageAnnotation(); // testGetFields(); }
From source file:it.txt.ens.core.impl.BasicENSResource.java
public static void main(String[] args) { try {/*w ww . jav a 2s .c o m*/ ENSResource r = ENSResourceURIParser.parse(new URI( "amqp://www.iot-at-work.eu/ENS?Namespace=Demo+IoTatWork+Namespace&Pattern=DemoIoTatWork.Turin.CRFPlant.WeldingCell1.%23.Energy"), new BasicENSResourceFactory()); System.out.println(r.getPattern()); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (URIParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:com.opengamma.batch.BatchJobRunner.java
/** * Creates an runs a batch job based on a properties file and configuration. *///from w w w .j a v a2 s . c o m public static void main(String[] args) throws Exception { // CSIGNORE if (args.length == 0) { usage(); System.exit(-1); } CommandLine line = null; Properties configProperties = null; final String propertyFile = "batchJob.properties"; String configPropertyFile = null; if (System.getProperty(propertyFile) != null) { configPropertyFile = System.getProperty(propertyFile); try { FileInputStream fis = new FileInputStream(configPropertyFile); configProperties = new Properties(); configProperties.load(fis); fis.close(); } catch (FileNotFoundException e) { s_logger.error("The system cannot find " + configPropertyFile); System.exit(-1); } } else { try { FileInputStream fis = new FileInputStream(propertyFile); configProperties = new Properties(); configProperties.load(fis); fis.close(); configPropertyFile = propertyFile; } catch (FileNotFoundException e) { // there is no config file so we expect command line arguments try { CommandLineParser parser = new PosixParser(); line = parser.parse(getOptions(), args); } catch (ParseException e2) { usage(); System.exit(-1); } } } RunCreationMode runCreationMode = getRunCreationMode(line, configProperties, configPropertyFile); if (runCreationMode == null) { // default runCreationMode = RunCreationMode.AUTO; } String engineURI = getProperty("engineURI", line, configProperties, configPropertyFile); String brokerURL = getProperty("brokerURL", line, configProperties, configPropertyFile); Instant valuationTime = getValuationTime(line, configProperties, configPropertyFile); LocalDate observationDate = getObservationDate(line, configProperties, configPropertyFile); UniqueId viewDefinitionUniqueId = getViewDefinitionUniqueId(line, configProperties); URI vpBase; try { vpBase = new URI(engineURI); } catch (URISyntaxException ex) { throw new OpenGammaRuntimeException("Invalid URI", ex); } ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(brokerURL); activeMQConnectionFactory.setWatchTopicAdvisories(false); JmsConnectorFactoryBean jmsConnectorFactoryBean = new JmsConnectorFactoryBean(); jmsConnectorFactoryBean.setConnectionFactory(activeMQConnectionFactory); jmsConnectorFactoryBean.setName("Masters"); JmsConnector jmsConnector = jmsConnectorFactoryBean.getObjectCreating(); ScheduledExecutorService heartbeatScheduler = Executors.newSingleThreadScheduledExecutor(); try { ViewProcessor vp = new RemoteViewProcessor(vpBase, jmsConnector, heartbeatScheduler); ViewClient vc = vp.createViewClient(UserPrincipal.getLocalUser()); HistoricalMarketDataSpecification marketDataSpecification = MarketData.historical(observationDate, null); ViewExecutionOptions executionOptions = ExecutionOptions.batch(valuationTime, marketDataSpecification, null); vc.attachToViewProcess(viewDefinitionUniqueId, executionOptions); vc.waitForCompletion(); } finally { heartbeatScheduler.shutdown(); } }
From source file:org.eclipse.lyo.client.oslc.samples.RQMFormSample.java
/** * Login to the RQM server and perform some OSLC actions * @param args//from w ww . jav a 2 s .co 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 RQMFormSample -url https://exmple.com:9443/ccm -user ADMIN -password ADMIN -project \"JKE Banking (Quality 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 QualityManagement catalog //RQM contains both Quality and Change Management providers, so need to look for QM specifically JazzRootServicesHelper helper = new JazzRootServicesHelper(webContextUrl, OSLCConstants.OSLC_QM_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 QualityManagement 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_QM_V2, OSLCConstants.QM_TEST_RESULT_QUERY); //SCENARIO A: Run a query for all TestResults with a status of passed with OSLC paging of 10 items per //page turned on and list the members of the result OslcQueryParameters queryParams = new OslcQueryParameters(); queryParams.setWhere("oslc_qm:status=\"com.ibm.rqm.execution.common.state.passed\""); 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 TestResult selecting only certain //attributes and then print it as raw XML. Change the dcterms:title below to match a //real TestResult in your RQM project area OslcQueryParameters queryParams2 = new OslcQueryParameters(); queryParams2 .setWhere("dcterms:title=\"Consistent_display_of_currency_Firefox_DB2_WAS_Windows_S1\""); queryParams2.setSelect( "dcterms:identifier,dcterms:title,dcterms:creator,dcterms:created,oslc_qm:status"); OslcQuery query2 = new OslcQuery(client, queryCapability, queryParams2); OslcQueryResult result2 = query2.submit(); ClientResponse rawResponse = result2.getRawResponse(); processRawResponse(rawResponse); rawResponse.consumeContent(); //SCENARIO C: RQM TestCase creation and update TestCase testcase = new TestCase(); testcase.setTitle("Accessibility verification using a screen reader"); testcase.setDescription( "This test case uses a screen reader application to ensure that the web browser content fully complies with accessibility standards"); testcase.addTestsChangeRequest(new Link(new URI("http://cmprovider/changerequest/1"), "Implement accessibility in Pet Store application")); //Get the Creation Factory URL for test cases so that we can create a test case String testcaseCreation = client.lookupCreationFactory(serviceProviderUrl, OSLCConstants.OSLC_QM_V2, testcase.getRdfTypes()[0].toString()); //Create the test case ClientResponse creationResponse = client.createResource(testcaseCreation, testcase, OslcMediaType.APPLICATION_RDF_XML); creationResponse.consumeContent(); String testcaseLocation = creationResponse.getHeaders().getFirst(HttpHeaders.LOCATION); System.out.println("Test Case created a location " + testcaseLocation); //Get the test case from the service provider and update its title property testcase = client.getResource(testcaseLocation, OslcMediaType.APPLICATION_RDF_XML) .getEntity(TestCase.class); testcase.setTitle(testcase.getTitle() + " (updated)"); //Create a partial update URL so that only the title will be updated. //Assuming (for readability) that the test case URL does not already contain a '?' String updateUrl = testcase.getAbout() + "?oslc.properties=dcterms:title"; //Update the test case at the service provider client.updateResource(updateUrl, testcase, OslcMediaType.APPLICATION_RDF_XML).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); } }