List of usage examples for java.net URI create
public static URI create(String str)
From source file:examples.mail.IMAPImportMbox.java
public static void main(String[] args) throws IOException { if (args.length < 2) { System.err.println(//from w w w . j a v a2 s .c o m "Usage: IMAPImportMbox imap[s]://user:password@host[:port]/folder/path <mboxfile> [selectors]"); System.err.println("\tWhere: a selector is a list of numbers/number ranges - 1,2,3-10" + " - or a list of strings to match in the initial From line"); System.exit(1); } final URI uri = URI.create(args[0]); final String file = args[1]; final File mbox = new File(file); if (!mbox.isFile() || !mbox.canRead()) { throw new IOException("Cannot read mailbox file: " + mbox); } String path = uri.getPath(); if (path == null || path.length() < 1) { throw new IllegalArgumentException("Invalid folderPath: '" + path + "'"); } String folder = path.substring(1); // skip the leading / List<String> contains = new ArrayList<String>(); // list of strings to find BitSet msgNums = new BitSet(); // list of message numbers for (int i = 2; i < args.length; i++) { String arg = args[i]; if (arg.matches("\\d+(-\\d+)?(,\\d+(-\\d+)?)*")) { // number,m-n for (String entry : arg.split(",")) { String[] parts = entry.split("-"); if (parts.length == 2) { // m-n int low = Integer.parseInt(parts[0]); int high = Integer.parseInt(parts[1]); for (int j = low; j <= high; j++) { msgNums.set(j); } } else { msgNums.set(Integer.parseInt(entry)); } } } else { contains.add(arg); // not a number/number range } } // System.out.println(msgNums.toString()); // System.out.println(java.util.Arrays.toString(contains.toArray())); // Connect and login final IMAPClient imap = IMAPUtils.imapLogin(uri, 10000, null); int total = 0; int loaded = 0; try { imap.setSoTimeout(6000); final BufferedReader br = new BufferedReader(new FileReader(file)); // TODO charset? String line; StringBuilder sb = new StringBuilder(); boolean wanted = false; // Skip any leading rubbish while ((line = br.readLine()) != null) { if (line.startsWith("From ")) { // start of message; i.e. end of previous (if any) if (process(sb, imap, folder, total)) { // process previous message (if any) loaded++; } sb.setLength(0); total++; wanted = wanted(total, line, msgNums, contains); } else if (startsWith(line, PATFROM)) { // Unescape ">+From " in body text line = line.substring(1); } // TODO process first Received: line to determine arrival date? if (wanted) { sb.append(line); sb.append(CRLF); } } br.close(); if (wanted && process(sb, imap, folder, total)) { // last message (if any) loaded++; } } catch (IOException e) { System.out.println(imap.getReplyString()); e.printStackTrace(); System.exit(10); return; } finally { imap.logout(); imap.disconnect(); } System.out.println("Processed " + total + " messages, loaded " + loaded); }
From source file:edu.usc.goffish.gopher.impl.Main.java
public static void main(String[] args) { Properties properties = new Properties(); try {//w ww.j a va 2 s . co m properties.load(new FileInputStream(CONFIG_FILE)); } catch (IOException e) { String message = "Error while loading Container Configuration from " + CONFIG_FILE + " Cause -" + e.getCause(); log.warning(message); } if (args.length == 4) { PropertiesConfiguration propertiesConfiguration; String url = null; URI uri = URI.create(args[3]); String dataDir = uri.getPath(); String currentHost = uri.getHost(); try { propertiesConfiguration = new PropertiesConfiguration(dataDir + "/gofs.config"); propertiesConfiguration.load(); url = (String) propertiesConfiguration.getString(DataNode.DATANODE_NAMENODE_LOCATION_KEY); } catch (ConfigurationException e) { String message = " Error while reading gofs-config cause -" + e.getCause(); handleException(message); } URI nameNodeUri = URI.create(url); INameNode nameNode = new RemoteNameNode(nameNodeUri); int partition = -1; try { for (URI u : nameNode.getDataNodes()) { if (URIHelper.isLocalURI(u)) { IDataNode dataNode = DataNode.create(u); IntCollection partitions = dataNode.getLocalPartitions(args[2]); partition = partitions.iterator().nextInt(); break; } } if (partition == -1) { String message = "Partition not loaded from uri : " + nameNodeUri; handleException(message); } properties.setProperty(GopherInfraHandler.PARTITION, String.valueOf(partition)); } catch (Exception e) { String message = "Error while loading Partitions from " + nameNodeUri + " Cause -" + e.getMessage(); e.printStackTrace(); handleException(message); } properties.setProperty(Constants.STATIC_PELLET_COUNT, String.valueOf(1)); FloeRuntimeEnvironment environment = FloeRuntimeEnvironment.getEnvironment(); environment.setSystemConfig(properties); properties.setProperty(Constants.CURRET_HOST, currentHost); String managerHost = args[0]; int managerPort = Integer.parseInt(args[1]); Container container = environment.getContainer(); container.setManager(managerHost, managerPort); DefaultClientConfig config = new DefaultClientConfig(); config.getProperties().put(ClientConfig.FEATURE_DISABLE_XML_SECURITY, true); config.getFeatures().put(ClientConfig.FEATURE_DISABLE_XML_SECURITY, true); Client c = Client.create(config); if (managerHost == null || managerPort == 0) { handleException("Manager Host / Port have to be configured in " + args[0]); } WebResource r = c.resource("http://" + managerHost + ":" + managerPort + "/Manager/addContainerInfo/Container=" + container.getContainerInfo().getContainerId() + "/Host=" + container.getContainerInfo().getContainerHost()); c.getProperties().put(ClientConfig.PROPERTY_FOLLOW_REDIRECTS, true); r.post(); log.log(Level.INFO, "Container started "); } else { String message = "Invalid arguments , arg[0]=Manager host, " + "arg[1] = mamanger port,arg[2]=graph id,arg[3]=partition uri"; message += "\n Current Arguments...." + args.length + "\n"; for (int i = 0; i < args.length; i++) { message += "arg " + i + " : " + args[i] + "\n"; } handleException(message); } }
From source file:com.kolich.aws.SQSTest.java
public static void main(String[] args) throws Exception { final String key = System.getProperty(AWS_ACCESS_KEY_PROPERTY); final String secret = System.getProperty(AWS_SECRET_PROPERTY); if (key == null || secret == null) { throw new IllegalArgumentException("You are missing the " + "-Daws.key and -Daws.secret required VM " + "properties on your command line."); }// w w w. j a v a 2s . c o m final HttpClient client = KolichHttpClientFactory.getNewInstanceNoProxySelector(); final SQSClient sqs = new KolichSQSClient(client, key, secret); URI queueURI = null; final Either<HttpFailure, CreateQueueResult> create = sqs.createQueue("----__________"); if (create.success()) { System.out.println("Created queue successfully: " + create.right().getQueueUrl()); queueURI = URI.create(create.right().getQueueUrl()); } else { System.err.println("Failed to create queue: " + create.left().getStatusCode()); } final Either<HttpFailure, ListQueuesResult> list = sqs.listQueues(); if (list.success()) { for (final String queueUrl : list.right().getQueueUrls()) { System.out.println("Queue: " + queueUrl); } } else { System.err.println("Listing queues failed."); } for (int i = 0; i < 5; i++) { final Either<HttpFailure, SendMessageResult> send = sqs.sendMessage(queueURI, "test message: " + ISO8601DateFormat.format(new Date())); if (send.success()) { System.out.println("Sent message [" + i + "]: " + send.right().getMessageId()); } else { System.err.println("Failed to send message."); } } for (int fetched = 0, error = 0; fetched < 5 && error == 0;) { final Either<HttpFailure, ReceiveMessageResult> messages = sqs.receiveMessage(queueURI, 10, 5); if (messages.success()) { fetched += messages.right().getMessages().size(); System.out.println("Loaded " + messages.right().getMessages().size() + " messages."); for (final Message m : messages.right().getMessages()) { System.out.println("Message [" + m.getMessageId() + "]: " + m.getBody()); final Option<HttpFailure> deleteMsg = sqs.deleteMessage(queueURI, m.getReceiptHandle()); if (deleteMsg.isNone()) { System.out.println("Deleted message [" + m.getMessageId() + "]"); } else { System.err.println("Failed to delete message: " + m.getReceiptHandle()); } } } else { error = 1; System.err.println("Loading messages failed."); } } System.out.println("No messages should be on queue... long poll waiting!"); final Either<HttpFailure, ReceiveMessageResult> lp = sqs.receiveMessage(queueURI, 20, 5); if (lp.success()) { System.out.println("Long poll finished waiting successfully."); } else { System.err.println("Failed to long poll wait."); } final Option<HttpFailure> delete = sqs.deleteQueue(queueURI); if (delete.isNone()) { System.out.println("Deleted queue successfully: " + queueURI); } else { System.err.println("Deletion of queue failed: " + queueURI); } }
From source file:com.github.trohovsky.jira.analyzer.Main.java
public static void main(String[] args) throws Exception { final Options options = new Options(); options.addOption("u", true, "username"); options.addOption("p", true, "password (optional, if not provided, the password is prompted)"); options.addOption("h", false, "show this help"); options.addOption("s", true, "use the strategy for querying and output, the strategy can be either 'issues_toatal' (default) or" + " 'per_month'"); options.addOption("d", true, "CSV delimiter"); // parsing of the command line arguments final CommandLineParser parser = new DefaultParser(); CommandLine cmdLine = null;//from w w w. j a v a2 s.c o m try { cmdLine = parser.parse(options, args); if (cmdLine.hasOption('h') || cmdLine.getArgs().length == 0) { final HelpFormatter formatter = new HelpFormatter(); formatter.setOptionComparator(null); formatter.printHelp(HELP_CMDLINE, HELP_HEADER, options, null); return; } if (cmdLine.getArgs().length != 3) { throw new ParseException("You should specify exactly three arguments JIRA_SERVER JQL_QUERY_TEMPLATE" + " PATH_TO_PARAMETER_FILE"); } } catch (ParseException e) { System.err.println("Error parsing command line: " + e.getMessage()); final HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(HELP_CMDLINE, HELP_HEADER, options, null); return; } final String csvDelimiter = (String) (cmdLine.getOptionValue('d') != null ? cmdLine.getOptionObject('d') : CSV_DELIMITER); final URI jiraServerUri = URI.create(cmdLine.getArgs()[0]); final String jqlQueryTemplate = cmdLine.getArgs()[1]; final List<List<String>> queryParametersData = readCSVFile(cmdLine.getArgs()[2], csvDelimiter); final String username = cmdLine.getOptionValue("u"); String password = cmdLine.getOptionValue("p"); final String strategy = cmdLine.getOptionValue("s"); try { // initialization of the REST client final AsynchronousJiraRestClientFactory factory = new AsynchronousJiraRestClientFactory(); if (username != null) { if (password == null) { final Console console = System.console(); final char[] passwordCharacters = console.readPassword("Password: "); password = new String(passwordCharacters); } restClient = factory.createWithBasicHttpAuthentication(jiraServerUri, username, password); } else { restClient = factory.create(jiraServerUri, new AnonymousAuthenticationHandler()); } final SearchRestClient searchRestClient = restClient.getSearchClient(); // choosing of an analyzer strategy AnalyzerStrategy analyzer = null; if (strategy != null) { switch (strategy) { case "issues_total": analyzer = new IssuesTotalStrategy(searchRestClient); break; case "issues_per_month": analyzer = new IssuesPerMonthStrategy(searchRestClient); break; default: System.err.println("The strategy does not exist"); return; } } else { analyzer = new IssuesTotalStrategy(searchRestClient); } // analyzing for (List<String> queryParameters : queryParametersData) { analyzer.analyze(jqlQueryTemplate, queryParameters); } } finally { // destroy the REST client, otherwise it stucks restClient.close(); } }
From source file:UploadUrlGenerator.java
public static void main(String[] args) throws Exception { Options opts = new Options(); opts.addOption(Option.builder().longOpt(ENDPOINT_OPTION).required().hasArg().argName("url") .desc("Sets the ECS S3 endpoint to use, e.g. https://ecs.company.com:9021").build()); opts.addOption(Option.builder().longOpt(ACCESS_KEY_OPTION).required().hasArg().argName("access-key") .desc("Sets the Access Key (user) to sign the request").build()); opts.addOption(Option.builder().longOpt(SECRET_KEY_OPTION).required().hasArg().argName("secret") .desc("Sets the secret key to sign the request").build()); opts.addOption(Option.builder().longOpt(BUCKET_OPTION).required().hasArg().argName("bucket-name") .desc("The bucket containing the object").build()); opts.addOption(Option.builder().longOpt(KEY_OPTION).required().hasArg().argName("object-key") .desc("The object name (key) to access with the URL").build()); opts.addOption(Option.builder().longOpt(EXPIRES_OPTION).hasArg().argName("minutes") .desc("Minutes from local time to expire the request. 1 day = 1440, 1 week=10080, " + "1 month (30 days)=43200, 1 year=525600. Defaults to 1 hour (60).") .build());//from w w w.j a va 2 s . c o m opts.addOption(Option.builder().longOpt(VERB_OPTION).hasArg().argName("http-verb").type(HttpMethod.class) .desc("The HTTP verb that will be used with the URL (PUT, GET, etc). Defaults to GET.").build()); opts.addOption(Option.builder().longOpt(CONTENT_TYPE_OPTION).hasArg().argName("mimetype") .desc("Sets the Content-Type header (e.g. image/jpeg) that will be used with the request. " + "Must match exactly. Defaults to application/octet-stream for PUT/POST and " + "null for all others") .build()); DefaultParser dp = new DefaultParser(); CommandLine cmd = null; try { cmd = dp.parse(opts, args); } catch (ParseException e) { System.err.println("Error: " + e.getMessage()); HelpFormatter hf = new HelpFormatter(); hf.printHelp("java -jar UploadUrlGenerator-xxx.jar", opts, true); System.exit(255); } URI endpoint = URI.create(cmd.getOptionValue(ENDPOINT_OPTION)); String accessKey = cmd.getOptionValue(ACCESS_KEY_OPTION); String secretKey = cmd.getOptionValue(SECRET_KEY_OPTION); String bucket = cmd.getOptionValue(BUCKET_OPTION); String key = cmd.getOptionValue(KEY_OPTION); HttpMethod method = HttpMethod.GET; if (cmd.hasOption(VERB_OPTION)) { method = HttpMethod.valueOf(cmd.getOptionValue(VERB_OPTION).toUpperCase()); } int expiresMinutes = 60; if (cmd.hasOption(EXPIRES_OPTION)) { expiresMinutes = Integer.parseInt(cmd.getOptionValue(EXPIRES_OPTION)); } String contentType = null; if (method == HttpMethod.PUT || method == HttpMethod.POST) { contentType = "application/octet-stream"; } if (cmd.hasOption(CONTENT_TYPE_OPTION)) { contentType = cmd.getOptionValue(CONTENT_TYPE_OPTION); } BasicAWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey); ClientConfiguration cc = new ClientConfiguration(); // Force use of v2 Signer. ECS does not support v4 signatures yet. cc.setSignerOverride("S3SignerType"); AmazonS3Client s3 = new AmazonS3Client(credentials, cc); s3.setEndpoint(endpoint.toString()); S3ClientOptions s3c = new S3ClientOptions(); s3c.setPathStyleAccess(true); s3.setS3ClientOptions(s3c); // Sign the URL Calendar c = Calendar.getInstance(); c.add(Calendar.MINUTE, expiresMinutes); GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(bucket, key).withExpiration(c.getTime()) .withMethod(method); if (contentType != null) { req = req.withContentType(contentType); } URL u = s3.generatePresignedUrl(req); System.out.printf("URL: %s\n", u.toURI().toASCIIString()); System.out.printf("HTTP Verb: %s\n", method); System.out.printf("Expires: %s\n", c.getTime()); System.out.println("To Upload with curl:"); StringBuilder sb = new StringBuilder(); sb.append("curl "); if (method != HttpMethod.GET) { sb.append("-X "); sb.append(method.toString()); sb.append(" "); } if (contentType != null) { sb.append("-H \"Content-Type: "); sb.append(contentType); sb.append("\" "); } if (method == HttpMethod.POST || method == HttpMethod.PUT) { sb.append("-T <filename> "); } sb.append("\""); sb.append(u.toURI().toASCIIString()); sb.append("\""); System.out.println(sb.toString()); System.exit(0); }
From source file:de.mycrobase.jcloudapp.Main.java
public static void main(String[] args) throws Exception { try {/*from w w w.j a va 2 s.c om*/ // borrowed from https://github.com/cmur2/gloudapp ImageNormal = ImageIO.read(Main.class.getResourceAsStream("gloudapp.png")); ImageWorking = ImageIO.read(Main.class.getResourceAsStream("gloudapp_working.png")); IconNormal = new ImageIcon(ImageNormal.getScaledInstance(64, 64, Image.SCALE_SMOOTH)); IconLarge = new ImageIcon(ImageNormal); } catch (IOException ex) { showErrorDialog("Could not load images!\n" + ex); System.exit(1); } URI serviceUrl = URI.create("http://my.cl.ly:80/"); File storage = getStorageFile(); if (storage.exists() && storage.isFile()) { Yaml yaml = new Yaml(); try { Map<String, String> m = (Map<String, String>) yaml.load(new FileInputStream(storage)); // avoid NPE by implicitly assuming the presence of a service URL if (m.containsKey("service_url")) { serviceUrl = URI.create(m.get("service_url")); } } catch (IOException ex) { showErrorDialog("Loading settings from .cloudapp-cli failed: " + ex); System.exit(1); } } Main app = new Main(serviceUrl); app.login(args); app.run(); }
From source file:com.unboundid.scim.sdk.examples.ClientExample.java
/** * The main method./*ww w . ja va2 s .c om*/ * * @param args Parameters for the application. * @throws Exception If an error occurs. */ public static void main(final String[] args) throws Exception { final URI uri = URI.create("https://localhost:8443"); final ClientConfig clientConfig = createHttpBasicClientConfig("bjensen", "password"); final SCIMService scimService = new SCIMService(uri, clientConfig); scimService.setAcceptType(MediaType.APPLICATION_JSON_TYPE); // Core user resource CRUD operation example final SCIMEndpoint<UserResource> endpoint = scimService.getUserEndpoint(); // Query for a specified user Resources<UserResource> resources = endpoint.query("userName eq \"bjensen\""); if (resources.getItemsPerPage() == 0) { System.out.println("User bjensen not found"); return; } UserResource user = resources.iterator().next(); Name name = user.getName(); if (name != null) { System.out.println(name); } Collection<Entry<String>> phoneNumbers = user.getPhoneNumbers(); if (phoneNumbers != null) { for (Entry<String> phoneNumber : phoneNumbers) { System.out.println(phoneNumber); } } // Attribute extension example Manager manager = user.getSingularAttributeValue("urn:scim:schemas:extension:enterprise:1.0", "manager", Manager.MANAGER_RESOLVER); if (manager == null) { resources = endpoint.query("userName eq \"jsmith\""); if (resources.getItemsPerPage() > 0) { UserResource boss = resources.iterator().next(); manager = new Manager(boss.getId(), null); } else { System.out.println("User jsmith not found"); } } user.setSingularAttributeValue("urn:scim:schemas:extension:enterprise:1.0", "manager", Manager.MANAGER_RESOLVER, manager); String employeeNumber = user.getSingularAttributeValue("urn:scim:schemas:extension:enterprise:1.0", "employeeNumber", AttributeValueResolver.STRING_RESOLVER); if (employeeNumber != null) { System.out.println("employeeNumber: " + employeeNumber); } user.setSingularAttributeValue("urn:scim:schemas:extension:enterprise:1.0", "department", AttributeValueResolver.STRING_RESOLVER, "sales"); user.setTitle("Vice President"); // Update the user endpoint.update(user); // Demonstrate retrieval by SCIM ID user = endpoint.get(user.getId()); // Resource type extension example ResourceDescriptor deviceDescriptor = scimService.getResourceDescriptor("Device", null); SCIMEndpoint<DeviceResource> deviceEndpoint = scimService.getEndpoint(deviceDescriptor, DEVICE_RESOURCE_FACTORY); }
From source file:eu.planets_project.ifr.core.servreg.utils.client.PlanetsCommand.java
/** * // w w w.j a va2 s. c o m * @param args */ public static void main(String[] args) { /* FIXME, point to log4j.properties instead of doing this? */ /* java.util.logging.Logger.getLogger("com.sun.xml.ws.model").setLevel(java.util.logging.Level.WARNING); java.util.logging.Logger.getAnonymousLogger().setLevel(java.util.logging.Level.WARNING); Logger sunlogger = Logger.getLogger("com.sun.xml.ws.model"); sunlogger.setLevel(Level.WARNING); java.util.logging.Logger.getLogger( com.sun.xml.ws.util.Constants.LoggingDomain).setLevel(java.util.logging.Level.WARNING); */ /* Lots of info please: */ java.util.logging.Logger.getAnonymousLogger().setLevel(java.util.logging.Level.FINEST); java.util.logging.Logger.getLogger(com.sun.xml.ws.util.Constants.LoggingDomain) .setLevel(java.util.logging.Level.FINEST); // TODO See https://jax-ws.dev.java.net/guide/Logging.html for info on more logging to set up. //System.setProperty("com.sun.xml.ws.transport.local.LocalTransportPipe.dump","true"); //System.setProperty("com.sun.xml.ws.util.pipe.StandaloneTubeAssembler.dump","true"); //System.setProperty("com.sun.xml.ws.transport.http.HttpAdapter.dump","true"); // Doing this KILLS STREAMING. Log that. //System.setProperty("com.sun.xml.ws.transport.http.client.HttpTransportPipe.dump","true"); URL wsdl; try { wsdl = new URL(args[0]); } catch (MalformedURLException e) { e.printStackTrace(); return; } PlanetsServiceExplorer pse = new PlanetsServiceExplorer(wsdl); System.out.println(".describe(): " + pse.getServiceDescription()); Service service = Service.create(wsdl, pse.getQName()); //service.addPort(portName, SOAPBinding.SOAP11HTTP_MTOM_BINDING, endpointAddress) PlanetsService ps = (PlanetsService) service.getPort(pse.getServiceClass()); // TODO The client wrapper code should enforce this stuff: SOAPBinding binding = (SOAPBinding) ((BindingProvider) ps).getBinding(); System.out.println("Logging MTOM=" + binding.isMTOMEnabled()); ((BindingProvider) ps).getRequestContext().put(JAXWSProperties.MTOM_THRESHOLOD_VALUE, 8192); ((BindingProvider) ps).getRequestContext().put(JAXWSProperties.HTTP_CLIENT_STREAMING_CHUNK_SIZE, 8192); System.out.println("Logging MTOM=" + binding.isMTOMEnabled()); binding.setMTOMEnabled(true); System.out.println("Logging MTOM=" + binding.isMTOMEnabled()); //System.out.println("Logging MTOM="+((BindingProvider)ps).getBinding().getBindingID()+" v. "+SOAPBinding.SOAP11HTTP_MTOM_BINDING); /* * The different services are invoked in different ways... */ if (pse.getQName().equals(Migrate.QNAME)) { System.out.println("Is a Migrate service. "); Migrate s = MigrateWrapper.createWrapper(wsdl); DigitalObject dobIn = new DigitalObject.Builder(Content.byReference(new File(args[1]))).build(); MigrateResult result = s.migrate(dobIn, URI.create(args[2]), URI.create(args[3]), null); System.out.println("ServiceReport: " + result.getReport()); DigitalObjectUtils.toFile(result.getDigitalObject(), new File("output")); } else if (pse.getQName().equals(Identify.QNAME)) { System.out.println("Is an Identify service. "); Identify s = new IdentifyWrapper(wsdl); DigitalObject dobIn = new DigitalObject.Builder(Content.byReference(new File(args[1]))).build(); IdentifyResult result = s.identify(dobIn, null); System.out.println("ServiceReport: " + result.getReport()); } }
From source file:com.github.autermann.wps.streaming.ExecuteBuilder.java
public static void main(String[] args) throws URISyntaxException, IOException, ExceptionReport, XmlException { OwsCodeType processId = new OwsCodeType(DelegatingStreamingAlgorithm.PROCESS_ID); ProcessInputs inputs = new ProcessInputs().addDataInput(INPUT_REMOTE_WPS_URL, LiteralData.of(WPS_URL)) .addDataInput(INPUT_REMOTE_PROCESS_DESCRIPTION, new ReferencedData( new URIBuilder(WPS_URL).addParameter(PARAMETER_SERVICE, SERVICE_TYPE_WPS) .addParameter(PARAMETER_VERSION, SERVICE_VERSION_100) .addParameter(PARAMETER_REQUEST, OPERATION_DESCRIBE_PROCESS) .addParameter(PARAMETER_IDENTIFIER, AddAlgorithm.class.getName()).build(), PROCESS_DESCRIPTION_FORMAT)); // StaticInputsDocument doc = StaticInputsDocument.Factory.newInstance(); InputsDocument doc = InputsDocument.Factory.newInstance(); InputsType d = doc.addNewInputs();//doc.addNewStaticInputs(); CommonEncoding ce = new CommonEncoding(); ce.encodeInput(d.addNewStreamingInput(), new DataProcessInput("intput1", LiteralData.of("input1"))); ce.encodeInput(d.addNewStreamingInput(), new DataProcessInput("intput2", new ComplexData(new Format("application/xml", "UTF-8"), "<hello>world</hello>"))); ce.encodeInput(d.addNewStreamingInput(), new DataProcessInput("intput3", new BoundingBoxData(BoundingBoxType.Factory.parse( "<wps:BoundingBoxData xmlns:wps=\"http://www.opengis.net/wps/1.0.0\" xmlns:ows=\"http://www.opengis.net/ows/1.1\" crs=\"EPSG:4326\" dimensions=\"2\">\n" + " <ows:LowerCorner>52.2 7.0</ows:LowerCorner>\n" + " <ows:UpperCorner>55.2 15.0</ows:UpperCorner>\n" + " </wps:BoundingBoxData>")))); ce.encodeInput(d.addNewStreamingInput(), new DataProcessInput("input4", new ReferencedData(URI.create( "http://geoprocessing.demo.52north.org:8080/geoserver/wfs?service=WFS&version=1.0.0&request=GetFeature&typeName=topp:tasmania_roads&srs=EPSG:4326&outputFormat=GML3"), new Format("application/xml", "UTF-8", "http://schemas.opengis.net/gml/3.1.1/base/gml.xsd")))); System.out.println(doc.xmlText(SchemaConstants.XML_OPTIONS)); // try (CloseableHttpClient httpClient = HttpClients.createDefault(); // WPSClient client = new WPSClient(WPS_URL, httpClient)) { // client.execute(processId, inputs, // Lists.newArrayList(OUTPUT_PROCESS_ID, // OUTPUT_SOCKET_URI)); // }//from ww w . j a va2 s .c om }
From source file:com.examples.cloud.speech.SyncRecognizeClient.java
public static void main(String[] args) throws Exception { String audioFile = ""; String host = "speech.googleapis.com"; Integer port = 443;//from w w w .jav a 2 s.co m Integer sampling = 16000; CommandLineParser parser = new DefaultParser(); Options options = new Options(); options.addOption(OptionBuilder.withLongOpt("uri").withDescription("path to audio uri").hasArg() .withArgName("FILE_PATH").create()); options.addOption( OptionBuilder.withLongOpt("host").withDescription("endpoint for api, e.g. speech.googleapis.com") .hasArg().withArgName("ENDPOINT").create()); options.addOption(OptionBuilder.withLongOpt("port").withDescription("SSL port, usually 443").hasArg() .withArgName("PORT").create()); options.addOption(OptionBuilder.withLongOpt("sampling").withDescription("Sampling Rate, i.e. 16000") .hasArg().withArgName("RATE").create()); try { CommandLine line = parser.parse(options, args); if (line.hasOption("uri")) { audioFile = line.getOptionValue("uri"); } else { System.err.println("An Audio uri must be specified (e.g. file:///foo/baz.raw)."); System.exit(1); } if (line.hasOption("host")) { host = line.getOptionValue("host"); } else { System.err.println("An API enpoint must be specified (typically speech.googleapis.com)."); System.exit(1); } if (line.hasOption("port")) { port = Integer.parseInt(line.getOptionValue("port")); } else { System.err.println("An SSL port must be specified (typically 443)."); System.exit(1); } if (line.hasOption("sampling")) { sampling = Integer.parseInt(line.getOptionValue("sampling")); } else { System.err.println("An Audio sampling rate must be specified."); System.exit(1); } } catch (ParseException exp) { System.err.println("Unexpected exception:" + exp.getMessage()); System.exit(1); } ManagedChannel channel = AsyncRecognizeClient.createChannel(host, port); SyncRecognizeClient client = new SyncRecognizeClient(channel, URI.create(audioFile), sampling); try { client.recognize(); } finally { client.shutdown(); } }