Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package tubeminer;
- import com.google.api.client.auth.oauth2.Credential;
- import com.google.api.client.googleapis.json.GoogleJsonResponseException;
- import com.google.api.client.http.HttpRequest;
- import com.google.api.client.http.HttpRequestInitializer;
- import com.google.api.client.util.DateTime;
- import com.google.api.services.samples.youtube.cmdline.Auth;
- import com.google.api.services.samples.youtube.cmdline.data.*;
- import com.google.api.services.youtube.YouTube;
- import com.google.api.services.youtube.model.Comment;
- import com.google.api.services.youtube.model.CommentListResponse;
- import com.google.api.services.youtube.model.CommentSnippet;
- import com.google.api.services.youtube.model.CommentThread;
- import com.google.api.services.youtube.model.CommentThreadListResponse;
- import com.google.api.services.youtube.model.ResourceId;
- import com.google.api.services.youtube.model.SearchListResponse;
- import com.google.api.services.youtube.model.SearchResult;
- import com.google.api.services.youtube.model.Thumbnail;
- import com.google.common.collect.Lists;
- import java.awt.BorderLayout;
- import java.awt.Color;
- import java.awt.Container;
- import java.awt.Dimension;
- import java.awt.FlowLayout;
- import java.awt.GridLayout;
- import java.awt.Image;
- import java.awt.Insets;
- import java.awt.Toolkit;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- import java.awt.event.KeyEvent;
- import java.awt.event.WindowEvent;
- import java.awt.event.WindowListener;
- import java.beans.PropertyChangeEvent;
- import java.beans.PropertyChangeListener;
- import java.io.File;
- import java.io.IOException;
- import java.io.InputStream;
- import java.net.URL;
- import java.util.ArrayList;
- import java.util.Iterator;
- import java.util.List;
- import java.util.Map;
- import java.util.Map.Entry;
- import java.util.Properties;
- import java.util.Random;
- import java.util.Timer;
- import javax.swing.ImageIcon;
- import javax.swing.JButton;
- import javax.swing.JCheckBox;
- import javax.swing.JComponent;
- import javax.swing.JFrame;
- import javax.swing.JLabel;
- import javax.swing.JOptionPane;
- import javax.swing.JPanel;
- import javax.swing.JProgressBar;
- import javax.swing.JRadioButton;
- import javax.swing.JSlider;
- import javax.swing.JTabbedPane;
- import javax.swing.JTextArea;
- import javax.swing.JTextField;
- import javax.swing.SwingUtilities;
- import javax.swing.SwingWorker;
- import javax.swing.UIManager;
- import javax.swing.event.ChangeEvent;
- import javax.swing.event.ChangeListener;
- import org.codehaus.jackson.JsonGenerationException;
- import org.codehaus.jackson.JsonNode;
- import org.codehaus.jackson.map.JsonMappingException;
- import org.codehaus.jackson.map.ObjectMapper;
- import org.mortbay.thread.Timeout.Task;
- public class TubeMiner extends JPanel implements ActionListener,WindowListener,ChangeListener,
- PropertyChangeListener {
- private static POIList poilist;
- private static YouTube youtube;
- private static YouTube.Search.List search;
- private static SearchListResponse searchResponse;
- private static List<SearchResult> searchResultList;
- private static String queryTerm;
- private static String apiKey;
- private static final long NUMBER_OF_VIDEOS_RETURNED = 50;
- private static Properties properties;
- private static final String developerKeyPath = "/youtube.properties";
- private static CommentThreadListResponse videoCommentsListResponse;
- private static List<CommentThread> videoComments;
- private static Credential credential;
- private static final String SSL = "https://www.googleapis.com/auth/youtube.force-ssl";
- private static boolean retrieveComments = false;
- //Set up slider parameters.
- static final int R_MIN = 0;
- static final int R_MAX = 1000;
- static final int R_INIT = 500; //initial frames per second
- int frameNumber = 0;
- int NUM_FRAMES = 14;
- ImageIcon[] images = new ImageIcon[NUM_FRAMES];
- int delay;
- Timer timer;
- boolean frozen = false;
- private JProgressBar progressBar;
- private JButton startButton;
- private JButton reset;
- private JTextArea taskOutput;
- private Task task;
- JCheckBox locationbox;
- JCheckBox datebox;
- private JTextField p2tf1;
- private JTextField p2tf2;
- private JTextField p2tf3;
- private JTextField p2tf4;
- private JTextField p2tf5;
- private JSlider radiusSlider;
- private String number_of_videos;
- private String developerKeyPath1;
- private String ssl;
- private String location;
- private String date;
- private int radius;
- class Task extends SwingWorker<Void, Void> {
- /*
- * Main task. Executed in background thread.
- */
- @Override
- public Void doInBackground() {
- Random random = new Random();
- int progress = 0;
- //Initialize progress property.
- setProgress(0);
- while (progress < 100) {
- //Sleep for up to one second.
- try {
- Thread.sleep(random.nextInt(1000));
- } catch (InterruptedException ignore) {}
- //Make random progress.
- progress += random.nextInt(10);
- setProgress(Math.min(progress, 100));
- }
- return null;
- }
- /*
- * Executed in event dispatching thread
- */
- @Override
- public void done() {
- Toolkit.getDefaultToolkit().beep();
- startButton.setEnabled(true);
- setCursor(null); //turn off the wait cursor
- taskOutput.append("Done!\n");
- }
- }
- public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
- //Schedule a job for the event dispatch thread:
- //creating and showing this application's GUI.
- SwingUtilities.invokeLater(new Runnable() {
- public void run() {
- //Turn off metal's use of bold fonts
- UIManager.put("swing.boldMetal", Boolean.FALSE);
- createAndShowGUI();
- }
- });
- //JFrame j = new JFrame("TubeMiner");
- TubeMiner j = new TubeMiner();
- j.setSize(300,350);
- j.setVisible(true);
- poilist = POIList.getPOIList();
- Iterator it = poilist.iterator();
- while (it.hasNext())
- findVideos((POI) it.next());
- }
- public TubeMiner () {
- super(new GridLayout(1, 1));
- JTabbedPane tabbedPane = new JTabbedPane();
- //1st pane
- JPanel panel1 = new JPanel();
- tabbedPane.addTab("POI Tab", null, panel1);
- tabbedPane.setMnemonicAt(0, KeyEvent.VK_1);
- //2nd pane
- JPanel panel2 = new JPanel();
- panel2.setLayout(null);
- tabbedPane.addTab("Miner Tab", null, panel2);
- tabbedPane.setMnemonicAt(1, KeyEvent.VK_2);
- //object of eventhandler class
- thehandler handler = new thehandler();
- //2nd pane 1st Reset button
- reset = new JButton("Reset");
- reset.setBounds(200,430,100,50);
- reset.addActionListener(handler);
- //2nd pane 1st Find Videos button
- startButton = new JButton("Find Videos");
- startButton.setActionCommand("start");
- startButton.addActionListener(handler);
- startButton.setBounds(330,430,100,50);
- //creates progress bar
- progressBar = new JProgressBar(0, 100);
- progressBar.setValue(0);
- progressBar.setStringPainted(true);
- progressBar.setBounds(30, 520, 430, 30);
- taskOutput = new JTextArea(5, 20);
- taskOutput.setMargin(new Insets(5,5,5,5));
- taskOutput.setEditable(false);
- //NUMBER_OF_VIDEOS_RETURNED label 1
- JLabel p2l1 = new JLabel();
- p2l1.setText("NUMBER_OF_VIDEOS_RETURNED");
- p2l1.setBounds(30, 20, 230, 30);
- //developerKeyPath label 2
- JLabel p2l2 = new JLabel();
- p2l2.setText("developerKeyPath");
- p2l2.setBounds(135, 70, 230, 30);
- //SSL label 3
- JLabel p2l3 = new JLabel();
- p2l3.setText("SSL");
- p2l3.setBounds(210, 120, 230, 30);
- //Location label 4
- JLabel p2l4 = new JLabel();
- p2l4.setText("Location");
- p2l4.setBounds(190, 165, 230, 30);
- //Radius label 5
- JLabel p2l5 = new JLabel();
- p2l5.setText("Radius (mi)");
- p2l5.setBounds(175, 215, 230, 30);
- //DateTime label 6
- JLabel p2l6 = new JLabel();
- p2l6.setText("DateTime");
- p2l6.setBounds(185, 275, 230, 30);
- //slider 0 label 6
- JLabel p2l7 = new JLabel();
- p2l7.setText("0");
- p2l7.setBounds(253, 240, 30, 30);
- //slider 1000 label 8
- JLabel p2l8 = new JLabel();
- p2l8.setText("1000");
- p2l8.setBounds(460, 240, 100, 30);
- //slider 500 label 9
- JLabel p2l9 = new JLabel();
- p2l9.setText("Filter by Location");
- p2l9.setBounds(337, 350, 100, 30);
- //checkbox location label 9
- JLabel p2l10 = new JLabel();
- p2l10.setText("Filter by publication date");
- p2l10.setBounds(300, 380, 150, 30);
- //checkbox date label 9
- JLabel p2l11 = new JLabel();
- p2l11.setText("500");
- p2l11.setBounds(355, 240, 100, 30);
- //2nd pane 1st textfield
- p2tf1= new JTextField();
- p2tf1.setText("50");
- p2tf1.setBounds(250, 20, 230, 30);
- p2tf1.addActionListener(handler);
- //2nd pane 2nd textfield
- p2tf2= new JTextField();
- p2tf2.setText("/youtube.properties");
- p2tf2.setBounds(250, 70, 230, 30);
- p2tf2.addActionListener(handler);
- //2nd pane 3rd textfield
- p2tf3= new JTextField();
- p2tf3.setText("https://www.googleapis.com/auth/youtube.force-ssl");
- p2tf3.setBounds(250, 120, 230, 30);
- p2tf3.addActionListener(handler);
- //2nd pane 4th textfield
- p2tf4= new JTextField();
- p2tf4.setText("-33.932699, 150.995834");
- p2tf4.setBounds(250, 170, 230, 30);
- p2tf4.addActionListener(handler);
- //2nd pane 5th textfield
- p2tf5= new JTextField();
- p2tf5.setText("12/05/2016");
- p2tf5.setBounds(250, 275, 230, 30);
- p2tf5.addActionListener(handler);
- //Create the slider.
- radiusSlider = new JSlider(JSlider.HORIZONTAL,R_MIN, R_MAX, R_INIT);
- radiusSlider.addChangeListener(this);
- radiusSlider.setMajorTickSpacing(100);
- radiusSlider.setPaintTicks(true);
- radiusSlider.setBounds(250, 220, 230, 30);
- //Create the check boxes.
- locationbox = new JCheckBox("Chin");
- locationbox.setBounds(440, 350, 30, 30);
- locationbox.setMnemonic(KeyEvent.VK_C);
- locationbox.setSelected(true);
- datebox = new JCheckBox("Glasses");
- datebox.setBounds(440, 380, 30, 30);
- datebox.setMnemonic(KeyEvent.VK_G);
- datebox.setSelected(true);
- panel2.add(p2l1);
- panel2.add(p2l2);
- panel2.add(p2l3);
- panel2.add(p2l4);
- panel2.add(p2l5);
- panel2.add(p2l6);
- panel2.add(p2l7);
- panel2.add(p2l8);
- panel2.add(p2l9);
- panel2.add(p2l10);
- panel2.add(p2l11);
- panel2.add(reset);
- panel2.add(startButton);
- panel2.add(p2tf1);
- panel2.add(p2tf2);
- panel2.add(p2tf3);
- panel2.add(p2tf4);
- panel2.add(p2tf5);
- panel2.add(radiusSlider);
- panel2.add(progressBar);
- panel2.add(locationbox);
- panel2.add(datebox);
- //3rd pane
- JPanel panel3 = new JPanel();
- panel3.setPreferredSize(new Dimension(500, 600));
- tabbedPane.addTab("Results Tab", null, panel3, "This msg displayed when mouse hovers tab");
- tabbedPane.setMnemonicAt(2, KeyEvent.VK_3);
- //Add the tabbed pane to this panel.
- add(tabbedPane);
- //The following line enables to use scrolling tabs.
- tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
- }
- protected JComponent makeTextPanel(String text) {
- JPanel panel = new JPanel(false);
- JLabel filler = new JLabel(text);
- filler.setHorizontalAlignment(JLabel.CENTER);
- panel.setLayout(new GridLayout(1, 1));
- panel.add(filler);
- return panel;
- }
- /**
- * Handles the events from panel 2 including:
- * search button, reset button and check boxes
- */
- private class thehandler implements ActionListener {
- public void actionPerformed(ActionEvent event) {
- String number_of_videos = "";
- String developerKeyPath = "";
- String ssl = "";
- String location = "";
- String date = "";
- int radius = 0;
- if (event.getSource()==startButton) {
- number_of_videos = p2tf1.getText();
- developerKeyPath = p2tf2.getText();
- ssl = p2tf3.getText();
- location = p2tf4.getText();
- date = p2tf5.getText();
- radius = radiusSlider.getValue();
- JOptionPane.showMessageDialog(null, "videos = "+ number_of_videos+ " " +"development Key = " + developerKeyPath
- + " " + "ssl = " + ssl + " " + "location = " + location + " " + "radius = "+ radius +
- " " + "date = " + date
- );}
- else if (event.getSource()==reset) {
- p2tf1.setText("50");
- p2tf2.setText("/youtube.properties");
- p2tf3.setText("https://www.googleapis.com/auth/youtube.force-ssl");
- p2tf4.setText("-33.932699, 150.995834");
- p2tf5.setText("12/05/2016");}
- }
- }
- /**
- * Invoked when task's progress property changes.
- */
- public void propertyChange(PropertyChangeEvent evt) {
- if ("progress" == evt.getPropertyName()) {
- int progress = (Integer) evt.getNewValue();
- progressBar.setValue(progress);
- taskOutput.append(String.format(
- "Completed %d%% of task.\n", task.getProgress()));
- }
- }
- /**
- * Create the GUI and show it. For thread safety,
- * this method should be invoked from
- * the event dispatch thread.
- */
- private static void createAndShowGUI() {
- // Function to set the Default Look
- // And Feel Decorated of JFrame.
- JFrame.setDefaultLookAndFeelDecorated(true);
- //Create and set up the window.
- JFrame frame = new JFrame("TubeMiner");
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- //Add content to the window.
- frame.add(new TubeMiner(), BorderLayout.CENTER);
- //Display the window.
- frame.pack();
- frame.setVisible(true);
- frame.setLocation(470,50);
- }
- public static Properties readDeveloperKey(String developerKeyPath) {
- Properties properties = new Properties();
- try {
- InputStream in = Search.class.getResourceAsStream(developerKeyPath);
- properties.load(in);
- } catch (IOException e) {
- System.err.println("There was an error reading " + "youtube.properties" + ": " + e.getCause() + " : "
- + e.getMessage());
- System.exit(1);
- }
- return properties;
- }
- // -------------------------------------------------------------------
- public static void setRetrieveComments(boolean retrieve) {
- retrieveComments = retrieve;
- }
- // -------------------------------------------------------------------
- public static void filterByType(String type, YouTube.Search.List search) {
- search.setType(type);
- }
- // -------------------------------------------------------------------
- public static void filterByPubllishingDate(DateTime date, YouTube.Search.List search) {
- search.setPublishedAfter(date);
- }
- // -------------------------------------------------------------------
- public static void filterByLocation(String location, String radious, YouTube.Search.List search) {
- search.setLocation(location).setLocationRadius(radious);
- }
- // -------------------------------------------------------------------
- public static void selectFileds(String fields) {
- search.setFields(fields);
- }
- // -------------------------------------------------------------------
- public static void setMaxSearchResults(long max) {
- search.setMaxResults(max);
- }
- // -------------------------------------------------------------------
- private static String buildQuery(POI poi) {
- // iterate over the items in poi and create a query string containing those
- // items
- // separated by | e.g., p1|p2|p3
- // return the query string
- StringBuilder query = new StringBuilder();
- Iterator it = poi.iterator();
- while (it.hasNext()) {
- query.append(((Product) it.next()).getName()).append("|");
- }
- return query.deleteCharAt(query.length() - 1).toString();
- }
- // -------------------------------------------------------------------------
- public static void findVideos(POI poi) {
- // Read the developer key from the properties file.
- properties = readDeveloperKey(developerKeyPath);
- try {
- // This object is used to make YouTube Data API requests. The last
- // argument is required, but since we don't need anything
- // initialized when the HttpRequest is initialized, we override
- // the interface and provide a no-op function.
- youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, new HttpRequestInitializer() {
- public void initialize(HttpRequest request) throws IOException {
- }
- }).setApplicationName("TubeMiner").build();
- // Define the API request for retrieving search results.
- search = youtube.search().list("id,snippet");
- // Set your developer key from the {{ Google Cloud Console }} for
- // non-authenticated requests. See:
- // {{ https://cloud.google.com/console }}
- apiKey = properties.getProperty("youtube.apikey");
- search.setKey(apiKey);
- // query term.
- queryTerm = buildQuery(poi);
- search.setQ(queryTerm);
- // filter by type. See:
- // https://developers.google.com/youtube/v3/docs/search/list#type
- filterByType("video", search);
- // filter by date
- filterByPubllishingDate(new DateTime("2017-01-01T00:00:00Z"), search);
- // filter by location
- // filterByLocation("-33.932699, 150.922834","10mi", search);
- // To increase efficiency, only retrieve the fields that the
- // application uses.
- selectFileds("items(id/kind,id/videoId,snippet/title,snippet/thumbnails/default/url)");
- // set maximum number of search results
- setMaxSearchResults(NUMBER_OF_VIDEOS_RETURNED);
- setRetrieveComments(false);
- // Call the API
- searchResponse = search.execute();
- searchResultList = searchResponse.getItems();
- // retrieve and display comments
- if (searchResultList != null) {
- displayResults(searchResultList, queryTerm);
- }
- } catch (GoogleJsonResponseException e) {
- System.err.println(
- "There was a service error: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage());
- } catch (IOException e) {
- System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage());
- } catch (Throwable t) {
- t.printStackTrace();
- }
- }
- // ---------------------------------------------------------------------------------------------------------
- public static void displayComments(ResourceId rId) {
- }
- // ----------------------------------------------------------------------------------------------------------
- private static void displayResults(List<SearchResult> serachResults, String query) {
- // Display the query
- Iterator<SearchResult> iteratorSearchResults = serachResults.iterator();
- System.out.println("\n=============================================================");
- System.out.println(" First " + NUMBER_OF_VIDEOS_RETURNED + " videos for search on \"" + query + "\".");
- System.out.println("=============================================================\n");
- // Iterate over “serachResults”
- if (!iteratorSearchResults.hasNext()) {
- System.out.println(" There aren't any results for your query.");
- }
- while (iteratorSearchResults.hasNext()) {
- // for each items in searchResults,
- // check if the item is a video: video.getId().getKind().equals("youtube#video")
- // if the item is a video then display the following
- // Video Id: video.getId().getVideoId()
- // Title: video..getSnippet().getTitle()
- // Thumbnail: video.getSnippet().getThumbnails().getDefault().getUrl()
- SearchResult singleVideo = iteratorSearchResults.next();
- ResourceId rId = singleVideo.getId();
- if (rId.getKind().equals("youtube#video")) {
- Thumbnail thumbnail = singleVideo.getSnippet().getThumbnails().getDefault();
- System.out.println(" Video Id: " + rId.getVideoId());
- System.out.println(" Title: " + singleVideo.getSnippet().getTitle());
- System.out.println(" Thumbnail: " + thumbnail.getUrl());
- System.out.println("\n-------------------------------------------------------------\n");
- // -------------------------------------------------------------------------
- if (retrieveComments) {
- displayComments(rId);
- }
- }
- }
- }
- public void stateChanged(ChangeEvent e) {
- // TODO Auto-generated method stub
- }
- @Override
- public void windowActivated(WindowEvent e) {
- // TODO Auto-generated method stub
- }
- @Override
- public void windowClosed(WindowEvent e) {
- // TODO Auto-generated method stub
- }
- @Override
- public void windowClosing(WindowEvent e) {
- // TODO Auto-generated method stub
- }
- @Override
- public void windowDeactivated(WindowEvent e) {
- // TODO Auto-generated method stub
- }
- @Override
- public void windowDeiconified(WindowEvent e) {
- // TODO Auto-generated method stub
- }
- @Override
- public void windowIconified(WindowEvent e) {
- // TODO Auto-generated method stub
- }
- @Override
- public void windowOpened(WindowEvent e) {
- // TODO Auto-generated method stub
- }
- @Override
- public void actionPerformed(ActionEvent e) {
- // TODO Auto-generated method stub
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement