/** Adds a connection to the idle pool. */
  void toIdle(ManagedPoolItem item) {
    try {
      if (_maxConnections < _connectionPool.size() || item.isConnectionError()) {
        return;
      }

      ManagedConnection mConn = item.getManagedConnection();

      if (mConn == null) {
        return;
      }

      mConn.cleanup();

      long now = CurrentTime.getCurrentTime();

      if (_idlePool.size() == 0) _idlePoolExpire = now + _idleTimeout;

      if (_idlePoolExpire < now) {
        // shrink the idle pool when non-empty for idleTimeout
        _idlePoolExpire = now + _idleTimeout;
      } else if (_idlePool.add(mConn)) {
        item = null;
        return;
      }
    } catch (Exception e) {
      log.log(Level.FINE, e.toString(), e);
    } finally {
      notifyConnectionAvailable();

      if (item != null) item.destroy();
    }
  }
  private boolean waitForAvailableConnection(long expireTime) {
    _availableWaitCount.incrementAndGet();

    try {
      synchronized (_availableLock) {
        // return false only if the timeout occurs before the wait
        boolean isAfterWait = false;

        while (!isIdleAvailable() && !isCreateAvailable()) {
          try {
            long now = CurrentTime.getCurrentTimeActual();

            long delta = expireTime - now;

            if (delta <= 0) return isAfterWait;

            Thread.interrupted();
            _availableLock.wait(delta);

            isAfterWait = true;
          } catch (InterruptedException e) {
            log.log(Level.FINER, e.toString(), e);
          }
        }

        return true;
      }
    } finally {
      _availableWaitCount.decrementAndGet();
    }
  }
  /** Creates a new connection. */
  private UserPoolItem createConnection(
      ManagedConnectionFactory mcf,
      Subject subject,
      ConnectionRequestInfo info,
      UserPoolItem oldPoolItem)
      throws ResourceException {
    boolean isValid = false;
    ManagedPoolItem poolItem = null;

    try {
      ManagedConnection mConn = mcf.createManagedConnection(subject, info);

      if (mConn == null)
        throw new ResourceException(
            L.l("'{0}' did not return a connection from createManagedConnection", mcf));

      poolItem = new ManagedPoolItem(this, mcf, mConn);

      UserPoolItem userPoolItem;

      // Ensure the connection is still valid
      userPoolItem = poolItem.toActive(subject, info, oldPoolItem);

      if (userPoolItem == null) {
        throw new ResourceException(L.l("Connection '{0}' was not valid on creation", poolItem));
      }

      _connectionCreateCountTotal.incrementAndGet();

      synchronized (_connectionPool) {
        _connectionPool.add(poolItem);
      }

      poolItem = null;
      isValid = true;

      return userPoolItem;
    } finally {
      if (!isValid) {
        _connectionFailCountTotal.incrementAndGet();
        _lastFailTime = CurrentTime.getCurrentTime();
      }

      // server/308b - connection removed on rollback-only, when it's
      // theoretically possible to reuse it
      if (poolItem != null) poolItem.destroy();
    }
  }
Exemplo n.º 4
0
  public void run() {

    do {
      try {
        BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
        File file = new File("time.txt");
        FileWriter fw = new FileWriter(file);
        Long start = 0l;
        Long end = 0l;
        BufferedWriter bw = new BufferedWriter(fw);
        System.out.println("Enter the preferred choice");
        System.out.println("1. REGISTER");
        System.out.println("2. LEAVE");
        System.out.println("3. SEARCH FOR RFC");
        System.out.println("4. KEEPALIVE");
        System.out.println("5. Do you want to EXIT");
        System.out.println("*********************************************");

        choice = Integer.parseInt(inFromUser.readLine());
        // System.out.println(" Client requesting for connection");
        clientSocket = new Socket("192.168.15.103", 6500);
        BufferedReader inFromServer =
            new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        PrintWriter outToServer =
            new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream()), true);

        // outToServer.println("Peer Requesting Connection");

        switch (choice) {
          case 4:
            outToServer.println(
                "KEEP ALIVE P2P-DI Cookieno "
                    + cookie
                    + " OS: "
                    + System.getProperty("os.name")
                    + " "
                    + "v"
                    + System.getProperty("os.version")
                    + " USER: "******"user.name"));
            System.out.println(inFromServer.readLine());
            System.out.println("*********************************************");
            break;
          case 1:
            try {
              // System.out.println("Case 1 entered"); // testing
              // statement
              System.out.println("Please enter your IP addres");
              ip = inFromUser.readLine();
              outToServer.println(
                  "REG P2P-DI/1.1 -1 Portno 6789 Hostname "
                      + ip
                      + " OS: "
                      + System.getProperty("os.name")
                      + " "
                      + "v"
                      + System.getProperty("os.version")
                      + " USER: "******"user.name"));
              cookie = Integer.parseInt(inFromServer.readLine());
              TTL = 7200;

              System.out.println(inFromServer.readLine());
              System.out.print("You are registered at time : ");
              ct.currenttime();
              System.out.println("Peer " + cookie); // peer cookie value
              System.out.println("TTL Value :" + TTL);
              System.out.println("*********************************************");

              break;
            } catch (Exception e) {
            }
          case 2:

            // System.out.println("Case 2 entered"); testing statement
            outToServer.println(
                "LEAVE P2P-DI Cookieno "
                    + cookie
                    + " OS: "
                    + System.getProperty("os.name")
                    + " "
                    + "v"
                    + System.getProperty("os.version")
                    + " USER: "******"user.name"));
            // System.out.println("I am in peer"); testing statement
            System.out.println(inFromServer.readLine());
            System.out.println("*********************************************");
            break;

          case 3:
            outToServer.println(
                "PQUERY P2P-DI Cookieno "
                    + cookie
                    + " Portno 6789"
                    + " OS: "
                    + System.getProperty("os.name")
                    + " "
                    + "v"
                    + System.getProperty("os.version")
                    + " USER: "******"user.name"));
            System.out.println("Which RFC number do you wish to have ?");
            reqrfc = Integer.parseInt(inFromUser.readLine());

            // System.out.println("Entered peer again");
            // outToServer.println("KEEP ALIVE cookieno "+cookie);

            String details = inFromServer.readLine();

            String[] parray = details.split(" ");
            int inactive = Integer.parseInt(parray[(parray.length - 1)]);
            // System.out.println(darray.length);
            if ((parray.length == 3) && (ip.equals(parray[1]))) {
              System.out.println("P2P-DI No Active Peers available");
              System.out.println("*********************************************");
            } else {
              System.out.println("****<POPULATING THE ACTIVE PEER LIST>****");
              System.out.println();
              System.out.println("The active peer list is as follows:");
              System.out.println();

              String[] darray = details.split(" ");

              // System.out.println("Array length"+darray.length);
              for (int i = 0; i < (darray.length - 2); i = i + 2) {

                acthostname[j] = darray[i + 1];
                System.out.println("Hostname :" + acthostname[j]);

                actportno[j] = Integer.parseInt(darray[i + 2]);
                System.out.println("Portno :" + actportno[j]);

                System.out.println("*****************************");
                j = j + 1;
              }

              System.out.println("Connecting to the active peers for its RFC Index");
              for (int x = 0; x < j; x++) {
                // System.out.println(ip);
                if (!(acthostname[x].equals(ip))) {
                  System.out.println("Connecting to " + acthostname[x]);

                  Socket peersocket = new Socket(acthostname[x], 6791); // implement
                  // a for
                  // loop

                  BufferedReader inFromPeer =
                      new BufferedReader(new InputStreamReader(peersocket.getInputStream()));
                  PrintWriter outToPeer =
                      new PrintWriter(new OutputStreamWriter(peersocket.getOutputStream()), true);

                  outToPeer.println("RFCIndex");
                  // System.out.println(inFromServer.readLine());
                  // int searchrfc=Integer.parseInt(inFromUser.readLine());
                  // outToServer.println(searchrfc);

                  String rfcindex = inFromPeer.readLine(); // tell server to
                  // send rfc in
                  // string
                  String rfcarray[] = rfcindex.split(" ");
                  //  System.out.println(rfcindex);
                  for (int i = 1; i < rfcarray.length; i = i + 4) {
                    trfcno[z] = Integer.parseInt(rfcarray[i]);
                    //	System.out.println("RFC number " + trfcno[z]);
                    trfctitle[z] = rfcarray[i + 1];
                    //	System.out.println("RFC Title " + trfctitle[z]);
                    tpeername[z] = rfcarray[i + 2];
                    //	System.out.println("Peer Ip Address " + tpeername[z]);
                    tpTTL[z] = Integer.parseInt(rfcarray[i + 3]);
                    //	System.out.println("TTL value :" + tpTTL[z]);

                    counter1 = counter1 + 1;

                    z = z + 1;
                  }
                  z = 0;
                  //         if(arraybound==0)
                  //         {
                  System.arraycopy(trfcno, 0, rfcno, counter2, trfcno.length);
                  System.arraycopy(trfctitle, 0, rfctitle, counter2, trfctitle.length);
                  System.arraycopy(tpeername, 0, peername, counter2, tpeername.length);
                  System.arraycopy(tpTTL, 0, pTTL, counter2, tpTTL.length);
                  z = 0;
                  counter2 = counter1;
                  counter1 = 0;
                  //         arraybound=arraybound+1;
                  //        }

                  System.out.println();
                  System.out.println();
                  System.out.println("*************************************************");
                  System.out.println("RFC Index received from the Peer");
                  //		System.out.println();
                  System.out.println("\n-----------------------------------------");
                  System.out.println("RFC Index System - Display RFC Idex");
                  System.out.println("-------------------------------------------");
                  System.out.format(
                      "%10s%15s%15s%10s", "RFC No", "RFC Title", "Peer Name", "TTL Value");
                  System.out.println();
                  // StudentNode current = top;
                  // while (current != null){
                  // Student read = current.getStudentNode();
                  for (int i = 0; i < 60; i++) {
                    System.out.format(
                        "%10s%15s%15s%10s",
                        " " + rfcno[i], rfctitle[i], peername[i], " " + pTTL[i]);
                    System.out.println();
                  }
                  // This will output with a set number of character spaces
                  // per field, giving the list a table-like quality
                  // }

                  peersocket.close();
                } // end of if

                for (int i = 0; i < rfcno.length; i++) {

                  if (rfcno[i] == reqrfc) {
                    String taddress = InetAddress.getByName(peername[i]).toString();
                    String[] taddr = taddress.split("/");
                    InetAddress tproperaddress = InetAddress.getByName(taddr[1]);
                    //	System.out.println("Inetaddress" + tproperaddress);

                    Socket peersocket1 = new Socket(tproperaddress, 6791); // implement
                    // a
                    // for
                    // loop
                    System.out.println("The connection to the Active Peer is establshed");
                    BufferedReader inFromP2P =
                        new BufferedReader(new InputStreamReader(peersocket1.getInputStream()));
                    PrintWriter outToP2P =
                        new PrintWriter(
                            new OutputStreamWriter(peersocket1.getOutputStream()), true);

                    System.out.println("Requested the RFC to the Active Peer Server");

                    start = System.currentTimeMillis();

                    outToP2P.println("GETRFC " + reqrfc);

                    // Socket socket = ;

                    try {

                      // Socket socket = null;
                      InputStream is = null;
                      FileOutputStream fos = null;
                      BufferedOutputStream bos = null;
                      int bufferSize = 0;

                      try {
                        is = peersocket1.getInputStream();

                        bufferSize = 64;
                        // System.out.println("Buffer size: " + bufferSize);
                      } catch (IOException ex) {
                        System.out.println("Can't get socket input stream. ");
                      }

                      try {
                        fos = new FileOutputStream("E:\\rfc" + reqrfc + "copy.txt");
                        bos = new BufferedOutputStream(fos);

                      } catch (FileNotFoundException ex) {
                        System.out.println("File not found. ");
                      }

                      byte[] bytes = new byte[bufferSize];

                      int count;

                      while ((count = is.read(bytes)) > 0) {
                        //	System.out.println(count);
                        bos.write(bytes, 0, count);
                      }
                      System.out.println("P2P-DI 200 OK The RFC is copied");
                      end = System.currentTimeMillis();
                      System.out.println(
                          "Total Time to download file   " + (end - start) + " milliseconds");

                      bos.flush();

                      bos.close();
                      is.close();
                      peersocket1.close();
                      break;

                    } catch (SocketException e) {
                      System.out.println("Socket exception");
                    }

                  } // end of if
                  else {
                    //  	System.out.println("No Peer with the required RFC could be found");

                  }
                  clientSocket.close();
                  //	System.out.println("Connection closed");
                  bw.close();
                  fw.close();
                } // end of inner for
              } // end of outer for
              System.out.println("Connection closed");
            } // end of switch
        } // end of else which checks the inactive conditions
      } // end of try
      catch (IOException ioe) {
        System.out.println("IOException on socket listen: " + ioe);
        ioe.printStackTrace();
      }

    } // end of do
    while (choice != 5);
  } // end of run
  /** Allocates a connection from the idle pool. */
  private UserPoolItem allocateIdleConnection(
      ManagedConnectionFactory mcf,
      Subject subject,
      ConnectionRequestInfo info,
      UserPoolItem oldPoolItem)
      throws ResourceException {
    while (_lifecycle.isActive()) {
      ManagedConnection mConn;

      long now = CurrentTime.getCurrentTime();

      if (_lastValidCheckTime + 15000L < now) {
        _lastValidCheckTime = now;

        if (mcf instanceof ValidatingManagedConnectionFactory) {
          ValidatingManagedConnectionFactory vmcf;
          vmcf = (ValidatingManagedConnectionFactory) mcf;

          validate(vmcf);
        }
      }

      ManagedPoolItem poolItem = null;

      while (true) {
        // asks the Driver's ManagedConnectionFactory to match an
        // idle connection
        synchronized (_connectionPool) {
          mConn = mcf.matchManagedConnections(_idlePool, subject, info);

          // If there are no more idle connections, return null
          if (mConn == null) return null;

          // remove can fail for threading reasons, so only succeed if it works.
          if (!_idlePool.remove(mConn)) {
            mConn = null;
          }
        }

        if (mConn != null) {
          poolItem = findPoolItem(mConn);

          if (poolItem == null)
            throw new IllegalStateException(
                L.l("Unexpected non-matching PoolItem found for {0}", mConn));

          break;
        }
      }

      try {
        // Ensure the connection is still valid
        UserPoolItem userPoolItem;
        userPoolItem = poolItem.toActive(subject, info, oldPoolItem);

        if (userPoolItem != null) {
          poolItem = null;
          return userPoolItem;
        }
      } finally {
        if (poolItem != null) poolItem.destroy();
      }
    }

    return null;
  }
  /**
   * Allocates the pool item for a connection, creating one if necessary.
   *
   * @param mcf the driver's ManagedConnectionFactory for creating pooled connections
   * @param subject the user's authentication credentials
   * @param info the user's extra connection information
   */
  UserPoolItem allocatePoolConnection(
      ManagedConnectionFactory mcf,
      Subject subject,
      ConnectionRequestInfo info,
      UserPoolItem oldPoolItem)
      throws ResourceException {
    long expireTime = CurrentTime.getCurrentTimeActual() + _connectionWaitTimeout;

    if (!_lifecycle.isActive()) {
      throw new IllegalStateException(
          L.l("{0}: Can't allocate connection because the connection pool is closed.", this));
    }

    do {
      UserPoolItem userPoolItem = allocateIdleConnection(mcf, subject, info, oldPoolItem);

      if (userPoolItem != null) return userPoolItem;

      // if no item in pool, try to create one
      if (startCreateConnection()) {
        try {
          return createConnection(mcf, subject, info, oldPoolItem);
        } finally {
          finishCreateConnection();
        }
      }
    } while (_lifecycle.isActive() && waitForAvailableConnection(expireTime));

    if (!_lifecycle.isActive())
      throw new IllegalStateException(
          L.l("{0}: Can't allocate connection because the connection pool is closed.", this));

    String message =
        (this
            + " pool throttled create timeout"
            + " (pool-size="
            + _connectionPool.size()
            + ", max-connections="
            + _maxConnections
            + ", create-count="
            + _createCount.get()
            + ", max-create-connections="
            + _maxCreateConnections
            + ")");

    HealthStatusService.updateCurrentHealthStatus(this, HealthStatus.WARNING, message);

    if (startCreateOverflow()) {
      try {
        return createConnection(mcf, subject, info, oldPoolItem);
      } finally {
        finishCreateConnection();
      }
    }

    message =
        (this
            + " pool overflow failed to create"
            + " (pool-size="
            + _connectionPool.size()
            + ", max-connections="
            + _maxConnections
            + ", create-count="
            + _createCount.get()
            + ", max-create-connections="
            + _maxCreateConnections
            + ")");

    HealthStatusService.updateCurrentHealthStatus(this, HealthStatus.CRITICAL, message);

    throw new ResourceException(
        L.l("Can't create overflow connection connection-max={0}", _maxConnections));
  }