· 6 years ago · Jan 18, 2020, 07:16 AM
1package tubeminer;
2
3import com.google.api.client.auth.oauth2.Credential;
4import com.google.api.client.googleapis.json.GoogleJsonResponseException;
5import com.google.api.client.http.HttpRequest;
6import com.google.api.client.http.HttpRequestInitializer;
7import com.google.api.client.util.DateTime;
8import com.google.api.services.samples.youtube.cmdline.Auth;
9import com.google.api.services.samples.youtube.cmdline.data.*;
10import com.google.api.services.youtube.YouTube;
11import com.google.api.services.youtube.model.Comment;
12import com.google.api.services.youtube.model.CommentListResponse;
13import com.google.api.services.youtube.model.CommentSnippet;
14import com.google.api.services.youtube.model.CommentThread;
15import com.google.api.services.youtube.model.CommentThreadListResponse;
16import com.google.api.services.youtube.model.ResourceId;
17import com.google.api.services.youtube.model.SearchListResponse;
18import com.google.api.services.youtube.model.SearchResult;
19import com.google.api.services.youtube.model.Thumbnail;
20import com.google.common.collect.Lists;
21
22import java.awt.BorderLayout;
23import java.awt.Color;
24import java.awt.Container;
25import java.awt.Dimension;
26import java.awt.FlowLayout;
27import java.awt.GridLayout;
28import java.awt.Image;
29import java.awt.Insets;
30import java.awt.Toolkit;
31import java.awt.event.ActionEvent;
32import java.awt.event.ActionListener;
33import java.awt.event.KeyEvent;
34import java.awt.event.WindowEvent;
35import java.awt.event.WindowListener;
36import java.beans.PropertyChangeEvent;
37import java.beans.PropertyChangeListener;
38import java.io.File;
39import java.io.IOException;
40import java.io.InputStream;
41import java.net.URL;
42import java.util.ArrayList;
43import java.util.Iterator;
44import java.util.List;
45import java.util.Map;
46import java.util.Map.Entry;
47import java.util.Properties;
48import java.util.Random;
49import java.util.Timer;
50
51import javax.swing.ImageIcon;
52import javax.swing.JButton;
53import javax.swing.JCheckBox;
54import javax.swing.JComponent;
55import javax.swing.JFrame;
56import javax.swing.JLabel;
57import javax.swing.JOptionPane;
58import javax.swing.JPanel;
59import javax.swing.JProgressBar;
60import javax.swing.JRadioButton;
61import javax.swing.JSlider;
62import javax.swing.JTabbedPane;
63import javax.swing.JTextArea;
64import javax.swing.JTextField;
65import javax.swing.SwingUtilities;
66import javax.swing.SwingWorker;
67import javax.swing.UIManager;
68import javax.swing.event.ChangeEvent;
69import javax.swing.event.ChangeListener;
70
71import org.codehaus.jackson.JsonGenerationException;
72import org.codehaus.jackson.JsonNode;
73import org.codehaus.jackson.map.JsonMappingException;
74import org.codehaus.jackson.map.ObjectMapper;
75import org.mortbay.thread.Timeout.Task;
76
77public class TubeMiner extends JPanel implements ActionListener,WindowListener,ChangeListener,
78PropertyChangeListener {
79
80 private static POIList poilist;
81
82 private static YouTube youtube;
83 private static YouTube.Search.List search;
84 private static SearchListResponse searchResponse;
85 private static List<SearchResult> searchResultList;
86 private static String queryTerm;
87 private static String apiKey;
88 private static final long NUMBER_OF_VIDEOS_RETURNED = 50;
89 private static Properties properties;
90 private static final String developerKeyPath = "/youtube.properties";
91
92 private static CommentThreadListResponse videoCommentsListResponse;
93 private static List<CommentThread> videoComments;
94 private static Credential credential;
95 private static final String SSL = "https://www.googleapis.com/auth/youtube.force-ssl";
96 private static boolean retrieveComments = false;
97
98 //Set up slider parameters.
99 static final int R_MIN = 0;
100 static final int R_MAX = 1000;
101 static final int R_INIT = 500; //initial frames per second
102 int frameNumber = 0;
103 int NUM_FRAMES = 14;
104 ImageIcon[] images = new ImageIcon[NUM_FRAMES];
105 int delay;
106 Timer timer;
107 boolean frozen = false;
108 private JProgressBar progressBar;
109 private JButton startButton;
110 private JButton reset;
111 private JTextArea taskOutput;
112 private Task task;
113 JCheckBox locationbox;
114 JCheckBox datebox;
115 private JTextField p2tf1;
116 private JTextField p2tf2;
117 private JTextField p2tf3;
118 private JTextField p2tf4;
119 private JTextField p2tf5;
120 private JSlider radiusSlider;
121 private String number_of_videos;
122 private String developerKeyPath1;
123 private String ssl;
124 private String location;
125 private String date;
126 private int radius;
127
128
129 class Task extends SwingWorker<Void, Void> {
130 /*
131 * Main task. Executed in background thread.
132 */
133 @Override
134 public Void doInBackground() {
135 Random random = new Random();
136 int progress = 0;
137 //Initialize progress property.
138 setProgress(0);
139 while (progress < 100) {
140 //Sleep for up to one second.
141 try {
142 Thread.sleep(random.nextInt(1000));
143 } catch (InterruptedException ignore) {}
144 //Make random progress.
145 progress += random.nextInt(10);
146 setProgress(Math.min(progress, 100));
147 }
148 return null;
149 }
150
151 /*
152 * Executed in event dispatching thread
153 */
154 @Override
155 public void done() {
156 Toolkit.getDefaultToolkit().beep();
157 startButton.setEnabled(true);
158 setCursor(null); //turn off the wait cursor
159 taskOutput.append("Done!\n");
160 }
161 }
162
163 public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
164
165
166 //Schedule a job for the event dispatch thread:
167 //creating and showing this application's GUI.
168 SwingUtilities.invokeLater(new Runnable() {
169 public void run() {
170 //Turn off metal's use of bold fonts
171 UIManager.put("swing.boldMetal", Boolean.FALSE);
172 createAndShowGUI();
173 }
174 });
175 //JFrame j = new JFrame("TubeMiner");
176 TubeMiner j = new TubeMiner();
177
178
179 j.setSize(300,350);
180 j.setVisible(true);
181
182 poilist = POIList.getPOIList();
183 Iterator it = poilist.iterator();
184 while (it.hasNext())
185 findVideos((POI) it.next());
186
187
188 }
189
190
191
192 public TubeMiner () {
193
194 super(new GridLayout(1, 1));
195
196 JTabbedPane tabbedPane = new JTabbedPane();
197
198 //1st pane
199 JPanel panel1 = new JPanel();
200 tabbedPane.addTab("POI Tab", null, panel1);
201 tabbedPane.setMnemonicAt(0, KeyEvent.VK_1);
202
203 //2nd pane
204 JPanel panel2 = new JPanel();
205 panel2.setLayout(null);
206 tabbedPane.addTab("Miner Tab", null, panel2);
207 tabbedPane.setMnemonicAt(1, KeyEvent.VK_2);
208
209 //object of eventhandler class
210 thehandler handler = new thehandler();
211
212
213 //2nd pane 1st Reset button
214 reset = new JButton("Reset");
215 reset.setBounds(200,430,100,50);
216 reset.addActionListener(handler);
217
218 //2nd pane 1st Find Videos button
219 startButton = new JButton("Find Videos");
220 startButton.setActionCommand("start");
221 startButton.addActionListener(handler);
222 startButton.setBounds(330,430,100,50);
223
224 //creates progress bar
225 progressBar = new JProgressBar(0, 100);
226 progressBar.setValue(0);
227 progressBar.setStringPainted(true);
228 progressBar.setBounds(30, 520, 430, 30);
229
230
231 taskOutput = new JTextArea(5, 20);
232 taskOutput.setMargin(new Insets(5,5,5,5));
233 taskOutput.setEditable(false);
234
235 //NUMBER_OF_VIDEOS_RETURNED label 1
236 JLabel p2l1 = new JLabel();
237 p2l1.setText("NUMBER_OF_VIDEOS_RETURNED");
238 p2l1.setBounds(30, 20, 230, 30);
239
240 //developerKeyPath label 2
241 JLabel p2l2 = new JLabel();
242 p2l2.setText("developerKeyPath");
243 p2l2.setBounds(135, 70, 230, 30);
244
245 //SSL label 3
246 JLabel p2l3 = new JLabel();
247 p2l3.setText("SSL");
248 p2l3.setBounds(210, 120, 230, 30);
249
250 //Location label 4
251 JLabel p2l4 = new JLabel();
252 p2l4.setText("Location");
253 p2l4.setBounds(190, 165, 230, 30);
254
255 //Radius label 5
256 JLabel p2l5 = new JLabel();
257 p2l5.setText("Radius (mi)");
258 p2l5.setBounds(175, 215, 230, 30);
259
260 //DateTime label 6
261 JLabel p2l6 = new JLabel();
262 p2l6.setText("DateTime");
263 p2l6.setBounds(185, 275, 230, 30);
264
265 //slider 0 label 6
266 JLabel p2l7 = new JLabel();
267 p2l7.setText("0");
268 p2l7.setBounds(253, 240, 30, 30);
269
270 //slider 1000 label 8
271 JLabel p2l8 = new JLabel();
272 p2l8.setText("1000");
273 p2l8.setBounds(460, 240, 100, 30);
274
275 //slider 500 label 9
276 JLabel p2l9 = new JLabel();
277 p2l9.setText("Filter by Location");
278 p2l9.setBounds(337, 350, 100, 30);
279
280 //checkbox location label 9
281 JLabel p2l10 = new JLabel();
282 p2l10.setText("Filter by publication date");
283 p2l10.setBounds(300, 380, 150, 30);
284
285 //checkbox date label 9
286 JLabel p2l11 = new JLabel();
287 p2l11.setText("500");
288 p2l11.setBounds(355, 240, 100, 30);
289
290 //2nd pane 1st textfield
291 p2tf1= new JTextField();
292 p2tf1.setText("50");
293 p2tf1.setBounds(250, 20, 230, 30);
294 p2tf1.addActionListener(handler);
295
296 //2nd pane 2nd textfield
297 p2tf2= new JTextField();
298 p2tf2.setText("/youtube.properties");
299 p2tf2.setBounds(250, 70, 230, 30);
300 p2tf2.addActionListener(handler);
301
302 //2nd pane 3rd textfield
303 p2tf3= new JTextField();
304 p2tf3.setText("https://www.googleapis.com/auth/youtube.force-ssl");
305 p2tf3.setBounds(250, 120, 230, 30);
306 p2tf3.addActionListener(handler);
307
308 //2nd pane 4th textfield
309 p2tf4= new JTextField();
310 p2tf4.setText("-33.932699, 150.995834");
311 p2tf4.setBounds(250, 170, 230, 30);
312 p2tf4.addActionListener(handler);
313
314 //2nd pane 5th textfield
315 p2tf5= new JTextField();
316 p2tf5.setText("12/05/2016");
317 p2tf5.setBounds(250, 275, 230, 30);
318 p2tf5.addActionListener(handler);
319
320 //Create the slider.
321 radiusSlider = new JSlider(JSlider.HORIZONTAL,R_MIN, R_MAX, R_INIT);
322 radiusSlider.addChangeListener(this);
323 radiusSlider.setMajorTickSpacing(100);
324 radiusSlider.setPaintTicks(true);
325 radiusSlider.setBounds(250, 220, 230, 30);
326
327 //Create the check boxes.
328 locationbox = new JCheckBox("Chin");
329 locationbox.setBounds(440, 350, 30, 30);
330 locationbox.setMnemonic(KeyEvent.VK_C);
331 locationbox.setSelected(true);
332
333 datebox = new JCheckBox("Glasses");
334 datebox.setBounds(440, 380, 30, 30);
335 datebox.setMnemonic(KeyEvent.VK_G);
336 datebox.setSelected(true);
337
338
339
340 panel2.add(p2l1);
341 panel2.add(p2l2);
342 panel2.add(p2l3);
343 panel2.add(p2l4);
344 panel2.add(p2l5);
345 panel2.add(p2l6);
346 panel2.add(p2l7);
347 panel2.add(p2l8);
348 panel2.add(p2l9);
349 panel2.add(p2l10);
350 panel2.add(p2l11);
351 panel2.add(reset);
352 panel2.add(startButton);
353 panel2.add(p2tf1);
354 panel2.add(p2tf2);
355 panel2.add(p2tf3);
356 panel2.add(p2tf4);
357 panel2.add(p2tf5);
358 panel2.add(radiusSlider);
359 panel2.add(progressBar);
360 panel2.add(locationbox);
361 panel2.add(datebox);
362
363 //3rd pane
364 JPanel panel3 = new JPanel();
365 panel3.setPreferredSize(new Dimension(500, 600));
366 tabbedPane.addTab("Results Tab", null, panel3, "This msg displayed when mouse hovers tab");
367 tabbedPane.setMnemonicAt(2, KeyEvent.VK_3);
368
369 //Add the tabbed pane to this panel.
370 add(tabbedPane);
371
372 //The following line enables to use scrolling tabs.
373 tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
374
375 }
376
377
378 protected JComponent makeTextPanel(String text) {
379 JPanel panel = new JPanel(false);
380 JLabel filler = new JLabel(text);
381 filler.setHorizontalAlignment(JLabel.CENTER);
382 panel.setLayout(new GridLayout(1, 1));
383 panel.add(filler);
384 return panel;
385 }
386 /**
387 * Handles the events from panel 2 including:
388 * search button, reset button and check boxes
389 */
390 private class thehandler implements ActionListener {
391
392 public void actionPerformed(ActionEvent event) {
393
394 String number_of_videos = "";
395 String developerKeyPath = "";
396 String ssl = "";
397 String location = "";
398 String date = "";
399 int radius = 0;
400
401 if (event.getSource()==startButton) {
402 number_of_videos = p2tf1.getText();
403 developerKeyPath = p2tf2.getText();
404 ssl = p2tf3.getText();
405 location = p2tf4.getText();
406 date = p2tf5.getText();
407 radius = radiusSlider.getValue();
408 JOptionPane.showMessageDialog(null, "videos = "+ number_of_videos+ " " +"development Key = " + developerKeyPath
409 + " " + "ssl = " + ssl + " " + "location = " + location + " " + "radius = "+ radius +
410 " " + "date = " + date
411 );}
412 else if (event.getSource()==reset) {
413 p2tf1.setText("50");
414 p2tf2.setText("/youtube.properties");
415 p2tf3.setText("https://www.googleapis.com/auth/youtube.force-ssl");
416 p2tf4.setText("-33.932699, 150.995834");
417 p2tf5.setText("12/05/2016");}
418 }
419 }
420 /**
421 * Invoked when task's progress property changes.
422 */
423
424 public void propertyChange(PropertyChangeEvent evt) {
425 if ("progress" == evt.getPropertyName()) {
426 int progress = (Integer) evt.getNewValue();
427 progressBar.setValue(progress);
428 taskOutput.append(String.format(
429 "Completed %d%% of task.\n", task.getProgress()));
430 }
431 }
432
433 /**
434 * Create the GUI and show it. For thread safety,
435 * this method should be invoked from
436 * the event dispatch thread.
437 */
438 private static void createAndShowGUI() {
439 // Function to set the Default Look
440 // And Feel Decorated of JFrame.
441 JFrame.setDefaultLookAndFeelDecorated(true);
442
443 //Create and set up the window.
444 JFrame frame = new JFrame("TubeMiner");
445 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
446
447 //Add content to the window.
448 frame.add(new TubeMiner(), BorderLayout.CENTER);
449
450 //Display the window.
451 frame.pack();
452 frame.setVisible(true);
453 frame.setLocation(470,50);
454 }
455
456
457 public static Properties readDeveloperKey(String developerKeyPath) {
458 Properties properties = new Properties();
459 try {
460 InputStream in = Search.class.getResourceAsStream(developerKeyPath);
461 properties.load(in);
462
463 } catch (IOException e) {
464 System.err.println("There was an error reading " + "youtube.properties" + ": " + e.getCause() + " : "
465 + e.getMessage());
466 System.exit(1);
467 }
468 return properties;
469 }
470
471 // -------------------------------------------------------------------
472 public static void setRetrieveComments(boolean retrieve) {
473 retrieveComments = retrieve;
474 }
475
476 // -------------------------------------------------------------------
477 public static void filterByType(String type, YouTube.Search.List search) {
478 search.setType(type);
479 }
480
481 // -------------------------------------------------------------------
482 public static void filterByPubllishingDate(DateTime date, YouTube.Search.List search) {
483 search.setPublishedAfter(date);
484 }
485
486 // -------------------------------------------------------------------
487 public static void filterByLocation(String location, String radious, YouTube.Search.List search) {
488 search.setLocation(location).setLocationRadius(radious);
489 }
490
491 // -------------------------------------------------------------------
492 public static void selectFileds(String fields) {
493 search.setFields(fields);
494 }
495
496 // -------------------------------------------------------------------
497 public static void setMaxSearchResults(long max) {
498 search.setMaxResults(max);
499 }
500
501 // -------------------------------------------------------------------
502 private static String buildQuery(POI poi) {
503 // iterate over the items in poi and create a query string containing those
504 // items
505 // separated by | e.g., p1|p2|p3
506 // return the query string
507 StringBuilder query = new StringBuilder();
508 Iterator it = poi.iterator();
509 while (it.hasNext()) {
510 query.append(((Product) it.next()).getName()).append("|");
511 }
512 return query.deleteCharAt(query.length() - 1).toString();
513 }
514
515 // -------------------------------------------------------------------------
516 public static void findVideos(POI poi) {
517 // Read the developer key from the properties file.
518 properties = readDeveloperKey(developerKeyPath);
519 try {
520 // This object is used to make YouTube Data API requests. The last
521 // argument is required, but since we don't need anything
522 // initialized when the HttpRequest is initialized, we override
523 // the interface and provide a no-op function.
524 youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, new HttpRequestInitializer() {
525 public void initialize(HttpRequest request) throws IOException {
526 }
527 }).setApplicationName("TubeMiner").build();
528
529 // Define the API request for retrieving search results.
530 search = youtube.search().list("id,snippet");
531
532 // Set your developer key from the {{ Google Cloud Console }} for
533 // non-authenticated requests. See:
534 // {{ https://cloud.google.com/console }}
535 apiKey = properties.getProperty("youtube.apikey");
536 search.setKey(apiKey);
537
538 // query term.
539 queryTerm = buildQuery(poi);
540 search.setQ(queryTerm);
541 // filter by type. See:
542 // https://developers.google.com/youtube/v3/docs/search/list#type
543 filterByType("video", search);
544 // filter by date
545 filterByPubllishingDate(new DateTime("2017-01-01T00:00:00Z"), search);
546 // filter by location
547 // filterByLocation("-33.932699, 150.922834","10mi", search);
548 // To increase efficiency, only retrieve the fields that the
549 // application uses.
550 selectFileds("items(id/kind,id/videoId,snippet/title,snippet/thumbnails/default/url)");
551 // set maximum number of search results
552 setMaxSearchResults(NUMBER_OF_VIDEOS_RETURNED);
553 setRetrieveComments(false);
554 // Call the API
555 searchResponse = search.execute();
556 searchResultList = searchResponse.getItems();
557 // retrieve and display comments
558 if (searchResultList != null) {
559 displayResults(searchResultList, queryTerm);
560 }
561 } catch (GoogleJsonResponseException e) {
562 System.err.println(
563 "There was a service error: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage());
564 } catch (IOException e) {
565 System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage());
566 } catch (Throwable t) {
567 t.printStackTrace();
568 }
569 }
570
571 // ---------------------------------------------------------------------------------------------------------
572 public static void displayComments(ResourceId rId) {
573
574 }
575
576 // ----------------------------------------------------------------------------------------------------------
577 private static void displayResults(List<SearchResult> serachResults, String query) {
578
579 // Display the query
580
581 Iterator<SearchResult> iteratorSearchResults = serachResults.iterator();
582 System.out.println("\n=============================================================");
583 System.out.println(" First " + NUMBER_OF_VIDEOS_RETURNED + " videos for search on \"" + query + "\".");
584 System.out.println("=============================================================\n");
585
586 // Iterate over “serachResults”
587
588 if (!iteratorSearchResults.hasNext()) {
589 System.out.println(" There aren't any results for your query.");
590 }
591
592 while (iteratorSearchResults.hasNext()) {
593 // for each items in searchResults,
594 // check if the item is a video: video.getId().getKind().equals("youtube#video")
595 // if the item is a video then display the following
596 // Video Id: video.getId().getVideoId()
597 // Title: video..getSnippet().getTitle()
598 // Thumbnail: video.getSnippet().getThumbnails().getDefault().getUrl()
599
600 SearchResult singleVideo = iteratorSearchResults.next();
601 ResourceId rId = singleVideo.getId();
602
603 if (rId.getKind().equals("youtube#video")) {
604 Thumbnail thumbnail = singleVideo.getSnippet().getThumbnails().getDefault();
605 System.out.println(" Video Id: " + rId.getVideoId());
606 System.out.println(" Title: " + singleVideo.getSnippet().getTitle());
607 System.out.println(" Thumbnail: " + thumbnail.getUrl());
608 System.out.println("\n-------------------------------------------------------------\n");
609 // -------------------------------------------------------------------------
610 if (retrieveComments) {
611 displayComments(rId);
612 }
613 }
614 }
615 }
616
617
618
619
620
621 public void stateChanged(ChangeEvent e) {
622 // TODO Auto-generated method stub
623
624 }
625
626
627
628
629 @Override
630 public void windowActivated(WindowEvent e) {
631 // TODO Auto-generated method stub
632
633 }
634
635
636
637
638 @Override
639 public void windowClosed(WindowEvent e) {
640 // TODO Auto-generated method stub
641
642 }
643
644
645
646
647 @Override
648 public void windowClosing(WindowEvent e) {
649 // TODO Auto-generated method stub
650
651 }
652
653
654
655
656 @Override
657 public void windowDeactivated(WindowEvent e) {
658 // TODO Auto-generated method stub
659
660 }
661
662
663
664
665 @Override
666 public void windowDeiconified(WindowEvent e) {
667 // TODO Auto-generated method stub
668
669 }
670
671
672
673
674 @Override
675 public void windowIconified(WindowEvent e) {
676 // TODO Auto-generated method stub
677
678 }
679
680
681
682
683 @Override
684 public void windowOpened(WindowEvent e) {
685 // TODO Auto-generated method stub
686
687 }
688
689
690
691
692 @Override
693 public void actionPerformed(ActionEvent e) {
694 // TODO Auto-generated method stub
695
696 }
697
698
699
700}