BitziPlugin.java
| Index Score | ||
|---|---|---|
![]() |
![]() |
org.xnap.plugin.bitzi |
![]() |
![]() |
XNap 3 |
View: Reasons, Metrics, Source Code
These are the metrics that contribute to the Enerjy Score for this file, ranked by impact. So the metrics listed at the top influence the score to a greater extent that the metrics listed at the bottom.
/*
* XNap - A P2P framework and client.
*
* See the file AUTHORS for copyright information.
*
* 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.
*
* 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 org.xnap.plugin.bitzi;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.Icon;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.SwingUtilities;
import net.n3.nanoxml.IXMLElement;
import net.n3.nanoxml.IXMLParser;
import net.n3.nanoxml.IXMLReader;
import net.n3.nanoxml.StdXMLReader;
import net.n3.nanoxml.XMLParserFactory;
import org.apache.log4j.Logger;
import org.xnap.XNap;
import org.xnap.gui.XNapFrame;
import org.xnap.gui.component.DefaultDialog;
import org.xnap.gui.util.GUIHelper;
import org.xnap.gui.viewer.Viewer;
import org.xnap.gui.viewer.ViewerManager;
import org.xnap.io.Library;
import org.xnap.io.MetaInfoFile;
import org.xnap.net.HttpConnection;
import org.xnap.plugin.AbstractPlugin;
import org.xnap.search.SearchResult;
import org.xnap.search.SearchResultActionProvider;
import org.xnap.util.AbstractPluginPreferences;
import com.bitzi.util.Base32;
//import com.limegroup.gnutella.UrnType;
//import com.limegroup.gnutella.util.IntWrapper;
/**
* BitziPlugin
*/
public class BitziPlugin extends AbstractPlugin
implements SearchResultActionProvider, Viewer {
private static final Logger logger = Logger.getLogger(BitziPlugin.class);
private static final String BITZI_BASE_URL = "http://ticket.bitzi.com/rdf/";
private JComponent viewerComponent;
static BitziPreferences bitziPrefs;
/**
* @see org.xnap.plugin.Plugin#start()
*/
public void start() throws Exception
{
// nothing to do.
}
/**
* @see org.xnap.plugin.Plugin#startGUI()
*/
public void startGUI()
{
bitziPrefs = new BitziPreferences();
XNapFrame.getInstance().getSearchPanel().registerActionProvider(this);
ViewerManager.getInstance().register(this);
}
/**
* @see org.xnap.plugin.Plugin#stop()
*/
public void stop()
{
// nothing to do.
}
/**
* @see org.xnap.plugin.Plugin#stopGUI()
*/
public void stopGUI()
{
ViewerManager.getInstance().unregister(this);
XNapFrame.getInstance().getSearchPanel().deregisterActionProvider(this);
BitziDialog.disposeInstance();
bitziPrefs = null;
}
private void lookup(SearchResult[] results)
{
for (int i = 0; i < results.length; i++) {
logger.debug("bitzi lookup for URN: "+ results[i].get("URN"));
BitziItemPanel panel = new BitziItemPanel();
panel.setFilename(results[i].getFilename());
String hash = (String)results[i].get(SearchResult.URN);
if (hash == null) {
hash = (String)results[i].get(SearchResult.SHA1);
}
LookupRunner runner = new LookupRunner(hash, panel);
BitziDialog.getInstance().add(panel);
Thread t = new Thread(runner, "BitziLookup");
t.start();
}
BitziDialog.getInstance().setVisible(true);
}
/**
* @see org.xnap.search.SearchResultActionProvider#getActions(org.xnap.search.SearchResult)
*/
public Action[] getActions(SearchResult[] results)
{
return new Action[] { new LookupAction(results) };
}
/**
* @see org.xnap.gui.viewer.Viewer#getIcon()
*/
public Icon getIcon()
{
return null;
}
/**
* @see org.xnap.gui.viewer.Viewer#getComponent()
*/
public JComponent getComponent()
{
if (viewerComponent == null) {
viewerComponent = new BitziItemPanel();
}
return viewerComponent;
}
/**
* @see org.xnap.gui.viewer.Viewer#getName()
*/
public String getName()
{
return XNap.tr("Bitzi Lookup");
}
/**
* @see org.xnap.gui.viewer.Viewer#open(java.io.File)
*/
public void open(File file)
{
BitziItemPanel panel = (BitziItemPanel)getComponent();
panel.setFilename(file.getName());
LookupRunner runner = new LookupRunner(file, panel);
Thread t = new Thread(runner, "BitziLookup");
t.start();
}
/**
* @see org.xnap.gui.viewer.Viewer#close()
*/
public void close()
{
}
private static class BitziDialog extends DefaultDialog
{
private JLabel content;
private JPanel lookups;
private static BitziDialog instance;
private BitziDialog()
{
super(DefaultDialog.BUTTON_CLOSE, true);
setTitle(XNap.tr("Bitzi Lookup"));
content = new JLabel();
lookups = new JPanel();
lookups.setLayout(new BoxLayout(lookups, BoxLayout.Y_AXIS));
lookups.setBorder(GUIHelper.createEmptyBorder(10));
lookups.setBackground(Color.white);
JScrollPane jsp = new JScrollPane(lookups);
jsp.getVerticalScrollBar().setUnitIncrement(25);
setMainComponent(jsp);
pack();
}
/**
*
*/
public static void disposeInstance()
{
if (instance != null) {
bitziPrefs.set("dialogWidth", instance.getWidth());
bitziPrefs.set("dialogHeight", instance.getHeight());
bitziPrefs.set("dialogX", instance.getX());
bitziPrefs.set("dialogY", instance.getY());
instance.dispose();
instance = null;
}
}
public static BitziDialog getInstance()
{
if (instance == null) {
instance = new BitziDialog();
instance.setSize(bitziPrefs.getInt("dialogWidth"),
bitziPrefs.getInt("dialogHeight"));
instance.setLocation(bitziPrefs.getInt("dialogX"),
bitziPrefs.getInt("dialogY"));
instance.setLocationRelativeTo(XNapFrame.getInstance());
}
return instance;
}
public void add(BitziItemPanel panel)
{
lookups.add(Box.createVerticalStrut(10), 0);
lookups.add(new JSeparator(), 0);
lookups.add(panel, 0);
}
public void addBitziInfo(final String filename, final IXMLElement bits)
{
SwingUtilities.invokeLater(new Runnable() {
public void run() {
add(new BitziItemPanel(filename, bits));
lookups.updateUI();
}
});
}
}
public class LookupAction extends AbstractAction
{
private SearchResult[] results;
public LookupAction(SearchResult[] results)
{
this.results = results;
putValue(Action.NAME, XNap.tr("Bitzi Lookup"));
putValue(Action.SHORT_DESCRIPTION,
XNap.tr("Looks up meta data."));
boolean enabled = false;
for (int i = 0; i < results.length; i++) {
enabled |= (results[i].get(SearchResult.URN) != null
|| results[i].get(SearchResult.SHA1) != null);
}
setEnabled(enabled);
}
public void actionPerformed(ActionEvent event)
{
lookup(results);
}
}
private static class BitziPreferences extends AbstractPluginPreferences {
public static final int VERSION = 1;
public BitziPreferences()
{
super("plugin.bitzi", VERSION);
setDefault("dialogHeight", "400");
setDefault("dialogWidth", "400");
setDefault("dialogX", "50");
setDefault("dialogY", "50");
}
}
private class LookupRunner implements Runnable {
private BitziItemPanel monitor;
private String hash;
private File file;
public LookupRunner(String hash, BitziItemPanel monitor)
{
if (hash == null) {
throw new IllegalArgumentException("Hash must not be null.");
}
this.hash = hash;
this.monitor = monitor;
}
public LookupRunner(File file, BitziItemPanel monitor)
{
if (file == null) {
throw new IllegalArgumentException("File must not be null.");
}
this.file = file;
this.monitor = monitor;
}
public void run()
{
if (hash == null) {
// lookup in library
MetaInfoFile libraryFile = Library.getInstance().get(file);
if (libraryFile != null) {
Object urn = libraryFile.get(SearchResult.URN);
if (urn instanceof String) {
this.hash = (String)urn;
}
}
if (hash == null) {
try {
// create hash from file
hash = createSHA1String(file);
}
catch (Exception e) {
logger.debug("Error while calculating hash", e);
return;
}
// save to library
if (libraryFile != null) {
libraryFile.put(SearchResult.URN, hash);
}
}
}
// connect to bitzi
final IXMLElement element = lookup(hash);
Runnable runner = new Runnable() {
public void run() {
monitor.setBitziInfo(element);
monitor.updateUI();
}
};
SwingUtilities.invokeLater(runner);
}
/**
* Create a new SHA1 hash string for the specified file on disk.
*
* @param file the file to construct the hash from
* @return the SHA1 hash string
* @throws <tt>IOException</tt> if there is an error creating the hash
* or if the specified algorithm cannot be found
* @throws <tt>InterruptedException</tt> if the calling thread was
* interrupted while hashing. (This method can take a while to
* execute.)
*/
private String createSHA1String(final File file)
throws IOException, InterruptedException {
FileInputStream fis = new FileInputStream(file);
// we can only calculate SHA1 for now
MessageDigest md = null;
try {
md = MessageDigest.getInstance("SHA");
} catch(NoSuchAlgorithmException e) {
throw new IOException("NO SUCH ALGORITHM");
}
try {
byte[] buffer = new byte[16384];
int read;
while ((read=fis.read(buffer))!=-1) {
long start = System.currentTimeMillis();
md.update(buffer,0,read);
long end = System.currentTimeMillis();
long interval = Math.max(0, end-start); //ensure non-negative
Thread.sleep(interval*2); //throws InterruptedException
}
} finally {
fis.close();
}
byte[] sha1 = md.digest();
// preferred casing: lowercase "urn:sha1:", uppercase encoded value
// note that all URNs are case-insensitive for the "urn:<type>:" part,
// but some MAY be case-sensitive thereafter (SHA1/Base32 is case
// insensitive)
return "urn:"+"sha1:"+Base32.encode(sha1);
}
private IXMLElement lookup(String hash)
{
HttpConnection conn = new HttpConnection();
IXMLElement xml = null;
try {
conn.connect(BITZI_BASE_URL + hash);
InputStream in = conn.getInputStream();
IXMLParser parser = XMLParserFactory.createDefaultXMLParser();
IXMLReader reader = new StdXMLReader(in);
parser.setReader(reader);
xml = (IXMLElement)parser.parse();
} catch (Exception e) {
logger.debug("Could not fetch meta data.", e);
} finally {
conn.close();
}
return xml;
}
}
}
The table below shows all metrics for BitziPlugin.java.




