List of usage examples for java.io ByteArrayInputStream ByteArrayInputStream
public ByteArrayInputStream(byte buf[])
From source file:S3ClientSideEncryptionAsymmetricMasterKey.java
public static void main(String[] args) throws Exception { // 1. Load keys from files byte[] bytes = FileUtils.readFileToByteArray(new File(keyDir + "/private.key")); KeyFactory kf = KeyFactory.getInstance("RSA"); PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(bytes); PrivateKey pk = kf.generatePrivate(ks); bytes = FileUtils.readFileToByteArray(new File(keyDir + "/public.key")); PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(bytes)); KeyPair loadedKeyPair = new KeyPair(publicKey, pk); // 2. Construct an instance of AmazonS3EncryptionClient. EncryptionMaterials encryptionMaterials = new EncryptionMaterials(loadedKeyPair); AWSCredentials credentials = new BasicAWSCredentials("Q3AM3UQ867SPQQA43P2F", "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG"); AmazonS3EncryptionClient encryptionClient = new AmazonS3EncryptionClient(credentials, new StaticEncryptionMaterialsProvider(encryptionMaterials)); Region usEast1 = Region.getRegion(Regions.US_EAST_1); encryptionClient.setRegion(usEast1); encryptionClient.setEndpoint("https://play.minio.io:9000"); final S3ClientOptions clientOptions = S3ClientOptions.builder().setPathStyleAccess(true).build(); encryptionClient.setS3ClientOptions(clientOptions); // Create the bucket encryptionClient.createBucket(bucketName); // 3. Upload the object. byte[] plaintext = "Hello World, S3 Client-side Encryption Using Asymmetric Master Key!".getBytes(); System.out.println("plaintext's length: " + plaintext.length); encryptionClient.putObject(new PutObjectRequest(bucketName, objectKey, new ByteArrayInputStream(plaintext), new ObjectMetadata())); // 4. Download the object. S3Object downloadedObject = encryptionClient.getObject(bucketName, objectKey); byte[] decrypted = IOUtils.toByteArray(downloadedObject.getObjectContent()); Assert.assertTrue(Arrays.equals(plaintext, decrypted)); System.out.println("decrypted length: " + decrypted.length); //deleteBucketAndAllContents(encryptionClient); }
From source file:de.tudarmstadt.ukp.experiments.dip.wp1.documents.Step6HITPreparator.java
public static void main(String[] args) throws Exception { // input dir - list of xml query containers // step5-linguistic-annotation/ System.err.println("Starting step 6 HIT Preparation"); File inputDir = new File(args[0]); // output dir File outputDir = new File(args[1]); if (outputDir.exists()) { outputDir.delete();//from w ww .jav a 2s .c o m } outputDir.mkdir(); List<String> queries = new ArrayList<>(); // iterate over query containers int countClueWeb = 0; int countSentence = 0; for (File f : FileUtils.listFiles(inputDir, new String[] { "xml" }, false)) { QueryResultContainer queryResultContainer = QueryResultContainer .fromXML(FileUtils.readFileToString(f, "utf-8")); if (queries.contains(f.getName()) || queries.size() == 0) { // groups contain only non-empty documents Map<Integer, List<QueryResultContainer.SingleRankedResult>> groups = new HashMap<>(); // split to groups according to number of sentences for (QueryResultContainer.SingleRankedResult rankedResult : queryResultContainer.rankedResults) { if (rankedResult.originalXmi != null) { byte[] bytes = new BASE64Decoder() .decodeBuffer(new ByteArrayInputStream(rankedResult.originalXmi.getBytes())); JCas jCas = JCasFactory.createJCas(); XmiCasDeserializer.deserialize(new ByteArrayInputStream(bytes), jCas.getCas()); Collection<Sentence> sentences = JCasUtil.select(jCas, Sentence.class); int groupId = sentences.size() / 40; if (rankedResult.originalXmi == null) { System.err.println("Empty document: " + rankedResult.clueWebID); } else { if (!groups.containsKey(groupId)) { groups.put(groupId, new ArrayList<>()); } } //handle it groups.get(groupId).add(rankedResult); countClueWeb++; } } for (Map.Entry<Integer, List<QueryResultContainer.SingleRankedResult>> entry : groups.entrySet()) { Integer groupId = entry.getKey(); List<QueryResultContainer.SingleRankedResult> rankedResults = entry.getValue(); // make sure the results are sorted // DEBUG // for (QueryResultContainer.SingleRankedResult r : rankedResults) { // System.out.print(r.rank + "\t"); // } Collections.sort(rankedResults, (o1, o2) -> o1.rank.compareTo(o2.rank)); // iterate over results for one query and group for (int i = 0; i < rankedResults.size() && i < TOP_RESULTS_PER_GROUP; i++) { QueryResultContainer.SingleRankedResult rankedResult = rankedResults.get(i); QueryResultContainer.SingleRankedResult r = rankedResults.get(i); int rank = r.rank; MustacheFactory mf = new DefaultMustacheFactory(); Mustache mustache = mf.compile("template/template.html"); String queryId = queryResultContainer.qID; String query = queryResultContainer.query; // make the first letter uppercase query = query.substring(0, 1).toUpperCase() + query.substring(1); List<String> relevantInformationExamples = queryResultContainer.relevantInformationExamples; List<String> irrelevantInformationExamples = queryResultContainer.irrelevantInformationExamples; byte[] bytes = new BASE64Decoder() .decodeBuffer(new ByteArrayInputStream(rankedResult.originalXmi.getBytes())); JCas jCas = JCasFactory.createJCas(); XmiCasDeserializer.deserialize(new ByteArrayInputStream(bytes), jCas.getCas()); List<generators.Sentence> sentences = new ArrayList<>(); List<Integer> paragraphs = new ArrayList<>(); paragraphs.add(0); for (WebParagraph webParagraph : JCasUtil.select(jCas, WebParagraph.class)) { for (Sentence s : JCasUtil.selectCovered(Sentence.class, webParagraph)) { String sentenceBegin = String.valueOf(s.getBegin()); generators.Sentence sentence = new generators.Sentence(s.getCoveredText(), sentenceBegin); sentences.add(sentence); countSentence++; } int SentenceID = paragraphs.get(paragraphs.size() - 1); if (sentences.size() > 120) while (SentenceID < sentences.size()) { if (!paragraphs.contains(SentenceID)) paragraphs.add(SentenceID); SentenceID = SentenceID + 120; } paragraphs.add(sentences.size()); } System.err.println("Output dir: " + outputDir); int startID = 0; int endID; for (int j = 0; j < paragraphs.size(); j++) { endID = paragraphs.get(j); int sentLength = endID - startID; if (sentLength > 120 || j == paragraphs.size() - 1) { if (sentLength > 120) { endID = paragraphs.get(j - 1); j--; } sentLength = endID - startID; if (sentLength <= 40) groupId = 40; else if (sentLength <= 80 && sentLength > 40) groupId = 80; else if (sentLength > 80) groupId = 120; File folder = new File(outputDir + "/" + groupId); if (!folder.exists()) { System.err.println("creating directory: " + outputDir + "/" + groupId); boolean result = false; try { folder.mkdir(); result = true; } catch (SecurityException se) { //handle it } if (result) { System.out.println("DIR created"); } } String newHtmlFile = folder.getAbsolutePath() + "/" + f.getName() + "_" + rankedResult.clueWebID + "_" + sentLength + ".html"; System.err.println("Printing a file: " + newHtmlFile); File newHTML = new File(newHtmlFile); int t = 0; while (newHTML.exists()) { newHTML = new File(folder.getAbsolutePath() + "/" + f.getName() + "_" + rankedResult.clueWebID + "_" + sentLength + "." + t + ".html"); t++; } mustache.execute(new PrintWriter(new FileWriter(newHTML)), new generators(query, relevantInformationExamples, irrelevantInformationExamples, sentences.subList(startID, endID), queryId, rank)) .flush(); startID = endID; } } } } } } System.out.println("Printed " + countClueWeb + " documents with " + countSentence + " sentences"); }
From source file:com.sourcecode.youku.ElementalHttpPost.java
public static void main(String[] args) throws Exception { HttpParams params = new SyncBasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "UTF-8"); HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1"); HttpProtocolParams.setUseExpectContinue(params, true); HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { // Required protocol interceptors new RequestContent(), new RequestTargetHost(), // Recommended protocol interceptors new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() }); HttpRequestExecutor httpexecutor = new HttpRequestExecutor(); HttpContext context = new BasicHttpContext(null); HttpHost host = new HttpHost("localhost", 8080); DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy(); context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host); try {/*from w ww . j a v a 2 s. com*/ HttpEntity[] requestBodies = { new StringEntity("This is the first test request", "UTF-8"), new ByteArrayEntity("This is the second test request".getBytes("UTF-8")), new InputStreamEntity(new ByteArrayInputStream( "This is the third test request (will be chunked)".getBytes("UTF-8")), -1) }; for (int i = 0; i < requestBodies.length; i++) { if (!conn.isOpen()) { Socket socket = new Socket(host.getHostName(), host.getPort()); conn.bind(socket, params); } BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/servlets-examples/servlet/RequestInfoExample"); request.setEntity(requestBodies[i]); System.out.println(">> Request URI: " + request.getRequestLine().getUri()); request.setParams(params); httpexecutor.preProcess(request, httpproc, context); HttpResponse response = httpexecutor.execute(request, conn, context); response.setParams(params); httpexecutor.postProcess(response, httpproc, context); System.out.println("<< Response: " + response.getStatusLine()); System.out.println(EntityUtils.toString(response.getEntity())); System.out.println("=============="); if (!connStrategy.keepAlive(response, context)) { conn.close(); } else { System.out.println("Connection kept alive..."); } } } finally { conn.close(); } }
From source file:S3ClientSideEncryptionWithSymmetricMasterKey.java
public static void main(String[] args) throws Exception { SecretKey mySymmetricKey = loadSymmetricAESKey(masterKeyDir, "AES"); EncryptionMaterials encryptionMaterials = new EncryptionMaterials(mySymmetricKey); AWSCredentials credentials = new BasicAWSCredentials("Q3AM3UQ867SPQQA43P2F", "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG"); AmazonS3EncryptionClient encryptionClient = new AmazonS3EncryptionClient(credentials, new StaticEncryptionMaterialsProvider(encryptionMaterials)); Region usEast1 = Region.getRegion(Regions.US_EAST_1); encryptionClient.setRegion(usEast1); encryptionClient.setEndpoint("https://play.minio.io:9000"); final S3ClientOptions clientOptions = S3ClientOptions.builder().setPathStyleAccess(true).build(); encryptionClient.setS3ClientOptions(clientOptions); // Create the bucket encryptionClient.createBucket(bucketName); // Upload object using the encryption client. byte[] plaintext = "Hello World, S3 Client-side Encryption Using Asymmetric Master Key!".getBytes(); System.out.println("plaintext's length: " + plaintext.length); encryptionClient.putObject(new PutObjectRequest(bucketName, objectKey, new ByteArrayInputStream(plaintext), new ObjectMetadata())); // Download the object. S3Object downloadedObject = encryptionClient.getObject(bucketName, objectKey); byte[] decrypted = IOUtils.toByteArray(downloadedObject.getObjectContent()); // Verify same data. Assert.assertTrue(Arrays.equals(plaintext, decrypted)); //deleteBucketAndAllContents(encryptionClient); }
From source file:io.aos.protocol.http.httpcommon.ElementalHttpPost.java
public static void main(String... args) throws Exception { HttpParams params = new SyncBasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "UTF-8"); HttpProtocolParams.setUserAgent(params, "Test/1.1"); HttpProtocolParams.setUseExpectContinue(params, true); HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { // Required protocol interceptors new RequestContent(), new RequestTargetHost(), // Recommended protocol interceptors new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() }); HttpRequestExecutor httpexecutor = new HttpRequestExecutor(); HttpContext context = new BasicHttpContext(null); HttpHost host = new HttpHost("localhost", 8080); DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy(); context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host); try {//from www .ja v a 2 s . c om HttpEntity[] requestBodies = { new StringEntity("This is the first test request", "UTF-8"), new ByteArrayEntity("This is the second test request".getBytes("UTF-8")), new InputStreamEntity(new ByteArrayInputStream( "This is the third test request (will be chunked)".getBytes("UTF-8")), -1) }; for (int i = 0; i < requestBodies.length; i++) { if (!conn.isOpen()) { Socket socket = new Socket(host.getHostName(), host.getPort()); conn.bind(socket, params); } BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/servlets-examples/servlet/RequestInfoExample"); request.setEntity(requestBodies[i]); System.out.println(">> Request URI: " + request.getRequestLine().getUri()); request.setParams(params); httpexecutor.preProcess(request, httpproc, context); HttpResponse response = httpexecutor.execute(request, conn, context); response.setParams(params); httpexecutor.postProcess(response, httpproc, context); System.out.println("<< Response: " + response.getStatusLine()); System.out.println(EntityUtils.toString(response.getEntity())); System.out.println("=============="); if (!connStrategy.keepAlive(response, context)) { conn.close(); } else { System.out.println("Connection kept alive..."); } } } finally { conn.close(); } }
From source file:com.ignorelist.kassandra.steam.scraper.TaggerCli.java
/** * @param args the command line arguments * @throws java.io.IOException//from w ww . j a va2 s.co m * @throws org.antlr.runtime.RecognitionException * @throws org.apache.commons.cli.ParseException */ public static void main(String[] args) throws IOException, RecognitionException, ParseException { Options options = buildOptions(); CommandLineParser parser = new DefaultParser(); CommandLine commandLine; try { commandLine = parser.parse(options, args); } catch (ParseException pe) { System.out.println(pe.getMessage()); System.out.println(); printHelp(options); System.exit(0); return; } if (commandLine.hasOption("h")) { printHelp(options); System.exit(0); } final PathResolver pathResolver = new PathResolver(); Configuration configuration; Path configurationFile = pathResolver.findConfiguration(); if (Files.isRegularFile(configurationFile)) { configuration = Configuration.fromPropertiesFile(configurationFile); } else { configuration = new Configuration(); } configuration = toConfiguration(configuration, commandLine); //configuration.toProperties().store(System.err, null); if (!Files.isRegularFile(configurationFile)) { configuration.writeProperties(configurationFile); System.err.println( "no configuration file present, write based on CLI options: " + configurationFile.toString()); configuration.toProperties().store(System.err, null); } Set<Path> sharedConfigPaths = configuration.getSharedConfigPaths(); if (sharedConfigPaths.size() > 1 && !commandLine.hasOption("w")) { System.err.println("multiple sharedconfig.vdf available:\n" + Joiner.on("\n").join(sharedConfigPaths) + "\n, can not write to stdout. Need to specify -w or -f with a single sharedconfig.vdf"); System.exit(1); } Tagger.Options taggerOptions = Tagger.Options.fromConfiguration(configuration); final String[] removeTagsValues = commandLine.getOptionValues("remove"); if (null != removeTagsValues) { taggerOptions.setRemoveTags(Sets.newHashSet(removeTagsValues)); } Set<TagType> tagTypes = configuration.getTagTypes(); if (null == tagTypes) { System.err.println("no tag types!"); System.exit(1); } final boolean printTags = commandLine.hasOption("p"); final HtmlTagLoader htmlTagLoader = new HtmlTagLoader(pathResolver.findCachePath("html"), null == configuration.getCacheExpiryDays() ? 7 : configuration.getCacheExpiryDays()); final BatchTagLoader tagLoader = new BatchTagLoader(htmlTagLoader, configuration.getDownloadThreads()); if (true || commandLine.hasOption("v")) { tagLoader.registerEventListener(new CliEventLoggerLoaded()); } Tagger tagger = new Tagger(tagLoader); if (printTags) { Set<String> availableTags = tagger.getAvailableTags(sharedConfigPaths, taggerOptions); Joiner.on("\n").appendTo(System.out, availableTags); } else { for (Path path : sharedConfigPaths) { VdfNode tagged = tagger.tag(path, taggerOptions); if (commandLine.hasOption("w")) { Path backup = path.getParent() .resolve(path.getFileName().toString() + ".bak" + new Date().getTime()); Files.copy(path, backup, StandardCopyOption.REPLACE_EXISTING); System.err.println("backup up " + path + " to " + backup); Files.copy(new ByteArrayInputStream(tagged.toPrettyString().getBytes(StandardCharsets.UTF_8)), path, StandardCopyOption.REPLACE_EXISTING); try { Files.setPosixFilePermissions(path, SHARED_CONFIG_POSIX_PERMS); } catch (Exception e) { System.err.println(e); } System.err.println("wrote " + path); } else { System.out.println(tagged.toPrettyString()); System.err.println("pipe to file and copy to: " + path.toString()); } } } }
From source file:net.padaf.xmpbox.parser.XMLPropertiesDescriptionManager.java
/** * Sample of using to write/read information * //w ww. j a va 2 s .c o m * @param args * Not used * @throws BuildPDFAExtensionSchemaDescriptionException * When errors during building/reading xml file */ public static void main(String[] args) throws BuildPDFAExtensionSchemaDescriptionException { XMLPropertiesDescriptionManager ptMaker = new XMLPropertiesDescriptionManager(); // add Descriptions for (int i = 0; i < 3; i++) { ptMaker.addPropertyDescription("name" + i, "description" + i); } // Display XML conversion System.out.println("Display XML Result:"); ptMaker.toXML(System.out); // Sample to show how to build object from XML file ByteArrayOutputStream bos = new ByteArrayOutputStream(); ptMaker.toXML(bos); IOUtils.closeQuietly(bos); // emulate a new reading InputStream is = new ByteArrayInputStream(bos.toByteArray()); ptMaker = new XMLPropertiesDescriptionManager(); ptMaker.loadListFromXML(is); List<PropertyDescription> result = ptMaker.getPropertiesDescriptionList(); System.out.println(); System.out.println(); System.out.println("Result of XML Loading :"); for (PropertyDescription propertyDescription : result) { System.out.println(propertyDescription.getPropertyName() + " :" + propertyDescription.getDescription()); } }
From source file:Filter3dTest.java
public static void main(String[] args) { // load a sound SimpleSoundPlayer sound = new SimpleSoundPlayer("../sounds/voice.wav"); // create the stream to play InputStream stream = new ByteArrayInputStream(sound.getSamples()); // play the sound sound.play(stream);/* w ww .ja v a 2 s.c o m*/ // exit System.exit(0); }
From source file:eu.sendregning.oxalis.Main.java
public static void main(String[] args) throws Exception { OptionParser optionParser = getOptionParser(); if (args.length == 0) { System.out.println(""); optionParser.printHelpOn(System.out); System.out.println(""); return;/*from w w w . j a v a 2s . co m*/ } OptionSet optionSet; try { optionSet = optionParser.parse(args); } catch (Exception e) { printErrorMessage(e.getMessage()); return; } File xmlInvoice = xmlDocument.value(optionSet); if (!xmlInvoice.exists()) { printErrorMessage("XML document " + xmlInvoice + " does not exist"); return; } String recipientId = recipient.value(optionSet); String senderId = sender.value(optionSet); try { System.out.println(""); System.out.println(""); // bootstraps the Oxalis outbound module OxalisOutboundModule oxalisOutboundModule = new OxalisOutboundModule(); // creates a transmission request builder and enable tracing TransmissionRequestBuilder requestBuilder = oxalisOutboundModule.getTransmissionRequestBuilder(); requestBuilder.trace(trace.value(optionSet)); System.out.println("Trace mode of RequestBuilder: " + requestBuilder.isTraceEnabled()); // add receiver participant if (recipientId != null) { requestBuilder.receiver(new ParticipantId(recipientId)); } // add sender participant if (senderId != null) { requestBuilder.sender((new ParticipantId(senderId))); } if (docType != null && docType.value(optionSet) != null) { requestBuilder.documentType(PeppolDocumentTypeId.valueOf(docType.value(optionSet))); } if (profileType != null && profileType.value(optionSet) != null) { requestBuilder.processType(PeppolProcessTypeId.valueOf(profileType.value(optionSet))); } // Supplies the payload requestBuilder.payLoad(new FileInputStream(xmlInvoice)); // Overrides the destination URL if so requested if (optionSet.has(destinationUrl)) { String destinationString = destinationUrl.value(optionSet); URL destination; try { destination = new URL(destinationString); } catch (MalformedURLException e) { printErrorMessage("Invalid destination URL " + destinationString); return; } // Fetches the transmission method, which was overridden on the command line BusDoxProtocol busDoxProtocol = BusDoxProtocol.instanceFrom(transmissionMethod.value(optionSet)); if (busDoxProtocol == BusDoxProtocol.AS2) { String accessPointSystemIdentifier = destinationSystemId.value(optionSet); if (accessPointSystemIdentifier == null) { throw new IllegalStateException("Must specify AS2 system identifier if using AS2 protocol"); } requestBuilder.overrideAs2Endpoint(destination, accessPointSystemIdentifier); } else { throw new IllegalStateException("Unknown busDoxProtocol : " + busDoxProtocol); } } // Specifying the details completed, creates the transmission request TransmissionRequest transmissionRequest = requestBuilder.build(); // Fetches a transmitter ... Transmitter transmitter = oxalisOutboundModule.getTransmitter(); // ... and performs the transmission TransmissionResponse transmissionResponse = transmitter.transmit(transmissionRequest); // Write the transmission id and where the message was delivered System.out.printf("Message using messageId %s sent to %s using %s was assigned transmissionId %s\n", transmissionResponse.getStandardBusinessHeader().getMessageId().stringValue(), transmissionResponse.getURL().toExternalForm(), transmissionResponse.getProtocol().toString(), transmissionResponse.getTransmissionId()); String evidenceFileName = transmissionResponse.getTransmissionId().toString() + "-evidence.dat"; IOUtils.copy(new ByteArrayInputStream(transmissionResponse.getEvidenceBytes()), new FileOutputStream(evidenceFileName)); System.out.printf("Wrote transmission receipt to " + evidenceFileName); } catch (Exception e) { System.out.println(""); System.out.println("Message failed : " + e.getMessage()); //e.printStackTrace(); System.out.println(""); } }
From source file:com.artistech.tuio.mouse.ZeroMqMouse.java
/** * Main entry point for ZeroMQ integration. * * @param args/* w w w .jav a 2 s. c o m*/ * @throws AWTException * @throws java.io.IOException */ public static void main(String[] args) throws AWTException, java.io.IOException { //read off the TUIO port from the command line String zeromq_port; Options options = new Options(); options.addOption("z", "zeromq-port", true, "ZeroMQ Server:Port to subscribe to. (-z localhost:5565)"); options.addOption("h", "help", false, "Show this message."); HelpFormatter formatter = new HelpFormatter(); try { CommandLineParser parser = new org.apache.commons.cli.BasicParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("help")) { formatter.printHelp("tuio-mouse-driver", options); return; } else { if (cmd.hasOption("z") || cmd.hasOption("zeromq-port")) { zeromq_port = cmd.getOptionValue("z"); } else { System.err.println("The zeromq-port value must be specified."); formatter.printHelp("tuio-mouse-driver", options); return; } } } catch (ParseException ex) { System.err.println("Error Processing Command Options:"); formatter.printHelp("tuio-mouse-driver", options); return; } //load conversion services ServiceLoader<ProtoConverter> services = ServiceLoader.load(ProtoConverter.class); //create zeromq context ZMQ.Context context = ZMQ.context(1); // Connect our subscriber socket ZMQ.Socket subscriber = context.socket(ZMQ.SUB); subscriber.setIdentity(ZeroMqMouse.class.getName().getBytes()); //this could change I guess so we can get different data subscrptions. subscriber.subscribe("TuioCursor".getBytes()); // subscriber.subscribe("TuioTime".getBytes()); subscriber.connect("tcp://" + zeromq_port); System.out.println("Subscribed to " + zeromq_port + " for ZeroMQ messages."); // Get updates, expect random Ctrl-C death String msg = ""; MouseDriver md = new MouseDriver(); while (!msg.equalsIgnoreCase("END")) { boolean success = false; byte[] recv = subscriber.recv(); com.google.protobuf.GeneratedMessage message = null; TuioPoint pt = null; String type = recv.length > 0 ? new String(recv) : ""; recv = subscriber.recv(); switch (type) { case "TuioCursor.PROTOBUF": try { //it is a cursor? message = com.artistech.protobuf.TuioProtos.Cursor.parseFrom(recv); success = true; } catch (Exception ex) { } break; case "TuioTime.PROTOBUF": // try { // //it is a cursor? // message = com.artistech.protobuf.TuioProtos.Time.parseFrom(recv); // success = true; // } catch (Exception ex) { // } break; case "TuioObject.PROTOBUF": try { //it is a cursor? message = com.artistech.protobuf.TuioProtos.Object.parseFrom(recv); success = true; } catch (Exception ex) { } break; case "TuioBlob.PROTOBUF": try { //it is a cursor? message = com.artistech.protobuf.TuioProtos.Blob.parseFrom(recv); success = true; } catch (Exception ex) { } break; case "TuioCursor.JSON": try { //it is a cursor? pt = mapper.readValue(recv, TUIO.TuioCursor.class); success = true; } catch (Exception ex) { } break; case "TuioTime.JSON": // try { // //it is a cursor? // pt = mapper.readValue(recv, TUIO.TuioTime.class); // success = true; // } catch (Exception ex) { // } break; case "TuioObject.JSON": try { //it is a cursor? pt = mapper.readValue(recv, TUIO.TuioObject.class); success = true; } catch (Exception ex) { } break; case "TuioBlob.JSON": try { //it is a cursor? pt = mapper.readValue(recv, TUIO.TuioBlob.class); success = true; } catch (Exception ex) { } break; case "TuioTime.OBJECT": break; case "TuioCursor.OBJECT": case "TuioObject.OBJECT": case "TuioBlob.OBJECT": try { //Try reading the data as a serialized Java object: try (ByteArrayInputStream bis = new ByteArrayInputStream(recv)) { //Try reading the data as a serialized Java object: ObjectInput in = new ObjectInputStream(bis); Object o = in.readObject(); //if it is of type Point (Cursor, Object, Blob), process: if (TuioPoint.class.isAssignableFrom(o.getClass())) { pt = (TuioPoint) o; process(pt, md); } success = true; } } catch (java.io.IOException | ClassNotFoundException ex) { } finally { } break; default: success = false; break; } if (message != null && success) { //ok, so we have a message that is not null, so it was protobuf: Object o = null; //look for a converter that will suppor this objec type and convert: for (ProtoConverter converter : services) { if (converter.supportsConversion(message)) { o = converter.convertFromProtobuf(message); break; } } //if the type is of type Point (Cursor, Blob, Object), process: if (o != null && TuioPoint.class.isAssignableFrom(o.getClass())) { pt = (TuioPoint) o; } } if (pt != null) { process(pt, md); } } }