List of usage examples for com.google.common.collect Lists newArrayList
@GwtCompatible(serializable = true) public static <E> ArrayList<E> newArrayList(Iterator<? extends E> elements)
From source file:com.siblinks.ws.util.MyUploads.java
/** * Authorize the user, call the youtube.channels.list method to retrieve the * playlist ID for the list of videos uploaded to the user's channel, and * then call the youtube.playlistItems.list method to retrieve the list of * videos in that playlist./*from w ww .j a v a 2s .c o m*/ * * @param args * command line args (not used). */ public static void main(String[] args) { // This OAuth 2.0 access scope allows for read-only access to the // authenticated user's account, but not other types of account access. // List<String> scopes = // Lists.newArrayList("https://www.googleapis.com/auth/youtube.readonly"); List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtubepartner"); // https://www.googleapis.com/auth/youtube try { // Authorize the request. Credential credential = Auth.authorize(scopes, "myuploads"); // This object is used to make YouTube Data API requests. youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential) .setApplicationName("youtube-cmdline-myuploads-sample").build(); // Call the API's channels.list method to retrieve the // resource that represents the authenticated user's channel. // In the API response, only include channel information needed for // this use case. The channel's contentDetails part contains // playlist IDs relevant to the channel, including the ID for the // list that contains videos uploaded to the channel. YouTube.Channels.List channelRequest = youtube.channels().list("contentDetails"); channelRequest.setMine(true); // channelRequest.setFields("items/contentDetails,nextPageToken,pageInfo"); ChannelListResponse channelResult = channelRequest.execute(); List<Channel> channelsList = channelResult.getItems(); if (channelsList != null) { // The user's default channel is the first item in the list. // Extract the playlist ID for the channel's videos from the // API response. String uploadPlaylistId = channelsList.get(0).getContentDetails().getRelatedPlaylists() .getUploads(); // Define a list to store items in the list of uploaded videos. List<PlaylistItem> playlistItemList = new ArrayList<PlaylistItem>(); // Retrieve the playlist of the channel's uploaded videos. /* * YouTube.PlaylistItems.List playlistItemRequest = * youtube.playlistItems * ().list("id,contentDetails,snippet,status"); */ YouTube.PlaylistItems.List playlistItemRequest = youtube.playlistItems() .list("id,contentDetails,snippet,status"); playlistItemRequest.setPlaylistId(uploadPlaylistId); playlistItemRequest.setFields("items(*),nextPageToken,pageInfo"); String nextToken = ""; // Call the API one or more times to retrieve all items in the // list. As long as the API response returns a nextPageToken, // there are still more items to retrieve. do { playlistItemRequest.setPageToken(nextToken); PlaylistItemListResponse playlistItemResult = playlistItemRequest.execute(); playlistItemList.addAll(playlistItemResult.getItems()); nextToken = playlistItemResult.getNextPageToken(); } while (nextToken != null); // Prints information about the results. prettyPrint(playlistItemList.size(), playlistItemList.iterator()); } } catch (GoogleJsonResponseException e) { e.printStackTrace(); System.err.println( "There was a service error: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage()); } catch (Throwable t) { t.printStackTrace(); } }
From source file:test.CommentHandling.java
/** * List, reply to comment threads; list, update, moderate, mark and delete * replies.//from ww w . j av a2 s .c om * * @param args command line args (not used). */ public static void main(String[] args) { // This OAuth 2.0 access scope allows for full read/write access to the // authenticated user's account and requires requests to use an SSL connection. List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube.force-ssl"); try { // Authorize the request. Credential credential = Auth.authorize(scopes, "commentthreads"); // This object is used to make YouTube Data API requests. youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential) .setApplicationName("youtube-cmdline-commentthreads-sample").build(); // Prompt the user for the ID of a video to comment on. // Retrieve the video ID that the user is commenting to. String videoId = getVideoId(); System.out.println("You chose " + videoId + " to subscribe."); // Call the YouTube Data API's commentThreads.list method to // retrieve video comment threads. CommentThreadListResponse videoCommentsListResponse = youtube.commentThreads().list("snippet") .setVideoId(videoId).setTextFormat("plainText").execute(); List<CommentThread> videoComments = videoCommentsListResponse.getItems(); ; if (videoComments.isEmpty()) { System.out.println("Can't get video comments."); } else { // Print information from the API response. System.out.println("\n================== Returned Video Comments ==================\n"); for (CommentThread videoComment : videoComments) { CommentSnippet snippet = videoComment.getSnippet().getTopLevelComment().getSnippet(); System.out.println(" - Author: " + snippet.getAuthorDisplayName()); System.out.println(" - Comment: " + snippet.getTextDisplay()); System.out.println(" - Date: " + snippet.getPublishedAt()); System.out.println(" - LikeCount: " + snippet.getLikeCount()); System.out.println("\n-------------------------------------------------------------\n"); } } } catch (GoogleJsonResponseException e) { System.err.println("GoogleJsonResponseException code: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage()); e.printStackTrace(); } catch (IOException e) { System.err.println("IOException: " + e.getMessage()); e.printStackTrace(); } catch (Throwable t) { System.err.println("Throwable: " + t.getMessage()); t.printStackTrace(); } }
From source file:org.opendaylight.protocol.pcep.pcc.mock.Main.java
public static void main(final String[] args) throws InterruptedException, ExecutionException, UnknownHostException { InetSocketAddress localAddress = new InetSocketAddress(LOCALHOST, DEFAULT_LOCAL_PORT); List<InetSocketAddress> remoteAddress = Lists .newArrayList(new InetSocketAddress(LOCALHOST, DEFAULT_REMOTE_PORT)); int pccCount = 1; int lsps = 1; boolean pcError = false; final LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); short ka = DEFAULT_KEEP_ALIVE; short dt = DEFAULT_DEAD_TIMER; String password = null;/*from w w w . j a v a 2 s .c om*/ long reconnectTime = -1; int redelegationTimeout = 0; int stateTimeout = -1; getRootLogger(lc).setLevel(ch.qos.logback.classic.Level.INFO); int argIdx = 0; while (argIdx < args.length) { if (args[argIdx].equals("--local-address")) { localAddress = InetSocketAddressUtil.getInetSocketAddress(args[++argIdx], DEFAULT_LOCAL_PORT); } else if (args[argIdx].equals("--remote-address")) { remoteAddress = InetSocketAddressUtil.parseAddresses(args[++argIdx], DEFAULT_REMOTE_PORT); } else if (args[argIdx].equals("--pcc")) { pccCount = Integer.valueOf(args[++argIdx]); } else if (args[argIdx].equals("--lsp")) { lsps = Integer.valueOf(args[++argIdx]); } else if (args[argIdx].equals("--pcerr")) { pcError = true; } else if (args[argIdx].equals("--log-level")) { getRootLogger(lc).setLevel(Level.toLevel(args[++argIdx], ch.qos.logback.classic.Level.INFO)); } else if (args[argIdx].equals("--keepalive") || args[argIdx].equals("-ka")) { ka = Short.valueOf(args[++argIdx]); } else if (args[argIdx].equals("--deadtimer") || args[argIdx].equals("-d")) { dt = Short.valueOf(args[++argIdx]); } else if (args[argIdx].equals("--password")) { password = args[++argIdx]; } else if (args[argIdx].equals("--reconnect")) { reconnectTime = Integer.valueOf(args[++argIdx]).intValue(); } else if (args[argIdx].equals("--redelegation-timeout")) { redelegationTimeout = Integer.valueOf(args[++argIdx]); } else if (args[argIdx].equals("--state-timeout")) { stateTimeout = Integer.valueOf(args[++argIdx]); } else if (args[argIdx].equals("--state-sync-avoidance")) { //"--state-sync-avoidance 10, 5, 10 includeDbv = Boolean.TRUE; final Long dbVersionAfterReconnect = Long.valueOf(args[++argIdx]); disonnectAfterXSeconds = Integer.valueOf(args[++argIdx]); reconnectAfterXSeconds = Integer.valueOf(args[++argIdx]); syncOptDBVersion = BigInteger.valueOf(dbVersionAfterReconnect); } else if (args[argIdx].equals("--incremental-sync-procedure")) { //TODO Check that DBv > Lsp always ?? includeDbv = Boolean.TRUE; incrementalSync = Boolean.TRUE; //Version of database to be used after restart final Long initialDbVersionAfterReconnect = Long.valueOf(args[++argIdx]); disonnectAfterXSeconds = Integer.valueOf(args[++argIdx]); reconnectAfterXSeconds = Integer.valueOf(args[++argIdx]); syncOptDBVersion = BigInteger.valueOf(initialDbVersionAfterReconnect); } else if (args[argIdx].equals("--triggered-initial-sync")) { triggeredInitSync = Boolean.TRUE; } else if (args[argIdx].equals("--triggered-re-sync")) { triggeredResync = Boolean.TRUE; } else { LOG.warn("WARNING: Unrecognized argument: {}", args[argIdx]); } argIdx++; } if (incrementalSync) { Preconditions.checkArgument(syncOptDBVersion.intValue() > lsps, "Synchronization Database Version which will be used after " + "reconnectes requires to be higher than lsps"); } final Optional<BigInteger> dBVersion = Optional.fromNullable(syncOptDBVersion); final PCCsBuilder pccs = new PCCsBuilder(lsps, pcError, pccCount, localAddress, remoteAddress, ka, dt, password, reconnectTime, redelegationTimeout, stateTimeout, getCapabilities()); final TimerHandler timerHandler = new TimerHandler(pccs, dBVersion, disonnectAfterXSeconds, reconnectAfterXSeconds); pccs.createPCCs(BigInteger.valueOf(lsps), Optional.fromNullable(timerHandler)); if (!triggeredInitSync) { timerHandler.createDisconnectTask(); } }
From source file:com.youtube.indianmovies.data.UploadThumbnail.java
/** * Prompt the user to specify a video ID and the path for a thumbnail * image. Then call the API to set the image as the thumbnail for the video. * * @param args command line args (not used). *///from w w w . j ava2 s . co m public static void main(String[] args) { // This OAuth 2.0 access scope allows for full read/write access to the // authenticated user's account. List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube"); try { // Authorize the request. Credential credential = Auth.authorize(scopes, "uploadthumbnail"); // This object is used to make YouTube Data API requests. youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential) .setApplicationName("youtube-cmdline-uploadthumbnail-sample").build(); // Prompt the user to enter the video ID of the video being updated. String videoId = getVideoIdFromUser(); System.out.println("You chose " + videoId + " to upload a thumbnail."); // Prompt the user to specify the location of the thumbnail image. File imageFile = getImageFromUser(); System.out.println("You chose " + imageFile + " to upload."); // Create an object that contains the thumbnail image file's // contents. InputStreamContent mediaContent = new InputStreamContent(IMAGE_FILE_FORMAT, new BufferedInputStream(new FileInputStream(imageFile))); mediaContent.setLength(imageFile.length()); // Create an API request that specifies that the mediaContent // object is the thumbnail of the specified video. Set thumbnailSet = youtube.thumbnails().set(videoId, mediaContent); // Set the upload type and add an event listener. MediaHttpUploader uploader = thumbnailSet.getMediaHttpUploader(); // Indicate whether direct media upload is enabled. A value of // "True" indicates that direct media upload is enabled and that // the entire media content will be uploaded in a single request. // A value of "False," which is the default, indicates that the // request will use the resumable media upload protocol, which // supports the ability to resume an upload operation after a // network interruption or other transmission failure, saving // time and bandwidth in the event of network failures. uploader.setDirectUploadEnabled(false); // Set the upload state for the thumbnail image. MediaHttpUploaderProgressListener progressListener = new MediaHttpUploaderProgressListener() { @Override public void progressChanged(MediaHttpUploader uploader) throws IOException { switch (uploader.getUploadState()) { // This value is set before the initiation request is // sent. case INITIATION_STARTED: System.out.println("Initiation Started"); break; // This value is set after the initiation request // completes. case INITIATION_COMPLETE: System.out.println("Initiation Completed"); break; // This value is set after a media file chunk is // uploaded. case MEDIA_IN_PROGRESS: System.out.println("Upload in progress"); System.out.println("Upload percentage: " + uploader.getProgress()); break; // This value is set after the entire media file has // been successfully uploaded. case MEDIA_COMPLETE: System.out.println("Upload Completed!"); break; // This value indicates that the upload process has // not started yet. case NOT_STARTED: System.out.println("Upload Not Started!"); break; } } }; uploader.setProgressListener(progressListener); // Upload the image and set it as the specified video's thumbnail. ThumbnailSetResponse setResponse = thumbnailSet.execute(); // Print the URL for the updated video's thumbnail image. System.out.println("\n================== Uploaded Thumbnail ==================\n"); System.out.println(" - Url: " + setResponse.getItems().get(0).getDefault().getUrl()); } catch (GoogleJsonResponseException e) { System.err.println("GoogleJsonResponseException code: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage()); e.printStackTrace(); } catch (IOException e) { System.err.println("IOException: " + e.getMessage()); e.printStackTrace(); } }
From source file:org.jclouds.examples.rackspace.clouddns.CRUDReverseDNSRecords.java
/** * To get a username and API key see http://jclouds.apache.org/guides/rackspace/ * * The first argument (args[0]) must be your username * The second argument (args[1]) must be your API key *//*from w w w .j a va 2s . co m*/ public static void main(String[] args) throws IOException { CRUDReverseDNSRecords crudReverseDNSRecords = new CRUDReverseDNSRecords(args[0], args[1]); try { List<String> argsList = Lists.newArrayList(args); argsList.add("1"); // the number of Cloud Servers to start NodeMetadata node = CloudServersPublish.getPublishedCloudServers(argsList).iterator().next(); RecordDetail recordDetail = crudReverseDNSRecords.createReverseDNSRecords(node); crudReverseDNSRecords.listReverseDNSRecords(node); crudReverseDNSRecords.updateReverseDNSRecords(node, recordDetail); crudReverseDNSRecords.deleteAllReverseDNSRecords(node); } catch (Exception e) { e.printStackTrace(); } finally { crudReverseDNSRecords.close(); } }
From source file:com.ltu.tube.CommentThreads.java
/** * Create, list and update top-level channel and video comments. * * @param args command line args (not used). *//*from w ww . j av a2 s .c o m*/ public static void main(String[] args) { // This OAuth 2.0 access scope allows for full read/write access to the // authenticated user's account and requires requests to use an SSL connection. List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube.force-ssl"); try { // Authorize the request. Credential credential = Auth.authorize(scopes, "commentthreads"); // This object is used to make YouTube Data API requests. youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential) .setApplicationName("youtube-cmdline-commentthreads-sample").build(); // Prompt the user for the ID of a channel to comment on. // Retrieve the channel ID that the user is commenting to. String channelId = getChannelId(); System.out.println("You chose " + channelId + " to subscribe."); // Prompt the user for the ID of a video to comment on. // Retrieve the video ID that the user is commenting to. String videoId = getVideoId(); System.out.println("You chose " + videoId + " to subscribe."); // Prompt the user for the comment text. // Retrieve the text that the user is commenting. String text = getText(); System.out.println("You chose " + text + " to subscribe."); // Insert channel comment by omitting videoId. // Create a comment snippet with text. CommentSnippet commentSnippet = new CommentSnippet(); commentSnippet.setTextOriginal(text); // Create a top-level comment with snippet. Comment topLevelComment = new Comment(); topLevelComment.setSnippet(commentSnippet); // Create a comment thread snippet with channelId and top-level // comment. CommentThreadSnippet commentThreadSnippet = new CommentThreadSnippet(); commentThreadSnippet.setChannelId(channelId); commentThreadSnippet.setTopLevelComment(topLevelComment); // Create a comment thread with snippet. CommentThread commentThread = new CommentThread(); commentThread.setSnippet(commentThreadSnippet); // Call the YouTube Data API's commentThreads.insert method to // create a comment. CommentThread channelCommentInsertResponse = youtube.commentThreads().insert("snippet", commentThread) .execute(); // Print information from the API response. System.out.println("\n================== Created Channel Comment ==================\n"); CommentSnippet snippet = channelCommentInsertResponse.getSnippet().getTopLevelComment().getSnippet(); System.out.println(" - Author: " + snippet.getAuthorDisplayName()); System.out.println(" - Comment: " + snippet.getTextDisplay()); System.out.println("\n-------------------------------------------------------------\n"); // Insert video comment commentThreadSnippet.setVideoId(videoId); // Call the YouTube Data API's commentThreads.insert method to // create a comment. CommentThread videoCommentInsertResponse = youtube.commentThreads().insert("snippet", commentThread) .execute(); // Print information from the API response. System.out.println("\n================== Created Video Comment ==================\n"); snippet = videoCommentInsertResponse.getSnippet().getTopLevelComment().getSnippet(); System.out.println(" - Author: " + snippet.getAuthorDisplayName()); System.out.println(" - Comment: " + snippet.getTextDisplay()); System.out.println("\n-------------------------------------------------------------\n"); // Call the YouTube Data API's commentThreads.list method to // retrieve video comment threads. CommentThreadListResponse videoCommentsListResponse = youtube.commentThreads().list("snippet") .setVideoId(videoId).setTextFormat("plainText").execute(); List<CommentThread> videoComments = videoCommentsListResponse.getItems(); if (videoComments.isEmpty()) { System.out.println("Can't get video comments."); } else { // Print information from the API response. System.out.println("\n================== Returned Video Comments ==================\n"); for (CommentThread videoComment : videoComments) { snippet = videoComment.getSnippet().getTopLevelComment().getSnippet(); System.out.println(" - Author: " + snippet.getAuthorDisplayName()); System.out.println(" - Comment: " + snippet.getTextDisplay()); System.out.println("\n-------------------------------------------------------------\n"); } CommentThread firstComment = videoComments.get(0); firstComment.getSnippet().getTopLevelComment().getSnippet().setTextOriginal("updated"); CommentThread videoCommentUpdateResponse = youtube.commentThreads().update("snippet", firstComment) .execute(); // Print information from the API response. System.out.println("\n================== Updated Video Comment ==================\n"); snippet = videoCommentUpdateResponse.getSnippet().getTopLevelComment().getSnippet(); System.out.println(" - Author: " + snippet.getAuthorDisplayName()); System.out.println(" - Comment: " + snippet.getTextDisplay()); System.out.println("\n-------------------------------------------------------------\n"); } // Call the YouTube Data API's commentThreads.list method to // retrieve channel comment threads. CommentThreadListResponse channelCommentsListResponse = youtube.commentThreads().list("snippet") .setChannelId(channelId).setTextFormat("plainText").execute(); List<CommentThread> channelComments = channelCommentsListResponse.getItems(); if (channelComments.isEmpty()) { System.out.println("Can't get channel comments."); } else { // Print information from the API response. System.out.println("\n================== Returned Channel Comments ==================\n"); for (CommentThread channelComment : channelComments) { snippet = channelComment.getSnippet().getTopLevelComment().getSnippet(); System.out.println(" - Author: " + snippet.getAuthorDisplayName()); System.out.println(" - Comment: " + snippet.getTextDisplay()); System.out.println("\n-------------------------------------------------------------\n"); } CommentThread firstComment = channelComments.get(0); firstComment.getSnippet().getTopLevelComment().getSnippet().setTextOriginal("updated"); CommentThread channelCommentUpdateResponse = youtube.commentThreads() .update("snippet", firstComment).execute(); // Print information from the API response. System.out.println("\n================== Updated Channel Comment ==================\n"); snippet = channelCommentUpdateResponse.getSnippet().getTopLevelComment().getSnippet(); System.out.println(" - Author: " + snippet.getAuthorDisplayName()); System.out.println(" - Comment: " + snippet.getTextDisplay()); System.out.println("\n-------------------------------------------------------------\n"); } } catch (GoogleJsonResponseException e) { System.err.println("GoogleJsonResponseException code: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage()); e.printStackTrace(); } catch (IOException e) { System.err.println("IOException: " + e.getMessage()); e.printStackTrace(); } catch (Throwable t) { System.err.println("Throwable: " + t.getMessage()); t.printStackTrace(); } }
From source file:cn.com.warlock.streaming.JavaSqlNetworkWordCount.java
public static void main(String[] args) { if (args.length < 2) { System.err.println("Usage: JavaNetworkWordCount <hostname> <port>"); System.exit(1);//from w w w . j a v a 2 s .co m } String hostname = args[0]; Integer port = Integer.valueOf(args[1]); SparkConf sparkConf = new SparkConf().setAppName("JavaSqlNetworkWordCount"); JavaStreamingContext ssc = new JavaStreamingContext(sparkConf, Durations.seconds(1)); // socket stream JavaReceiverInputDStream<String> lines = ssc.socketTextStream(hostname, port, StorageLevels.MEMORY_AND_DISK_SER); JavaDStream<String> words = lines.flatMap(new FlatMapFunction<String, String>() { @Override public Iterable<String> call(String x) { return Lists.newArrayList(SPACE.split(x)); } }); // Convert RDDs of the words DStream to DataFrame and run SQL query words.foreachRDD(new VoidFunction2<JavaRDD<String>, Time>() { @Override public void call(JavaRDD<String> rdd, Time time) throws Exception { // ?SQLContext? SQLContext sqlContext = JavaSQLContextSingleton.getInstance(rdd.context()); // Convert JavaRDD[String] to JavaRDD[bean class] to DataFrame JavaRDD<JavaRecord> rowRDD = rdd.map(new Function<String, JavaRecord>() { @Override public JavaRecord call(String word) { JavaRecord record = new JavaRecord(); record.setWord(word); return record; } }); DataFrame wordsDataFrame = sqlContext.createDataFrame(rowRDD, JavaRecord.class); // table wordsDataFrame.registerTempTable("words"); // SQLcount DataFrame wordCountsDataFrame = sqlContext .sql("select word, count(*) as total from words group by word"); System.out.println("========= " + time + "========="); wordCountsDataFrame.show(); } }); ssc.start(); ssc.awaitTermination(); }
From source file:com.google.api.services.samples.youtube.cmdline.live.GetLiveChatId.java
/** * Poll live chat messages and SuperChat details from a live broadcast. * * @param args videoId (optional). If the videoId is given, live chat messages will be retrieved * from the chat associated with this video. If the videoId is not specified, the signed in * user's current live broadcast will be used instead. *//*from w w w .ja v a 2s . c om*/ public static void main(String[] args) { // This OAuth 2.0 access scope allows for read-only access to the // authenticated user's account, but not other types of account access. List<String> scopes = Lists.newArrayList(YouTubeScopes.YOUTUBE_READONLY); try { // Authorize the request. Credential credential = Auth.authorize(scopes, "getlivechatid"); // This object is used to make YouTube Data API requests. youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential) .setApplicationName("youtube-cmdline-getlivechatid-sample").build(); // Get the liveChatId String liveChatId = args.length == 1 ? getLiveChatId(youtube, args[0]) : getLiveChatId(youtube); if (liveChatId != null) { System.out.println("Live chat id: " + liveChatId); } else { System.err.println("Unable to find a live chat id"); System.exit(1); } } catch (GoogleJsonResponseException e) { System.err.println("GoogleJsonResponseException code: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage()); e.printStackTrace(); } catch (IOException e) { System.err.println("IOException: " + e.getMessage()); e.printStackTrace(); } catch (Throwable t) { System.err.println("Throwable: " + t.getMessage()); t.printStackTrace(); } }
From source file:brooklyn.demo.StandaloneQpidBrokerExample.java
public static void main(String[] argv) { List<String> args = Lists.newArrayList(argv); String port = CommandLineUtil.getCommandLineOption(args, "--port", "8081+"); String location = CommandLineUtil.getCommandLineOption(args, "--location", DEFAULT_LOCATION); BrooklynLauncher launcher = BrooklynLauncher.newInstance().application(EntitySpec .create(StartableApplication.class, StandaloneQpidBrokerExample.class).displayName("Qpid app")) .webconsolePort(port).location(location).start(); Entities.dumpInfo(launcher.getApplications()); }
From source file:Assignment.java
public static void main(String[] args) { // Create the context with a 10 second batch size SparkConf sparkConf = new SparkConf().setAppName("Assignment"); JavaStreamingContext ssc = new JavaStreamingContext(sparkConf, new Duration(10000)); // Create a JavaReceiverInputDStream on target ip:port and count the // words in input stream of \n delimited text (eg. generated by 'nc') // Note that no duplication in storage level only for running locally. // Replication necessary in distributed scenario for fault tolerance. JavaReceiverInputDStream<String> lines = ssc.socketTextStream("localhost", Integer.parseInt("9999"), StorageLevels.MEMORY_AND_DISK_SER); JavaDStream<String> words = lines.flatMap(new FlatMapFunction<String, String>() { @Override/*w ww.j a v a 2s .c om*/ public Iterable<String> call(String x) { return Lists.newArrayList(SPACE.split(x)); } }); JavaPairDStream<String, Integer> wordCounts = words.filter(new Function<String, Boolean>() { public Boolean call(String s) { return s.toLowerCase().contains("#obama"); } }).mapToPair(new PairFunction<String, String, Integer>() { @Override public Tuple2<String, Integer> call(String s) { return new Tuple2<String, Integer>(s, 1); } }); // Reduce function adding two integers, defined separately for clarity Function2<Integer, Integer, Integer> reduceFunc = new Function2<Integer, Integer, Integer>() { @Override public Integer call(Integer i1, Integer i2) throws Exception { return i1 + i2; } }; // Reduce last 30 seconds of data, every 10 seconds JavaPairDStream<String, Integer> windowedWordCounts = wordCounts.reduceByKeyAndWindow(reduceFunc, new Duration(30000), new Duration(10000)); windowedWordCounts.print(); ssc.start(); ssc.awaitTermination(); }