List of usage examples for java.net URI create
public static URI create(String str)
From source file:examples.mail.IMAPExportMbox.java
public static void main(String[] args) throws IOException { int connect_timeout = CONNECT_TIMEOUT; int read_timeout = READ_TIMEOUT; int argIdx = 0; String eol = EOL_DEFAULT;/*from w w w .j av a2s. c o m*/ boolean printHash = false; boolean printMarker = false; int retryWaitSecs = 0; for (argIdx = 0; argIdx < args.length; argIdx++) { if (args[argIdx].equals("-c")) { connect_timeout = Integer.parseInt(args[++argIdx]); } else if (args[argIdx].equals("-r")) { read_timeout = Integer.parseInt(args[++argIdx]); } else if (args[argIdx].equals("-R")) { retryWaitSecs = Integer.parseInt(args[++argIdx]); } else if (args[argIdx].equals("-LF")) { eol = LF; } else if (args[argIdx].equals("-CRLF")) { eol = CRLF; } else if (args[argIdx].equals("-.")) { printHash = true; } else if (args[argIdx].equals("-X")) { printMarker = true; } else { break; } } final int argCount = args.length - argIdx; if (argCount < 2) { System.err.println("Usage: IMAPExportMbox [-LF|-CRLF] [-c n] [-r n] [-R n] [-.] [-X]" + " imap[s]://user:password@host[:port]/folder/path [+|-]<mboxfile> [sequence-set] [itemnames]"); System.err.println( "\t-LF | -CRLF set end-of-line to LF or CRLF (default is the line.separator system property)"); System.err.println("\t-c connect timeout in seconds (default 10)"); System.err.println("\t-r read timeout in seconds (default 10)"); System.err.println("\t-R temporary failure retry wait in seconds (default 0; i.e. disabled)"); System.err.println("\t-. print a . for each complete message received"); System.err.println("\t-X print the X-IMAP line for each complete message received"); System.err.println( "\tthe mboxfile is where the messages are stored; use '-' to write to standard output."); System.err.println( "\tPrefix filename with '+' to append to the file. Prefix with '-' to allow overwrite."); System.err.println( "\ta sequence-set is a list of numbers/number ranges e.g. 1,2,3-10,20:* - default 1:*"); System.err .println("\titemnames are the message data item name(s) e.g. BODY.PEEK[HEADER.FIELDS (SUBJECT)]" + " or a macro e.g. ALL - default (INTERNALDATE BODY.PEEK[])"); System.exit(1); } final URI uri = URI.create(args[argIdx++]); final String file = args[argIdx++]; String sequenceSet = argCount > 2 ? args[argIdx++] : "1:*"; final String itemNames; // Handle 0, 1 or multiple item names if (argCount > 3) { if (argCount > 4) { StringBuilder sb = new StringBuilder(); sb.append("("); for (int i = 4; i <= argCount; i++) { if (i > 4) { sb.append(" "); } sb.append(args[argIdx++]); } sb.append(")"); itemNames = sb.toString(); } else { itemNames = args[argIdx++]; } } else { itemNames = "(INTERNALDATE BODY.PEEK[])"; } final boolean checkSequence = sequenceSet.matches("\\d+:(\\d+|\\*)"); // are we expecting a sequence? final MboxListener chunkListener; if (file.equals("-")) { chunkListener = null; } else if (file.startsWith("+")) { final File mbox = new File(file.substring(1)); System.out.println("Appending to file " + mbox); chunkListener = new MboxListener(new BufferedWriter(new FileWriter(mbox, true)), eol, printHash, printMarker, checkSequence); } else if (file.startsWith("-")) { final File mbox = new File(file.substring(1)); System.out.println("Writing to file " + mbox); chunkListener = new MboxListener(new BufferedWriter(new FileWriter(mbox, false)), eol, printHash, printMarker, checkSequence); } else { final File mbox = new File(file); if (mbox.exists()) { throw new IOException("mailbox file: " + mbox + " already exists!"); } System.out.println("Creating file " + mbox); chunkListener = new MboxListener(new BufferedWriter(new FileWriter(mbox)), eol, printHash, printMarker, checkSequence); } String path = uri.getPath(); if (path == null || path.length() < 1) { throw new IllegalArgumentException("Invalid folderPath: '" + path + "'"); } String folder = path.substring(1); // skip the leading / // suppress login details final PrintCommandListener listener = new PrintCommandListener(System.out, true) { @Override public void protocolReplyReceived(ProtocolCommandEvent event) { if (event.getReplyCode() != IMAPReply.PARTIAL) { // This is dealt with by the chunk listener super.protocolReplyReceived(event); } } }; // Connect and login final IMAPClient imap = IMAPUtils.imapLogin(uri, connect_timeout * 1000, listener); String maxIndexInFolder = null; try { imap.setSoTimeout(read_timeout * 1000); if (!imap.select(folder)) { throw new IOException("Could not select folder: " + folder); } for (String line : imap.getReplyStrings()) { maxIndexInFolder = matches(line, PATEXISTS, 1); if (maxIndexInFolder != null) { break; } } if (chunkListener != null) { imap.setChunkListener(chunkListener); } // else the command listener displays the full output without processing while (true) { boolean ok = imap.fetch(sequenceSet, itemNames); // If the fetch failed, can we retry? if (!ok && retryWaitSecs > 0 && chunkListener != null && checkSequence) { final String replyString = imap.getReplyString(); //includes EOL if (startsWith(replyString, PATTEMPFAIL)) { System.err.println("Temporary error detected, will retry in " + retryWaitSecs + "seconds"); sequenceSet = (chunkListener.lastSeq + 1) + ":*"; try { Thread.sleep(retryWaitSecs * 1000); } catch (InterruptedException e) { // ignored } } else { throw new IOException( "FETCH " + sequenceSet + " " + itemNames + " failed with " + replyString); } } else { break; } } } catch (IOException ioe) { String count = chunkListener == null ? "?" : Integer.toString(chunkListener.total); System.err.println("FETCH " + sequenceSet + " " + itemNames + " failed after processing " + count + " complete messages "); if (chunkListener != null) { System.err.println("Last complete response seen: " + chunkListener.lastFetched); } throw ioe; } finally { if (printHash) { System.err.println(); } if (chunkListener != null) { chunkListener.close(); final Iterator<String> missingIds = chunkListener.missingIds.iterator(); if (missingIds.hasNext()) { StringBuilder sb = new StringBuilder(); for (;;) { sb.append(missingIds.next()); if (!missingIds.hasNext()) { break; } sb.append(","); } System.err.println("*** Missing ids: " + sb.toString()); } } imap.logout(); imap.disconnect(); } if (chunkListener != null) { System.out.println("Processed " + chunkListener.total + " messages."); } if (maxIndexInFolder != null) { System.out.println("Folder contained " + maxIndexInFolder + " messages."); } }
From source file:com.google.cloud.speech.grpc.demos.NonStreamingRecognizeClient.java
public static void main(String[] args) throws Exception { String audioFile = ""; String host = "speech.googleapis.com"; Integer port = 443;/*from ww w. j av a2s .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); } NonStreamingRecognizeClient client = new NonStreamingRecognizeClient(host, port, URI.create(audioFile), sampling); try { client.recognize(); } finally { client.shutdown(); } }
From source file:craterdog.marketplace.DigitalMarketplaceCli.java
static public void main(String[] args) { logger.entry((Object) args);/*from www . j a v a 2 s . co m*/ logger.debug("Ensuring the data directory exists..."); File directory = new File(dataDirectory); if (!directory.exists() && !directory.mkdir()) { logger.error("Unable to create ~/.cdt/ directory, exiting..."); System.exit(1); } logger.debug("Configuring the CLI..."); String digitalMarketplaceUriString = defaultDigitalAccountantUri; if (args.length > 0) { digitalMarketplaceUriString = args[0]; } URI digitalMarketplaceUri = URI.create(digitalMarketplaceUriString); DigitalMarketplaceCli cli = new DigitalMarketplaceCli(digitalMarketplaceUri); logger.debug("Running the CLI..."); int status = cli.run(); logger.exit(status); }
From source file:com.examples.cloud.speech.AsyncRecognizeClient.java
public static void main(String[] args) throws Exception { String audioFile = ""; String host = "speech.googleapis.com"; Integer port = 443;// w w w . j ava 2 s . c o 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); AsyncRecognizeClient client = new AsyncRecognizeClient(channel, URI.create(audioFile), sampling); try { client.recognize(); } finally { client.shutdown(); } }
From source file:Main.java
public static final String dereference(String idRef) { URI uri = URI.create(idRef); String part = uri.getSchemeSpecificPart(); if (part != null && part.length() > 0) { throw new UnsupportedOperationException( "modlur does not support external sources (" + uri.toString() + ")"); }/*from w w w . ja va 2 s . c o m*/ return uri.getFragment(); }
From source file:Main.java
private static FileSystem createZipFileSystem(String zipFilename, boolean create) throws IOException { final Path path = Paths.get(zipFilename); final URI uri = URI.create("jar:file:" + path.toUri().getPath()); final Map<String, String> env = new HashMap<>(); if (create) { env.put("create", "true"); }//from w w w. ja v a 2 s . c om return FileSystems.newFileSystem(uri, env); }
From source file:de.mpg.imeji.presentation.util.SearchAndExportHelper.java
public static String getCitation(Publication publication) { URI uri = publication.getUri(); URI searchAndExportUri = URI.create("http://" + uri.getHost() + "/search/SearchAndExport"); String itemId = null;/*from ww w . j av a 2 s .c om*/ if (uri.getQuery() != null && uri.getQuery().contains("itemId=")) { itemId = uri.getQuery().split("itemId=")[1]; } else if (uri.getPath() != null && uri.getPath().contains("/item/")) { itemId = uri.getPath().split("/item/")[1]; } if (UrlHelper.isValidURI(searchAndExportUri)) { try { HttpClient client = new HttpClient(); String exportUri = searchAndExportUri.toString() + "?cqlQuery=" + URLEncoder.encode( "escidoc.objid=" + itemId + " or escidoc.property.version.objid=" + itemId, "ISO-8859-1") + "&exportFormat=" + publication.getExportFormat() + "&outputFormat=html_linked"; GetMethod method = new GetMethod(exportUri); client.executeMethod(method); return method.getResponseBodyAsString(); } catch (Exception e) { return null; } } return null; }
From source file:Main.java
public static void deepCopyDocument(Document ttml, File target) throws IOException { try {// w w w.jav a 2 s. c o m XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); XPathExpression expr = xpath.compile("//*/@backgroundImage"); NodeList nl = (NodeList) expr.evaluate(ttml, XPathConstants.NODESET); for (int i = 0; i < nl.getLength(); i++) { Node backgroundImage = nl.item(i); URI backgroundImageUri = URI.create(backgroundImage.getNodeValue()); if (!backgroundImageUri.isAbsolute()) { copyLarge(new URI(ttml.getDocumentURI()).resolve(backgroundImageUri).toURL().openStream(), new File(target.toURI().resolve(backgroundImageUri).toURL().getFile())); } } copyLarge(new URI(ttml.getDocumentURI()).toURL().openStream(), target); } catch (XPathExpressionException e) { throw new IOException(e); } catch (URISyntaxException e) { throw new IOException(e); } }
From source file:net.jadler.stubbing.server.jetty.RequestUtils.java
public static Request convert(HttpServletRequest source) throws IOException { String method = source.getMethod(); URI requestUri = URI.create(source.getRequestURL() + getQueryString(source)); InputStream body = source.getInputStream(); InetSocketAddress localAddress = new InetSocketAddress(source.getLocalAddr(), source.getLocalPort()); InetSocketAddress remoteAddress = new InetSocketAddress(source.getRemoteAddr(), source.getRemotePort()); String encoding = source.getCharacterEncoding(); Map<String, List<String>> headers = converHeaders(source); return new Request(method, requestUri, headers, body, localAddress, remoteAddress, encoding); }
From source file:Main.java
static URI createJournalURI(String path) throws Exception { return URI.create("bookkeeper://" + zkEnsemble + path); }