List of usage examples for java.net URI URI
public URI(String str) throws URISyntaxException
From source file:io.fluo.cluster.WorkerApp.java
public static void main(String[] args) throws ConfigurationException, Exception { AppOptions options = new AppOptions(); JCommander jcommand = new JCommander(options, args); if (options.displayHelp()) { jcommand.usage();//from w w w . j a v a2 s.com System.exit(-1); } Logging.init("worker", options.getFluoHome() + "/conf", "STDOUT"); File configFile = new File(options.getFluoHome() + "/conf/fluo.properties"); FluoConfiguration config = new FluoConfiguration(configFile); if (!config.hasRequiredWorkerProps()) { log.error("fluo.properties is missing required properties for worker"); System.exit(-1); } Environment env = new Environment(config); YarnConfiguration yarnConfig = new YarnConfiguration(); yarnConfig.addResource(new Path(options.getHadoopPrefix() + "/etc/hadoop/core-site.xml")); yarnConfig.addResource(new Path(options.getHadoopPrefix() + "/etc/hadoop/yarn-site.xml")); TwillRunnerService twillRunner = new YarnTwillRunnerService(yarnConfig, env.getZookeepers()); twillRunner.startAndWait(); TwillPreparer preparer = twillRunner.prepare(new WorkerApp(options, config)); // Add any observer jars found in lib observers File observerDir = new File(options.getFluoHome() + "/lib/observers"); for (File f : observerDir.listFiles()) { String jarPath = "file:" + f.getCanonicalPath(); log.debug("Adding observer jar " + jarPath + " to YARN app"); preparer.withResources(new URI(jarPath)); } TwillController controller = preparer.start(); controller.start(); while (controller.isRunning() == false) { Thread.sleep(2000); } env.close(); System.exit(0); }
From source file:org.tommy.stationery.moracle.core.client.load.StompWebSocketLoadTestClient.java
public static void main(String[] args) throws Exception { // Modify host and port below to match wherever StompWebSocketServer.java is running!! // When StompWebSocketServer starts it prints the selected available String host = "localhost"; if (args.length > 0) { host = args[0];//from w w w . j av a 2 s. c om } int port = 59984; if (args.length > 1) { port = Integer.valueOf(args[1]); } String url = "http://" + host + ":" + port + "/home"; logger.debug("Sending warm-up HTTP request to " + url); HttpStatus status = new RestTemplate().getForEntity(url, Void.class).getStatusCode(); Assert.state(status == HttpStatus.OK); final CountDownLatch connectLatch = new CountDownLatch(NUMBER_OF_USERS); final CountDownLatch subscribeLatch = new CountDownLatch(NUMBER_OF_USERS); final CountDownLatch messageLatch = new CountDownLatch(NUMBER_OF_USERS); final CountDownLatch disconnectLatch = new CountDownLatch(NUMBER_OF_USERS); final AtomicReference<Throwable> failure = new AtomicReference<Throwable>(); Executor executor = Executors.newFixedThreadPool(THREAD_POOL_SIZE); org.eclipse.jetty.websocket.client.WebSocketClient jettyClient = new WebSocketClient(executor); JettyWebSocketClient webSocketClient = new JettyWebSocketClient(jettyClient); webSocketClient.start(); HttpClient jettyHttpClient = new HttpClient(); jettyHttpClient.setMaxConnectionsPerDestination(1000); jettyHttpClient.setExecutor(new QueuedThreadPool(1000)); jettyHttpClient.start(); List<Transport> transports = new ArrayList<>(); transports.add(new WebSocketTransport(webSocketClient)); transports.add(new JettyXhrTransport(jettyHttpClient)); SockJsClient sockJsClient = new SockJsClient(transports); try { URI uri = new URI("ws://" + host + ":" + port + "/stomp"); WebSocketStompClient stompClient = new WebSocketStompClient(uri, null, sockJsClient); stompClient.setMessageConverter(new StringMessageConverter()); logger.debug("Connecting and subscribing " + NUMBER_OF_USERS + " users "); StopWatch stopWatch = new StopWatch("STOMP Broker Relay WebSocket Load Tests"); stopWatch.start(); List<ConsumerStompMessageHandler> consumers = new ArrayList<>(); for (int i = 0; i < NUMBER_OF_USERS; i++) { consumers.add(new ConsumerStompMessageHandler(BROADCAST_MESSAGE_COUNT, connectLatch, subscribeLatch, messageLatch, disconnectLatch, failure)); stompClient.connect(consumers.get(i)); } if (failure.get() != null) { throw new AssertionError("Test failed", failure.get()); } if (!connectLatch.await(5000, TimeUnit.MILLISECONDS)) { logger.info("Not all users connected, remaining: " + connectLatch.getCount()); } if (!subscribeLatch.await(5000, TimeUnit.MILLISECONDS)) { logger.info("Not all users subscribed, remaining: " + subscribeLatch.getCount()); } stopWatch.stop(); logger.debug("Finished: " + stopWatch.getLastTaskTimeMillis() + " millis"); logger.debug("Broadcasting " + BROADCAST_MESSAGE_COUNT + " messages to " + NUMBER_OF_USERS + " users "); stopWatch.start(); ProducerStompMessageHandler producer = new ProducerStompMessageHandler(BROADCAST_MESSAGE_COUNT, failure); stompClient.connect(producer); if (failure.get() != null) { throw new AssertionError("Test failed", failure.get()); } if (!messageLatch.await(1 * 60 * 1000, TimeUnit.MILLISECONDS)) { for (ConsumerStompMessageHandler consumer : consumers) { if (consumer.messageCount.get() < consumer.expectedMessageCount) { logger.debug(consumer); } } } if (!messageLatch.await(1 * 60 * 1000, TimeUnit.MILLISECONDS)) { logger.info("Not all handlers received every message, remaining: " + messageLatch.getCount()); } producer.session.disconnect(); if (!disconnectLatch.await(5000, TimeUnit.MILLISECONDS)) { logger.info("Not all disconnects completed, remaining: " + disconnectLatch.getCount()); } stopWatch.stop(); logger.debug("Finished: " + stopWatch.getLastTaskTimeMillis() + " millis"); System.out.println("\nPress any key to exit..."); System.in.read(); } catch (Throwable t) { t.printStackTrace(); } finally { webSocketClient.stop(); jettyHttpClient.stop(); } logger.debug("Exiting"); System.exit(0); }
From source file:edu.stanford.junction.props2.PropDaemon.java
/** * Conveniance runner for PropDaemon// w ww. j ava 2s . c om * Expects two arguments: junction-url propName */ public static void main(String[] args) { if (args.length != 2) { System.out.println("Usage: PROGRAM junction-url propName"); System.exit(0); } final String urlStr = args[0]; final String propName = args[1]; JunctionActor actor = new JunctionActor("prop-daemon") { public void onActivityJoin() { System.out.println("Joined activity!"); } public void onActivityCreate() { System.out.println("Created activity!"); } public void onMessageReceived(MessageHeader header, JSONObject msg) { System.out.println("Got message!"); } public List<JunctionExtra> getInitialExtras() { ArrayList<JunctionExtra> l = new ArrayList<JunctionExtra>(); l.add(new PropDaemon(propName)); return l; } }; try { URI uri = new URI(urlStr); SwitchboardConfig sb = JunctionMaker.getDefaultSwitchboardConfig(uri); JunctionMaker jxMaker = JunctionMaker.getInstance(sb); Junction jx = jxMaker.newJunction(uri, actor); } catch (URISyntaxException e) { System.err.println("Failed to parse url!"); e.printStackTrace(System.err); } catch (JunctionException e) { System.err.println("Failed to connect to junction activity!"); e.printStackTrace(System.err); } catch (Exception e) { System.err.println("Failed to connect to junction activity!"); e.printStackTrace(System.err); } }
From source file:com.p2p.peercds.cli.TorrentMain.java
/** * Torrent reader and creator.//from w w w.j a v a2s. c o m * * <p> * You can use the {@code main()} function of this class to read or create * torrent files. See usage for details. * </p> * */ public static void main(String[] args) { BasicConfigurator.configure(new ConsoleAppender(new PatternLayout("%-5p: %m%n"))); CmdLineParser parser = new CmdLineParser(); CmdLineParser.Option help = parser.addBooleanOption('h', "help"); CmdLineParser.Option filename = parser.addStringOption('t', "torrent"); CmdLineParser.Option create = parser.addBooleanOption('c', "create"); CmdLineParser.Option announce = parser.addStringOption('a', "announce"); try { parser.parse(args); } catch (CmdLineParser.OptionException oe) { System.err.println(oe.getMessage()); usage(System.err); System.exit(1); } // Display help and exit if requested if (Boolean.TRUE.equals((Boolean) parser.getOptionValue(help))) { usage(System.out); System.exit(0); } String filenameValue = (String) parser.getOptionValue(filename); if (filenameValue == null) { usage(System.err, "Torrent file must be provided!"); System.exit(1); } Boolean createFlag = (Boolean) parser.getOptionValue(create); //For repeated announce urls @SuppressWarnings("unchecked") Vector<String> announceURLs = (Vector<String>) parser.getOptionValues(announce); String[] otherArgs = parser.getRemainingArgs(); if (Boolean.TRUE.equals(createFlag) && (otherArgs.length != 1 || announceURLs.isEmpty())) { usage(System.err, "Announce URL and a file or directory must be " + "provided to create a torrent file!"); System.exit(1); } OutputStream fos = null; try { if (Boolean.TRUE.equals(createFlag)) { if (filenameValue != null) { fos = new FileOutputStream(filenameValue); } else { fos = System.out; } //Process the announce URLs into URIs List<URI> announceURIs = new ArrayList<URI>(); for (String url : announceURLs) { announceURIs.add(new URI(url)); } //Create the announce-list as a list of lists of URIs //Assume all the URI's are first tier trackers List<List<URI>> announceList = new ArrayList<List<URI>>(); announceList.add(announceURIs); File source = new File(otherArgs[0]); if (!source.exists() || !source.canRead()) { throw new IllegalArgumentException( "Cannot access source file or directory " + source.getName()); } String creator = String.format("%s (ttorrent)", System.getProperty("user.name")); Torrent torrent = null; if (source.isDirectory()) { File[] files = source.listFiles(Constants.hiddenFilesFilter); Arrays.sort(files); torrent = Torrent.create(source, Arrays.asList(files), announceList, creator); } else { torrent = Torrent.create(source, announceList, creator); } torrent.save(fos); } else { Torrent.load(new File(filenameValue), true); } } catch (Exception e) { logger.error("{}", e.getMessage(), e); System.exit(2); } finally { if (fos != System.out) { IOUtils.closeQuietly(fos); } } }
From source file:dataflow.examples.TransferFiles.java
public static void main(String[] args) throws IOException, URISyntaxException { Options options = PipelineOptionsFactory.fromArgs(args).withValidation().as(Options.class); List<FilePair> filePairs = new ArrayList<FilePair>(); URI ftpInput = new URI(options.getInput()); FTPClient ftp = new FTPClient(); ftp.connect(ftpInput.getHost());//from w w w . java 2s . c o m // After connection attempt, you should check the reply code to verify // success. int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); logger.error("FTP server refused connection."); throw new RuntimeException("FTP server refused connection."); } ftp.login("anonymous", "someemail@gmail.com"); String ftpPath = ftpInput.getPath(); FTPFile[] files = ftp.listFiles(ftpPath); URI gcsUri = null; if (options.getOutput().endsWith("/")) { gcsUri = new URI(options.getOutput()); } else { gcsUri = new URI(options.getOutput() + "/"); } for (FTPFile f : files) { logger.info("File: " + f.getName()); FilePair p = new FilePair(); p.server = ftpInput.getHost(); p.ftpPath = f.getName(); // URI ftpURI = new URI("ftp", p.server, f.getName(), ""); p.gcsPath = gcsUri.resolve(FilenameUtils.getName(f.getName())).toString(); filePairs.add(p); } ftp.logout(); Pipeline p = Pipeline.create(options); PCollection<FilePair> inputs = p.apply(Create.of(filePairs)); inputs.apply(ParDo.of(new FTPToGCS()).named("CopyToGCS")) .apply(AvroIO.Write.withSchema(FilePair.class).to(options.getOutput())); p.run(); }
From source file:org.apache.uima.examples.as.GetMetaRequest.java
/** * retrieve meta information for a UIMA-AS Service attached to a broker * It uses the port 1099 as the JMX port on the broker, unless overridden * by defining the system property activemq.broker.jmx.port with a value of another port number * It uses the default JMX ActiveMQ Domain "org.apache.activemq", unless overridden * by defining the system property activemq.broker.jmx.domain with a value of the domain to use * This normally never needs to be done unless multiple brokers are run on the same node * as is sometimes done for unit tests. * @param args - brokerUri serviceName [-verbose] *//* w ww .ja v a 2s . co m*/ public static void main(String[] args) { if (args.length < 2) { System.err.println("Need arguments: brokerURI serviceName [-verbose]"); System.exit(1); } String brokerURI = args[0]; String queueName = args[1]; boolean printReply = false; if (args.length > 2) { if (args[2].equalsIgnoreCase("-verbose")) { printReply = true; } else { System.err.println("Unknown argument: " + args[2]); System.exit(1); } } final Connection connection; Session producerSession = null; Queue producerQueue = null; MessageProducer producer; MessageConsumer consumer; Session consumerSession = null; TemporaryQueue consumerDestination = null; long startTime = 0; // Check if JMX server port number was specified jmxPort = System.getProperty("activemq.broker.jmx.port"); if (jmxPort == null || jmxPort.trim().length() == 0) { jmxPort = "1099"; // default } try { // First create connection to a broker ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(brokerURI); connection = factory.createConnection(); connection.start(); Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { public void run() { try { if (connection != null) { connection.close(); } if (jmxc != null) { jmxc.close(); } } catch (Exception ex) { } } })); URI target = new URI(brokerURI); String brokerHost = target.getHost(); attachToRemoteBrokerJMXServer(brokerURI); if (isQueueAvailable(queueName) == QueueState.exists) { System.out.println("Queue " + queueName + " found on " + brokerURI); System.out.println("Sending getMeta..."); } else if (isQueueAvailable(queueName) == QueueState.existsnot) { System.err.println("Queue " + queueName + " does not exist on " + brokerURI); System.exit(1); } else { System.out.println("Cannot see queues on JMX port " + brokerHost + ":" + jmxPort); System.out.println("Sending getMeta anyway..."); } producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); producerQueue = producerSession.createQueue(queueName); producer = producerSession.createProducer(producerQueue); consumerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); consumerDestination = consumerSession.createTemporaryQueue(); // ----------------------------------------------------------------------------- // Create message consumer. The consumer uses a selector to filter out messages other // then GetMeta replies. Currently UIMA AS service returns two messages for each request: // ServiceInfo message and GetMeta message. The ServiceInfo message is returned by the // service immediately upon receiving a message from a client. This serves dual purpose, // 1) to make sure the client reply destination exists // 2) informs the client which service is processing its request // ----------------------------------------------------------------------------- consumer = consumerSession.createConsumer(consumerDestination, "Command=2001"); TextMessage msg = producerSession.createTextMessage(); msg.setStringProperty(AsynchAEMessage.MessageFrom, consumerDestination.getQueueName()); msg.setStringProperty(UIMAMessage.ServerURI, brokerURI); msg.setIntProperty(AsynchAEMessage.MessageType, AsynchAEMessage.Request); msg.setIntProperty(AsynchAEMessage.Command, AsynchAEMessage.GetMeta); msg.setJMSReplyTo(consumerDestination); msg.setText(""); producer.send(msg); startTime = System.nanoTime(); System.out.println("Sent getMeta request to " + queueName + " at " + brokerURI); System.out.println("Waiting for getMeta reply..."); ActiveMQTextMessage reply = (ActiveMQTextMessage) consumer.receive(); long waitTime = (System.nanoTime() - startTime) / 1000000; System.out.println( "Reply from " + reply.getStringProperty("ServerIP") + " received in " + waitTime + " ms"); if (printReply) { System.out.println("Reply MessageText: " + reply.getText()); } } catch (Exception e) { System.err.println(e.toString()); } System.exit(0); }
From source file:com.image32.demo.simpleapi.SimpleApiDemo.java
final public static void main(String[] args) { me = new SimpleApiDemo(); me.contentHandlers = new ContentHandler(); //load configurations try {// w ww .j a v a 2 s . c o m Properties prop = new Properties(); InputStream input = SimpleApiDemo.class.getResourceAsStream("/demoConfig.properties"); // load a properties file prop.load(input); image32ApiClientId = prop.getProperty("image32ApiClientId"); image32ApiSecrect = prop.getProperty("image32ApiSecrect"); image32ApiAuthUrl = prop.getProperty("image32ApiAuthUrl"); image32ApiGetStudiesUrl = prop.getProperty("image32ApiGetStudiesUrl"); demoDataFile = prop.getProperty("demoDataFile"); input.close(); } catch (Exception ex) { logger.info("No configuration found."); System.exit(1); } // test port availability while (!checkPortAvailablity(port)) { if (port > 8090) { logger.info("Port is not available. Exiting..."); System.exit(1); } port++; } ; // run server server = new Server(port); HashSessionIdManager hashSessionIdManager = new HashSessionIdManager(); server.setSessionIdManager(hashSessionIdManager); WebAppContext homecontext = new WebAppContext(); homecontext.setContextPath("/home"); ResourceCollection resources = new ResourceCollection(new String[] { "site" }); homecontext.setBaseResource(resources); HashSessionManager manager = new HashSessionManager(); manager.setSecureCookies(true); SessionHandler sessionHandler = new SessionHandler(manager); sessionHandler.setHandler(me.contentHandlers); ContextHandler context = new ContextHandler(); context.setContextPath("/app"); context.setResourceBase("."); context.setClassLoader(Thread.currentThread().getContextClassLoader()); context.setHandler(sessionHandler); HandlerList handlers = new HandlerList(); handlers.setHandlers(new Handler[] { homecontext, context }); server.setHandler(handlers); try { server.start(); logger.info("Server started on port " + port); logger.info("Please access this demo from browser with this url: http://localhost:" + port); if (Desktop.isDesktopSupported()) Desktop.getDesktop().browse(new URI("http://localhost:" + port + "/home")); server.join(); } catch (Exception exception) { logger.error(exception.getMessage()); } System.exit(1); }
From source file:de.uniko.west.winter.test.basics.JenaTests.java
public static void main(String[] args) { Model newModel = ModelFactory.createDefaultModel(); // /* ww w.j a va2 s. c o m*/ Model newModel2 = ModelFactory.createModelForGraph(ModelFactory.createMemModelMaker().getGraphMaker() .createGraph("http://www.defaultgraph.de/graph1")); StringBuilder updateString = new StringBuilder(); updateString.append("PREFIX dc: <http://purl.org/dc/elements/1.1/>"); updateString.append("PREFIX xsd: <http://bla.org/dc/elements/1.1/>"); updateString.append("INSERT { "); updateString.append( "<http://example/egbook1> dc:title <http://example/egbook1/#Title1>, <http://example/egbook1/#Title2>. "); //updateString.append("<http://example/egbook1> dc:title \"Title1.1\". "); //updateString.append("<http://example/egbook1> dc:title \"Title1.2\". "); updateString.append("<http://example/egbook21> dc:title \"Title2\"; "); updateString.append("dc:title \"2.0\"^^xsd:double. "); updateString.append("<http://example/egbook3> dc:title \"Title3\". "); updateString.append("<http://example/egbook4> dc:title \"Title4\". "); updateString.append("<http://example/egbook5> dc:title \"Title5\". "); updateString.append("<http://example/egbook6> dc:title \"Title6\" "); updateString.append("}"); UpdateRequest update = UpdateFactory.create(updateString.toString()); UpdateAction.execute(update, newModel); StmtIterator iter = newModel.listStatements(); System.out.println("After add"); while (iter.hasNext()) { System.out.println(iter.next().toString()); } StringBuilder constructQueryString = new StringBuilder(); constructQueryString.append("PREFIX dc: <http://purl.org/dc/elements/1.1/>"); constructQueryString.append("CONSTRUCT {?sub dc:title <http://example/egbook1/#Title1>}"); constructQueryString.append("WHERE {"); constructQueryString.append("?sub dc:title <http://example/egbook1/#Title1>"); constructQueryString.append("}"); StringBuilder askQueryString = new StringBuilder(); askQueryString.append("PREFIX dc: <http://purl.org/dc/elements/1.1/>"); askQueryString.append("ASK {"); askQueryString.append("?sub dc:title <http://example/egbook1/#Title1>"); askQueryString.append("}"); StringBuilder selectQueryString = new StringBuilder(); selectQueryString.append("PREFIX dc: <http://purl.org/dc/elements/1.1/>"); selectQueryString.append("SELECT * "); selectQueryString.append("WHERE {"); selectQueryString.append("?sub ?pred ?obj"); selectQueryString.append("}"); Query cquery = QueryFactory.create(constructQueryString.toString()); System.out.println(cquery.getQueryType()); Query aquery = QueryFactory.create(askQueryString.toString()); System.out.println(aquery.getQueryType()); Query query = QueryFactory.create(selectQueryString.toString()); System.out.println(query.getQueryType()); QueryExecution queryExecution = QueryExecutionFactory.create(query, newModel); ByteArrayOutputStream baos = new ByteArrayOutputStream(); URI test = null; try { test = new URI("http://bla.org/dc/elements/1.1/double"); } catch (URISyntaxException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } System.out.println(test.getPath().toString().substring(test.getPath().lastIndexOf("/") + 1)); System.out.println("java.lang." + test.getPath().toString().substring(test.getPath().lastIndexOf("/") + 1).substring(0, 1) .toUpperCase() + test.getPath().toString().substring(test.getPath().lastIndexOf("/") + 1).substring(1)); String typ = "java.lang.Boolean"; String val = "true"; try { Object typedLiteral = Class.forName(typ, true, ClassLoader.getSystemClassLoader()) .getConstructor(String.class).newInstance(val); System.out.println("Type: " + typedLiteral.getClass().getName() + " Value: " + typedLiteral); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { System.out.println("Query..."); com.hp.hpl.jena.query.ResultSet results = queryExecution.execSelect(); System.out.println("RESULT:"); ResultSetFormatter.output(System.out, results, ResultSetFormat.syntaxJSON); // // // ResultSetFormatter.outputAsJSON(baos, results); // System.out.println(baos.toString()); // System.out.println("JsonTest: "); // JSONObject result = new JSONObject(baos.toString("ISO-8859-1")); // for (Iterator key = result.keys(); result.keys().hasNext(); ){ // System.out.println(key.next()); // // for (Iterator key2 = ((JSONObject)result.getJSONObject("head")).keys(); key2.hasNext(); ){ // System.out.println(key2.next()); // } // } // Model results = queryExecution.execConstruct(); // results.write(System.out, "TURTLE"); // for ( ; results.hasNext() ; ){ // QuerySolution soln = results.nextSolution() ; // RDFNode x = soln.get("sub") ; // System.out.println("result: "+soln.get("sub")+" hasTitle "+soln.get("obj")); // Resource r = soln.getResource("VarR") ; // Literal l = soln.getLiteral("VarL") ; // // } } catch (Exception e) { // TODO: handle exception } // StringBuilder updateString2 = new StringBuilder(); // updateString2.append("PREFIX dc: <http://purl.org/dc/elements/1.1/>"); // updateString2.append("DELETE DATA { "); // updateString2.append("<http://example/egbook3> dc:title \"Title3\" "); // updateString2.append("}"); // // UpdateAction.parseExecute(updateString2.toString(), newModel); // // iter = newModel.listStatements(); // System.out.println("After delete"); // while (iter.hasNext()) { // System.out.println(iter.next().toString()); // // } // // StringBuilder updateString3 = new StringBuilder(); // updateString3.append("PREFIX dc: <http://purl.org/dc/elements/1.1/>"); // updateString3.append("DELETE DATA { "); // updateString3.append("<http://example/egbook6> dc:title \"Title6\" "); // updateString3.append("}"); // updateString3.append("INSERT { "); // updateString3.append("<http://example/egbook6> dc:title \"New Title6\" "); // updateString3.append("}"); // // UpdateAction.parseExecute(updateString3.toString(), newModel); // UpdateAction.parseExecute( "prefix exp: <http://www.example.de>"+ // "prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>"+ // "INSERT { graph <http://www.defaultgraph.de/graph1> {"+ // " <http://www.test.de#substructure1> <exp:has_relation3> <http://www.test.de#substructure2> ."+ // " <http://www.test.de#substructure1> <rdf:type> <http://www.test.de#substructuretype1> ."+ // " <http://www.test.de#substructure2> <rdf:type> <http://www.test.de#substructuretype2> ."+ // "}}", newModel2); // // iter = newModel.listStatements(); // System.out.println("After update"); // while (iter.hasNext()) { // System.out.println(iter.next().toString()); // // } }
From source file:com.turn.ttorrent.cli.TorrentMain.java
/** * Torrent reader and creator./*from w w w. j av a2s. c o m*/ * * <p> * You can use the {@code main()} function of this class to read or create * torrent files. See usage for details. * </p> * */ public static void main(String[] args) { BasicConfigurator.configure(new ConsoleAppender(new PatternLayout("%-5p: %m%n"))); CmdLineParser parser = new CmdLineParser(); CmdLineParser.Option help = parser.addBooleanOption('h', "help"); CmdLineParser.Option filename = parser.addStringOption('t', "torrent"); CmdLineParser.Option create = parser.addBooleanOption('c', "create"); CmdLineParser.Option pieceLength = parser.addIntegerOption('l', "length"); CmdLineParser.Option announce = parser.addStringOption('a', "announce"); try { parser.parse(args); } catch (CmdLineParser.OptionException oe) { System.err.println(oe.getMessage()); usage(System.err); System.exit(1); } // Display help and exit if requested if (Boolean.TRUE.equals((Boolean) parser.getOptionValue(help))) { usage(System.out); System.exit(0); } String filenameValue = (String) parser.getOptionValue(filename); if (filenameValue == null) { usage(System.err, "Torrent file must be provided!"); System.exit(1); } Integer pieceLengthVal = (Integer) parser.getOptionValue(pieceLength); if (pieceLengthVal == null) { pieceLengthVal = Torrent.DEFAULT_PIECE_LENGTH; } else { pieceLengthVal = pieceLengthVal * 1024; } logger.info("Using piece length of {} bytes.", pieceLengthVal); Boolean createFlag = (Boolean) parser.getOptionValue(create); //For repeated announce urls @SuppressWarnings("unchecked") Vector<String> announceURLs = (Vector<String>) parser.getOptionValues(announce); String[] otherArgs = parser.getRemainingArgs(); if (Boolean.TRUE.equals(createFlag) && (otherArgs.length != 1 || announceURLs.isEmpty())) { usage(System.err, "Announce URL and a file or directory must be " + "provided to create a torrent file!"); System.exit(1); } OutputStream fos = null; try { if (Boolean.TRUE.equals(createFlag)) { if (filenameValue != null) { fos = new FileOutputStream(filenameValue); } else { fos = System.out; } //Process the announce URLs into URIs List<URI> announceURIs = new ArrayList<URI>(); for (String url : announceURLs) { announceURIs.add(new URI(url)); } //Create the announce-list as a list of lists of URIs //Assume all the URI's are first tier trackers List<List<URI>> announceList = new ArrayList<List<URI>>(); announceList.add(announceURIs); File source = new File(otherArgs[0]); if (!source.exists() || !source.canRead()) { throw new IllegalArgumentException( "Cannot access source file or directory " + source.getName()); } String creator = String.format("%s (ttorrent)", System.getProperty("user.name")); Torrent torrent = null; if (source.isDirectory()) { List<File> files = new ArrayList<File>( FileUtils.listFiles(source, TrueFileFilter.TRUE, TrueFileFilter.TRUE)); Collections.sort(files); torrent = Torrent.create(source, files, pieceLengthVal, announceList, creator); } else { torrent = Torrent.create(source, pieceLengthVal, announceList, creator); } torrent.save(fos); } else { Torrent.load(new File(filenameValue), true); } } catch (Exception e) { logger.error("{}", e.getMessage(), e); System.exit(2); } finally { if (fos != System.out) { IOUtils.closeQuietly(fos); } } }
From source file:com.antbrains.crf.hadoop.InstanceGenerator.java
public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs(); if (otherArgs.length != 4) { System.err.println("InstanceGenerator <in> <out> <featuredict> <template>"); System.exit(-1);//from w w w . j a v a 2 s .com } Template template = new Template(otherArgs[3], "UTF8"); conf.set("template", object2String(template)); // conf.set("tc", object2String(tc)); DistributedCache.addCacheFile(new URI(otherArgs[2]), conf); conf.set("dict", otherArgs[2]); conf.set("mapred.reduce.tasks", "0"); Job job = new Job(conf, InstanceGenerator.class.getSimpleName()); job.setJarByClass(InstanceGenerator.class); job.setMapperClass(CounterMapper.class); job.setOutputKeyClass(IntWritable.class); job.setOutputValueClass(Text.class); FileInputFormat.addInputPath(job, new Path(otherArgs[0])); FileOutputFormat.setOutputPath(job, new Path(otherArgs[1])); System.exit(job.waitForCompletion(true) ? 0 : 1); }