public static void eraseIndex(User user, String indexName)
     throws SearchLibException, NamingException, IOException {
   if (user != null && !user.isAdmin()) throw new SearchLibException("Operation not permitted");
   File indexDir = getIndexDirectory(indexName);
   Client client = null;
   synchronized (ClientCatalog.class) {
     clientsLock.r.lock();
     try {
       client = CLIENTS.get(indexDir);
     } finally {
       clientsLock.r.unlock();
     }
     if (client != null) {
       client.close();
       client.delete();
     } else FileUtils.deleteDirectory(indexDir);
     if (client != null) {
       clientsLock.w.lock();
       try {
         CLIENTS.remove(client.getDirectory());
       } finally {
         clientsLock.w.unlock();
       }
       PushEvent.eventClientSwitch.publish(client);
     }
   }
 }
Exemple #2
0
  /** Expert: Make multiple, parallel calls to a set of servers. */
  public static Object[] call(
      Method method,
      Object[][] params,
      InetSocketAddress[] addrs,
      UserGroupInformation ticket,
      Configuration conf)
      throws IOException {

    Invocation[] invocations = new Invocation[params.length];
    for (int i = 0; i < params.length; i++) invocations[i] = new Invocation(method, params[i]);
    Client client = CLIENTS.getClient(conf);
    try {
      Writable[] wrappedValues =
          client.call(invocations, addrs, method.getDeclaringClass(), ticket);

      if (method.getReturnType() == Void.TYPE) {
        return null;
      }

      Object[] values = (Object[]) Array.newInstance(method.getReturnType(), wrappedValues.length);
      for (int i = 0; i < values.length; i++)
        if (wrappedValues[i] != null) values[i] = ((ObjectWritable) wrappedValues[i]).get();

      return values;
    } finally {
      CLIENTS.stopClient(client);
    }
  }
Exemple #3
0
  static void reqGetSelectionOwner(Client c) throws IOException {
    int foo;
    int selection;
    IO io = c.client;
    selection = io.readInt();

    c.length -= 2;

    if (!Atom.valid(selection)) {
      c.errorValue = selection;
      c.errorReason = 5; // BadAtom
      return;
    }

    synchronized (io) {
      io.writeByte(1);
      Selection s = getSelection(selection);
      io.writePad(1);
      io.writeShort(c.seq);
      io.writeInt(0);
      if (s != null) {
        io.writeInt(s.wid);
      } else {
        io.writeInt(0);
      }
      io.writePad(20);
      io.flush();
    }
  }
Exemple #4
0
  /** Test the http protocol handler with one WWW-Authenticate header with the value "NTLM". */
  static void testNTLM() throws Exception {
    // server reply
    String reply = authReplyFor("NTLM");

    System.out.println("====================================");
    System.out.println("Expect client to fail with 401 Unauthorized");
    System.out.println(reply);

    try (ServerSocket ss = new ServerSocket(0)) {
      Client client = new Client(ss.getLocalPort());
      Thread thr = new Thread(client);
      thr.start();

      // client ---- GET ---> server
      // client <--- 401 ---- client
      try (Socket s = ss.accept()) {
        new MessageHeader().parseHeader(s.getInputStream());
        s.getOutputStream().write(reply.getBytes("US-ASCII"));
      }

      // the client should fail with 401
      System.out.println("Waiting for client to terminate");
      thr.join();
      IOException ioe = client.ioException();
      if (ioe != null) System.out.println("Client failed: " + ioe);
      int respCode = client.respCode();
      if (respCode != 0 && respCode != -1)
        System.out.println("Client received HTTP response code: " + respCode);
      if (respCode != HttpURLConnection.HTTP_UNAUTHORIZED)
        throw new RuntimeException("Unexpected response code");
    }
  }
Exemple #5
0
  /**
   * ( begin auto-generated from Server_available.xml )
   *
   * <p>Returns the next client in line with a new message.
   *
   * <p>( end auto-generated )
   *
   * @brief Returns the next client in line with a new message.
   * @webref server
   * @usage application
   */
  public Client available() {
    synchronized (clients) {
      int index = lastAvailable + 1;
      if (index >= clientCount) index = 0;

      for (int i = 0; i < clientCount; i++) {
        int which = (index + i) % clientCount;
        Client client = clients[which];
        // Check for valid client
        if (!client.active()) {
          removeIndex(which); // Remove dead client
          i--; // Don't skip the next client
          // If the client has data make sure lastAvailable
          // doesn't end up skipping the next client
          which--;
          // fall through to allow data from dead clients
          // to be retreived.
        }
        if (client.available() > 0) {
          lastAvailable = which;
          return client;
        }
      }
    }
    return null;
  }
Exemple #6
0
  static void reqListProperties(Client c) throws IOException {
    int foo, n;
    IO io = c.client;

    foo = io.readInt();
    Window w = c.lookupWindow(foo);
    c.length -= 2;
    if (w == null) {
      c.errorValue = foo;
      c.errorReason = 3; // BadWindow;
      return;
    }
    synchronized (io) {
      io.writeByte(1);
      Property p = w.getProperty();
      int i = 0;
      while (p != null) {
        i++;
        p = p.next;
      }

      io.writePad(1);
      io.writeShort(c.seq);
      io.writeInt(i);
      io.writeShort(i);
      io.writePad(22);

      p = w.getProperty();
      while (p != null) {
        io.writeInt(p.propertyName);
        p = p.next;
      }
      io.flush();
    }
  }
  public static void main(String[] args) {

    stat.addDescription("ejb-ejb30-hello-dcode");
    Client client = new Client(args);
    client.doTest();
    stat.printSummary("ejb-ejb30-hello-dcodeID");
  }
  /** The listener method. */
  public void actionPerformed(ActionEvent event) {
    Object source = event.getSource();

    if (source == b1) // click button
    {
      try {
        String message = tf.getText();
        server.sendPrivateMessage(parent, selfIdentity, message);
        ta.append("<" + parent.getUserName() + ">: " + message + lineSeparator);
        ta.setCaretPosition(ta.getText().length());
        tf.setText("");
      } catch (RemoteException ex) {
        System.out.print("Exception encountered while sending" + " private message.");
      }
    }

    if (source == tf) // press return
    {
      try {
        String message = tf.getText();
        server.sendPrivateMessage(parent, selfIdentity, message);
        ta.append("<" + parent.getUserName() + ">: " + message + lineSeparator);
        ta.setCaretPosition(ta.getText().length());
        tf.setText("");
      } catch (RemoteException ex) {
        System.out.print("Exception encountered while sending" + " private message.");
      }
    }
    if (source == jMenuItem3) {
      JFileChooser fileChooser = new JFileChooser();

      fileChooser.setDialogTitle("Choose or create a new file to store the conversation");
      fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
      fileChooser.setDoubleBuffered(true);

      fileChooser.showOpenDialog(this);

      File file = fileChooser.getSelectedFile();

      try {
        if (file != null) {

          Writer writer = new BufferedWriter(new FileWriter(file));

          writer.write(ta.getText());
          writer.flush();
          writer.close();
        }
      } catch (IOException ex) {
        System.out.println("Can't write to file. " + ex);
      }
    }
    if (source == jMenuItem4) {
      selfRemove();
      this.dispose();
    }
  }
 /**
  * This method updates the relevant sections of the GUI when a new LookReply and RenderHint are
  * received from the server.
  */
 public void updateGUI(char[][] newCells, String[] newRenderHint, boolean ourTurn) {
   char[] playerDirections = processRenderHint(newRenderHint);
   boolean hasLantern = (newCells[0].length == 7); // the size of the lookreply determines whether
   // the player has a lantern
   dungeonPanel.updateCells(newCells, hasLantern, playerDirections); // updates the map panel
   int goldHeld = client.getGoldHeld();
   int goldNeeded = client.getGoldNeeded();
   dungeonPanelOverlay.updateOverlay(hasLantern, ourTurn, goldHeld, goldNeeded);
   // updates the overlay
 }
Exemple #10
0
 /**
  * Stop a RPC client connection A RPC client is closed only when its reference count becomes
  * zero.
  */
 private void stopClient(Client client) {
   synchronized (this) {
     client.decCount();
     if (client.isZeroReference()) {
       clients.remove(client.getSocketFactory());
     }
   }
   if (client.isZeroReference()) {
     client.stop();
   }
 }
 public static final long countAllDocuments() throws IOException, SearchLibException {
   long count = 0;
   clientsLock.r.lock();
   try {
     for (Client client : CLIENTS.values()) {
       if (client.isTrueReplicate()) continue;
       count += client.getStatistics().getNumDocs();
     }
   } finally {
     clientsLock.r.unlock();
   }
   return count;
 }
 public static final void closeIndex(String indexName) throws SearchLibException {
   Client client = null;
   clientsLock.w.lock();
   try {
     File indexDirectory = getIndexDirectory(indexName);
     client = CLIENTS.get(indexDirectory);
     if (client == null) return;
     Logging.info("Closing client " + indexName);
     client.close();
     CLIENTS.remove(indexDirectory);
   } finally {
     clientsLock.w.unlock();
   }
   if (client != null) PushEvent.eventClientSwitch.publish(client);
 }
Exemple #13
0
 /**
  * Construct & cache an IPC client with the user-provided SocketFactory if no cached client
  * exists.
  *
  * @param conf Configuration
  * @return an IPC client
  */
 private synchronized Client getClient(Configuration conf, SocketFactory factory) {
   // Construct & cache client.  The configuration is only used for timeout,
   // and Clients have connection pools.  So we can either (a) lose some
   // connection pooling and leak sockets, or (b) use the same timeout for all
   // configurations.  Since the IPC is usually intended globally, not
   // per-job, we choose (a).
   Client client = clients.get(factory);
   if (client == null) {
     client = new Client(ObjectWritable.class, conf, factory);
     clients.put(factory, client);
   } else {
     client.incCount();
   }
   return client;
 }
 public static final void closeAll() {
   synchronized (ClientCatalog.class) {
     clientsLock.r.lock();
     try {
       for (Client client : CLIENTS.values()) {
         if (client == null) continue;
         Logging.info("OSS unloads index " + client.getIndexName());
         client.close();
       }
     } finally {
       clientsLock.r.unlock();
     }
     rendererResults.release();
   }
 }
Exemple #15
0
  public static void main(String[] args) throws IOException {

    for (int i = 0; i < 10; i++) {
      new Thread(
              () -> {
                Client client = new Client();
                try {
                  client.startClient(args[0]);
                } catch (IOException e) {
                  e.printStackTrace();
                }
              })
          .start();
    }
  }
Exemple #16
0
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
      final boolean logDebug = LOG.isDebugEnabled();
      long startTime = 0;
      if (logDebug) {
        startTime = System.currentTimeMillis();
      }

      ObjectWritable value = null;
      try {
        value =
            (ObjectWritable)
                client.call(
                    new Invocation(method, args), getAddress(), protocol, ticket, rpcTimeout);
      } catch (RemoteException re) {
        throw re;
      } catch (ConnectException ce) {
        needCheckDnsUpdate = true;
        throw ce;
      } catch (NoRouteToHostException nrhe) {
        needCheckDnsUpdate = true;
        throw nrhe;
      } catch (PortUnreachableException pue) {
        needCheckDnsUpdate = true;
        throw pue;
      } catch (UnknownHostException uhe) {
        needCheckDnsUpdate = true;
        throw uhe;
      }
      if (logDebug) {
        long callTime = System.currentTimeMillis() - startTime;
        LOG.debug("Call: " + method.getName() + " " + callTime);
      }
      return value.get();
    }
Exemple #17
0
 /** start_notification */
 public synchronized void start_notification() throws RemoteException {
   JOptionPane.showMessageDialog(
       null,
       "Le serveur est connecté de nouveau",
       "Notification du client",
       JOptionPane.INFORMATION_MESSAGE);
   srv_state = true;
   try {
     for (int i = 0; i < J.getnbrcon(); i++) {
       if (J.list_con()[i].compareTo(C.get_nom()) != 0) {
         C.ajout(J.list_con()[i]);
       }
     }
   } catch (RemoteException ex) {
   }
 }
 private static List<Client> findDepends(String indexName) {
   clientsLock.r.lock();
   try {
     ArrayList<Client> list = new ArrayList<Client>();
     for (Client client : CLIENTS.values()) {
       IndexConfig indexConfig = client.getIndex().getIndexConfig();
       if (indexConfig.isMulti())
         if (indexConfig.isIndexMulti(indexName)) {
           list.add(client);
         }
     }
     return list;
   } finally {
     clientsLock.r.unlock();
   }
 }
Exemple #19
0
 /**
  * ( begin auto-generated from Server_disconnect.xml )
  *
  * <p>Disconnect a particular client.
  *
  * <p>( end auto-generated )
  *
  * @brief Disconnect a particular client.
  * @webref server:server
  * @param client the client to disconnect
  */
 public void disconnect(Client client) {
   client.stop();
   int index = clientIndex(client);
   if (index != -1) {
     removeIndex(index);
   }
 }
Exemple #20
0
  static void reqChangeProperty(Client c) throws IOException {
    int foo;
    byte mode;
    int prpty;
    byte frmt;
    int typ;
    int n;
    IO io = c.client;

    mode = (byte) c.data;
    if ((mode != PropModeReplace) && (mode != PropModeAppend) && (mode != PropModePrepend)) {
      // System.err.println("error!!");
      c.errorValue = mode;
      c.errorReason = 2; // BadValue;
    }

    n = c.length;
    ;
    foo = io.readInt();
    Window w = c.lookupWindow(foo);
    if (c.errorReason == 0 && w == null) {
      c.errorValue = foo;
      c.errorReason = 3; // BadWindow;
    }
    prpty = io.readInt();
    typ = io.readInt();
    frmt = (byte) io.readByte();
    if (c.errorReason == 0 && (frmt != 8) && (frmt != 16) && (frmt != 32)) {
      c.errorValue = frmt;
      c.errorReason = 3; // BadWindow;
    }
    io.readPad(3);
    foo = io.readInt();
    int totalSize = foo * (frmt / 8);
    byte[] bar = null;
    if (totalSize > 0) {
      bar = new byte[totalSize];
      io.readByte(bar, 0, totalSize);
      if (c.swap) {
        switch (frmt) {
          case 16:
            swapS(bar, 0, totalSize);
            break;
          case 32:
            swapL(bar, 0, totalSize);
            break;
          default:
        }
      }
      io.readPad((-totalSize) & 3);
    }
    c.length = 0;
    if (c.errorReason != 0) {
      return;
    }
    changeWindowProperty(c, w, prpty, typ, frmt, mode, foo, bar, true);
  }
Exemple #21
0
  ///
  /// Lit une requete depuis le Terminal, envoie cette requete au serveur,
  /// recupere sa reponse et l'affiche sur le Terminal.
  /// Noter que le programme bloque si le serveur ne repond pas.
  ///
  public static void main(String argv[]) {
    String host = DEFAULT_HOST;
    int port = DEFAULT_PORT;
    if (argv.length >= 1) host = argv[0];
    if (argv.length >= 2) port = Integer.parseInt(argv[1]);

    Client client = null;

    try {
      client = new Client(host, port);
    } catch (Exception e) {
      System.err.println("Client: Couldn't connect to " + host + ":" + port);
      System.exit(1);
    }

    System.out.println("Client connected to " + host + ":" + port);

    // pour lire depuis la console
    BufferedReader cin = new BufferedReader(new InputStreamReader(System.in));

    while (true) {
      System.out.print(""); // ne marche pas sans.
      /* try {
          String request = cin.readLine();
          String response = client.send(request);
          System.out.println("Response: " + response);
        }
        catch (java.io.IOException e) {
          System.err.println("Client: IO error");
          return;
      }*/
      // try {
      String request = "";
      String response = "";
      if (client.windows.getCommand() != "") {
        request = client.windows.getCommand();
        client.windows.setCommand("");
        response = client.send(request);
        client.windows.setTextArea(response);
      }
      //   }
      // catch (java.io.IOException e) {
      //  System.err.println("Client: IO error");
      //  return;
      // }
    }
  }
Exemple #22
0
 static void reqDeleteProperty(Client c) throws IOException {
   int foo, propty;
   IO io = c.client;
   foo = io.readInt();
   Window w = c.lookupWindow(foo);
   if (w == null) {
     c.errorValue = foo;
     c.errorReason = 3; // BadWindow;
   }
   propty = foo = io.readInt();
   c.length -= 3;
   if (c.errorReason != 0) {
     return;
   }
   if (w.parent != null) {
     Property.delProperty(c, w, propty, 0);
   }
 }
Exemple #23
0
 /** close_notification */
 public synchronized void close_notification() throws RemoteException {
   JOptionPane.showMessageDialog(
       null,
       "Le serveur est injoignable pour le moment",
       "Erreur distante",
       JOptionPane.INFORMATION_MESSAGE);
   srv_state = false;
   C.initialiser();
 }
Exemple #24
0
  public void run() {
    while (Thread.currentThread() == thread) {
      try {
        Socket socket = server.accept();
        Client client = new Client(parent, socket);

        if (clientValidationMethod != null) {
          try {
            clientValidationMethod.invoke(parent, new Object[] {this, client});
          } catch (Exception e) {
            // System.err.println("Disabling serverEvent() for port " + port);
            e.printStackTrace();
          }
        }

        if (client.active()) {
          synchronized (clients) {
            addClient(client);
            if (serverEventMethod != null) {
              try {
                serverEventMethod.invoke(parent, new Object[] {this, client});
              } catch (Exception e) {
                // System.err.println("Disabling serverEvent() for port " + port);
                e.printStackTrace();
              }
            }
          }
        }
      } catch (SocketException e) {
        // thrown when server.close() is called and server is waiting on accept
        System.err.println("Server SocketException: " + e.getMessage());
        thread = null;
      } catch (IOException e) {
        // errorMessage("run", e);
        e.printStackTrace();
        thread = null;
      }
      try {
        Thread.sleep(8);
      } catch (InterruptedException ex) {
      }
    }
  }
  /**
   * Overriding the parent class behavior, this sends this simulator's current output message to the
   * server, rather than to other local simulators or coordinators.
   */
  public void sendMessages() {
    // if this simulator's output message is non-empty
    if (!output.isEmpty()) {
      // send the output message to the server
      client.sendMessageToServer(output.toString());

      // clear the output message
      output = new message();
    }
  }
 public static final boolean receive_file_exists(
     Client client, String filePath, long lastModified, long length) throws IOException {
   File existsFile = new File(client.getDirectory(), filePath);
   if (!existsFile.exists()) return false;
   if (existsFile.lastModified() != lastModified) return false;
   if (existsFile.length() != length) return false;
   File rootDir = getTempReceiveDir(client);
   IOUtils.appendLines(new File(rootDir, PATH_TO_MOVE), filePath);
   return true;
 }
 public static void receive_merge(WebApp webapp, Client client)
     throws SearchLibException, IOException {
   File tempDir = getTempReceiveDir(client);
   File clientDir = client.getDirectory();
   Client newClient = null;
   lockClientDir(clientDir);
   try {
     client.close();
     new ReplicationMerge(tempDir, clientDir);
     newClient =
         ClientFactory.INSTANCE.newClient(
             clientDir, true, true, ClientFactory.INSTANCE.properties.getSilentBackupUrl());
     newClient.writeReplCheck();
   } finally {
     unlockClientDir(clientDir, newClient);
   }
   PushEvent.eventClientSwitch.publish(client);
   FileUtils.deleteDirectory(tempDir);
 }
Exemple #28
0
  public static void main(String argv[]) {

    if (argv.length != 1) {
      System.out.println("java Irc <name>");
      return;
    }
    myName = argv[0];

    // initialize the system
    Client.init();

    // look up the IRC object in the name server
    // if not found, create it, and register it in the name server
    Sentence_itf s = (Sentence_itf) Client.lookup("IRC");
    if (s == null) {
      s = (Sentence_itf) Client.create(new Sentence());
      Client.register("IRC", s);
    }
    // create the graphical part
    new Irc(s);
  }
 public static void receive_switch(WebApp webapp, Client client)
     throws SearchLibException, NamingException, IOException {
   File trashDir = getTrashReceiveDir(client);
   File clientDir = client.getDirectory();
   if (trashDir.exists()) FileUtils.deleteDirectory(trashDir);
   Client newClient = null;
   List<Client> clientDepends = findDepends(client.getIndexName());
   lockClientDir(clientDir);
   try {
     lockClients(clientDepends);
     closeClients(clientDepends);
     try {
       client.trash(trashDir);
       getTempReceiveDir(client).renameTo(clientDir);
       File pathToMoveFile = new File(clientDir, PATH_TO_MOVE);
       if (pathToMoveFile.exists()) {
         for (String pathToMove : FileUtils.readLines(pathToMoveFile)) {
           File from = new File(trashDir, pathToMove);
           File to = new File(clientDir, pathToMove);
           FileUtils.moveFile(from, to);
         }
         if (!pathToMoveFile.delete())
           throw new IOException("Unable to delete the file: " + pathToMoveFile.getAbsolutePath());
       }
       newClient =
           ClientFactory.INSTANCE.newClient(
               clientDir, true, true, ClientFactory.INSTANCE.properties.getSilentBackupUrl());
       newClient.writeReplCheck();
     } finally {
       unlockClients(clientDepends);
     }
   } finally {
     unlockClientDir(clientDir, newClient);
   }
   PushEvent.eventClientSwitch.publish(client);
   FileUtils.deleteDirectory(trashDir);
 }
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
      long startTime = 0;
      if (LOG.isDebugEnabled()) {
        startTime = Time.now();
      }

      ObjectWritable value =
          (ObjectWritable)
              client.call(RPC.RpcKind.RPC_WRITABLE, new Invocation(method, args), remoteId);
      if (LOG.isDebugEnabled()) {
        long callTime = Time.now() - startTime;
        LOG.debug("Call: " + method.getName() + " " + callTime);
      }
      return value.get();
    }