PK wC8 META-INF/PK vC8_ivMETA-INF/MANIFEST.MFManifest-Version: 1.0 Ant-Version: Apache Ant 1.6.5 Created-By: 1.6.0_02-b06 (Sun Microsystems Inc.) Main-Class: BJTorrent.GUI.Principal Class-Path: X-COMMENT: Main-Class will be added automatically by build PK wC8 BJTorrent/PK wC8BJTorrent/ConexionServer/PK wC8BJTorrent/ControlDescarga/PK wC8BJTorrent/FicheroTorrent/PK wC8BJTorrent/GUI/PK wC8BJTorrent/GUI/iconos/PK wC8BJTorrent/GUI/properties/PK wC8BJTorrent/P2P/PK vC8BJTorrent/Tracker/PK wC8BJTorrent/Traker/PK vC8z{P= = -BJTorrent/ConexionServer/ConexionServer.class2 'V &W &X &YZ V &[\ ] &^ &_` ab Vc d e f gh i &j &kl mnop q rO s &tu vwxy server_socketLjava/net/ServerSocket;runZpuertoI escuchadores%Ljavax/swing/event/EventListenerList;()VCodeLineNumberTableLocalVariableTablethis)LBJTorrent/ConexionServer/ConexionServer;conectar(I)ZioeLjava/io/IOException; StackMapTable`pararie Ljava/lang/InterruptedException;b[BAncreaConexionServerEscuchador.(LBJTorrent/ControlDescarga/DownloadTorrent;)V escuchador+LBJTorrent/ControlDescarga/DownloadTorrent;leeConexionServerEscuchadores.()[LBJTorrent/ControlDescarga/DownloadTorrent;eliminaConexionServerEscuchadorlanzaConexionAceptada(Ljava/net/Socket;)V4LBJTorrent/ControlDescarga/ConexionServerEscuchador;arr$,[LBJTorrent/ControlDescarga/DownloadTorrent;len$i$sLjava/net/Socket; SourceFileConexionServer.java 01 () *+ ,-#javax/swing/event/EventListenerList ./java/net/ServerSocket 0z {| }1java/io/IOException ~1java/lang/StringBuilder0No se pudo cerrar el socket daemon por el puerto    KL Error en ConexionServer: java/lang/InterruptedExceptionCerrado el socket daemon)BJTorrent/ControlDescarga/DownloadTorrent HIAceptada Conexion por puerto  L'BJTorrent/ConexionServer/ConexionServerjava/lang/Thread(I)V setDaemon(Z)Vstartcloseappend-(Ljava/lang/String;)Ljava/lang/StringBuilder;(I)Ljava/lang/StringBuilder;toString()Ljava/lang/String;BJTorrent/Salidaescribe(Ljava/lang/String;)Vaccept()Ljava/net/Socket;sleep(J)V getMessageadd-(Ljava/lang/Class;Ljava/util/EventListener;)V getListeners-(Ljava/lang/Class;)[Ljava/util/EventListener;remove2BJTorrent/ControlDescarga/ConexionServerEscuchadorconexionAceptada!&'()*+,-./012]*****Y3-# %')14 56782**Y * * M 3;<=>?@A4 9:56,-;\<=12*** LY*  3HJ MKL)N49:*56;O<*12GL***!MY,M #  @3. WY [\ e#`$a=e@cAgFh4*$9:A>?G56C@A;BB<\CDE2D *+3 r s4 56 FGHI28* !3z4 56!JE2D *+"3  4 56 FGKL2?*#M,>60,2:Y$*+%б308>4>!FM9NO6P- 3Q-?56?RS;  !2TUPK wC8,BJTorrent/ConexionServer/ConexionServer.java/* * ConexionesServer.java * * Created on 18 de noviembre de 2007, 17:39 * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package BJTorrent.ConexionServer; import BJTorrent.ControlDescarga.DownloadTorrent; import BJTorrent.Salida; import BJTorrent.ControlDescarga.ConexionServerEscuchador; /** * * @author Benjamn Muiz Garca */ import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import javax.swing.event.EventListenerList; /** * * Subclase de Thread que acepta conexiones por el puerto indicado en VentanaPreferencias * y que cuando se conecta con un peer lanza un evento a la clase DownloadTorrent. * */ public class ConexionServer extends Thread{ //Socket servidor por el que aceptamos conexiones de peers private ServerSocket server_socket = null; //Atributo que indica si el hilo debe seguir ejecutndose private boolean run = true; //Nmero de puerto por el que escucha y acepta conexiones el socker servidor. private int puerto=0; //Lista de objetos que esperan eventos private final EventListenerList escuchadores = new EventListenerList(); /** * Crea una nueva instancia de ConexionServer */ public ConexionServer() { } /** * Crea el socket servidor por el puerto pasado como argumento y arranca la ejecucin del hilo. * @param puerto int Nmero de puerto por el se crea el socket servidor que escucha */ public boolean conectar(int puerto){ try { this.puerto=puerto; this.server_socket = new ServerSocket(puerto); this.setDaemon(true); this.start(); return true; } catch (IOException ioe) {} return false; } /** * * Mtodo que para el hilo y cierra el socket del servidor */ public void parar() { this.run=false; try{ this.server_socket.close(); } catch (IOException ioe){ Salida.escribe("No se pudo cerrar el socket daemon por el puerto"+this.puerto); } } /** * * Mientras corre el hilo acepta conexiones, cada vez que es aceptada una conexin * con un peer se llama al mtodo lanzaConexionAceptada() * */ public void run() { byte[] b = new byte[0]; try { while (this.run==true) { this.lanzaConexionAceptada(this.server_socket.accept()); sleep(1000); } } catch (IOException ioe) { Salida.escribe("Error en ConexionServer: "+ioe.getMessage()); } catch(InterruptedException ie){ } Salida.escribe("Cerrado el socket daemon"); } /** * * Guarda un objeto de la clase DonwloadTorrent en la lista de escuchadores que esperan * un evento. * @param escuchador DownloadTorrent Objeto que almacenamos en la lista de escuchadores */ public void creaConexionServerEscuchador(DownloadTorrent escuchador) { escuchadores.add(DownloadTorrent.class, escuchador); } /** * * Devuelve la lista de escuchadores que son objetos DownloadTorrent que esperan un evento. * @return DownloadTorrent[] Objetos de la clase DownloadTorrrent que llamarn al mtodo creaConexinServerEscuchador. */ public DownloadTorrent[] leeConexionServerEscuchadores() { return escuchadores.getListeners(DownloadTorrent.class); } /** * * Quita un objeto de la lista de escuchadores de esta instancia de ConexionServer * @param escuchador DownloadTorrent Objeto a ser eliminado de la lista de escuchadores * */ public synchronized void eliminaConexionServerEscuchador(DownloadTorrent escuchador) { escuchadores.remove(DownloadTorrent.class, escuchador); } /** * * Mtodo que llama al mtodo conexionAceptada() de los objetos la clase DownloadTorrent * almacenados en la lista de escuchadores. * @param s Socket conectado al peer remoto */ public void lanzaConexionAceptada(Socket s){ for (ConexionServerEscuchador escuchador : leeConexionServerEscuchadores()) { //Salida.escribeVentana("Aceptada Conexion por puerto "+this.puerto); Salida.escribe("Aceptada Conexion por puerto "+this.puerto); escuchador.conexionAceptada(s); } } }PK wC8~BJTorrent/Constantes.class2r UVWXYZ[\]^_`abcdef g hi jklDEBUGZ ConstantValueERRORICHOKEUNCHOKE INTERESTEDNOT_INTERESTEDHAVEBITFIELDREQUESTPIECECANCEL KEEP_ALIVE  PEER_CON_COLAd PEER_SIN_COLAeHAVE_ALL HAVE_NONE SUGGEST_PIECE REJECT_REQUEST ALLOWED_FASTMENSAJE[Ljava/lang/String; TAM_BLOQUE@BYTES_TAM_BLOQUE[BPROGRAMALjava/lang/String;mVERSIONn()VCodeLineNumberTableLocalVariableTablethisLBJTorrent/Constantes; SourceFileConstantes.java KLjava/lang/String Choke/BANNED Unchoke/UNBAN Interesado No_Interesado Have/TengoBitfieldPeticion BloqueTransmitiendo BloqueCancelar Peticion Keep_Alive Suggest PieceHave ALL Have NONEReject Request Allowed Fast @Ao pq DEBJTorrent/Constantesjava/lang/ObjectBJBT0.3.0.0BJTorrent/UtilsintToByteArray(I)[B! !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIGJKLM/*NO PQRLMxYSYSYSYSYSYSY SY SY SY  SY  SY  SY  SY SYSYSYSYS@N <nESTPK wC8RՌ BJTorrent/Constantes.java/* * ProtocoloPeers.java * * Created on 1 de noviembre de 2007, 16:08 * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ /** * * @author Benjamn Muiz Garca */ package BJTorrent; /** * * Declara constantes usadas en el programa, como el nmero entero y cadena de caracteres * que sirve para identificar cada mensaje del protocolo, el tamao del bloque en bytes, etc... * * */ public class Constantes { public static final boolean DEBUG = true; public static final int ERROR = -1; public static final int CHOKE = 0; public static final int UNCHOKE = 1; public static final int INTERESTED = 2; public static final int NOT_INTERESTED = 3; public static final int HAVE = 4; public static final int BITFIELD = 5; public static final int REQUEST = 6; public static final int PIECE = 7; public static final int CANCEL = 8; public static final int KEEP_ALIVE = 9; //indica que el peer puede almacenar varias peticiones de bloques y podemos pedir //un bloque sin haber recibido el anterior. public static final int PEER_CON_COLA = 100; //indica que el peer no tiene cola y no recuerda las peticiones por lo que //slo podemos pedirle un bloque de cada vez public static final int PEER_SIN_COLA = 101; //Have All: public static final int HAVE_ALL = 0x0E; //Have None: public static final int HAVE_NONE = 0x0F; //Suggest Piece: public static final int SUGGEST_PIECE = 0x0D; //Reject Request: public static final int REJECT_REQUEST = 0x10; //Allowed Fast: public static final int ALLOWED_FAST = 0x11; public static final String[] MENSAJE = {"Choke/BANNED", "Unchoke/UNBAN", "Interesado", "No_Interesado", "Have/Tengo", "Bitfield", "Peticion Bloque", "Transmitiendo Bloque", "Cancelar Peticion", "Keep_Alive","","","","Suggest Piece","Have ALL", "Have NONE","Reject Request","Allowed Fast"}; //Tamo en bytes de cada bloque que compone una pieza public static final int TAM_BLOQUE = 16384; public static final byte[] BYTES_TAM_BLOQUE = Utils.intToByteArray(16384); public static final String PROGRAMA = "BJBT"; public static final String VERSION = "0.3.0.0"; } PK vC8m8BJTorrent/ControlDescarga/ConexionServerEscuchador.class2   conexionAceptada(Ljava/net/Socket;)V SourceFileConexionServerEscuchador.java2BJTorrent/ControlDescarga/ConexionServerEscuchadorjava/lang/Objectjava/util/EventListenerPK wC8'q>7BJTorrent/ControlDescarga/ConexionServerEscuchador.java/* * ConexionesServerEscuchador.java * * Created on 18 de noviembre de 2007, 17:48 * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package BJTorrent.ControlDescarga; import BJTorrent.ConexionServer.ConexionServer; /** * * @author Benjamn Muiz Garca */ import java.util.EventListener; import java.net.Socket; /** * Interface implementado en la clase DownloadTorrent */ public interface ConexionServerEscuchador extends EventListener{ /** * * Evento que nos informa que el socket servidor * acept una conexin de un peer, lanzado por un objeto ConexionServer. * @param s Socket conectado al peer */ public void conexionAceptada(Socket s); }PK vC8ƌ@@/BJTorrent/ControlDescarga/DownloadTorrent.class2                                $  '                7           7 D  7 D D 7 '     R D D $  ' $,  a a ] a  g  g g $ T'  '         ~   i       7    R ] ] ] ] R    !  " ]#$ %&' ( ) *e + ,  %   -. / 0 1 23 456 27 a8 ]9:;< = > ? @ gABCD ]EF ZF ]GHI@Y JK ZLM ]N O P Q ]R 'ST 'UVWXY ListaPiezas[LBJTorrent/Pieza; id_cliente[Btorrente*LBJTorrent/FicheroTorrent/FicheroTorrente; num_piezasI tam_piezatrackerLBJTorrent/Tracker/Tracker; ListaTrackersLjava/util/LinkedList; Signature*Ljava/util/LinkedList;intervalo_trackertracker_elegidoLjava/lang/String; infohashURL num_ficheroslongitudJfaltanbajadosbajados_sesionsubidos ListaPeersLjava/util/LinkedHashMap;=Ljava/util/LinkedHashMap;tam_ultima_piezaFicheroCompletado(Ljava/util/LinkedList;PeersDisponiblesLjava/util/TreeMap;@Ljava/util/TreeMap; peersdownloadpeersnointeresados peerschocked ListaChocked1Ljava/util/LinkedList;unchokeoptimistarunZparandosumaDLDsumaULsemillasclientessalidaLBJTorrent/Salida;prefs#LBJTorrent/GUI/VentanaPreferencias;conexLBJTorrent/P2P/Conexion; KBenviados KBrecibidos KBpedidostiempoULlimiteULlimiteDLpath proxyhost proxypuertopuerto handshakeLBJTorrent/Handshake; escuchadores%Ljavax/swing/event/EventListenerList;Y([BLBJTorrent/FicheroTorrent/FicheroTorrente;[LBJTorrent/Pieza;Ljava/util/LinkedList;JJ)VCodeLineNumberTableLocalVariableTablethis+LBJTorrent/ControlDescarga/DownloadTorrent;torrentLocalVariableTypeTablek([BLBJTorrent/FicheroTorrent/FicheroTorrente;[LBJTorrent/Pieza;Ljava/util/LinkedList;JJ)V pararDownload()VeLjava/lang/Exception;cpLBJTorrent/P2P/Protocolo;itLjava/util/Iterator;b lconexionesLjava/util/List;+Ljava/util/List; StackMapTableWZ[actualizaIntervaloTracker(I)V intervaloactualizaListaPeers.(Ljava/util/LinkedHashMap;Ljava/lang/String;)VpLBJTorrent/Peer;listatrackerElegido conexiones peerstring(Ljava/util/Iterator;ie Ljava/lang/InterruptedException;ioeLjava/io/IOException; primeravez unchokePeers peerschokediunchokeOptimistadownloadCompleto()Z leeFaltan()J leeSubidosleeBajadosSesioncreaEscuchador"(LBJTorrent/GUI/VentanaDownload;)V escuchadorLBJTorrent/GUI/VentanaDownload;eliminaEscuchadorleeEscuchadores"()[LBJTorrent/GUI/VentanaDownload;actualizaTablasGUIY([[Ljava/lang/String;IJJLjava/util/LinkedList;Ljava/util/LinkedList;Ljava/lang/String;I)Varr$ [LBJTorrent/GUI/VentanaDownload;len$i$cadenas[[Ljava/lang/String;num_cad fichcompleto fichlongitudintervaloTrackeractualizaFicheroCompletadokauxLjava/lang/Long;pieza faltanleerleidosposbuff ficheroleidos[JposicionposfichjwconexionAceptada(Ljava/net/Socket;)VsocketLjava/net/Socket;idcreaTorrenteAbiertoEscuchador(LBJTorrent/GUI/Principal;)VLBJTorrent/GUI/Principal; eliminaTorrenteAbiertoEscuchadorleeTorrenteAbiertoEscuchadores()[LBJTorrent/GUI/Principal;actualizaVelocidadesactualizaTorrenteAbierto[LBJTorrent/GUI/Principal; recibidaPieza enviadoBloquetamconexionActiva.(Ljava/lang/String;LBJTorrent/P2P/Protocolo;)V conexionFin(Ljava/lang/String;)V SourceFileDownloadTorrent.java )  java/util/LinkedList        !BJTorrent/GUI/VentanaPreferencias     #javax/swing/event/EventListenerList  java/util/LinkedHashMap java/util/TreeMap \ ]^ _^ `a bX cd ef g^BJTorrent/Salida h    if j^  k^  lf m^ n^ BJTorrent/Tracker/Tracker op q r st u)Parando Torrente vw xy zZ {|[ }V ~BJTorrent/P2P/Protocolo )java/lang/ExceptionProblema parando hilo Protocolo  java/lang/String  BJTorrent/Peer java/lang/StringBuilderLanzado  fBJTorrent/P2P/Conexion    t Error lanzando conexiones Terminamos de esperar 10 segs f ^)TORRENTE PARADO - Todos los peers parados Q) ) )    X java/lang/InterruptedExceptionError en run() DownloadTorrent UVDescarga completada  bc ) )java/io/IOException%No se pudo Cerrar el fichero de traza v3BJTorrent/ControlDescarga/VelocidadSubidaComparador 3BJTorrent/ControlDescarga/VelocidadBajadaComparador @A V V V   <   T)  f unchoke optimista VBJTorrent/GUI/VentanaDownload     `a java/lang/Long ^    f: ^  Pendiente conexion con peer  por el puerto BJTorrent/Handshake     Aceptada conexion con peer HANDSHAKE fallido con el peer BJTorrent/GUI/Principal    Total:    Kb/seg V   n< <%Llegamos a añadir el peer disponibleConexion fin- final &Llegamos a eliminar el peer disponible)BJTorrent/ControlDescarga/DownloadTorrentjava/lang/Thread2BJTorrent/ControlDescarga/ConexionServerEscuchadorjava/util/Listjava/util/Iterator(BJTorrent/FicheroTorrent/FicheroTorrente leeNumPiezas()I leeTamPieza leeLongitud()Ljava/lang/Long; longValue leeTrackers()Ljava/util/LinkedList;leeInfoHashURL()Ljava/lang/String;leeNumFicherosnombrelee_directorioCompartidoleeLimiteVelocidadULleeLimiteVelocidadDL leeProxySOCKSleeProxySOCKSPuerto leePuertotrazaLjava/io/BufferedWriter;H(Ljava/util/LinkedList;[BLjava/lang/String;JJJLjava/io/BufferedWriter;)VescribeVentanacreaTrackerEscuchador.(LBJTorrent/ControlDescarga/DownloadTorrent;)Vstartescribe-(Ljava/lang/String;Ljava/io/BufferedWriter;)Vvalues()Ljava/util/Collection;(Ljava/util/Collection;)Viterator()Ljava/util/Iterator;hasNextnext()Ljava/lang/Object;pararstopkeySet()Ljava/util/Set; java/util/Set containsKey(Ljava/lang/Object;)Zget&(Ljava/lang/Object;)Ljava/lang/Object;sleep(J)Vappend-(Ljava/lang/String;)Ljava/lang/StringBuilder;toString info_hash(LBJTorrent/Peer;[B[BLBJTorrent/FicheroTorrent/FicheroTorrente;[LBJTorrent/Pieza;Ljava/io/BufferedWriter;Ljava/lang/String;Ljava/lang/String;I)VcreaConexionEscuchadorput8(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;getNamesizejava/lang/SystemcurrentTimeMillisListaLongitudesjava/io/BufferedWriterflushclosejava/util/Collectionssort)(Ljava/util/List;Ljava/util/Comparator;)Vlee_hecho_Bitfieldlee_El_Interesado lee_El_Chokedpon_El_Chocked(Z)VenviaLBJTorrent/P2P/EnviarMensaje;BJTorrent/P2P/EnviarMensajeescribeMensajecontainsadd removeFirst leeIdClienteBJTorrent/Pieza leeCompleta-(Ljava/lang/Class;Ljava/util/EventListener;)Vremove getListeners-(Ljava/lang/Class;)[Ljava/util/EventListener;getListenerCount(Ljava/lang/Class;)I(I)Ljava/lang/Object;intValuevalueOf(J)Ljava/lang/Long;set'(ILjava/lang/Object;)Ljava/lang/Object;java/net/SocketgetInetAddress()Ljava/net/InetAddress;java/net/InetAddressgetHostAddressgetPort(I)Ljava/lang/StringBuilder;(Ljava/lang/String;I)V<(LBJTorrent/Peer;Ljava/net/Socket;Ljava/io/BufferedWriter;)V leeHandShake([B[B)ZescribeHandShake([B[B)V(LBJTorrent/Peer;Ljava/net/Socket;[B[BLBJTorrent/FicheroTorrent/FicheroTorrente;[LBJTorrent/Pieza;Ljava/io/BufferedWriter;Ljava/lang/String;LBJTorrent/Handshake;)VleeVelocidadUL(Z)F(F)Ljava/lang/String;leeVelocidadDLjava/lang/Mathround(D)J(D)Ljava/lang/String; esSemillaactualizaTorrrenteAbiertoD(Ljava/lang/String;JJJDDII[LBJTorrent/Pieza;Ljava/util/LinkedList;)VescribeListaHave!.             **x**** * * * * * * ***Y********Y***8* Y!"*+#*$Y%&*'Y()*,**,+,*,-.*,/0*,12*,3*-4*5* **,6*7Y**89:**W;*W*W<=*W*W>?**W@**WA**WBC*DY*2+** * *:EFG*:W*H*G*I*GJ!5C EGJL N%P*R/T4]9g>iCkHmSoXq]sbugwlyq{v '4AMYe"H#$%& '() NjLK*:ELY*)MNN-O:P&QRM,S:U*:EL*GV*GW*<@CT!. 1<@T\di">E *+<,-'-./j#$f0K12& K134@'567856978:567!;< >*! "#$=!>?  *,>:+XY:PQZ:*)[+\]:*W^`aYbcdedf*:EL*gY*#**h***4*:E***ij*j*k*jl*&emW&:aYbndodf*:EL3CT!J+,- . 0,384C7K:l;<=>C@AFK"R!*+C@A./#$BCD E& .F4/G85HGG8I:")  <**Wp`aYbrd*sdf*:EL**)t*u*:EL*v*w*xyz{|}*Y d$MaYbd,df*:EL*^ZH6Y*)MN:*YYO:PQR::T&* *W*Y`E*YZd **!!  /;NZailq|"\ Z,-a@AD./#$R S12& 134N /57 8' 59I782" 57T) Q*I*RL+6++aYb+ddf*:EL+!" !)LP";,-Q#$4  A9UV t <*,*42! "S #$4 WX /*!" #$YX /* ! " #$ZX /* !" #$[\ D *"+!  " #$ ]^_\ D *"+! ' )" #$ ]^`a 8*"!1" #$bc  C*"*:  6 6   "  2:+!  ݱ!E FH*J<HBP" *]^.de )f &g C#$ChiCjCCCkClCC Cm 4 %!n< C *42=>6** :**h776 ** +** e77 P  6  **J P** d>  P Pd= 7  6  **5*5 0 /a: *5  W P ű!zZ [ \]^&_*`-bFc^dbehgnj~knoqsvxz|}j"z rSo pq >o #$r s tuvw&x*y-z 4)- 5{@7=!|} # *aYb+dd+fM*),[T]Y++NaYbd-edd+f*:EL*Y-+*:E**#**h**#**h*&-e-mW*gY-+*#**h***4*:E**j*j*k*jlaYbd-edd*WBfHaYbd-edd*WBf*:EL3aYbd-edd*WBf*:EL!F)4Gs"U"*G>@A#$~)]4LGI/ D *"+!  " #$ ] D *"+!  " #$ ] 8*"!" #$)  }*)t`L6Y*)MN:*YY**O:PsQRM,N+2-S+2-eS+2-nS+2-nS*Y-nc*Y-nc+2S+2S**k**Ɋo**k**Ɋo+2aYb*ʶd˶dfS+2aYb*ʶd˶dfS*+* * *5****!v")8DINalq{ 8WZ | "Hle,-q`@AWz./}#$nhikS"[12& "[134857 8y) Y*)MNM**,ON-P2-QRL+*Y`*Y`>*:66@2:**8** * *****4*5΄!6 )3>KX!Z#v$#*"\ 3%,- 8./v0]`LdeGfhDg#$12ZSS& 134D 78*5978 5757C!< %z*Y *42a *Y *42a *Y*42e*ϻY*)MNN-O:PQRM,:Ч߱!. 56&799>>MA_BjCpDvGyJ">p@Aj,-U$./z#$zrM-12& M-134U78#!< D *Y a ! Q R" #$  u"*)+[ *)+,W*:EL!^ _a!c" "#$"",-4 z-*:EL*)+[*)+W*:EL!l no p,s"-#$-4,) 5yz{ }! PK wC8kzbb.BJTorrent/ControlDescarga/DownloadTorrent.java/* * DownloadTorrent.java * * Created on 16 de noviembre de 2007, 14:35 * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package BJTorrent.ControlDescarga; import BJTorrent.Peer; import BJTorrent.Pieza; import BJTorrent.Handshake; import BJTorrent.Salida; import BJTorrent.Constantes; import BJTorrent.GUI.VentanaPreferencias; import BJTorrent.GUI.Principal; import BJTorrent.GUI.VentanaDownload; import BJTorrent.ConexionServer.ConexionServer; import BJTorrent.FicheroTorrent.FicheroTorrente; import BJTorrent.Tracker.Tracker; import BJTorrent.P2P.Conexion; import BJTorrent.P2P.Protocolo; /** * * @author Benjamn Muiz Garca */ import java.util.BitSet; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.io.IOException; import java.util.Iterator; import java.util.Collections; import java.util.TreeMap; import java.security.MessageDigest; import java.net.Socket; import javax.swing.event.EventListenerList; import java.io.DataInputStream; import java.io.DataOutputStream; import java.net.Socket; /** * Clase que maneja los peers devueltos por el tracker creando un hilo conexin para cada peer * , tambin cada cierto intervalo actualiza el interfaz de la ventana principal y VentanaDownload. * */ public class DownloadTorrent extends Thread implements ConexionServerEscuchador{ //Array de piezas que componen el torrente public Pieza[] ListaPiezas; //ID de nuestro cliente generada al arrancar la aplicacin private byte[] id_cliente; //Objeto que almacena la informacin del fichero .torrent private FicheroTorrente torrente; //Nmero de piezas que componen el torrente private int num_piezas; //Tamao de la pieza excepto la ltima private int tam_pieza; //Hilo del tracker private Tracker tracker; //Lista de Trackers private LinkedList ListaTrackers; //Segundos de intervalo entre actualizaciones con el tracker private int intervalo_tracker=2 * 60; //IP o dominio del Tracker private String tracker_elegido=""; //Hash SHA1 del torrente en codificacin URL private String infohashURL=""; //Nmero de ficheros del torrente private int num_ficheros = 0; //tamao total en bytes del torrente private long longitud = 0; //Nmero de bytes que faltan para completar el download private long faltan = 0; //Nmero de bytes descargados de otros peer en este torrente private long bajados=0; //Nmero de bytes bajados de otros peer en esta descarga o sesin private long bajados_sesion=0; //Nmero de bytes subidos a otros peer en esta descarga o sesin private long subidos=0; //Mapa que almacena los peers devueltos por el Tracker private LinkedHashMap ListaPeers; //Tamao de la ultima pieza private int tam_ultima_pieza=0; //Lista con el nmero de bytes descargados de cada fichero del torrente private LinkedList FicheroCompletado; //Mapa con los PeersDisponibles, peers con los que estamos conectados private TreeMap PeersDisponibles; //Nmero de peers que estn descargando de nuestro cliente en este torrente private int peersdownload=0; //Nmero de peers que no interesados en nuestras piezas de nuestro cliente en este torrente private int peersnointeresados=0; //Nmero de peers que tenemos CHOKE. Cade 30 segundos hacemos un UNCHOKE optimista a un peer, eso si tenemos mas de 4 peers downloaders private int peerschocked=0; //peers downloaders que tenemos CHOKE private LinkedList ListaChocked = new LinkedList(); //indica el intervalo entre un UNCHOKE optimista cuando tenemos ms downloaders de los permitidos. private int unchokeoptimista = 3; //Indica si este objeto sigue ejecutndose public boolean run=true; //Indica que se quiere parar el download, este hilo private boolean parando=false; //Suma de la velocidades de download de todos los peers private double sumaDL=0; //Suma de la velocidades de upload de todos los peers private double sumaUL=0; //Nmero de semillas del torrente private int semillas=0; //Nmero de cliente del torrente private int clientes=0; //Fichero por el que escribimos la traza de ejecucin del programa private Salida salida; private VentanaPreferencias prefs=new VentanaPreferencias(); //Objeto con el que instanciamos hilos Conexion para cada peer private Conexion conex; //Nmero de KB enviados mientras el atributo tiempoUL no supera un cierto lmite de tiempo. public static int KBenviados=0; //Nmero de KB recibidos para comprobar el limite de velocidad de bajada de la aplicacin. public static int KBrecibidos=0; //Nmero de KB pedidos con el mensaje REQUESTS nunca rebasa el limiteDL, para fijar el limte maximo de download public static int KBpedidos=0; //Tiempo en el que medimos la velocidad de Upload, antes de poner el atributo KBenviados a cero. public static long tiempoUL=0; //Velocidad mxima de Upload establecida en VentanaPreferencias public static int limiteUL; //Velocidad mxima de Download establecida en VentanaPreferencias public static int limiteDL; //ruta o path desde donde almacenamos los ficheros que componen el torrente private String path=""; //IP o nombre del host que hace como proxy private String proxyhost=""; //Nmero de puerto SOCKS del proxy private int proxypuerto=1080; //Puerto de VentanaPreferencias por el que aceptamos conexiones private int puerto; //Objeto con el que se realiza el handshake con el peer remoto, cuando se acepta una conexin por el socket servidor. Handshake handshake; //Lista de objetos que esperan eventos private final EventListenerList escuchadores = new EventListenerList(); /** * Crea una nueva instancia de DownloadTorrent. * Almacena las preferencias de VentanaPreferencias en atributos del objeto. * Arranca el hilo que se anuncia con el tracker. * @param id_cliente byte ID con el cdigo el programa versin. * @param torrent FicheroTorrente Objeto que almacena los datos del fichero METAINFO .torrent * @param ListaPiezas Pieza[] Array con las piezas del torrente * @param FicheroCompletado LinkedList * @param faltan long Nmero de bytes que faltan para completar el download * @param bajados long Nmero de bytes bajados de otros peer en este torrente */ public DownloadTorrent(byte[] id_cliente, FicheroTorrente torrent,Pieza[] ListaPiezas, LinkedList FicheroCompletado,long faltan,long bajados){ this.id_cliente = id_cliente; this.ListaPeers =new LinkedHashMap(); this.PeersDisponibles = new TreeMap (); this.torrente=torrent; this.num_piezas = torrent.leeNumPiezas(); this.tam_pieza=torrent.leeTamPieza(); this.longitud=torrent.leeLongitud(); this.ListaTrackers=torrent.leeTrackers(); this.infohashURL=torrent.leeInfoHashURL(); // this.faltan = this.longitud; //this.ListaPiezas = new Pieza[this.num_piezas]; this.ListaPiezas = ListaPiezas; this.FicheroCompletado=FicheroCompletado; this.bajados=bajados; this.faltan=faltan; this.num_ficheros = torrent.leeNumFicheros(); this.salida= new Salida(this.torrente.nombre); this.path=prefs.lee_directorioCompartido(); this.limiteUL=prefs.leeLimiteVelocidadUL(); this.limiteDL=prefs.leeLimiteVelocidadDL(); this.proxyhost=prefs.leeProxySOCKS(); this.proxypuerto=prefs.leeProxySOCKSPuerto(); this.puerto=prefs.leePuerto(); this.tracker=new Tracker(ListaTrackers,id_cliente,infohashURL,faltan,bajados_sesion,subidos,salida.traza); salida.escribeVentana(infohashURL); this.tracker.creaTrackerEscuchador(this); this.tracker.start(); } /** * Mtodo que para la ejecucin los hilos Protocolo que envan y reciben mensajes de los peers, * tambin para la ejecucin del hilo tracker y cierra el fichero de traza de este torrente. */ public void pararDownload(){ byte []b=new byte[0]; Salida.escribe("Parando Torrente",salida.traza); //anunciarse(this.trackerElegido, this.id_cliente,this.infohashURL,this.faltan,this.bajados,this.subidos,"&event=Stopped"); Protocolo cp; List lconexiones = new LinkedList(this.PeersDisponibles.values()); for (Iterator it = lconexiones.iterator();it.hasNext(); ) { cp = (Protocolo) it.next(); try{ cp.parar(); //Salida.escribe("Parando el hilo "+cp.getName(),salida.traza); } catch (Exception e) {Salida.escribe("Problema parando hilo Protocolo",salida.traza);} } //tracker.TrackerSTOPPEDCOMPLETED(this.id_cliente,this.infohashURL,this.faltan,this.bajados,this.subidos,"stopped"); tracker.stop=true; tracker.run=false; this.parando=true; //this.run=false; /*do { try{ this.sleep(1000); Salida.escribe("Esperamos 1 segundo antes de cerrar",salida.traza); } catch (InterruptedException ie){} } while(this.PeersDisponibles.size()>0); */ //this.PeersDisponibles=null; //this.ListaPeers=null; } /** * Almacena los segundos de intervalo entre actualizaciones con el Tracker * en un atributo de la clase. Mtodo invocado desde el objeto Tracker cuando el host tracker * nos responde positivamente. * @param intervalo int Segundos que deben pasar para actualizar el tracker. */ public synchronized void actualizaIntervaloTracker(int intervalo){ this.intervalo_tracker=intervalo; //en segundos } /** * * Mtodo invocado desde el objeto Tracker cuando un host Tracker responde * con la lista de peers del torrente. * @param lista LinkedHashMap Lista con los peers disponibles en el torrente * @param trackerElegido String Tracker que nos respondi */ public synchronized void actualizaListaPeers(LinkedHashMap lista,String trackerElegido) { this.tracker_elegido=trackerElegido; int conexiones=0; String peerstring=""; for (Iterator it = lista.keySet().iterator(); it.hasNext(); ) { peerstring = (String) it.next(); if (!this.PeersDisponibles.containsKey(peerstring)) { Peer p = (Peer) lista.get(peerstring); try{ this.sleep(300); // Salida.escribeVentana("Lanzado "+p.toString(),2); Salida.escribe("Lanzado "+p.toString(),salida.traza); conex=new Conexion(p,this.id_cliente,this.torrente.info_hash,this.torrente,this.ListaPiezas,salida.traza,this.path,this.proxyhost,this.proxypuerto); conex.creaConexionEscuchador(this); conex.start(); this.ListaPeers.put(p.toString(), p); } catch (Exception e) { Salida.escribe("Error lanzando conexiones "+e.toString(),salida.traza); //this.run=false; } }//fin if }//fin for //ultimaActualizacion=System.currentTimeMillis(); } /** * Mientras el hilo corre, cada 10 segundos hace unchoke de los peers y actualiza * el interfaz. Actualiza el componente JTable de la ventana Principal y * la ventana VentanaDownload del GUI. Llama a los mtodos unchokePeers(), actualizaVelocidades(), * y actualizaTorrenteAbierto(). * Mtodo sobre-escrito. */ public void run() { //byte[] b = new byte[0]; boolean primeravez=true; while (this.run) { //actualizamos Velocidades cado 10 segundos // Y damos CHOKE/UNCHOKE cada 10 try { this.sleep(10000); Salida.escribe("Terminamos de esperar 10 segs "+this.getName(),salida.traza); //synchronized (lock) { // lock.wait(10000); if (this.parando && this.PeersDisponibles.size()==0) { this.run=false; Salida.escribe("TORRENTE PARADO - Todos los peers parados",salida.traza); } unchokePeers(); actualizaVelocidades(); actualizaTorrenteAbierto(); KBenviados=0; KBrecibidos=0; KBpedidos=0; tiempoUL=System.currentTimeMillis();; intervalo_tracker-=10; //lock.notifyAll(); //} } catch (InterruptedException ie) { Salida.escribe("Error en run() DownloadTorrent"+ie.toString(),salida.traza); //this.run=false; } if (downloadCompleto() && primeravez) { // tracker.TrackerSTOPPEDCOMPLETED(this.id_cliente,this.infohashURL,this.faltan,this.bajados,this.subidos,"completed"); Salida.escribeVentana("Descarga completada"); primeravez=false; } }//fin while run actualizaTablasGUI(null,0,this.bajados,this.subidos,this.FicheroCompletado,this.torrente.ListaLongitudes,"",0); try{ salida.traza.flush(); salida.traza.close(); } catch(IOException ioe) { Salida.escribe("No se pudo Cerrar el fichero de traza"); } } /** * Pone UNCHOKE a los peers, y slo permite que tengamos 4 peers bajndose * piezas de nuestro cliente poniendo el resto de peers que bajan piezas a CHOKE. * Slo permite 4 peers downloaders quedndose con los que tienen mayor velocidad * de subida y al resto de downloaders los pone a CHOKE y los mete en la listaChoked. */ public void unchokePeers(){ int peersnointeresados = 0; int peersdownload = 0; int peerschoked = 0; Protocolo cp; Peer p; int i=0; //Salida.escribe("Enviando Unchokes cada 10 segundos\n\n\n"); List lconexiones = new LinkedList(this.PeersDisponibles.values()); if (downloadCompleto()) Collections.sort(lconexiones, new VelocidadSubidaComparador()); else Collections.sort(lconexiones, new VelocidadBajadaComparador()); //Iterator itp = lpeers.iterator(); for (Iterator it = lconexiones.iterator();it.hasNext(); ) { cp = (Protocolo) it.next(); p=(Peer) cp.p; if (!p.lee_hecho_Bitfield()) break; if (peersdownload < 4) { if (!cp.p.lee_El_Interesado()) { if (cp.p.lee_El_Choked()) { cp.p.pon_El_Chocked(false); cp.envia.escribeMensaje(Constantes.UNCHOKE); peersnointeresados++; } } else if (cp.p.lee_El_Choked()) { // this.Unchoke.put(p.toString(), p); cp.p.pon_El_Chocked(false); cp.envia.escribeMensaje(Constantes.UNCHOKE); peersdownload++; } } else { if (!cp.p.lee_El_Choked()) { cp.p.pon_El_Chocked(true); cp.envia.escribeMensaje(Constantes.CHOKE); } if (!this.ListaChocked.contains(cp)) this.ListaChocked.add(cp); peerschocked++; } } if (this.unchokeoptimista-- == 0) { this.unchokeOptimista(); this.unchokeoptimista = 3; } } /** * Cada 30 segundos hacemos un UNCHOKE optimista a un peer downloader de la listaChoked, * para ello tenemos que tener mas de 4 peers downloaders. */ private void unchokeOptimista() { if (this.ListaChocked.size()>0) { Protocolo cp; do { cp = this.ListaChocked.removeFirst(); if (cp!=null) { cp.envia.escribeMensaje(Constantes.UNCHOKE); cp.p.pon_El_Chocked(false); Salida.escribe(cp.p.leeIdCliente() + " unchoke optimista",salida.traza); } } while (cp==null); } } /** * Indica si se han descargado todas las piezas * @return boolean true si el torrente se ha descargado por completo y false si quedan * piezas por recibir. */ public boolean downloadCompleto(){ for (int i=0;i=this.torrente.ListaLongitudes.get(j).intValue()) { posicion=posicion -this.torrente.ListaLongitudes.get(j).intValue(); posfich=posicion; ficheroleidos[j]=0; j++; } for (int k = j; k < this.torrente.num_ficheros; k++) { ficheroleidos[k]=0; leidos=(int)this.torrente.ListaLongitudes.get(k).intValue()-(int)posfich; if (faltanleer<=leidos) { ficheroleidos[k]=faltanleer; break; } else { if (leidos<=0) break; ficheroleidos[k]=leidos; faltanleer=faltanleer-leidos; posfich=0; } } for (int k = j; k < this.torrente.num_ficheros; k++) { Long aux=this.FicheroCompletado.get(k)+ficheroleidos[k]; FicheroCompletado.set(k,aux); //Salida.escribe("Completado->"+FicheroCompletado[k]); ficheroleidos[k]=0; } } /** * Mtodo llamado por un objeto de la clase ConexionServer cuando el socket servidor * acepta una conexin de un peer. * Hacemos el handshake para comprobar que el peer comparte este torrente * y no otros que estemos descargando. Si hacemos correctamente el handshake el peer * remoto comparte este torrente y creamos el hilo conexin como si se tratase * de un peer devuelto por el tracker. * @param socket Socket conectado al peer */ public synchronized void conexionAceptada(Socket socket){ if (this.run==false) return; String id = socket.getInetAddress().getHostAddress() +":" + socket.getPort(); if (PeersDisponibles.containsKey(id)==false) { Peer p=new Peer(socket.getInetAddress().getHostAddress(),socket.getPort()); Salida.escribe("Pendiente conexion con peer "+p.toString()+" por el puerto "+socket.getPort(),salida.traza); handshake=new Handshake(p,socket,salida.traza); if (handshake.leeHandShake(this.id_cliente,this.torrente.info_hash)) { handshake.escribeHandShake(this.id_cliente,this.torrente.info_hash); ListaPeers.put(p.toString(), p); conex=new Conexion(p,socket,this.id_cliente,this.torrente.info_hash,this.torrente,this.ListaPiezas,salida.traza,this.path,handshake); conex.creaConexionEscuchador(this); conex.start(); Salida.escribeVentana("Aceptada conexion con peer "+p.toString()+" por el puerto "+this.prefs.leePuerto()); Salida.escribe("Aceptada conexion con peer "+p.toString()+" por el puerto "+this.prefs.leePuerto(),salida.traza); } else Salida.escribe("HANDSHAKE fallido con el peer "+p.toString()+" por el puerto "+this.prefs.leePuerto(),salida.traza); } } /** * Guarda en la lista de escuchadores al objeto de la ventana Principal pasado como argumento * @param escuchador Objeto Principal */ public void creaTorrenteAbiertoEscuchador(Principal escuchador) { //Salida.escribe("Aadido Listener DownloadTorrent"); escuchadores.add(Principal.class, escuchador); } /** * Elimima de la lista de escuchadores al objeto Principal pasado como argumento * @param escuchador Objeto Principal */ public void eliminaTorrenteAbiertoEscuchador(Principal escuchador) { escuchadores.remove(Principal.class, escuchador); } /** * Devuelve el objeto de la clase Principal de la lista de * escuchadores. * @return Principal[] Objetos de la lista de escuchadores */ public Principal[] leeTorrenteAbiertoEscuchadores() { return escuchadores.getListeners(Principal.class); } /** * * Mtodo que bsicamente prepara los datos para ser mostrados por el interfaz y * despus llama al mtodo ActivualizaTablasGUI(). * */ public void actualizaVelocidades(){ String [][]cadenas=new String[this.PeersDisponibles.size()+1][4]; Protocolo cp; Peer p; int i=0; List lconexiones = new LinkedList(this.PeersDisponibles.values()); if (!this.downloadCompleto()) Collections.sort(lconexiones, new VelocidadSubidaComparador()); else Collections.sort(lconexiones, new VelocidadBajadaComparador()); this.sumaUL=0; this.sumaDL=0; //Iterator itp = lpeers.iterator(); for (Iterator it = lconexiones.iterator();it.hasNext(); ) { cp = (Protocolo) it.next(); p=(Peer) cp.p; cadenas[i][0]=p.leeIdCliente(); cadenas[i][1]=p.toString(); cadenas[i][2]=String.valueOf(p.leeVelocidadUL(false) / (1024 * 10)); cadenas[i][3]=String.valueOf(p.leeVelocidadDL(false) / (1024 * 10)); this.sumaUL+=(p.leeVelocidadUL(true) / (1024 * 10)); this.sumaDL+=(p.leeVelocidadDL(true) / (1024 * 10)); i++; } cadenas[i][0]=" "; cadenas[i][1]="Total: "; sumaUL=sumaUL*100; sumaUL=(Math.round(sumaUL)/100.0); sumaDL=sumaDL*100; sumaDL=(Math.round(sumaDL)/100.0); cadenas[i][2]=String.valueOf(sumaUL)+" Kb/seg"; cadenas[i][3]=String.valueOf(sumaDL)+" Kb/seg"; i++; actualizaTablasGUI(cadenas,i,this.bajados,this.subidos,this.FicheroCompletado,this.torrente.ListaLongitudes,this.tracker_elegido,this.intervalo_tracker); } /** * Mtodo que llama al mtodo actualizaTorrrenteAbierto() del objeto Principal que * est en la lista de escuchadores. * Sirve para actualizar el interfaz de la ventana Principal. */ public void actualizaTorrenteAbierto(){ Protocolo cp; List lconexiones = new LinkedList(this.PeersDisponibles.values()); this.semillas=0; this.clientes=0; for (Iterator it = lconexiones.iterator();it.hasNext(); ) { cp = (Protocolo) it.next(); if (cp.p.esSemilla()==true) this.semillas++; else this.clientes++; } int i=0; //quitar for (Principal escuchador : leeTorrenteAbiertoEscuchadores()) { escuchador.actualizaTorrrenteAbierto(this.torrente.nombre,this.faltan,this.bajados,this.subidos, this.sumaUL, this.sumaDL, this.semillas, this.clientes, this.ListaPiezas,this.FicheroCompletado); } } /** * Indica que hemos recibido una pieza. * Actualiza el nmero de bytes 'bajados', bytes que 'faltan' por descargar, * en este torrente. Tambin llama al mtodo a actualizaFicheroCompletado(pieza). * @param pieza int Nmero de pieza recibida. */ public synchronized void recibidaPieza(int pieza){ this.bajados+=ListaPiezas[pieza].leeTamPieza(); this.bajados_sesion+=ListaPiezas[pieza].leeTamPieza(); this.faltan-=ListaPiezas[pieza].leeTamPieza(); actualizaFicheroCompletado(pieza);//interfaz - progreso del torrente y ficheros Protocolo cp; List lconexiones = new LinkedList(this.PeersDisponibles.values()); for (Iterator it = lconexiones.iterator();it.hasNext(); ) { cp = (Protocolo) it.next(); Peer p=cp.p; p.escribeListaHave(pieza); } } /** * Indica que se ha enviado un bloque. Actualiza el nmero de bytes 'subidos' * por el cliente en este torrente. * @param tam int Tamao en bytes del bloque */ public synchronized void enviadoBloque(int tam){ this.subidos+=tam; } /** * * Indica que estamos conectados a un peer y se ha realizado correctamente el handshake. * Almacenamos el peer en el mapa PeersDisponibles. * @param id String ID del peer * @param cp Protocolo Objeto que enva/recibe mensajes del peer. */ public void conexionActiva(String id,Protocolo cp) { if (!this.PeersDisponibles.containsKey(id)) this.PeersDisponibles.put(id, cp); Salida.escribe("Llegamos a aadir el peer disponible",salida.traza); } /** * Indica que se ha realizado mal el handshake o que hemos perdidos la conexin con el * peer. Borramos el peer del mapa PeersDisponibles. * @param id String ID del peer */ public void conexionFin(String id){ Salida.escribe("Conexion fin- final\n",salida.traza); if (this.PeersDisponibles.containsKey(id)) { this.PeersDisponibles.remove(id); Salida.escribe("Llegamos a eliminar el peer disponible",salida.traza); } } } PK wC8g[%//9BJTorrent/ControlDescarga/VelocidadBajadaComparador.class2'    !"()VCodeLineNumberTableLocalVariableTablethis5LBJTorrent/ControlDescarga/VelocidadBajadaComparador;compare'(Ljava/lang/Object;Ljava/lang/Object;)IaLBJTorrent/Peer;bxLjava/lang/Object;y StackMapTable# SourceFileVelocidadBajadaComparador.java  BJTorrent/P2P/Protocolo $# %&3BJTorrent/ControlDescarga/VelocidadBajadaComparadorjava/lang/Objectjava/util/ComparatorBJTorrent/PeerpleeVelocidadDL(Z)F!  /*    C+=,6+N,:-- "&(),.-0.?/A2 4+"C CC0PK wC8-#N8BJTorrent/ControlDescarga/VelocidadBajadaComparador.java/* * VelocidadBajadaComparador.java * * Created on 10 de noviembre de 2007, 15:43 * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ /** * * @author Benjamn Muiz Garca */ package BJTorrent.ControlDescarga; import BJTorrent.Peer; import BJTorrent.P2P.Protocolo; import java.util.Comparator; /** * * Clase que implementa el interfaz Comparator. Sirve para ordenar los peers por su velocidad * de bajada. * */ public class VelocidadBajadaComparador implements Comparator { /** * Compara la velocidad de bajada de 2 objetos Peer desde nuestro cliente. * * @param x Object el primer objeto Peer que va a ser comparado * @param y Object el segundo objeto Peer que va a ser comparado * @return int -1 si el primer objeto tiene una velocidad de bajada mayor que el segundo, * 1 si el primer objeto Peer tiene una velocidad de bajada inferior al segundo, * y 0 en caso de igualdad. */ public int compare(Object x, Object y) { if (x instanceof Protocolo && y instanceof Protocolo) { Peer a=((Protocolo) x).p; Peer b=((Protocolo) y).p; if (((Peer) a).leeVelocidadDL(false) > ((Peer) b).leeVelocidadDL(false)) return -1; else if (((Peer) a).leeVelocidadDL(false) < ((Peer) b).leeVelocidadDL(false)) return 1; } return 0; } } PK wC8r//9BJTorrent/ControlDescarga/VelocidadSubidaComparador.class2'    !"()VCodeLineNumberTableLocalVariableTablethis5LBJTorrent/ControlDescarga/VelocidadSubidaComparador;compare'(Ljava/lang/Object;Ljava/lang/Object;)IaLBJTorrent/Peer;bxLjava/lang/Object;y StackMapTable# SourceFileVelocidadSubidaComparador.java  BJTorrent/P2P/Protocolo $# %&3BJTorrent/ControlDescarga/VelocidadSubidaComparadorjava/lang/Objectjava/util/ComparatorBJTorrent/PeerpleeVelocidadUL(Z)F!  /*    C+=,6+N,:-- "')*-..0/?0A3 4+"C CC0PK wC8m8BJTorrent/ControlDescarga/VelocidadSubidaComparador.java/* * VelocidadSubidaComparador.java * * Created on 10 de noviembre de 2007, 14:43 * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ /** * * @author Benjamn Muiz Garca */ package BJTorrent.ControlDescarga; import BJTorrent.Peer; import BJTorrent.P2P.Protocolo; import java.util.Comparator; /** * * Clase que implementa el interfaz Comparator. * Sirve para ordenar los peers por su velocidad de bajada. * */ public class VelocidadSubidaComparador implements Comparator { /** * Compara la velocidad de subida de 2 objetos Peer a nuestro cliente * * @param x Object el primer objeto Peer que va a ser comparado * @param y Object el segundo objeto Peer que va a ser comparado * @return int -1 si el primer objeto tiene una velocidad de subida mayor que el segundo, * 1 si el primer objeto Peer tiene una velocidad de subida inferior al segundo, * y 0 en caso de igualdad. */ public int compare(Object x, Object y) { if (x instanceof Protocolo && y instanceof Protocolo) { Peer a=((Protocolo) x).p; Peer b=((Protocolo) y).p; if (((Peer) a).leeVelocidadUL(false) > ((Peer) b).leeVelocidadUL(false)) return -1; else if (((Peer) a).leeVelocidadUL(false) < ((Peer) b).leeVelocidadUL(false)) return 1; } return 0; } } PK vC8m!!.BJTorrent/FicheroTorrent/FicheroTorrente.class2 r q q q q q q q q q q q q q q q q q q q  q ? q q   %  %  % % %   K q    q   ? q q K q !" q# $% $&' () (* +,- U. T/ T %0 T123 45 46 47 489 a :; d <= <>? K@A (BC KD KE KFGHIdatos[Binfo info_hash infohashURLLjava/lang/String; infohashhex datos_cadenaposI pos_ini_info pos_fin_info pos_ini_hash ListaTrackersLjava/util/LinkedList; Signature*Ljava/util/LinkedList; ListaFicheros ListaRutasListaLongitudes(Ljava/util/LinkedList; num_ficherosanuncionombrelongitudJ tam_pieza num_piezasfLjava/io/File;ficherotorrentLjava/io/RandomAccessFile;(Ljava/io/File;)VCodeLineNumberTableLocalVariableTableioeLjava/io/IOException;this*LBJTorrent/FicheroTorrent/FicheroTorrente; StackMapTableHJleeInfoHashURL()Ljava/lang/String; leeAnnounce leeNumPiezas()I leeTamPieza leeLongitud()Ljava/lang/Long;leeNumFicheros leePiezaSHA1(I)[Bjindiceinihash20t leeNombre leeTrackers()Ljava/util/LinkedList;,()Ljava/util/LinkedList; parseTorrent()Zi leerBytes()VbBtambytes f_in_torrentLjava/io/DataInputStream;, hash_SHA1()[BmdLjava/security/MessageDigest;nsae(Ljava/security/NoSuchAlgorithmException;eLjava/lang/Exception;9; leeBEntero()Jvalor leeBCadena valor_cad! leeBTrackers leeBFicherostamsepauxaux2 SourceFileFicheroTorrente.java st ut vt wx yx zx }| ~|java/util/LinkedList | x x | | java/io/RandomAccessFiler K java/io/IOException3Error accediendo aleatoriamente al fichero torrenteL MN OP | {| QR STjava/lang/StringBuilder U VW- XY VZ [Pos Ini piezas: V\ pos ] ^_!Fallo leyendo la SHA1 de la pieza` aN d8:announce bc  announce: de4:nameNombre del Torrente: 4:info5:files f ghjava/lang/Long i6:length  piece length6:pieces jk13:announce-list Tracker : java/lang/String 7:private l mn on HASH SHA1: J p ? qrjava/io/DataInputStreamjava/io/FileInputStream s Vt u%Problema leyendo el fichero .torrent SHA-1v wx y z{ |&java/security/NoSuchAlgorithmException }Njava/lang/Exception~ O length path  N ? Path->(BJTorrent/FicheroTorrent/FicheroTorrentejava/lang/Object java/io/File#(Ljava/io/File;Ljava/lang/String;)VBJTorrent/SalidaescribeVentana(Ljava/lang/String;)VvalueOf(J)Ljava/lang/Long;seek(J)VreadByte()B getMessageappend-(Ljava/lang/String;)Ljava/lang/StringBuilder;getCause()Ljava/lang/Throwable;-(Ljava/lang/Object;)Ljava/lang/StringBuilder;toString(I)Ljava/lang/StringBuilder;java/lang/SystemerrLjava/io/PrintStream;java/io/PrintStreamprintlnindexOf(Ljava/lang/String;)Iadd(ILjava/lang/Object;)Vsizeget(I)Ljava/lang/Object; longValuecharAt(I)CBJTorrent/Utils bytesToHex([B)Ljava/lang/String;byteArrayToURLStringexistsexit(I)V(Ljava/io/InputStream;)V(C)Ljava/lang/StringBuilder;closejava/security/MessageDigest getInstance1(Ljava/lang/String;)Ljava/security/MessageDigest;resetupdate([BII)Vdigestescribejava/lang/Integer(I)Ljava/lang/Integer;intValueequalsIgnoreCase(Ljava/lang/String;)Z separatorCharC substring(II)Ljava/lang/String;!qrstutvtwxyxzx{|}|~| ||xx||`******* * * * Y * Y * Y * Y **** ***+*Y+ MfN "$"&((.,3.82C4N6Y8d:i=o?uAzCEPRUSTV /*\ /*d /*l /*u 2* ~ /* I*!"*"h`=N*#6-*$TW:%Y&'()(*+,%Y&-(!./(.,0121-:=>)4:=?a>"|?R||}t"BS/* /* 5** 34"*Y" `"**5%Y&6(*(,**7** 84"*Y"`"**5%Y&9(*(,**** :4Z"*Y"`"**" ** ;4Z"J*Y"`"*<**=<*= *Y*>?@aۧT** A4"*"*Y"`"***B**C7*7** 7** D4"*Y" `"**B** E4"*"J*Y"`"**Bl* *Y"Z`"F:**"*h` *"!* *** G4"*"N*Y"`"*H<*=2%Y&I(.J(*>K(,** L4"*"*Y" `"*BX**" * <* `**3T**M**N**O%Y&P(*(,>  9ER]e~"-2:FP_lw    ! "#$D#J&W'^(i)n*v,-,4789:*(|:|{|#P'1d$9+P @*Q*R@STYUY*VWN63-X6*T%Y&*Z (Y, -Z L0%Y&[(+'(,2mp>IJ LNY.[9\?]H_c[icmipeqfk>?*18|k.?q 7;\]L+^+** * * d`_+`L+bc L+ec%&a%1d*  !&'.129* '2; fJ @>* *"Fi *Y"`"* *"F0;* *"F9+i* *Y"Z`"F0dfga@ >* *"Fe *Y"`"* >`fv ~| Gj @N*B@* *"F:*Y"`"*"6*"a$%Y&-(* FY,N*Y"a"-*  ';V\h*-/|jhex .X<=* *"Fl*Y"`"**57* *"Fe*Y"`"2 $0@CPSW XV|T|  maLMN666* *"Fl* *"Fd*Y"`"*5L+hi**B 7+jiϻ%Y&kY*C(,M* *Y"Z`"Fl>* *"Fe$*5N%Y&,(kY-(,M*Y"`"KY%Y&l(kY,m:,,n-ndnd`oM%Y&p(,(,c*,7*-7* *"Fe*Y"`"z  25BGPfo$.8; K N [`RDxa^x[x Xx U|R|O|" #70 a!0PK wC8LfCC-BJTorrent/FicheroTorrent/FicheroTorrente.java/* * FicheroTorrente.java * * Created on 27 de octubre de 2007, 5:11 * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ /** * * @author Benjamn Muiz Garca */ package BJTorrent.FicheroTorrent; import BJTorrent.Salida; import BJTorrent.Utils; import java.io.*; import java.util.LinkedList; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * Clase que almacena los datos del fichero .torrent que leemos y parsemanos */ public class FicheroTorrente { //Buffer en el que almacenamos los bytes del fichero .torrent public byte[] datos = new byte[200 * 1024]; //Buffer en el que almacenamos la clave info del fichero METAINFO del .torrent sobre el que calcularemos la clave SHA1 del torrente public byte[] info = new byte[200 * 1024]; //Clave SHA1 del torrente public byte[] info_hash = new byte[20]; //URL que codifica la SHA1 del torrente y que ser usada por la clase Tracker private String infohashURL = ""; //La clave SHA1 del torrente en formato hexadecimal public String infohashhex = ""; //String que almacena todo el fichero METAINFO .torrent para buscar claves y parsear. private String datos_cadena = ""; //posicin actual en la que leemos de datos_cadena; private int pos; //Posicin o byte de inicio de la clave info del METAFILE .torrent private int pos_ini_info = 0; //Posicin o byte final de la clave info del METAINFO .torrent que ciframos para hallar la clave SHA1 del torrente private int pos_fin_info = 0; //Posicin de inicio de las hash SHA1 en el METAINFO .torrent private static int pos_ini_hash =0; //Lista de trackers que aparecen en el fichero METAINFO private LinkedList ListaTrackers = new LinkedList (); //Nombre de los ficheros del torrente public LinkedList ListaFicheros = new LinkedList (); //Rutas o paths de cada uno de los ficheros del torrente public LinkedList ListaRutas = new LinkedList (); //Tamao en bytes o longitud de cada uno de los ficheros del torrente public LinkedList ListaLongitudes = new LinkedList (); //Nmero de ficheros que componen el torrente public int num_ficheros=0; //clave anuncio del fichero METAINFO .torrent public String anuncio=""; //nombre del torrente public String nombre=""; //longitud -> sumatorio total de la longitud de todos los ficheros public long longitud=0; //Tamao de la pieza, suele ser mltiplo de 16KB public int tam_pieza=0; //nmero de piezas del torrente public int num_piezas=0; //Fichero .torrent que leemos y parseamos private File f; public RandomAccessFile ficherotorrent; /** * Crea una nueva instancia de FicheroTorrente * @param f File Fichero .torrent que leemos y parseamos */ public FicheroTorrente(File f) { this.f = f; try { this.ficherotorrent = new RandomAccessFile(f,"r"); } catch (IOException ioe) { Salida.escribeVentana("Error accediendo aleatoriamente al fichero torrente"); } } /** * Devuelve la SHA-1 del torrente en formato URL * @return String SHA-1 del torrente en codificacin URL */ public String leeInfoHashURL() { return infohashURL; } /** * Devuelve la clave announce del .torrent * @return String Clave announce */ public String leeAnnounce() { return anuncio; } /** * Devuelve el nmero de piezas del .torrent * @return int Nmero de piezas */ public int leeNumPiezas() { return num_piezas; } /** * Devuelve el tamao de la pieza excepto la ltima * @return int Tamao de la pieza en bytes */ public int leeTamPieza() { return tam_pieza; } /** * * Devuelve el tamao en bytes total de los ficheros del torrente a descargar * @return Long Tamao en bytes del torrente a descargar */ public Long leeLongitud() { return longitud; } /** * * Devuelve el nmero de ficheros del torrente * @return int Nmero de ficheros que componen el torrente */ public int leeNumFicheros() { return num_ficheros; } /** * Devuelve la hash SHA1 de una pieza pasada como argumento leyndola del fichero .torrent * @param indice int Nmero de pieza * @return byte[] hash SHA1 de la pieza segn aparece en el fichero METAINFO .torrent */ public byte[] leePiezaSHA1(int indice){ pos=pos_ini_hash; int ini=pos+indice*20; byte []hash20=new byte[20]; try { ficherotorrent.seek(ini); for (int j=0;j<20;j++) hash20[j]=ficherotorrent.readByte(); } catch (IOException ioe) { Salida.escribeVentana(ioe.getMessage()+"-"+ioe.getCause()); Salida.escribeVentana("Pos Ini piezas:"+pos_ini_hash+" pos "+ini); System.err.println("Fallo leyendo la SHA1 de la pieza"); Salida.escribeVentana("Fallo leyendo la SHA1 de la pieza"); return null; } // Salida.escribe(Utils.byteArrayToByteString(hash20)); return hash20; } /** * Devuelve el nombre del torrente * @return String Nombre del Torrente */ public String leeNombre() { return nombre; } /** * * Devuelve la lista de Trackers del METAINFO .torrent * @return LinkedList Lista de trackers */ public LinkedList leeTrackers() { return ListaTrackers; } /** * * Mtodo que busca las claves 'announce', 'info', 'files', 'path', 'length', 'pieces' * 'announce-list', etc.. en el String que almacena todo el .torrent y llama a los mtodos leeBCadena() * leeBEntero() para almacenar los valores de las claves en los atributos de la clase adecuados. * */ public boolean parseTorrent() { pos = datos_cadena.indexOf("d8:announce"); pos += 11; anuncio=leeBCadena(); Salida.escribeVentana("announce: "+anuncio); ListaTrackers.add(0,anuncio); pos = datos_cadena.indexOf("4:name"); pos += 6; nombre=leeBCadena(); Salida.escribeVentana("Nombre del Torrente: "+nombre); if (nombre=="" && anuncio=="") //System.out.println("Fichero .torrent de entrada con formato incorrecto"); return false; if ((pos = datos_cadena.indexOf("4:info")) > 0) { pos += 6; pos_ini_info = pos; if ((pos = datos_cadena.indexOf("5:files")) >0) { pos += 7; leeBFicheros(); num_ficheros=ListaFicheros.size(); for (int j = 0; j < ListaFicheros.size(); j++) { // Salida.escribeVentana("Fichero: " + j + ": " // + ListaFicheros.get(j)+" bytes",0); // Salida.escribeVentana("Ruta: " + j + ": " // + ListaRutas.get(j),0); longitud+=ListaLongitudes.get(j); // Salida.escribeVentana("Longitud: " + j + ": " // + ListaLongitudes.get(j)+" bytes",0); } } else { pos = datos_cadena.indexOf("6:length"); if (pos> 0) pos += 8; num_ficheros=1; longitud=leeBEntero(); ListaFicheros.add(0, leeNombre()); ListaRutas.add(0,""); ListaLongitudes.add(0,longitud); //Salida.escribeVentana("Fichero: "+leeNombre(),0); //Salida.escribeVentana("Longitud: "+longitud+" bytes",0); } } pos = datos_cadena.indexOf("piece length"); pos += 12; tam_pieza=(int)leeBEntero(); //Salida.escribe("Tam Pieza"+tam_pieza); //Salida.escribeVentana("Tam Pieza: "+(tam_pieza/1024)+"Kb",0); pos = datos_cadena.indexOf("6:pieces"); if (pos > 0) { pos += 8; num_piezas =(int) leeBEntero() /20; //Salida.escribeVentana("Numero de Piezas: "+num_piezas,0); if (datos_cadena.charAt(pos++) != ':') return false; //System.exit(100); pos_fin_info = pos + (int) num_piezas*20; pos_ini_hash =pos; //Ahora leemos la hash SHA1 de cada pieza // long mipos=leePiezasHash(pos); // if (mipos!=pos_fin_info) // System.exit(100); } if (this.tam_pieza==0 && this.num_piezas==0) return false; pos = datos_cadena.indexOf("13:announce-list"); if (pos > 0) { pos += 16; leeBTrackers(); for (int i = 0; i < ListaTrackers.size(); i++) Salida.escribeVentana("Tracker "+i+": "+ListaTrackers.get(i)); } pos = datos_cadena.indexOf("7:private"); if (pos > 0) { pos += 9; leeBEntero(); pos_fin_info=pos; } for (int j = pos_ini_info; j < pos_fin_info + 1; j++) { info[j] = datos[j]; // Salida.escribe("pos :"+j+"-val :"+info[j]); } //Salida.escribe("pos ini: " + pos_ini_info + "pos fin"+ pos_fin_info); info_hash = hash_SHA1(); //Salida.escribe("SHA1->" + info_hash.toString()); infohashhex = Utils.bytesToHex(info_hash); infohashURL = Utils.byteArrayToURLString(info_hash); Salida.escribeVentana("HASH SHA1: "+infohashhex); return true; //Salida.escribe("INFOHASH->" + infohashhex); //Salida.escribe("INFOHASHURL->" + infohashURL); } /** * * Lee los bytes del fichero .torrent y los almacena en byte[] datos y en un String * datos_cadena */ public void leerBytes() { try { long tambytes = 0; if (f.exists()) { tambytes = f.length(); } else System.exit(1); DataInputStream f_in_torrent; //if (datos_cadena.contains("6:pieces") == true // && datos_cadena.length() > datos_cadena // .indexOf("6:pieces") + 20) // break; f_in_torrent = new DataInputStream(new FileInputStream(f)); byte b; for (int i = 0; i < tambytes; i++) { b = f_in_torrent.readByte(); datos[i] = b; datos_cadena += (char) b; } f_in_torrent.close(); } catch (IOException ioe) { System.err.println("Problema leyendo el fichero .torrent " + ioe.getMessage()); } } /* public long leePiezasHash(int posicion){ byte []hash20=new byte[20]; PiezasHash= new LinkedList(); for (int i=0; i= '0' && datos_cadena.charAt(pos) <= '9') { valor = valor * j + Integer.valueOf(datos_cadena.charAt(pos++) - '0'); j = 10; } if (datos_cadena.charAt(pos) == 'e') pos++; return valor; } /** * Devuelve el String ledo, en la posicin indicada por el atributo de la clase 'pos' ,del String que almacena * todo el .torrent. * Lee una cadena Bcode y la traduce a String. * @return String Cadena leida. */ public String leeBCadena() { long valor = 0; String valor_cad = ""; valor = leeBEntero(); while (datos_cadena.charAt(pos) == ':') pos++; for (int i = pos; i < pos + valor; i++) valor_cad += datos_cadena.charAt(i); // Salida.escribe("pos:"+pos+" "+valor_cad); pos += valor; return valor_cad; } /** * Almacena los trackers de la clave 'announce-list' del .torrent en la lista * ListaTrackers. */ public void leeBTrackers() { int i = 0; int e = 0; do { while (datos_cadena.charAt(pos) == 'l') { e--; pos++; } ListaTrackers.add(i, leeBCadena()); while (datos_cadena.charAt(pos) == 'e') { e++; pos++; } i++; } while (e != 0); } /** * * Lee los valores de las claves 'path' y 'length' de cada unos de los ficheros que * componen el .torrent. Almacena los nombres de los ficheros en ListaFicheros, sus rutas * en ListaRutas y su tamao en bytes en ListaLongitudes. */ public void leeBFicheros() { String aux = ""; String aux2 = ""; String nombre=""; int i = 0; int j = 0; int e = 0; do { while (datos_cadena.charAt(pos) == 'l' || datos_cadena.charAt(pos) == 'd') { e--; pos++; } aux = leeBCadena();// clave if (aux.equalsIgnoreCase("length")) ListaLongitudes.add(i++, leeBEntero()); else if (aux.equalsIgnoreCase("path")) { aux2 = File.separatorChar+this.leeNombre(); if (datos_cadena.charAt(pos++) == 'l') { while (datos_cadena.charAt(pos) != 'e') { nombre=leeBCadena(); aux2 = aux2 + File.separatorChar+ nombre ; } pos++; } String tamsep=new String(" "+File.separatorChar); aux2 = aux2.substring(0, aux2.length()-nombre.length()-tamsep.length()+1); Salida.escribe("Path->" + aux2); ListaRutas.add(j, aux2); ListaFicheros.add(j,nombre); j++; } // aux=leeBCadena(); //valor while (datos_cadena.charAt(pos) == 'e') { e++; pos++; } } while (e != 0); } }PK wC8- 1BJTorrent/FicheroTorrent/VentanaPiezasDisco.class2 } |  | | | | | | | | | | |   | | `  ` ` ` | | |  |  | b " %    : :   : 9 9 9 :  9  %  % | |   " | % %   " :!" # "$%& `' b |()* e+ b,-. |/ j0 12 34 j5 j6 78 79 :; 7< 7= 7> j? 3@ :A jB |CDE ListaPiezas[LBJTorrent/Pieza;torrente*LBJTorrent/FicheroTorrent/FicheroTorrente; num_piezasI tam_piezapathLjava/lang/String;prefs#LBJTorrent/GUI/VentanaPreferencias; num_ficheroslongitudJfaltanbajadosprogresoficheros_bajadosjava/io/RandomAccessFile;ficheroLjava/io/RandomAccessFile;tam_ultima_piezaFicheroCompletadoLjava/util/LinkedList; Signature(Ljava/util/LinkedList;graphLjava/awt/Graphics; jProgressBar1Ljavax/swing/JProgressBar; labeltituloLjavax/swing/JLabel;-(LBJTorrent/FicheroTorrent/FicheroTorrente;)VCodeLineNumberTableLocalVariableTablethis-LBJTorrent/FicheroTorrent/VentanaPiezasDisco;torrentmaximoLjava/lang/Long; creaPiezas()ViioeLjava/io/IOException;ltempLjava/io/File; StackMapTableDleePiezasBajadaskauxj datospieza[Btampiezaposicionposfichleidosposbuff faltanleer ficheroleidos[JinitComponentslayoutLjavax/swing/GroupLayout; SourceFileVentanaPiezasDisco.java  !BJTorrent/GUI/VentanaPreferencias java/util/LinkedList F GH IH JK LMjava/lang/Long N OP QH RP SP TU VW BJTorrent/Pieza ~ XHjava/io/RandomAccessFile YZ 130[ \] ^_ `a b c d e fjava/io/IOException9Error cerrando el fichero de acceso aleatorio al .torrentg h_ ij kl java/io/Filejava/lang/StringBuilder mn o pqjava/lang/String rZ _ st uv mw x ytrw z { |N }~  ,No se pudieron crear los ficheros temporales _ N !No se pudo leer la pieza en disco _ P Pieza m leida de disco y validada  U NO VALIDAjavax/swing/JProgressBarjavax/swing/JLabel U java/awt/FontTahoma  #Leyendo Piezas descargadas en Discojavax/swing/GroupLayout                 +BJTorrent/FicheroTorrent/VentanaPiezasDiscojavax/swing/JFrame(BJTorrent/FicheroTorrent/FicheroTorrente leeNumPiezas()I leeTamPieza leeLongitud()Ljava/lang/Long; longValue()J(J)V setMinimum(I)VintValue setMaximumsetValuesetStringPainted(Z)V getGraphics()Ljava/awt/Graphics;leeNumFicheroslee_directorioCompartido()Ljava/lang/String;BJTorrent/GUI/IdiomaleeEtiquetaIdioma&(Ljava/lang/String;)Ljava/lang/String;setText(Ljava/lang/String;)V leePiezaSHA1(I)[B(III[B)VficherotorrentcloseinfodatosBJTorrent/SalidaescribeVentanavalueOf(J)Ljava/lang/Long;add(ILjava/lang/Object;)Vappend-(Ljava/lang/String;)Ljava/lang/StringBuilder; ListaRutasget(I)Ljava/lang/Object;toStringmkdirs()Z separatorCharC(C)Ljava/lang/StringBuilder; ListaFicherosexists#(Ljava/io/File;Ljava/lang/String;)VListaLongitudes setLengthupdate(Ljava/awt/Graphics;)Vjava/lang/SystemerrLjava/io/PrintStream;java/io/PrintStreamprintlnseekread([BII)Iescribeexit validaSHA1([B)Z(I)Ljava/lang/StringBuilder;set'(ILjava/lang/Object;)Ljava/lang/Object;escribeCompletasetAlwaysOnTop(Ljava/lang/String;II)VsetFont(Ljava/awt/Font;)VgetContentPane()Ljava/awt/Container;(Ljava/awt/Container;)Vjava/awt/Container setLayout(Ljava/awt/LayoutManager;)V!javax/swing/GroupLayout$Alignment Alignment InnerClassesLEADING#Ljavax/swing/GroupLayout$Alignment;createParallelGroup ParallelGroupL(Ljavax/swing/GroupLayout$Alignment;)Ljavax/swing/GroupLayout$ParallelGroup;createSequentialGroupSequentialGroup+()Ljavax/swing/GroupLayout$SequentialGroup;'javax/swing/GroupLayout$SequentialGroupaddGap.(III)Ljavax/swing/GroupLayout$SequentialGroup; addComponentB(Ljava/awt/Component;III)Ljavax/swing/GroupLayout$SequentialGroup;%javax/swing/GroupLayout$ParallelGroupaddGroupGroupH(Ljavax/swing/GroupLayout$Group;)Ljavax/swing/GroupLayout$ParallelGroup;?(Ljava/awt/Component;)Ljavax/swing/GroupLayout$SequentialGroup;J(Ljavax/swing/GroupLayout$Group;)Ljavax/swing/GroupLayout$SequentialGroup;addContainerGap-(II)Ljavax/swing/GroupLayout$SequentialGroup;setHorizontalGroup"(Ljavax/swing/GroupLayout$Group;)VTRAILINGk(Ljavax/swing/GroupLayout$Alignment;Ljavax/swing/GroupLayout$Group;)Ljavax/swing/GroupLayout$ParallelGroup;setVerticalGrouppackjavax/swing/GroupLayout$Group!|}~v***Y** * * * * * Y*+*+*+*+Y*M***,**** !**"#*+$**%&**W'*()*+nO, .135$7)9.?3A>QCRKSST^WjYnZv[\]abdfghj jf **,*p <*>*#"Y*d ***q@*-.S*/0*1*2 L45<*6* 78<*9Y:Y;*<*=>?<@ABW9Y:Y;*<*=>?<CD*E>?<@AM,F*&%Y,GHS*&2*I>J*Y *I>a *Y *I>` *&20** **!K *L NMNOVps33~tuwPuV`hpsty'A[u~HCt{W"     \B*P@ 7 766 6 *6 : 6  *6  P 6  *Q*# 2R6  N66  i776 *I >%*I >e77  6*6H  P*I>d6 ~9Y:Y;*<*=>?<CD*E>?<@A:*%YGHS*ST*S-  UW*S0  P9Y:Y;*<*=>?<CD*E>?<@A:*%YGHS*ST*S- UW*S0 P `6  d6 7:VWX*# 2-Y:Y;Z< [\<@W*Y *# 2Ra *Y *# 2R` ** **!K 6*65*> /a7:*]W  P*# 2^d:Y;Z< [_<@W*Y *# 2Ra *# 2^*Y *# 2R` ** **!K &Z3]b3e3E #28>MY^adkor&5>KRZ]be- A T _ gw"& &7E Qk>r ^A      # h& 0 : h= ` H *`Ya*bYc(*d*(eYfgh*(i+jY*klL*k+m++no+p+no+p)))q*rs+p111q*(tsu,vsw++nox+pCv*(tq*$rZZZqyz*{. ' (*,.-7/C0K1=FGC"3j@:j7jjPK wC82 0BJTorrent/FicheroTorrent/VentanaPiezasDisco.form
PK wC8 7.4.40BJTorrent/FicheroTorrent/VentanaPiezasDisco.java/* * VentanaPiezasDisco.java * * Created on 19 de noviembre de 2007, 16:33 */ /** * * @author Benjamn Muiz Garca */ package BJTorrent.FicheroTorrent; import BJTorrent.Pieza; import BJTorrent.Salida; //import BJTorrent.Utils; import BJTorrent.GUI.Idioma; import BJTorrent.GUI.VentanaPreferencias; import java.io.RandomAccessFile; import java.io.File; import java.io.IOException; import java.util.LinkedList; import javax.swing.JProgressBar; //import javax.swing.event.EventListenerList; /** * Subclase de JFrame. * Crea la estructura de directorios y ficheros que componen el torrente * en el sistema de archivos si esta no hubiese sido creada. * Tambin indica la lectura de las piezas previamente descargadas. */ public class VentanaPiezasDisco extends javax.swing.JFrame { //Array de piezas que forman el torrente public Pieza[] ListaPiezas; //Objeto que almacena la informacin del fichero .torrent public FicheroTorrente torrente; //Nmero de piezas del torrente private int num_piezas; //Tamao en bytes de las piezas excepto la ltima private int tam_pieza; //Ruta o path del directorio compartido que leemos de VentanaPreferencias private String path=""; //Objeto que almacena las preferencias de la aplicacin private VentanaPreferencias prefs=new VentanaPreferencias(); //Nmero de ficheros del torrente private int num_ficheros = 0; //Tamao en bytes del torrente private long longitud = 0; //Nmero de bytes que faltan por descargar para completar el download. public long faltan = 0; //Nmero de bytes descargados public long bajados=0; //Progreso del componente JProgessBar private int progreso=0; //Array usado para crear en disco los ficheros y directorios del torrente private RandomAccessFile[] ficheros_bajados; //Objeto con el que leemos las piezas descargadas de los ficheros que componen el torrente private RandomAccessFile fichero; //Tamao en bytes de la ltima pieza private int tam_ultima_pieza=0; //Lista con el nmero de bytes descargados de cada fichero que compone el torrente public LinkedList FicheroCompletado=new LinkedList(); //objeto usado para actualizar y repintar esta ventana private java.awt.Graphics graph; /** * * Constructor de la clase VentanaPiezasDisco * @param torrent FicheroTorrente El fichero .torrent que abrimos lo parseamos almacenando la * informacin del torrente, que ser el argumento para el constructor de esta clase. */ public VentanaPiezasDisco(FicheroTorrente torrent ) { this.torrente=torrent; this.num_piezas = torrent.leeNumPiezas(); this.tam_pieza=torrent.leeTamPieza(); this.longitud=torrent.leeLongitud(); Long maximo=new Long(this.longitud); initComponents(); this.jProgressBar1.setMinimum(0); this.jProgressBar1.setMaximum(maximo.intValue()); this.jProgressBar1.setValue(0); jProgressBar1.setStringPainted(true); this.graph=this.getGraphics(); this.ListaPiezas = new Pieza[this.num_piezas]; this.num_ficheros = torrent.leeNumFicheros(); this.ficheros_bajados = new RandomAccessFile[this.num_ficheros]; this.path=prefs.lee_directorioCompartido(); this.labeltitulo.setText(Idioma.leeEtiquetaIdioma("130")); } /** * Mtodo que crea los directorio y ficheros y les asigna el tamao adecuado indicado en FicheroTorrente. * En el caso de que los ficheros del torrente ya existiesen este mtodo llama a leePiezasBajadas() */ public void creaPiezas(){ this.tam_ultima_pieza=(int)this.torrente.longitud % tam_pieza; for (int i=0; i=this.torrente.ListaLongitudes.get(j).intValue()) { posicion=posicion -this.torrente.ListaLongitudes.get(j).intValue(); posfich=posicion; j++; } for (int k = j; k < this.torrente.num_ficheros; k++) { ficheroleidos[k]=0; //Salida.escribe("posfich "+posfich+" longitud fichero"+this.torrente.ListaLongitudes.get(k).intValue()); try { leidos=(int)this.torrente.ListaLongitudes.get(k).intValue()-(int)posfich; if (faltanleer<=leidos) { File temp = new File(this.path+torrente.ListaRutas.get(k)+File.separatorChar+torrente.ListaFicheros.get(k)); this.fichero = new RandomAccessFile(temp, "rw"); this.fichero.seek(posfich); this.fichero.read(datospieza,posbuff,faltanleer); this.fichero.close(); ficheroleidos[k]=faltanleer; break; } else { if (leidos<=0) break; File temp = new File(this.path+torrente.ListaRutas.get(k)+File.separatorChar+torrente.ListaFicheros.get(k)); this.fichero= new RandomAccessFile(temp, "rw"); this.fichero.seek(posfich); this.fichero.read(datospieza,posbuff,leidos); //Salida.escribe("Lectura de una pieza dividida en varios ficheros"); this.fichero.close(); ficheroleidos[k]=leidos; posbuff=posbuff+leidos; faltanleer=faltanleer-leidos; posfich=0; } } catch (IOException ioe) { Salida.escribe("No se pudo leer la pieza en disco"); System.exit(1); } } if (this.ListaPiezas[i].validaSHA1(datospieza)==true) { Salida.escribe("Pieza "+i+" leida de disco y validada"); // Salida.escribeVentana("Pieza "+i+" leida de disco y validada",0); bajados+=this.ListaPiezas[i].leeTamPieza(); progreso+=this.ListaPiezas[i].leeTamPieza(); this.jProgressBar1.setValue(progreso); this.update(graph); for (int k = j; k < this.torrente.num_ficheros; k++) { Long aux=this.FicheroCompletado.get(k)+ficheroleidos[k]; FicheroCompletado.set(k,aux); // Salida.escribe("Leidos :"+ficheroleidos[k] +" Completado->"+FicheroCompletado.get(k).intValue()); ficheroleidos[k]=0; } this.ListaPiezas[i].escribeCompleta(true); } else { Salida.escribe("Pieza "+i+" NO VALIDA"); faltan+=this.ListaPiezas[i].leeTamPieza(); this.ListaPiezas[i].escribeCompleta(false); progreso+=this.ListaPiezas[i].leeTamPieza(); this.jProgressBar1.setValue(progreso); this.update(graph); } }//fin for } // //GEN-BEGIN:initComponents private void initComponents() { jProgressBar1 = new javax.swing.JProgressBar(); labeltitulo = new javax.swing.JLabel(); setAlwaysOnTop(true); labeltitulo.setFont(new java.awt.Font("Tahoma", 1, 14)); labeltitulo.setText("Leyendo Piezas descargadas en Disco"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(41, 41, 41) .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 272, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(49, 49, 49) .addComponent(labeltitulo))) .addContainerGap(44, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(67, Short.MAX_VALUE) .addComponent(labeltitulo) .addGap(14, 14, 14) .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(90, 90, 90)) ); pack(); }// //GEN-END:initComponents // Declaracin de varibales -no modificar//GEN-BEGIN:variables private javax.swing.JProgressBar jProgressBar1; private javax.swing.JLabel labeltitulo; // Fin de declaracin de variables//GEN-END:variables } PK wC8 88BJTorrent/GUI/Idioma.class2i 56 7 89: 5 ; <= >? @A B CDE 5F G H H IJK <LMNO PQRidiomaLjava/lang/String; propidiomaLjava/util/Properties; propStreamLjava/io/InputStream;()VCodeLineNumberTableLocalVariableTableioeLjava/io/IOException;thisLBJTorrent/GUI/Idioma; StackMapTableQDleeEtiquetaIdioma&(Ljava/lang/String;)Ljava/lang/String;clave SourceFile Idioma.java $%ESPAÑOL S TUjava/util/Properties !V WX YZproperties/spanish.properties[ \] "# ^_java/io/IOExceptionjava/lang/StringBuilderError IO Clase Preferencias `a bUc deENGLISH fgproperties/english.propertiesFRANCAISproperties/francais.properties h1BJTorrent/GUI/Idiomajava/lang/Object!BJTorrent/GUI/VentanaPreferencias leeIdioma()Ljava/lang/String;java/lang/Stringcontains(Ljava/lang/CharSequence;)ZgetClass()Ljava/lang/Class;java/lang/ClassgetResourceAsStream)(Ljava/lang/String;)Ljava/io/InputStream;load(Ljava/io/InputStream;)Vappend-(Ljava/lang/String;)Ljava/lang/StringBuilder;toStringBJTorrent/Salidaescribe(Ljava/lang/String;)Vequals(Ljava/lang/Object;)Z getProperty! !"#$%&***Y*:**  * LY+*:**  * `LY+C*7**  * LY+4>Aw'^% )?@'B4E>IAHBI^ajdwgkjk(*B)*)*)*+,-A./e/e/ 01&2*'( 234PK wC8PջgBJTorrent/GUI/Idioma.java/* * Idioma.java * * Created on 26 de noviembre de 2007, 16:33 * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package BJTorrent.GUI; import BJTorrent.Salida; /** * * @author Benjamn Muiz Garca */ import java.io.InputStream; import java.io.IOException; import java.util.Properties; /** * Clase que determina el Idioma que usa nuestra aplicacin en las etiquetas de texto JLabel */ public class Idioma { //Cadena que indica el idioma seleccionado private String idioma="ESPAOL"; //Objeto del que leemos las propiedades private static Properties propidioma; //Stream usado leer el fichero .properties private InputStream propStream; /** * Crea una nueva instancia de Idioma. * Segn el idioma seleccionado en VentanaPreferencias carga el fichero properties que almacena * las claves/valores en el idioma adecuado, para ser mostradas por las etiquetas Jlabel de nuestro * programa. */ public Idioma() { //prop=new Properties(); this.idioma=VentanaPreferencias.leeIdioma(); /* fichero=new File("preferencias.properties"); try { if (fichero.exists()==true) { //in=new DataInputStream( fichero); //out=new DataOutputStream(fichero); in= new BufferedReader(new FileReader(fichero)); prop.load(in); idioma=prop.getProperty("idioma"); } } catch (IOException ioe) {Salida.escribe("Error IO Clase Preferencias "+ioe.toString()); } */ //Salida.escribe("Idioma "+idioma); propidioma=new Properties(); if (idioma.contains("ESPAOL")) { propStream = getClass().getResourceAsStream("properties/spanish.properties"); try { propidioma.load(propStream); } catch (IOException ioe) {Salida.escribe("Error IO Clase Preferencias "+ioe.toString());} /*fichero=new File("spanish.properties"); try { if (fichero.exists()==true) { //in=new DataInputStream( fichero); //out=new DataOutputStream(fichero); in= new BufferedReader(new FileReader(fichero)); propidioma.load(in); Salida.escribe("Leimos las propiedades"); } } catch (IOException ioe) {Salida.escribe("Error IO Clase Preferencias "+ioe.toString()); } */ } else if (idioma.equals("ENGLISH")) { propStream = getClass().getResourceAsStream("properties/english.properties"); try { propidioma.load(propStream); } catch (IOException ioe) {Salida.escribe("Error IO Clase Preferencias "+ioe.toString());} /* fichero=new File("english.properties"); try { if (fichero.exists()==true) { //in=new DataInputStream( fichero); //out=new DataOutputStream(fichero); in= new BufferedReader(new FileReader(fichero)); propidioma.load(in); } } catch (IOException ioe) {Salida.escribe("Error IO Clase Preferencias "+ioe.toString()); } */ } else if (idioma.equals("FRANCAIS")) { propStream = getClass().getResourceAsStream("properties/francais.properties"); try { propidioma.load(propStream); } catch (IOException ioe) {Salida.escribe("Error IO Clase Preferencias "+ioe.toString());} /* fichero=new File("francais.properties"); try { if (fichero.exists()==true) { //in=new DataInputStream( fichero); //out=new DataOutputStream(fichero); in= new BufferedReader(new FileReader(fichero)); propidioma.load(in); } } catch (IOException ioe) {Salida.escribe("Error IO Clase Preferencias "+ioe.toString()); } */ } } /** * Devuelve el literal en el Idioma adecuado para ser mostrado en la etiqueta JLabel del GUI. * @param clave String Cadena que es la clave de la propiedad almacenada en un fichero .properties * @return String Devuelve el literal en el idioma seleccionado en VentanaPreferencias que se mostrara en el texto * de la etiqueta JLabel que hizo la llamada al mtodo. */ public static String leeEtiquetaIdioma(String clave){ return propidioma.getProperty(clave); } } PK wC8ҵlBJTorrent/GUI/MiFiltro.class2@ $ %& %' () (* (+ (,- (./01()VCodeLineNumberTableLocalVariableTablethisLBJTorrent/GUI/MiFiltro;accept(Ljava/io/File;)Z extensionLjava/lang/String;fLjava/io/File;siI StackMapTable2getDescription()Ljava/lang/String;type SourceFile MiFiltro.java 3 45 6 2 78 9: ;< = torrent >?Fichero BitTorrentBJTorrent/GUI/MiFiltro"javax/swing/filechooser/FileFilterjava/lang/String java/io/File isDirectory()ZgetName lastIndexOf(I)Ilength()I substring(I)Ljava/lang/String; toLowerCaseequals(Ljava/lang/Object;)Z!  /* ?++M,.>',d,`: * ! $%'#(/)9*;,=04/??1* 1 = L+ :<!"#PK wC8BJTorrent/GUI/MiFiltro.java/* * MiFiltro.java * * Created on 8 de octubre de 2007, 18:01 * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package BJTorrent.GUI; import java.io.File; /** * * @author Benjamn Muiz Garca */ /** * * Subclase de FileFilter que sirve para redefinir el filtro por el * que selecciona los ficheros el componente JFileChooser de nuestro GUI. */ public class MiFiltro extends javax.swing.filechooser.FileFilter { /** * Filtra o determina que tipos de ficheros (extensiones) se pueden seleccionar en un componente JFileChooser. *@param f File Fichero el cual filtramos su extensin. *@return boolean Cierto si se trata de un directorio o un fichero con extensin .torrent
* Falso en caso contrario. */ public boolean accept(File f) { if (f.isDirectory()) { return true; } String s = f.getName(); int i = s.lastIndexOf('.'); if (i > 0 && i < s.length() - 1) { String extension = s.substring(i+1).toLowerCase(); if ("torrent".equals(extension) ) { return true; } else { return false; } } return false; } /** * Mtodo sobre-escrito. * @return String Devuelve como descripcin "Fichero BitTorrent". */ public String getDescription() { String type = "Fichero BitTorrent"; return type; } }PK wC82gxxBJTorrent/GUI/ModeloTabla.class2* $ % & '()data[[Ljava/lang/Object; columnNames[Ljava/lang/String;longitudI()VCodeLineNumberTableLocalVariableTablethisLBJTorrent/GUI/ModeloTabla;+([[Ljava/lang/Object;I[Ljava/lang/String;)VdatoscolumnasgetColumnCount()I getRowCount getColumnName(I)Ljava/lang/String;col getValueAt(II)Ljava/lang/Object;filaisCellEditable(II)Z SourceFileModeloTabla.java   BJTorrent/GUI/ModeloTabla$javax/swing/table/AbstractTableModel!   3* !"  l**+*-*-/ 012*  0*9 /*B ;*2K G *22W       !@a   "#PK wC8sAi i BJTorrent/GUI/ModeloTabla.java/* * ModeloTabla.java * * Created on 27 de noviembre de 2007, 5:31 * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package BJTorrent.GUI; /** * * @author Benjamn Muiz Garca */ import javax.swing.table.AbstractTableModel