stationpanel.java

来自「java语言开发的P2P流媒体系统」· Java 代码 · 共 411 行

JAVA
411
字号
/* Stream-2-Stream - Peer to peer television and radio
 * Project homepage: http://s2s.sourceforge.net/
 * Copyright (C) 2005-2006 Jason Hooks
 * ---------------------------------------------------------------------------
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 * ---------------------------------------------------------------------------
 */
package p2pradio.gui;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.MulticastSocket;
import java.net.SocketException;
import java.net.URL;
import java.sql.*;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.TreeSet;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.AbstractTableModel;

import p2pradio.Messages;
import p2pradio.sources.*;
import stream2stream.XML.SettingsXML;
import stream2stream.stationlist.LANPages;
import stream2stream.stationlist.YellowPages;

public class StationPanel extends JPanel implements Runnable{
		private boolean DEBUG = false;
		public static final String PHP_FILE = "integrated.php";
		public static final String URL = "http://" + YellowPages.YP_HOST + YellowPages.YP_DIR + PHP_FILE;
		public static final int LAN_WAIT_TIME = 200; //ms
		public static final int MAX_BROADCAST_PACKET_SIZE = 10000;
		private Object[][] data = null;
		private Thread thread;
		private JTable table;
		private JComboBox network;
		private String internet;
		private String lan;
		private MainFrame mf;
		private SettingsXML xml;
		
	    public StationPanel(MainFrame mf) {
	        super(new GridBagLayout());
	        this.mf = mf;
	        xml = mf.getSettingsXML();
	        thread = new Thread(this);
	        thread.run();
	        
	    }
	    public void run()
	    {
	    	
	        //Make the components
	        
	        internet = Messages.getString("StationPanel.INTERNET");
	        lan = Messages.getString("StationPanel.LAN");
	        String[] choices = {internet, lan};
	        network = new JComboBox(choices);
	        network.setSelectedIndex(xml.getStationPanelChoice());
	        network.addActionListener(new ActionListener()//public
	        {
    			public void actionPerformed(ActionEvent e)
    			{
    				new RefreshThread().start();
    			}
    		});
	        getStations();
	        JButton refresh = new JButton(Messages.getString("StationPanel.REFRESH"));
	        refresh.addActionListener(new ActionListener()//public
	        		{
	        			public void actionPerformed(ActionEvent e)
	        			{
	        				new RefreshThread().start();
	        			}
	        		});
	        table = new JTable(new MyTableModel());
	        table.setPreferredScrollableViewportSize(new Dimension(500, 70));
	        table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
	        table.addMouseListener(new MouseAdapter(){
	            public void mouseClicked(MouseEvent e){
	             if (e.getClickCount() == 2){
	                if (!mf.getIsServer())
	                {
	                	boolean isConnected = mf.getIsConnected();
	                	JButton button1 = mf.getButton1();
	                	int row = table.getSelectedRow();
	                	String url = (String) data[row][6]; //url is on column 5
	                	//System.out.println("len" + url.length());
	                	mf.setUrl(url);
	                	if (isConnected)
	                		button1.doClick();
	                	else
	                		button1.doClick(2);
	                	mf.setMainSelected();
	                		
	                }
	                }
	             }
	            } );

	        //Create the scroll pane and add the table to it.
	        JScrollPane scrollPane = new JScrollPane(table);
	        
	        //Add the components
	        GridBagConstraints c = new GridBagConstraints();
	        c.anchor = GridBagConstraints.PAGE_START;
			c.weightx = .01;
			c.weighty = .01;
			c.fill = GridBagConstraints.NONE;
			c.gridwidth = 1;
			c.gridx = 0;
			c.gridy = 0;
			c.insets = new Insets(10, 10, 10, 10);
	        add(network, c);
	        
	        c.gridx = 1;
	        add(refresh, c);
	        
	        c.weightx = 1;
			c.weighty = 1;
			c.fill = GridBagConstraints.BOTH;
			c.gridwidth = 2;
			c.gridheight = 1;
			c.gridy = 1;
			c.gridx = 0;
	        add(scrollPane, c);
	    }

	    class MyTableModel extends AbstractTableModel {
	        private String[] columnNames = {"Station",
	                                        "Song",
	                                        "Type",
	                                        "Genre",
	                                        "Rate (kilobits/s)", "Listeners"};

	        public int getColumnCount() {
	        	if (data == null)
	        		return 0;
	            return columnNames.length;
	        }

	        public int getRowCount() {
	        	if (data == null)
	        		return 0;
	            return data.length;
	        }

	        public String getColumnName(int col) {
	            return columnNames[col];
	        }

	        public Object getValueAt(int row, int col) {
	            return data[row][col];
	        }

	        /*
	         * JTable uses this method to determine the default renderer/
	         * editor for each cell.  If we didn't implement this method,
	         * then the last column would contain text ("true"/"false"),
	         * rather than a check box.
	         */
	        public Class getColumnClass(int c) {
	            return PHP_FILE.getClass();
	        }

	        /*
	         * Don't need to implement this method unless your table's
	         * editable.
	         */
	        public boolean isCellEditable(int row, int col) {
	            //Note that the data/cell address is constant,
	            //no matter where the cell appears onscreen.
	            return false;
	        }

	        /*
	         * Don't need to implement this method unless your table's
	         * data can change.
	         */
	        public void setValueAt(Object value, int row, int col) {
	            if (DEBUG) {
	                System.out.println("Setting value at " + row + "," + col
	                                   + " to " + value
	                                   + " (an instance of "
	                                   + value.getClass() + ")");
	            }

	            data[row][col] = value;
	            fireTableCellUpdated(row, col);

	            if (DEBUG) {
	                System.out.println("New value of data:");
	                printDebugData();
	            }
	        }

	        private void printDebugData() {
	            int numRows = getRowCount();
	            int numCols = getColumnCount();

	            for (int i=0; i < numRows; i++) {
	                System.out.print("    row " + i + ":");
	                for (int j=0; j < numCols; j++) {
	                    System.out.print("  " + data[i][j]);
	                }
	                System.out.println();
	            }
	            System.out.println("--------------------------");
	        }
	    }
	    private void getStations()
	    {
	    	/*
	    	 * {
	    	 * [n,s,t,g,r,u]
	    	 * [,,,,,,]
	    	 * [,,,,,,]
	    	 * [,,,,,,]
	    	 * }
	    	 *
	    	 */
	    	if (network.getSelectedItem().equals(internet))
	    	{
	    		try {
	    			URL phpURL = new URL(URL);
	    			InputStreamReader input = new InputStreamReader(phpURL.openStream());
	    			BufferedReader in = new BufferedReader(
	    				new InputStreamReader(
						phpURL.openStream()));
				
	    			String inputLine = in.readLine();
	    			//System.out.println(inputLine);
	    			data = new Object[0][7];
	    			if (inputLine != null)
	    			{
	    				int index1;
	    				int index2 = 0;
	    				int nstations = 0;
	    				while ((index1 = inputLine.indexOf("\\\\", index2)) != -1) //Escaped, represents \\ plaintext
	    				{
	    					nstations++;
	    					index2 = index1 + 2;
	    				}
	    				//System.out.println("nstations" + nstations);
	    				//nstations = 2;
	    				int lastIndex = 1;
	    				if (nstations > 0)
	    				{
	    					data = new Object[nstations][7];
	    					for (int i = 0; i < nstations; i++)
	    					{
	    						index1 = inputLine.indexOf("\\n", lastIndex);  //Escaped, represents \n plaintext 
																				
	    						index2 = inputLine.indexOf("\\s", lastIndex); 	
	    						customSubstring(index1, index2, i, inputLine, 0);
	    						index1 = inputLine.indexOf("\\t", lastIndex);
	    						//System.out.println("index2" + index2 + "index1" + index1);
	    						customSubstring(index2, index1, i, inputLine, 1);
	    						index2 = inputLine.indexOf("\\g", lastIndex);
	    						customSubstring(index1, index2, i, inputLine, 2);
	    						index1 = inputLine.indexOf("\\r", lastIndex);
	    						customSubstring(index2, index1, i, inputLine, 3);
	    						index2 = inputLine.indexOf("\\l", lastIndex);
	    						customSubstring(index1, index2, i, inputLine, 4);
	    						index1 = inputLine.indexOf("\\u", lastIndex);
	    						customSubstring(index2, index1, i, inputLine, 5);
	    						
	    						index2 = inputLine.indexOf("\\\\", index1);
	    						if (index2 == -1)
	    							index2 = inputLine.length();
	    						//System.out.println(index1 + "%" + index2);
	    						customSubstring(index1, index2, i, inputLine, 6);
	    						lastIndex = index2;
	    						
	    					}
	    				}
	    			}
			in.close();
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				//e.printStackTrace();
			}
			catch (IOException e) {
				//e.printStackTrace();
			}
	    	}
	    	else
	    	{
	    		
	    		TreeSet packets = new TreeSet();
	    		MulticastSocket socket = null;
	    		DatagramPacket packet = new DatagramPacket(new byte[MAX_BROADCAST_PACKET_SIZE], MAX_BROADCAST_PACKET_SIZE);
				
	    		try {
	    			socket = new MulticastSocket(LANPages.MULTICAST_PORT); 
					InetAddress group = InetAddress.getByName(LANPages.MULTICAST_ADDRESS);
					socket.joinGroup(group);
					long start = System.currentTimeMillis();
		    		long end = start + LAN_WAIT_TIME;
	    			long timeLeft;
	    			while((timeLeft = end - System.currentTimeMillis()) > 0)
	    			{
	    				socket.setSoTimeout((int)timeLeft);
						socket.receive(packet);
						byte[] infomax = packet.getData();
						int length = packet.getLength();
						byte[] info = new byte[length];
						System.arraycopy(infomax, 0, info, 0, length);
						String sinfo = new String(info);
						if (packet != null)
							packets.add(sinfo);
	    			}
					
				} catch (SocketException e) {
					// TODO Auto-generated catch block
				}
				catch (IOException e) {
					// TODO Auto-generated catch block
				}
				finally
				{
					if (socket != null)
						socket.close();
				}
				Iterator iter = packets.iterator();
				data = new Object[packets.size()][7];
				int index1, index2;
				int i = 0;
				while (iter.hasNext())
				{	
					String sinfo = (String) iter.next();
					index1 = sinfo.indexOf("\\n");  //Escaped, represents \n plaintext 
					
					index2 = sinfo.indexOf("\\s"); 	
					customSubstring(index1, index2, i, sinfo, 0);
					index1 = sinfo.indexOf("\\t");
					customSubstring(index2, index1, i, sinfo, 1);
					index2 = sinfo.indexOf("\\g");
					customSubstring(index1, index2, i, sinfo, 2);
					index1 = sinfo.indexOf("\\r");
					customSubstring(index2, index1, i, sinfo, 3);
					index2 = sinfo.indexOf("\\l");
					customSubstring(index1, index2, i, sinfo, 4);
					index1 = sinfo.indexOf("\\u");
					customSubstring(index2, index1, i, sinfo, 5);
					index2 = sinfo.length();
					//System.out.println(index1 + "%" + index2);
					customSubstring(index1, index2, i, sinfo, 6);
					//System.out.println(lastIndex);
					i++;
				}
			}
	    }
	   
	    private void customSubstring(int index1, int index2, int i, String inputLine, int inner)
	    {
	    	if (index1 != -1 && index2 != -1)
	    	{
				data[i][inner] = inputLine.substring(index1 + 2, index2);
	    	}
	    }
	    private class RefreshThread extends Thread
	    {
	    	public void run()
	    	{
	    		data = null;
				getStations();
				table.setModel(new MyTableModel());
				table.repaint();
	    	}
	    }
	    public int getStationPanelChoice()
	    {
	    	return network.getSelectedIndex();
	    }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?