⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 servicesapi.java

📁 We intend to develop a wifi enabled p2p file sharing system on a linux platform using jxta and java.
💻 JAVA
字号:
package edu.uiuc.cs.cs327.linuxwifi.services; import java.awt.*;
import java.util.Vector.*;
import java.util.*;
import de.ueberdosis.mp3info.*;
import java.io.*; import edu.uiuc.cs.cs327.linuxwifi.app.*;
import edu.uiuc.cs.cs327.linuxwifi.gui.*;
import edu.uiuc.cs.cs327.linuxwifi.util.*;     /**
     * Class used as the API to the Services package for other underlying packages
     */    

public class ServicesApi implements FileInfoListener, MusicProfileListener
{
	private static final boolean DEBUG = false;
	private static ConfigurationInfo configInfo = new ConfigurationInfo();
	private Vector availableNodesVector;
	private PeerDiscovery peerNodes;
	private MainGUI mainGUI;
    private AppAPI _appAPI;
	private Vector _searchResponses;
	private Vector _fileInfoListeners;
	private Vector _files = null;

	public ServicesApi()
      {
	    _fileInfoListeners = new Vector();
          _appAPI = new AppAPI();
          _appAPI.addFileInfoListener(this);
          _appAPI.addMusicProfileListener(this);
           
         _searchResponses = new Vector();
         _files = new Vector(10,5);
      }

    public ServicesApi(MainGUI mainGUI) 
    {  
        this();	
        this.mainGUI = mainGUI;
        availableNodesVector = new Vector();

        
        System.out.println("Staring peer discovery");
        peerNodes = new PeerDiscovery(this);
        System.out.println("Done Starting Peer Discovery");                /** TEST CASES **/
        
       MessageHandler mh = new MessageHandler(peerNodes.netPeerGroup, _appAPI);
        
    }     /**
     * Gets current configuration info object
     * @return ConfigurationInfo object
     */
    public ConfigurationInfo getCurrentConfigurationInfo()
    {
        return(configInfo);
    }
    
    /**
     * Sets current configuration info object
     * @param aConfigInfo object
     */
    public void setCurrentConfigurationInfo(ConfigurationInfo aConfigInfo)
    {
        configInfo = aConfigInfo;
        configInfo.save();
    }
    
    public synchronized void addFileInfoListener(FileInfoListener l)
    {
        _fileInfoListeners.add(l);
    }
    public synchronized void removeFileInfoListener(FileInfoListener l)
    {
        _fileInfoListeners.remove(l);
    }
    public synchronized void fireFileInfoReceivedEvent(FileInfo fi)
    {
        FileInfoEvent e = new FileInfoEvent(this, fi);
        Iterator listeners = _fileInfoListeners.iterator();
        while(listeners.hasNext()) {
            ((FileInfoListener)listeners.next()).fileInfoReceived(e);
        }
    }
    
    /**
     * Executed to have a MusicProfile searched across all present peers
     * @return a vector of FileInfo objects
     */     public void searchPeers(MusicProfile aMusicProfile)
    {
		_searchResponses.clear();
		fireFileInfoReceivedEvent(null);
        _appAPI.requestSearch(aMusicProfile,availableNodesVector);

// To test search code:
/*
        Iterator nodes = availableNodes.iterator();
        while(nodes.hasNext()) {
            ((MusicProfileListener)listeners.next()).musicRequestReceived(e);
            
            NodeObject nob = (NodeObject) nodes.next();
            JxtaSocketLinuxwifi socEx = new JxtaSocketLinuxwifi();
            System.out.println("reading in socket.adv");
            try {
                    FileInputStream is = new FileInputStream("C:\\linuxwifi\\linuxwifi\\socket.adv");
                    socEx.setpipeAdv( (PipeAdvertisement) AdvertisementFactory.newAdvertisement(MimeMediaType.XMLUTF8, is) );
                    is.close();
                    System.out.println("creating the socket");
                    System.out.println("peer group: " + socEx.getnetPeerGroup());
                    socEx.setsocket( new JxtaSocket(socEx.getnetPeerGroup(), socEx.getpipeAdv()) );

            } catch (Exception e) {
                    System.out.println("failed to read/parse pipe advertisement");
                    e.printStackTrace();
                    System.exit(-1);
            }
            socEx.setProfile("Computer 1");
            //Run the example
            socEx.run();
            
            
            
        }
*/        
        
        
    }

    public void fileInfoReceived(FileInfoEvent e)
    {
		_searchResponses.add(e.getFileInfo());
		fireFileInfoReceivedEvent(e.getFileInfo());
    }
    
    public Vector getSearchResponses()
    {
		return _searchResponses;
    }
    
    public void musicRequestReceived(MusicProfileEvent e)
    {
		MusicProfile mp = e.getMusicProfile();
		
		System.out.println("Searching local files");
		
		checkLocalFiles(mp);
		
		System.out.println("Done. Searching local files");
    } 	
    
    private void checkLocalFiles(MusicProfile mp)
	{
		Iterator directories = configInfo.getUploadDirectories().iterator();
		
        while(directories.hasNext()) {
            checkDirectory((String)directories.next(), mp); 
        }
	}
	
	private void checkDirectory(String dirName, final MusicProfile mp)
	{
		File directory = new File(dirName);
		
System.out.println("Checking directory: " + dirName);		
System.out.println("Checking directory: " + mp.getFileFormat() );
		
		File[] files = directory.listFiles(new FileFilter() {
				public boolean accept(File f)
				{
					return f.getName().endsWith(mp.getFileFormat());
				}
			});
		for (int i = 0; i < files.length; i++)
		{
			checkFile(files[i], mp);
		}
	}
	
	private void checkFile(File f, MusicProfile mp)
	{
		try
		{
			ID3Tag tag = ID3Reader.readTag(new RandomAccessFile(f, "r"));
			if (match(mp.getArtist(), tag.getArtist()) &&
				match(mp.getSong(), tag.getTitle()) &&
				match(mp.getGenre(), tag.getGenreS()) &&
				match(mp.getMaxFileSize(), f.length()))
			{
				FileInfo response = new FileInfo(f.getName(), f.getCanonicalPath(), false);
				_appAPI.respondSearch(response);
			}
		}
		catch (Exception e)
		{
			System.err.println("Error occurred processing file " + f);
		}
	}
	
	private boolean match(String a, String b)
	{
		return a.trim().equals("") || b.trim().toUpperCase().indexOf(a.trim().toUpperCase()) != -1;
	}
	
	private boolean match(long a, long b)
	{
		return a == 0 || a >= b;
	}
	
    /**
     * Queues a previously searched file for download
     * @param a FileInfo object of the file that is to be downloaded
     */     public void startDownload(FileInfo aFileInfo)
    {
        //Add to download vector
        //Queue for download
        
        _files.add(aFileInfo);
        Downloader d = new Downloader(aFileInfo, peerNodes.netPeerGroup);
        return;
    } 
    /**
     * Retrieves a list of available nodes
     * @return a vector of NodeObject objects
     */                public Vector getAvailableNodes()
    {
        return(availableNodesVector);
    }    
     /**
     * Retrieves a list of available nodes
     * @return a vector of NodeObject objects
     */                public void setAvailableNodes(Vector aNodesVector)
    {
        availableNodesVector = aNodesVector;
        mainGUI.notifyPeerVectorChanged();
    }                  /**
     * Retrieves a list of files that are currently being uploaded
     * @return a vector of FileInfo objects
     */            public Vector getUploadFileVector()
    {
        return(null);
    }          /**
     * Retrieves a list of files that are currently being downloaded;
     * necessary when running in auto-drive mode and the gui was not
     * the download initiator.
     * @return a vector of FileInfo objects
     */            public Vector getDownloadFileVector()
    {
        return(null);
    }               /**
     * Retrieves a list of files that are currently paused
     * @return a vector of FileInfo objects
     * @deprecated Now paused status is returned as the state in the FileInfo objects
     *             of the download and upload vectors.
     */                public Vector getPausedFileVector()
    {
        return(null);
    }                /**
    * Cancels a file from being downloaded/uploaded
    * param aFileInfo - The file being cancelled
    */               public void cancelTranfer(FileInfo aFileInfo)
    {
        // Do appropriate work in the services layer to cancel download/upload         aFileInfo.setFileState(FileInfo.CANCELLED);
    }                 /**     * Places a file being downloaded/uploaded into a paused state
    * param aFileInfo - The file being paused
    */                public void pauseTransfer(FileInfo aFileInfo)
    {
        // Do appropriate work in the services layer to pause download/upload           aFileInfo.setFileState(FileInfo.PAUSED);
    }
}

⌨️ 快捷键说明

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