@Override
  public DatagramChannel bind(SocketAddress local) throws IOException {
    synchronized (readLock) {
      synchronized (writeLock) {
        synchronized (stateLock) {
          ensureOpen();
          if (localAddress != null) throw new AlreadyBoundException();
          InetSocketAddress isa;
          if (local == null) {
            // only Inet4Address allowed with IPv4 socket
            if (family == StandardProtocolFamily.INET) {
              isa = new InetSocketAddress(InetAddress.getByName("0.0.0.0"), 0);
            } else {
              isa = new InetSocketAddress(0);
            }
          } else {
            isa = Net.checkAddress(local);

            // only Inet4Address allowed with IPv4 socket
            if (family == StandardProtocolFamily.INET) {
              InetAddress addr = isa.getAddress();
              if (!(addr instanceof Inet4Address)) throw new UnsupportedAddressTypeException();
            }
          }
          SecurityManager sm = System.getSecurityManager();
          if (sm != null) {
            sm.checkListen(isa.getPort());
          }
          Net.bind(family, fd, isa.getAddress(), isa.getPort());
          localAddress = Net.localAddress(fd);
        }
      }
    }
    return this;
  }
  public static void main(String[] args) {
    String host = args[0];
    int port = Integer.parseInt(args[1]);
    long id = Long.parseLong(args[2]);
    String character = args[3];
    long actorId = Long.parseLong(args[4]);

    // Install an RMISecurityManager, if there is not a
    // SecurityManager already installed
    if (System.getSecurityManager() == null) {
      System.setSecurityManager(new RMISecurityManager());
    }

    String name = "rmi://" + host + ":" + port + "/MovieDatabase";

    try {
      MovieDatabase db = (MovieDatabase) Naming.lookup(name);
      db.noteCharacter(id, character, actorId);

      Movie movie = db.getMovie(id);
      out.println(movie.getTitle());
      for (Map.Entry entry : movie.getCharacters().entrySet()) {
        out.println("  " + entry.getKey() + "\t" + entry.getValue());
      }

    } catch (RemoteException | NotBoundException | MalformedURLException ex) {
      ex.printStackTrace(System.err);
    }
  }
  public DatagramChannel connect(SocketAddress sa) throws IOException {
    int localPort = 0;

    synchronized (readLock) {
      synchronized (writeLock) {
        synchronized (stateLock) {
          ensureOpenAndUnconnected();
          InetSocketAddress isa = Net.checkAddress(sa);
          SecurityManager sm = System.getSecurityManager();
          if (sm != null) sm.checkConnect(isa.getAddress().getHostAddress(), isa.getPort());
          int n = Net.connect(family, fd, isa.getAddress(), isa.getPort());
          if (n <= 0) throw new Error(); // Can't happen

          // Connection succeeded; disallow further invocation
          state = ST_CONNECTED;
          remoteAddress = sa;
          sender = isa;
          cachedSenderInetAddress = isa.getAddress();
          cachedSenderPort = isa.getPort();

          // set or refresh local address
          localAddress = Net.localAddress(fd);
        }
      }
    }
    return this;
  }
  private JarFile getCachedJarFile(URL url) {
    JarFile result = (JarFile) fileCache.get(url);

    /* if the JAR file is cached, the permission will always be there */
    if (result != null) {
      Permission perm = getPermission(result);
      if (perm != null) {
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
          try {
            sm.checkPermission(perm);
          } catch (SecurityException se) {
            // fallback to checkRead/checkConnect for pre 1.2
            // security managers
            if ((perm instanceof java.io.FilePermission)
                && perm.getActions().indexOf("read") != -1) {
              sm.checkRead(perm.getName());
            } else if ((perm instanceof java.net.SocketPermission)
                && perm.getActions().indexOf("connect") != -1) {
              sm.checkConnect(url.getHost(), url.getPort());
            } else {
              throw se;
            }
          }
        }
      }
    }
    return result;
  }
  public boolean connect(SocketAddress sa) throws IOException {
    int trafficClass = 0; // ## Pick up from options
    int localPort = 0;

    synchronized (readLock) {
      synchronized (writeLock) {
        ensureOpenAndUnconnected();
        InetSocketAddress isa = Net.checkAddress(sa);
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) sm.checkConnect(isa.getAddress().getHostAddress(), isa.getPort());
        synchronized (blockingLock()) {
          int n = 0;
          try {
            try {
              begin();
              synchronized (stateLock) {
                if (!isOpen()) {
                  return false;
                }
                readerThread = NativeThread.current();
              }
              for (; ; ) {
                InetAddress ia = isa.getAddress();
                if (ia.isAnyLocalAddress()) ia = InetAddress.getLocalHost();
                n = connectImpl(ia, isa.getPort(), trafficClass);
                if ((n == IOStatus.INTERRUPTED) && isOpen()) continue;
                break;
              }
            } finally {
              readerCleanup();
              end((n > 0) || (n == IOStatus.UNAVAILABLE));
              assert IOStatus.check(n);
            }
          } catch (IOException x) {
            // If an exception was thrown, close the channel after
            // invoking end() so as to avoid bogus
            // AsynchronousCloseExceptions
            close();
            throw x;
          }
          synchronized (stateLock) {
            remoteAddress = isa;
            if (n > 0) {

              // Connection succeeded; disallow further
              // invocation
              state = ST_CONNECTED;
              return true;
            }
            // If nonblocking and no exception then connection
            // pending; disallow another invocation
            if (!isBlocking()) state = ST_PENDING;
            else assert false;
          }
        }
        return false;
      }
    }
  }
  @Override
  <A> Future<Void> implConnect(
      SocketAddress remote, A attachment, CompletionHandler<Void, ? super A> handler) {
    if (!isOpen()) {
      Throwable exc = new ClosedChannelException();
      if (handler == null) return CompletedFuture.withFailure(exc);
      Invoker.invoke(this, handler, attachment, null, exc);
      return null;
    }

    InetSocketAddress isa = Net.checkAddress(remote);

    // permission check
    SecurityManager sm = System.getSecurityManager();
    if (sm != null) sm.checkConnect(isa.getAddress().getHostAddress(), isa.getPort());

    // check and update state
    // ConnectEx requires the socket to be bound to a local address
    IOException bindException = null;
    synchronized (stateLock) {
      if (state == ST_CONNECTED) throw new AlreadyConnectedException();
      if (state == ST_PENDING) throw new ConnectionPendingException();
      if (localAddress == null) {
        try {
          bind(new InetSocketAddress(0));
        } catch (IOException x) {
          bindException = x;
        }
      }
      if (bindException == null) state = ST_PENDING;
    }

    // handle bind failure
    if (bindException != null) {
      try {
        close();
      } catch (IOException ignore) {
      }
      if (handler == null) return CompletedFuture.withFailure(bindException);
      Invoker.invoke(this, handler, attachment, null, bindException);
      return null;
    }

    // setup task
    PendingFuture<Void, A> result = new PendingFuture<Void, A>(this, handler, attachment);
    ConnectTask task = new ConnectTask<A>(isa, result);
    result.setContext(task);

    // initiate I/O
    if (Iocp.supportsThreadAgnosticIo()) {
      task.run();
    } else {
      Invoker.invokeOnThreadInThreadPool(this, task);
    }
    return result;
  }
Beispiel #7
0
  private Descrittore contatta_server(String nome) {

    // variabili per l'RMI
    RMIServerInt serv = null; // server
    Descrittore descr_rit = null; // descrittore ritornato

    if (nome == null) {
      System.out.println("## contatta_server di Download ha ricevuto parametro null ! ");
      return null;
    }

    System.out.println("@ provo a contattare il server RMI ");
    // ################  RMI ################
    if (System.getSecurityManager() == null) {
      System.setSecurityManager(new SecurityManager());
    }

    Object o = null;
    try {
      // o = Naming.lookup("rmi://192.168.0.10:1099/srmi");
      Registry registry = LocateRegistry.getRegistry(server.getHostAddress());
      o = registry.lookup("srmi");

    } catch (RemoteException e) {
      System.out.println("## Problemi nell'RMI di Download - contatta_server di " + nome);
      e.printStackTrace();
    } catch (NotBoundException e) {
      System.out.println("## Problemi nell'RMI di Download - contatta_server di " + nome);
      e.printStackTrace();
    }

    if (o == null) {
      System.out.println(
          "## l'RMI di Download - contatta_server di " + nome + " ha ritornato l'oggetto o null");
      return null;
    }

    serv = (RMIServerInt) o;

    try {
      descr_rit = serv.lookup(nome, InetAddress.getLocalHost());
    } catch (RemoteException e) {
      e.printStackTrace();
      System.out.println("## Problemi con Lookup di " + nome);
      return null;

    } catch (UnknownHostException e) {
      e.printStackTrace();
      System.out.println("## Problemi con Lookup di " + nome);
      return null;
    }

    return descr_rit;
  }
 public SocketAddress receive(ByteBuffer dst) throws IOException {
   if (dst.isReadOnly()) throw new IllegalArgumentException("Read-only buffer");
   if (dst == null) throw new NullPointerException();
   synchronized (readLock) {
     ensureOpen();
     // Socket was not bound before attempting receive
     if (localAddress() == null) bind(null);
     int n = 0;
     ByteBuffer bb = null;
     try {
       begin();
       if (!isOpen()) return null;
       SecurityManager security = System.getSecurityManager();
       readerThread = NativeThread.current();
       if (isConnected() || (security == null)) {
         do {
           n = receive(fd, dst);
         } while ((n == IOStatus.INTERRUPTED) && isOpen());
         if (n == IOStatus.UNAVAILABLE) return null;
       } else {
         bb = Util.getTemporaryDirectBuffer(dst.remaining());
         for (; ; ) {
           do {
             n = receive(fd, bb);
           } while ((n == IOStatus.INTERRUPTED) && isOpen());
           if (n == IOStatus.UNAVAILABLE) return null;
           InetSocketAddress isa = (InetSocketAddress) sender;
           try {
             security.checkAccept(isa.getAddress().getHostAddress(), isa.getPort());
           } catch (SecurityException se) {
             // Ignore packet
             bb.clear();
             n = 0;
             continue;
           }
           bb.flip();
           dst.put(bb);
           break;
         }
       }
       return sender;
     } finally {
       if (bb != null) Util.releaseTemporaryDirectBuffer(bb);
       readerThread = 0;
       end((n > 0) || (n == IOStatus.UNAVAILABLE));
       assert IOStatus.check(n);
     }
   }
 }
  public int send(ByteBuffer src, SocketAddress target) throws IOException {
    if (src == null) throw new NullPointerException();

    synchronized (writeLock) {
      ensureOpen();
      InetSocketAddress isa = Net.checkAddress(target);
      InetAddress ia = isa.getAddress();
      if (ia == null) throw new IOException("Target address not resolved");
      synchronized (stateLock) {
        if (!isConnected()) {
          if (target == null) throw new NullPointerException();
          SecurityManager sm = System.getSecurityManager();
          if (sm != null) {
            if (ia.isMulticastAddress()) {
              sm.checkMulticast(ia);
            } else {
              sm.checkConnect(ia.getHostAddress(), isa.getPort());
            }
          }
        } else { // Connected case; Check address then write
          if (!target.equals(remoteAddress)) {
            throw new IllegalArgumentException("Connected address not equal to target address");
          }
          return write(src);
        }
      }

      int n = 0;
      try {
        begin();
        if (!isOpen()) return 0;
        writerThread = NativeThread.current();
        do {
          n = send(fd, src, isa);
        } while ((n == IOStatus.INTERRUPTED) && isOpen());

        synchronized (stateLock) {
          if (isOpen() && (localAddress == null)) {
            localAddress = Net.localAddress(fd);
          }
        }
        return IOStatus.normalize(n);
      } finally {
        writerThread = 0;
        end((n > 0) || (n == IOStatus.UNAVAILABLE));
        assert IOStatus.check(n);
      }
    }
  }
  @Override
  public DatagramChannel connect(SocketAddress sa) throws IOException {
    int localPort = 0;

    synchronized (readLock) {
      synchronized (writeLock) {
        synchronized (stateLock) {
          ensureOpenAndUnconnected();
          InetSocketAddress isa = Net.checkAddress(sa);
          SecurityManager sm = System.getSecurityManager();
          if (sm != null) sm.checkConnect(isa.getAddress().getHostAddress(), isa.getPort());
          int n = Net.connect(family, fd, isa.getAddress(), isa.getPort());
          if (n <= 0) throw new Error(); // Can't happen

          // Connection succeeded; disallow further invocation
          state = ST_CONNECTED;
          remoteAddress = isa;
          sender = isa;
          cachedSenderInetAddress = isa.getAddress();
          cachedSenderPort = isa.getPort();

          // set or refresh local address
          localAddress = Net.localAddress(fd);

          // flush any packets already received.
          boolean blocking = false;
          synchronized (blockingLock()) {
            try {
              blocking = isBlocking();
              // remainder of each packet thrown away
              ByteBuffer tmpBuf = ByteBuffer.allocate(1);
              if (blocking) {
                configureBlocking(false);
              }
              do {
                tmpBuf.clear();
              } while (receive(tmpBuf) != null);
            } finally {
              if (blocking) {
                configureBlocking(true);
              }
            }
          }
        }
      }
    }
    return this;
  }
Beispiel #11
0
 // security check to see whether the caller can perform attach
 private void checkProcessAttach(int pid) {
   SecurityManager sm = System.getSecurityManager();
   if (sm != null) {
     String os = System.getProperty("os.name");
     try {
       // Whether the caller can perform link against SA native library?
       checkNativeLink(sm, os);
       if (os.equals("SunOS") || os.equals("Linux")) {
         // Whether the caller can read /proc/<pid> file?
         sm.checkRead("/proc/" + pid);
       }
     } catch (SecurityException se) {
       throw new SecurityException("permission denied to attach to " + pid);
     }
   }
 }
  public DatagramChannel disconnect() throws IOException {
    synchronized (readLock) {
      synchronized (writeLock) {
        synchronized (stateLock) {
          if (!isConnected() || !isOpen()) return this;
          InetSocketAddress isa = (InetSocketAddress) remoteAddress;
          SecurityManager sm = System.getSecurityManager();
          if (sm != null) sm.checkConnect(isa.getAddress().getHostAddress(), isa.getPort());
          disconnect0(fd);
          remoteAddress = null;
          state = ST_UNCONNECTED;

          // refresh local address
          localAddress = Net.localAddress(fd);
        }
      }
    }
    return this;
  }
  public static void main(String[] args) {
    String host = args[0];
    int port = Integer.parseInt(args[1]);

    if (System.getSecurityManager() == null) {
      System.setSecurityManager(new RMISecurityManager());
    }

    String name = "//" + host + ":" + port + "/EquationSolver";

    double[][] A = {
      {4.0, 3.0, 1.0},
      {2.0, -6.0, 4.0},
      {7.0, 5.0, 3.0}
    };
    double[] b = {17.0, 8.0, 32.0};

    try {
      EquationSolver solver = (EquationSolver) Naming.lookup(name);
      double[] x = solver.solve(A, b);

      StringBuffer sb = new StringBuffer();
      for (int i = 0; i < x.length; i++) {
        sb.append(x[i]);
        sb.append(' ');
      }
      System.out.println(sb);

    } catch (RemoteException ex) {
      ex.printStackTrace(System.err);

    } catch (NotBoundException ex) {
      ex.printStackTrace(System.err);

    } catch (MalformedURLException ex) {
      ex.printStackTrace(System.err);
    }
  }
Beispiel #14
0
  /** Utility routine for setting the context class loader. Returns previous class loader. */
  public static ClassLoader setContextClassLoader(ClassLoader newClassLoader) {

    // Can only reference final local variables from dopriveleged block
    final ClassLoader classLoaderToSet = newClassLoader;

    final Thread currentThread = Thread.currentThread();
    ClassLoader originalClassLoader = currentThread.getContextClassLoader();

    if (classLoaderToSet != originalClassLoader) {
      if (System.getSecurityManager() == null) {
        currentThread.setContextClassLoader(classLoaderToSet);
      } else {
        java.security.AccessController.doPrivileged(
            new java.security.PrivilegedAction() {
              public java.lang.Object run() {
                currentThread.setContextClassLoader(classLoaderToSet);
                return null;
              }
            });
      }
    }
    return originalClassLoader;
  }
  /**
   * loads a class from a file or a parent classloader.
   *
   * @param name of the class to be loaded
   * @param lookupScriptFiles if false no lookup at files is done at all
   * @param preferClassOverScript if true the file lookup is only done if there is no class
   * @param resolve see {@link java.lang.ClassLoader#loadClass(java.lang.String, boolean)}
   * @return the class found or the class created from a file lookup
   * @throws ClassNotFoundException if the class could not be found
   * @throws CompilationFailedException if the source file could not be compiled
   */
  public Class loadClass(
      final String name, boolean lookupScriptFiles, boolean preferClassOverScript, boolean resolve)
      throws ClassNotFoundException, CompilationFailedException {
    // look into cache
    Class cls = getClassCacheEntry(name);

    // enable recompilation?
    boolean recompile = isRecompilable(cls);
    if (!recompile) return cls;

    // try parent loader
    ClassNotFoundException last = null;
    try {
      Class parentClassLoaderClass = super.loadClass(name, resolve);
      // always return if the parent loader was successful
      if (cls != parentClassLoaderClass) return parentClassLoaderClass;
    } catch (ClassNotFoundException cnfe) {
      last = cnfe;
    } catch (NoClassDefFoundError ncdfe) {
      if (ncdfe.getMessage().indexOf("wrong name") > 0) {
        last = new ClassNotFoundException(name);
      } else {
        throw ncdfe;
      }
    }

    // check security manager
    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
      String className = name.replace('/', '.');
      int i = className.lastIndexOf('.');
      // no checks on the sun.reflect classes for reflection speed-up
      // in particular ConstructorAccessorImpl, MethodAccessorImpl, FieldAccessorImpl and
      // SerializationConstructorAccessorImpl
      // which are generated at runtime by the JDK
      if (i != -1 && !className.startsWith("sun.reflect.")) {
        sm.checkPackageAccess(className.substring(0, i));
      }
    }

    // prefer class if no recompilation
    if (cls != null && preferClassOverScript) return cls;

    // at this point the loading from a parent loader failed
    // and we want to recompile if needed.
    if (lookupScriptFiles) {
      // try groovy file
      try {
        // check if recompilation already happened.
        final Class classCacheEntry = getClassCacheEntry(name);
        if (classCacheEntry != cls) return classCacheEntry;
        URL source = resourceLoader.loadGroovySource(name);
        // if recompilation fails, we want cls==null
        Class oldClass = cls;
        cls = null;
        cls = recompile(source, name, oldClass);
      } catch (IOException ioe) {
        last = new ClassNotFoundException("IOException while opening groovy source: " + name, ioe);
      } finally {
        if (cls == null) {
          removeClassCacheEntry(name);
        } else {
          setClassCacheEntry(cls);
        }
      }
    }

    if (cls == null) {
      // no class found, there should have been an exception before now
      if (last == null) throw new AssertionError(true);
      throw last;
    }
    return cls;
  }
 /**
  * Initializes a new instance of this class.
  *
  * @throws SecurityException If a security manager has been installed and it denies {@link
  *     RuntimePermission}{@code ("httpServerProvider")}
  */
 protected HttpServerProvider() {
   SecurityManager sm = System.getSecurityManager();
   if (sm != null) sm.checkPermission(new RuntimePermission("httpServerProvider"));
 }
  /** Joins channel's socket to the given group/interface and optional source address. */
  private MembershipKey innerJoin(InetAddress group, NetworkInterface interf, InetAddress source)
      throws IOException {
    if (!group.isMulticastAddress())
      throw new IllegalArgumentException("Group not a multicast address");

    // check multicast address is compatible with this socket
    if (group instanceof Inet4Address) {
      if (family == StandardProtocolFamily.INET6 && !Net.canIPv6SocketJoinIPv4Group())
        throw new IllegalArgumentException("IPv6 socket cannot join IPv4 multicast group");
    } else if (group instanceof Inet6Address) {
      if (family != StandardProtocolFamily.INET6)
        throw new IllegalArgumentException("Only IPv6 sockets can join IPv6 multicast group");
    } else {
      throw new IllegalArgumentException("Address type not supported");
    }

    // check source address
    if (source != null) {
      if (source.isAnyLocalAddress())
        throw new IllegalArgumentException("Source address is a wildcard address");
      if (source.isMulticastAddress())
        throw new IllegalArgumentException("Source address is multicast address");
      if (source.getClass() != group.getClass())
        throw new IllegalArgumentException("Source address is different type to group");
    }

    SecurityManager sm = System.getSecurityManager();
    if (sm != null) sm.checkMulticast(group);

    synchronized (stateLock) {
      if (!isOpen()) throw new ClosedChannelException();

      // check the registry to see if we are already a member of the group
      if (registry == null) {
        registry = new MembershipRegistry();
      } else {
        // return existing membership key
        MembershipKey key = registry.checkMembership(group, interf, source);
        if (key != null) return key;
      }

      MembershipKeyImpl key;
      if ((family == StandardProtocolFamily.INET6)
          && ((group instanceof Inet6Address) || Net.canJoin6WithIPv4Group())) {
        int index = interf.getIndex();
        if (index == -1) throw new IOException("Network interface cannot be identified");

        // need multicast and source address as byte arrays
        byte[] groupAddress = Net.inet6AsByteArray(group);
        byte[] sourceAddress = (source == null) ? null : Net.inet6AsByteArray(source);

        // join the group
        int n = Net.join6(fd, groupAddress, index, sourceAddress);
        if (n == IOStatus.UNAVAILABLE) throw new UnsupportedOperationException();

        key =
            new MembershipKeyImpl.Type6(
                this, group, interf, source, groupAddress, index, sourceAddress);

      } else {
        // need IPv4 address to identify interface
        Inet4Address target = Net.anyInet4Address(interf);
        if (target == null) throw new IOException("Network interface not configured for IPv4");

        int groupAddress = Net.inet4AsInt(group);
        int targetAddress = Net.inet4AsInt(target);
        int sourceAddress = (source == null) ? 0 : Net.inet4AsInt(source);

        // join the group
        int n = Net.join4(fd, groupAddress, targetAddress, sourceAddress);
        if (n == IOStatus.UNAVAILABLE) throw new UnsupportedOperationException();

        key =
            new MembershipKeyImpl.Type4(
                this, group, interf, source, groupAddress, targetAddress, sourceAddress);
      }

      registry.add(key);
      return key;
    }
  }