Package org.gudy.azureus2.core3.util

Examples of org.gudy.azureus2.core3.util.AESemaphore


     
      if ( pi == null ){
       
        listener.updateActivity( "Installing " + name );
       
        final AESemaphore sem = new AESemaphore( "analyserWait" );

        synchronized( StreamManager.this ){
         
          if ( cancelled ){
           
            throw( new Exception( "Cancelled" ));
          }
         
          active_sem  = sem;
        }
       
        final Throwable[] error = { null };
       
        new SimplePluginInstaller(
            id,
              "dlg.install." + id,
              new UIFunctions.actionListener()
            {
              public void
              actionComplete(
                Object    result )
              {
                try{
                  if ( result instanceof Boolean ){
                   
                  }else{
                   
                    error[0] = (Throwable)result;
                  }
                }finally{
                 
                  sem.release();
                }
              }
            });
       
        sem.reserve();
       
        synchronized( StreamManager.this ){
         
          if ( cancelled ){
             
View Full Code Here


        final DHTTransportContact  contact = (DHTTransportContact)data[0];
       
          // move to anti-spoof on cache forwards - gotta do a find-node first
          // to get the random id
       
        final AESemaphore  sem = new AESemaphore( "DHTDB:cacheForward" );
       
        contact.sendFindNode(
            new DHTTransportReplyHandlerAdapter()
            {
              public void
              findNodeReply(
                DHTTransportContact   _contact,
                DHTTransportContact[]  _contacts )
              { 
                anti_spoof_done.add( _contact );
             
                try{
                  // System.out.println( "cacheForward: pre-store findNode OK" );
               
                  List<HashWrapper>        keys  = (List<HashWrapper>)data[1];
                   
                  byte[][]        store_keys     = new byte[keys.size()][];
                  DHTTransportValue[][]  store_values   = new DHTTransportValue[store_keys.length][];
                 
                  keys_published[0] += store_keys.length;
                 
                  for (int i=0;i<store_keys.length;i++){
                   
                    HashWrapper  wrapper = keys.get(i);
                   
                    store_keys[i] = wrapper.getHash();
                   
                    List<DHTDBValueImpl>    values  = republish.get( wrapper );
                   
                    store_values[i] = new DHTTransportValue[values.size()];
             
                    values_published[0] += store_values[i].length;
                   
                    for (int j=0;j<values.size();j++){
                   
                      DHTDBValueImpl  value  = values.get(j);
                       
                        // we reduce the cache distance by 1 here as it is incremented by the
                        // recipients
                     
                      store_values[i][j] = value.getValueForRelay(local_contact);
                    }
                  }
                   
                  List<DHTTransportContact>  contacts = new ArrayList<DHTTransportContact>();
                 
                  contacts.add( contact );
                 
                  republish_ops[0]++;
                 
                  control.putDirectEncodedKeys(
                      store_keys,
                      "Republish cache",
                      store_values,
                      contacts );
                }finally{
                 
                  sem.release();
                }
              }
             
              public void
              failed(
                DHTTransportContact   _contact,
                Throwable        _error )
              {
                try{
                  // System.out.println( "cacheForward: pre-store findNode Failed" );
 
                  DHTLog.log( "cacheForward: pre-store findNode failed " + DHTLog.getString( _contact ) + " -> failed: " + _error.getMessage());
                                     
                  router.contactDead( _contact.getID(), false);
                 
                }finally{
                 
                  sem.release();
                }
              }
            },
            contact.getProtocolVersion() >= DHTTransportUDP.PROTOCOL_VERSION_ANTI_SPOOF2?new byte[0]:new byte[20] );
       
        sem.reserve();
      }
     
      try{
        this_mon.enter();
       
View Full Code Here

 
  public boolean
  isAlive(
    long    timeout )
  {
    final AESemaphore  sem = new AESemaphore( "DHTTransportContact:alive");
   
    final boolean[]  alive = { false };
   
    try{
      sendPing(
        new DHTTransportReplyHandlerAdapter()
        {
          public void
          pingReply(
            DHTTransportContact contact )
          {
            alive[0= true;
           
            sem.release();
          }
         
          public void
          failed(
            DHTTransportContact   contact,
            Throwable         cause )
          {
            sem.release();
          }
        });
     
      sem.reserve( timeout );
   
      return( alive[0] );
     
    }catch( Throwable e ){
     
View Full Code Here

 
    throws SubscriptionException
  {
    SubscriptionDownloader downloader;
   
    AESemaphore  sem = null;
   
    synchronized( active_subscription_downloaders ){
     
      List  waiting = (List)active_subscription_downloaders.get( subs );
     
      if ( waiting != null ){
       
        sem = new AESemaphore( "SS:waiter" );
       
        waiting.add( sem );
       
        if ( !is_auto ){
         
          active_subs_download_is_auto = false;
        }
      }else{
             
        active_subscription_downloaders.put( subs, new ArrayList());
       
        active_subs_download_is_auto = is_auto;
      }
 
      downloader = new SubscriptionDownloader(manager, (SubscriptionImpl)subs );
    }
   
    try{
      if ( sem == null ){
     
        downloader.download();
       
      }else{
       
        sem.reserve();
      }
    }finally{
     
      boolean  was_auto;
     
View Full Code Here

       
        tivo_manager.search();
       
        drive_manager.search();
       
        AESemaphore  sem = new AESemaphore( "DM:search" );
       
        DeviceManagerListener  dm_listener =
          new DeviceManagerListener()
          {
            public void
            deviceAdded(
              Device    device )
            {
              listener.deviceFound( device );
            }
           
            public void
            deviceChanged(
              Device    device )
            {
            }
           
            public void
            deviceAttentionRequest(
              Device    device )
            { 
            }
           
            public void
            deviceRemoved(
              Device    device )
            {
            }

            public void
            deviceManagerLoaded() {
            }
          };
         
        try{
          addListener( dm_listener );
       
          upnp_manager.search();
         
          sem.reserve( millis );
         
        }finally{
         
          synchronized( DeviceManagerImpl.this ){
           
View Full Code Here

  {
    final int RES_CONNECT_FAILED  = 0;
    final int RES_PROXY_FAILED    = 1;
    final int RES_OK        = 3;
 
    final AESemaphore  sem = new AESemaphore( "NetworkAdminSocksProxy:test" );
   
    final int[]  result = { RES_CONNECT_FAILED };
   
    final NetworkAdminException[]    error = { null };
    final ProxyDetails[]        details = {null};
   
    try{
      InetSocketAddress    socks_address =
        new InetSocketAddress( InetAddress.getByName( http_host ), Integer.parseInt(http_port));
     
      final InetSocketAddress  target_address = new InetSocketAddress( TARGET_HOST, TARGET_PORT );
     
      TCPConnectionManager.ConnectListener connect_listener =
        new TCPConnectionManager.ConnectListener()
        {
          public int
          connectAttemptStarted(
            int  default_connect_timeout )
          { 
            return( default_connect_timeout );
          }
   
          public void
          connectSuccess(
            SocketChannel channel )
          {
            final TCPTransportImpl  transport =
              new TCPTransportImpl(
                  (ProtocolEndpointTCP)ProtocolEndpointFactory.createEndpoint( ProtocolEndpoint.PROTOCOL_TCP, target_address ), false, false, null );
           
            transport.setFilter( TCPTransportHelperFilterFactory.createTransparentFilter( channel ));
   
            final long start_time = SystemTime.getCurrentTime();
           
            try{
              String  get_str = VersionCheckClient.getSingleton().getHTTPGetString( true, false );
             
              ByteBuffer  request = ByteBuffer.wrap( get_str.getBytes());
             
              while( request.hasRemaining()){
               
                if ( transport.write( new ByteBuffer[]{ request }, 0, 1 ) < 1 ) {
                 
                  if( SystemTime.getCurrentTime() - start_time > 30*1000 ) {
                   
                    String error = "proxy handshake message send timed out after 30sec";
                   
                    Debug.out( error );
                   
                    throw new IOException( error );
                  }
                 
                  try{
                    Thread.sleep( 50 );
                   
                  }catch( Throwable t ){
                   
                    t.printStackTrace();
                  }
                }
              }
                               
              TCPNetworkManager.getSingleton().getReadSelector().register(
                transport.getSocketChannel(),
                new VirtualChannelSelector.VirtualSelectorListener()
                {
                  private byte[]    reply_buffer = new byte[8192];
                 
                  private ByteBuffer  reply = ByteBuffer.wrap( reply_buffer );
                 
                  public boolean
                  selectSuccess(
                    VirtualChannelSelector   selector,
                    SocketChannel       sc,
                    Object           attachment )
                  {
                    try{
                       if( SystemTime.getCurrentTime() - start_time > 30*1000 ){
                        
                         throw( new Exception( "Timeout" ));
                       }

                       long len = transport.read( new ByteBuffer[]{ reply }, 0, 1 );

                       if ( len <= 0 ){
                        
                         return( false );
                       }
                      
                       String  str = new String( reply_buffer, 0, reply.position());
                                             
                       if ( str.indexOf( NL + NL ) != -1 ){
                       
                         System.out.println( str );
                        
                         String  server_name = "unknown";
                         String  auth    = "none";
                         String  response  = "unknown";
                          
                         StringTokenizer tok = new StringTokenizer( str, "\n" );
                        
                         int  line_num = 0;
                        
                         while( tok.hasMoreTokens()){
                          
                           String  token = tok.nextToken().trim();
                          
                           if ( token.length() == 0 ){
                            
                             continue;
                           }
                          
                           line_num++;
                          
                           if ( line_num == 1 ){
                            
                             int pos = token.indexOf(' ');
                            
                             if ( pos != -1 ){
                              
                               response = token.substring( pos + 1 ).trim();
                             }
                           }else{
                            
                             int  pos = token.indexOf(':');
                            
                             if ( pos != -1 ){
                              
                               String  lhs = token.substring( 0, pos ).trim().toLowerCase( MessageText.LOCALE_ENGLISH );
                               String  rhs = token.substring( pos+1 ).trim();

                               if ( lhs.equals( "server" )){
                                
                                 if ( !response.startsWith( "200" )){
                                 
                                   server_name = rhs;
                                 }
                               }else if ( lhs.equals( "via" )){
                                  
                                 server_name = rhs;
                                
                                 int  p = server_name.indexOf(' ');
                                
                                 if ( p != -1 ){
                                  
                                   server_name = server_name.substring( p+1 ).trim();
                                 }
                                
                               }else if ( lhs.equals( "proxy-authenticate" )){
                                
                                 auth = rhs;
                               }
                             }
                           }
                         }
                        
                         details[0] =
                           new ProxyDetails(
                               server_name,
                               response,
                               auth );
                        
                         transport.close( "Done" );
                        
                         result[0]   = RES_OK;

                         sem.release()
                       
                       }else{
                       
                        TCPNetworkManager.getSingleton().getReadSelector().resumeSelects( transport.getSocketChannel() );
                      }
     
                       return( true );
                     
                    }
                    catch( Throwable t ) {
 
 
                      return false;
                    }
                  }
   
                  public void
                  selectFailure(
                    VirtualChannelSelector   selector,
                    SocketChannel       sc,
                    Object           attachment,
                    Throwable        msg )
                  {
                    result[0]   = RES_PROXY_FAILED;
                    error[0= new NetworkAdminException( "Proxy error", msg );
                   
                    transport.close( "Proxy error" );
                   
                    sem.release();     
                  }
                },
                null );
             
            }catch( Throwable t ) {

              result[0]   = RES_PROXY_FAILED;
              error[0= new NetworkAdminException( "Proxy connect failed", t );
             
              sem.release();            }
          }
         
          public void
          connectFailure(
            Throwable failure_msg )
          {
            result[0]   = RES_CONNECT_FAILED;
            error[0= new NetworkAdminException( "Connect failed", failure_msg );
             
            sem.release();
          }
        };
   
      TCPNetworkManager.getSingleton().getConnectDisconnectManager().requestNewConnection(
          socks_address, connect_listener, ProtocolEndpoint.CONNECT_PRIORITY_MEDIUM );
           
    }catch( Throwable e ){
     
      result[0]   = RES_CONNECT_FAILED;
      error[0= new NetworkAdminException( "Connect failed", e );
     
      sem.release();
    }
   
    if ( !sem.reserve(10000)){
     
      result[0]   = RES_CONNECT_FAILED;
      error[0]   = new NetworkAdminException( "Connect timeout" );
    }
   
View Full Code Here

    if ( !send_azid ){
   
      message.setSendAZID( false );
    }
   
    final AESemaphore sem = new AESemaphore( "PlatformMessengerConfig:syncInvoke" );
   
    final Object[] result = { null };
   
    PlatformMessenger.queueMessage(
      message,
      new PlatformMessengerListener()
      {
        public void
        messageSent(
          PlatformMessage   message )
        {
        }
 
        public void
        replyReceived(
          PlatformMessage   message,
          String         replyType,
          Map         reply )
        {
          try{
            if ( replyType.equals( PlatformMessenger.REPLY_EXCEPTION )){
             
              String    e_message   = (String)reply.get( "message" );

              if ( e_message != null ){
               
                result[0] = new PlatformMessengerException( e_message );

              }else{
               
                String    text   = (String)reply.get( "text" );
               
                Throwable  e     = (Throwable)reply.get( "Throwable" );
               
                if ( text == null && e == null ){
                 
                  result[0] = new PlatformMessengerException( "Unknown error" );
                 
                }else if ( text == null ){
                 
                  result[0] = new PlatformMessengerException( "Failed to send RPC", e );
                 
                }else if ( e == null ){
                 
                  result[0] = new PlatformMessengerException( text );
                 
                }else{
                 
                  result[0] = new PlatformMessengerException( text, e );
                }
              }
            }else{
             
              result[0] = reply;
            }
          }finally{
           
            sem.release();
          }
        }
      });
   
    sem.reserve();
   
    if ( result[0] instanceof PlatformMessengerException ){
     
      throw((PlatformMessengerException)result[0]);
    }
View Full Code Here

  {
      // unfortunately we need this to run synchronously as the caller may be disabling it
      // and then setting speed limits in which case we can't go async and restore the
      // original values below and overwrite the new limit...
   
    final AESemaphore  sem = new AESemaphore( "SpeedManagerImpl.setEnabled" );
   
      // single thread enable/disable (and derivative reset) ops
   
    dispatcher.dispatch(
      new AERunnable()
      {
        public void
        runSupport()
        {
          try{
            setEnabledSupport( _enabled );
           
          }finally{
           
            sem.release();
          }
        }
      });
   
    if ( !sem.reserve( 10000 )){
     
      Debug.out( "operation didn't complete in time" );
    }
  }
View Full Code Here

    DHTTransportContact       rendezvous,
    final DHTTransportUDPContact  target,
    Map                originator_client_data,
    boolean              no_tunnel )
  {   
    AESemaphore  wait_sem   = new AESemaphore( "DHTNatPuncher::sendPunch" );
    Object[]  wait_data   = new Object[]{ target, wait_sem, new Integer(0)};
   
    try{

      try{
        punch_mon.enter();
     
        oustanding_punches.add( wait_data );
       
      }finally{
       
        punch_mon.exit();
      }
     
      Map  request = new HashMap();
     
      request.put("type", new Long( RT_PUNCH_REQUEST ));
     
      request.put("target", target.getAddress().toString().getBytes());
     
      if ( originator_client_data != null ){
       
        if ( no_tunnel ){
         
          originator_client_data.put( "_notunnel", new Long(1));
        }
       
        request.put( "client_data", originator_client_data );
      }
 
        // for a message payload (i.e. no_tunnel) we double the initiator timeout to give
        // more chance for reasonable size messages to get through as they have to go through
        // 2 xfer processes
     
      Map response = sendRequest( rendezvous, request, no_tunnel?TRANSFER_TIMEOUT*2:TRANSFER_TIMEOUT );
     
      if ( response == null ){
       
        return( null );
      }
     
      if (((Long)response.get( "type" )).intValue() == RT_PUNCH_REPLY ){
       
        int  result = ((Long)response.get("ok")).intValue();

        trace( "received " + ( no_tunnel?"message":"punch") + " reply: " + (result==0?"failed":"ok" ));
       
        if ( result == 1 ){
         
            // pick up port changes from the rendezvous
                     
          Long  indirect_port = (Long)response.get( "port" );
         
          if ( indirect_port != null ){
           
            int transport_port  = indirect_port.intValue();
       
            if ( transport_port != 0 ){
           
              InetSocketAddress  existing_address = target.getTransportAddress();
           
              if ( transport_port != existing_address.getPort()){
             
                target.setTransportAddress(
                    new InetSocketAddress(existing_address.getAddress(), transport_port ));
              }
            }
          } 
         
          if ( !no_tunnel ){
           
              // ping the target a few times to try and establish a tunnel
                     
            UTTimerEvent  event =
              timer.addPeriodicEvent(
                  3000,
                  new UTTimerEventPerformer()
                  {
                    private int  pings = 1;
                   
                    public void
                    perform(
                      UTTimerEvent    event )
                    {
                      if ( pings > 3 ){
                       
                        event.cancel();
                     
                        return;
                      }
                   
                      pings++;
                       
                      if ( sendTunnelOutbound( target )){
                       
                        event.cancel();
                      }
                    }
                  });
             
            if ( sendTunnelOutbound( target )){
             
              event.cancel();
            }
           
              // give the other end a few seconds to kick off some tunnel events to us
           
            if ( wait_sem.reserve(10000)){
             
              event.cancel();
            }
          }
                     
View Full Code Here

              }
             
              long  start    = SystemTime.getMonotonousTime();
              long  max      = MAX_REMOTE_SEARCH_MILLIS;
             
              final AESemaphore  sem = new AESemaphore( "RCM:rems" );
             
              int  sent = 0;
             
              final int[]      done = {0};
             
              for (int i=0;i<ddb_contacts.size();i++){
               
                final DistributedDatabaseContact c = ddb_contacts.get( i );
                               
                new AEThread2( "RCM:rems", true )
                {
                  public void
                  run()
                  {
                    try{
                      sendRemoteSearch( si, hashes, c, term, observer );
                                           
                    }finally{
                     
                      synchronized( done ){
                     
                        done[0]++;
                      }
                     
                      sem.release();
                    }
                  }
                }.start();
               
                sent++;
               
                synchronized( done ){
                 
                  if ( done[0] >= ddb_contacts.size() / 2 ){
                   
                    start    = SystemTime.getMonotonousTime();
                    max      = 5*1000;
                   
                    break;
                  }
                }
               
                if ( i > 10 ){
                 
                  try{
                    Thread.sleep( 250 );
                   
                  }catch( Throwable e ){
                  }
                }
              }
             
              for (int i=0;i<sent;i++){
               
                if ( done[0] > sent*4/5 ){
                 
                  break;
                }
               
                long  elapsed = SystemTime.getMonotonousTime() - start;
               
                if ( elapsed < max ){
                 
                  sem.reserve( max - elapsed );
                 
                }else{
                 
                  break;
                }
View Full Code Here

TOP

Related Classes of org.gudy.azureus2.core3.util.AESemaphore

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.