예제 #1
0
파일: Selection.java 프로젝트: imkafo/xhttp
  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();
    }
  }
예제 #2
0
파일: Property.java 프로젝트: imkafo/xhttp
  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();
    }
  }
  // TODO The secret should be a char[].
  private Representation doNoneFlow(
      String clientId, String clientSecret, Series<Parameter> params) {
    Client client = validate(clientId, clientSecret);

    // null check on failed
    if (client == null) {
      setStatus(Status.CLIENT_ERROR_FORBIDDEN);
      return sendError(OAuthError.invalid_client, "Client id verification failed.", null);
    }

    if (!client.containsUser(AUTONOMOUS_USER)) {
      client.createUser(AUTONOMOUS_USER);
    }

    AuthenticatedUser user = client.findUser(AUTONOMOUS_USER);

    // Adding all scopes since super-user
    // String[] scopes = parseScope(params.getFirstValue(SCOPE));
    List<Role> roles = Scopes.toRoles(params.getFirstValue(SCOPE));
    for (Role r : roles) {
      getLogger().fine("Requested scopes none flow = " + roles);
      user.addRole(r, "");
      getLogger().fine("Adding scope = " + r.getName() + " to auto user");
    }

    Token token = this.generator.generateToken(user, this.tokenTimeSec);
    JSONObject body = createJsonToken(token, null); // Scopes N/A

    // Sets the no-store Cache-Control header
    getResponse().setCacheDirectives(noStore);
    return new JsonStringRepresentation(body);
  }
예제 #4
0
  @GET
  @Path("/getclient")
  @Produces("application/json; charset=utf-8")
  // http://localhost:8080/ProjetRestFull/eources/getjson
  public JResponse getEtudiant(@QueryParam("numcli") int numCli) throws ParseException {
    try {
      EntityManager em = HibUtil.getEntityManager();
      em.getTransaction().begin();
      Client c = em.find(Client.class, numCli);
      Hibernate.initialize(c);

      // On met le séjour à null, sinon il y a des références circulaires.
      em.detach(c);
      c.setSejours(null);

      GenericEntity<Client> entity = new GenericEntity<Client>(c) {};
      JResponse r = JResponse.ok(entity).build();
      em.getTransaction().commit();
      HibUtil.closeEntityManager();
      return r;
    } catch (Exception e) {
      // em.getTransaction().commit();
      HibUtil.closeEntityManager();
      return null;
    }
  }
예제 #5
0
  public static void main(String argv[]) {
    Client c = new Client("http://*****:*****@localhost:8889/wsman");

    ClientOptions op = new ClientOptions();
    WsXmlDoc doc = c.identify(op);
    System.out.println(doc.dump("UTF-8"));
  }
예제 #6
0
  public static void main(String argv[]) {

    System.out.println("[TestClient2]: Starting testing client 2 (this one retreive a file).");
    if (argv.length < 2) {
      System.out.println(
          "[TestClient2]: The client starts with command: java Client ServerHost ServerPort ClientPort");
      System.exit(-1);
    }
    try {

      /* adresarea serverului (ip, port) */
      String serverHost = argv[0];
      int serverPort = Integer.parseInt(argv[1]);

      /* adresarea clientului (ip, port) */
      String clientHost = InetAddress.getLocalHost().getHostName();
      int clientPort = Integer.parseInt(argv[2]);

      Client cli = new Client(clientHost, clientPort, serverHost, serverPort);
      cli.retrieveFile(fileName);
      System.out.println("[TestClient2]: File " + fileName + " was retrieved... DONE!");

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
예제 #7
0
 private String getSocketIn() {
   try {
     String s = "";
     while (true) {
       int count = socket_in.read(buffer);
       if (count < 0) {
         for (Iterator<Client> it = clients.iterator(); it.hasNext(); ) {
           Client client = it.next();
           if (client.host.equals(host)) {
             client.deleteThis();
             break;
           }
         }
         deleteThis();
         Bundle bundle = new Bundle();
         bundle.putInt(Constants.CLIENTS_STATUS, Constants.CLIENTS_STATUS_UPDATE_STATUS);
         Message msg = new Message();
         msg.setData(bundle);
         MainActivity.this.clientMessageHandler.sendMessage(msg);
         return null;
       }
       s += new String(buffer, 0, count);
       if (s.endsWith("\n")) {
         s = s.substring(0, s.length() - 1);
         break;
       }
     }
     return s;
   } catch (Exception e) {
     return null;
   }
 }
예제 #8
0
  // calculate the coordinates of the startpoint (endpoint) if parameter is
  // true (false) of the arrow when drawing this link
  private Point calcCoord(boolean startpoint) {
    if (!startpoint && (end == null)) return openEnd;

    int deltaX;
    int deltaY;

    if (end == null) {
      deltaX = start.getX() - openEnd.x;
      deltaY = start.getY() - openEnd.y;
    } else {
      deltaX = start.getX() - end.getX();
      deltaY = start.getY() - end.getY();
    }

    double dist = Math.sqrt(deltaX * deltaX + deltaY * deltaY);

    double prop = (Client.RADIUS) / dist;

    int offsetX = (int) Math.round(deltaX * prop);
    int offsetY = (int) Math.round(deltaY * prop);

    if (startpoint) {
      return new Point(start.getX() - offsetX, start.getY() - offsetY);
    } else return new Point(end.getX() + offsetX, end.getY() + offsetY);
  }
예제 #9
0
 public String toString() {
   if (end == null) {
     return new String("Open link starting in " + start.getName());
   } else {
     return new String("Link between " + start.getName() + " and " + end.getName());
   }
 }
예제 #10
0
 public static void release(int x, int y, int button) {
   int buttonModifiers = getButtonModifiers(button);
   Component target = getTarget();
   Client.getMouse()
       .sendEvent(
           new MouseEvent(
               target,
               MouseEvent.MOUSE_RELEASED,
               System.currentTimeMillis(),
               buttonModifiers,
               x,
               y,
               1,
               false,
               button));
   isPressed = false;
   Client.getMouse()
       .sendEvent(
           new MouseEvent(
               target,
               MouseEvent.MOUSE_CLICKED,
               System.currentTimeMillis(),
               buttonModifiers,
               x,
               y,
               1,
               false,
               button));
 }
예제 #11
0
    @Override
    public void run() {
      Message tempMessage = null;
      try {
        Client tempClient = clients.take();
        clients.add(tempClient);
        BufferedReader reader = tempClient.getReader();

        StringBuilder sb = new StringBuilder();
        Thread.sleep(1000);

        while (reader.ready()) {
          sb.append(reader.readLine());

          tempMessage = new Message(tempClient.getId(), sb.toString());

          messages.add(tempMessage);
          clients.add(tempClient);
          // pool.submit(this);

          System.out.println(sb.toString());
        }
      } catch (InterruptedException | IOException e) {
        clients.remove(tempMessage);
        e.printStackTrace();
      }
      pool.execute(this);
    }
예제 #12
0
  public Connector(
      SocketAddress remoteAddress,
      TimeProperty autoReconnectInterval,
      MessageEncodingProtocol messageEncodingProtocol) {
    this.remoteAddress = remoteAddress;
    loopGroup =
        new MessageQueueLoopGroup(
            Executors.newCachedThreadPool(),
            messageHandler,
            new SingleMessageQueueStrategy(),
            new LoopShiftingStrategy());
    client = new NetLightClient(remoteAddress, getSslContext(), messageEncodingProtocol, loopGroup);
    if (autoReconnectInterval != null) {
      client.addChannelStateListener(
          new AutoReconnector(autoReconnectInterval.to(TimeUnit.MILLISECONDS)));
    }
    clientHandler =
        (ClientHandler)
            client.getChannelInitializer().getTcpChannelInitializer().getChannelHandler();
    serverSentMessageNotifier =
        new EventNotifier<>(
            new EventNotifierHandler<Message, ServerSentMessageListener>() {
              @Override
              public void handle(Message message, ServerSentMessageListener listener) {
                listener.onMessage(message);
              }

              @Override
              public void exceptionCaught(Throwable cause) {
                serverSentMessageNotifier.start();
              }
            },
            Message.class);
  }
 /** 检查serverNameList */
 public boolean isHealthy() {
   for (String serverName : serverNameList) {
     Client<T> client = getClient(serverName);
     if (client != null && client.isHealthy()) return true;
   }
   return false;
 }
  /** 如果使用Curator的话,所有的serverName都用zookeeper取; 如果使用本地的话,所有的serverName都用serverNameList取 */
  public T proxy() throws Exception {
    List<Client<T>> healthyClients = new ArrayList<Client<T>>();

    List<String> list = null;

    if (isUseCurator) { // 如果使用curator
      List<String> rpcList = TZCuratorFrameworkNoProperty.getRpcAdress(serviceName, prefix);
      if (rpcList == null || rpcList.size() == 0) {
        list = serverNameList;
      } else {
        list = rpcList;
      }
    } else {
      list = serverNameList;
    }
    logger.info("rpcList--->" + list);
    for (String serverName : list) {
      Client<T> client = getClient(serverName);
      if (client.isHealthy()) {
        healthyClients.add(client);
      }
    }

    if (healthyClients.size() == 0) throw new ClientUnavailableException();
    // System.out.println(healthyClients);
    int index = rand.nextInt(healthyClients.size());
    Client<T> client = healthyClients.get(index);
    // logger.debug("use client: {}", client.toString());
    // System.out.println("use client " + client.toString());
    return client.proxy();
  }
예제 #15
0
 public void btn1_onClick(View view) {
   Log.w("HablamosClient", "Boton 1 pulsado");
   tClient.setUserNum(
       Integer.parseInt(((EditText) findViewById(R.id.txtUsuario)).getText().toString()));
   tClient.start();
   view.setBackgroundColor(Color.BLACK);
 }
예제 #16
0
 public boolean newPlayerClient(Client client1) {
   int slot = -1;
   for (int i = 1; i < Config.MAX_PLAYERS; i++) {
     if (players[i] == null || players[i].disconnected) {
       slot = i;
       break;
     }
   }
   if (slot == -1) return false;
   client1.handler = this;
   client1.playerId = slot;
   players[slot] = client1;
   players[slot].isActive = true;
   players[slot].connectedFrom =
       ((InetSocketAddress) client1.getSession().getRemoteAddress()).getAddress().getHostAddress();
   if (Config.SERVER_DEBUG)
     Misc.println(
         "Player Slot "
             + slot
             + " slot 0 "
             + players[0]
             + " Player Hit "
             + players[
                 slot]); // does nothing.... ;;players dont give the right amount of playesr? i am
   // getting the right amount why not me? logout log inand u wont get the
   // right
   return true;
 }
예제 #17
0
 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);
     }
   }
 }
예제 #18
0
 @Override
 public CompletableFuture<Connection> connect(Address address) {
   if (this.address.equals(address)) {
     return local.connect(address);
   }
   return remote.connect(address);
 }
예제 #19
0
 @Override
 public void run() {
   ConnectivityManager connMgr =
       (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
   NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
   if ((networkInfo == null)
       || (!networkInfo.isConnected())
       || (networkInfo.getType() != ConnectivityManager.TYPE_WIFI)) {
     bundle.putInt(
         Constants.SERVER_THREAD_STATUS, Constants.SERVER_THREAD_STATUS_WIFI_NOT_CONNECTED);
     msg.setData(bundle);
     MainActivity.this.serverThreadMessageHandler.sendMessage(msg);
     return;
   }
   WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
   WifiInfo wifiInfo = wifiManager.getConnectionInfo();
   int ipAddress = wifiInfo.getIpAddress();
   String ip =
       (ipAddress & 0xff)
           + "."
           + (ipAddress >> 8 & 0xff)
           + "."
           + (ipAddress >> 16 & 0xff)
           + "."
           + (ipAddress >> 24 & 0xff);
   try {
     serverSocket = new ServerSocket(Constants.SERVER_PORT);
     bundle.putInt(Constants.SERVER_THREAD_STATUS, Constants.SERVER_THREAD_STATUS_LISTENING);
     bundle.putString(Constants.IP_ADDRESS, ip);
     msg.setData(bundle);
     MainActivity.this.serverThreadMessageHandler.sendMessage(msg);
   } catch (Exception e) {
     bundle.putInt(Constants.SERVER_THREAD_STATUS, Constants.SERVER_THREAD_STATUS_INIT_FAILED);
     msg.setData(bundle);
     MainActivity.this.serverThreadMessageHandler.sendMessage(msg);
     return;
   }
   Socket clientSocket;
   while (true) {
     try {
       clientSocket = serverSocket.accept();
       String hostAddress = clientSocket.getInetAddress().getHostAddress();
       boolean inClients = false;
       for (Client client : clients)
         if (client.host.equals(hostAddress)) {
           inClients = true;
           break;
         }
       if (!inClients) {
         Client newClient = new Client(hostAddress);
         clients.add(newClient);
         newClient.connect();
       }
       Server server = new Server(clientSocket, hostAddress);
       servers.add(server);
       server.start();
     } catch (Exception e) {
     }
   }
 }
예제 #20
0
  @Test
  public void testStatVFS() throws Exception, VolumeNotFoundException {
    final String VOLUME_NAME_1 = "foobar";
    client.createVolume(mrcAddress, auth, userCredentials, VOLUME_NAME_1);

    Volume volume = client.openVolume(VOLUME_NAME_1, null, options);

    StatVFS volumeVFS = volume.statFS(userCredentials);

    MRCServiceClient mrcClient = new MRCServiceClient(testEnv.getRpcClient(), null);

    StatVFS mrcClientVFS = null;
    RPCResponse<StatVFS> resp = null;
    try {
      statvfsRequest input =
          statvfsRequest.newBuilder().setVolumeName(VOLUME_NAME_1).setKnownEtag(0).build();
      resp = mrcClient.statvfs(testEnv.getMRCAddress(), auth, userCredentials, input);
      mrcClientVFS = resp.get();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (resp != null) {
        resp.freeBuffers();
      }
    }
    assertNotNull(volumeVFS);
    assertEquals(mrcClientVFS, volumeVFS);
  }
예제 #21
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;
  }
예제 #22
0
  @Test
  public void testReplicaAddListRemove() throws Exception {
    VOLUME_NAME = "testReplicaAddListRemove";
    final String fileName = "testfile";
    client.createVolume(mrcAddress, auth, userCredentials, VOLUME_NAME);
    Volume volume = client.openVolume(VOLUME_NAME, null, options);

    // set replication update policy of the file
    int flags = ReplicationFlags.setSequentialStrategy(0);
    flags = ReplicationFlags.setFullReplica(flags);
    volume.setDefaultReplicationPolicy(
        userCredentials, "/", ReplicaUpdatePolicies.REPL_UPDATE_PC_WARONE, 2, flags);
    FileHandle fileHandle =
        volume.openFile(
            userCredentials, fileName, SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_CREAT.getNumber(), 0777);
    fileHandle.close();

    assertEquals(2, volume.listReplicas(userCredentials, fileName).getReplicasCount());

    String osdUUID = volume.getSuitableOSDs(userCredentials, fileName, 1).get(0);
    Replica replica =
        Replica.newBuilder()
            .addOsdUuids(osdUUID)
            .setStripingPolicy(defaultStripingPolicy)
            .setReplicationFlags(flags)
            .build();
    volume.addReplica(userCredentials, fileName, replica);
    assertEquals(3, volume.listReplicas(userCredentials, fileName).getReplicasCount());

    volume.removeReplica(userCredentials, fileName, replica.getOsdUuids(0));
    assertEquals(2, volume.listReplicas(userCredentials, fileName).getReplicasCount());
  }
예제 #23
0
  /** Check for new client connections */
  private void acceptNewConnections() {

    try {
      SocketChannel clientChannel;
      // since sSockChan is non-blocking, this will return immediately
      // regardless of whether there is a connection available
      while ((clientChannel = sSockChan.accept()) != null) {
        if (getContext().getServer().isRedirectActive()) {
          LOG.debug(
              "Client redirected to {}: {}",
              getContext().getServer().getRedirectAddress().getHostAddress(),
              clientChannel.socket().getInetAddress().getHostAddress());
          redirectAndKill(clientChannel.socket());
          continue;
        }

        Client client =
            getContext().getClients().addNewClient(clientChannel, readSelector, SEND_BUFFER_SIZE);
        if (client == null) {
          continue;
        }

        // from this point on, we know that client
        // has been successfully connected
        client.sendWelcomeMessage();

        LOG.debug("New client connected: {}", client.getIp().getHostAddress());
      }
    } catch (Exception ex) {
      LOG.error("Exception in acceptNewConnections(): " + ex.getMessage(), ex);
    }
  }
예제 #24
0
  @Test
  public void testRenameFile() throws Exception {
    VOLUME_NAME = "testRenameFile";
    String fileName = "testfile";
    String renamedFileName = "renamed";
    client.createVolume(mrcAddress, auth, userCredentials, VOLUME_NAME);
    Volume volume = client.openVolume(VOLUME_NAME, null, options);
    FileHandle fh =
        volume.openFile(
            userCredentials,
            fileName,
            SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_CREAT.getNumber()
                | SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_RDWR.getNumber(),
            0777);
    fh.close();
    // nothing should happen
    volume.rename(userCredentials, fileName, fileName);
    DirectoryEntries dir = volume.readDir(userCredentials, "/", 0, 100, true);
    assertEquals(fileName, dir.getEntries(2).getName());
    assertEquals(3, dir.getEntriesCount());

    volume.rename(userCredentials, fileName, renamedFileName);
    dir = volume.readDir(userCredentials, "/", 0, 100, true);
    assertEquals(renamedFileName, dir.getEntries(2).getName());
    assertEquals(3, dir.getEntriesCount());
  }
예제 #25
0
  private int enqueueToPlace() throws Exception {
    DistributionServer.logging("Philosoph-" + this.getIndex() + " enqueues.");
    Place minPlace = table.getPlace(distributedClient.getStartPlace());
    DistributionServer.logging("Philosoph-" + this.getIndex() + " Has min place");

    // Try enqueue local and get shortest queue
    for (Place place : table.getPlaces()) {
      if (place.tryEnqueue()) {
        System.out.println(this + " is enqueued at local place " + place.getIndex());
        return place.getIndex();
      }
      if (place.getQueueLength() < minPlace.getQueueLength()) {
        minPlace = place;
      }
    }
    DistributionServer.logging("Philosoph-" + this.getIndex() + " tried enqueue locally");

    // Try enqueue remote
    List<Client> clients = distributedClient.getClients();
    DistributionServer.logging("Philosoph-" + this.getIndex() + " has clinets");
    for (Client client : clients) {
      int placeIndex = client.tryEnqueue();
      if (placeIndex >= 0) {
        System.out.println(this + " is enqueued at remote place " + placeIndex);
        return placeIndex;
      }
    }

    DistributionServer.logging("Philosoph-" + this.getIndex() + " tried enqueue remote");

    // Enqueue at local place with shortest queue
    minPlace.enqueue();
    System.out.println(this + " is enqueued at local minPlace " + minPlace.getIndex());
    return minPlace.getIndex();
  }
예제 #26
0
 @Test
 public void testGetXattrSize() throws Exception {
   VOLUME_NAME = "testGetXattrSize";
   String fileName = "testfile";
   client.createVolume(mrcAddress, auth, userCredentials, VOLUME_NAME);
   Volume volume = client.openVolume(VOLUME_NAME, null, options);
   FileHandle fh =
       volume.openFile(
           userCredentials,
           fileName,
           SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_CREAT.getNumber()
               | SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_RDWR.getNumber()
               | SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_SYNC.getNumber(),
           0777);
   fh.close();
   int size = volume.getXAttrSize(userCredentials, fileName, "xtreemfs.set_repl_update_policy");
   assertEquals(0, size);
   size = volume.getXAttrSize(userCredentials, fileName, "xtreemfs.owner");
   assertEquals(userCredentials.getUsername().length(), size);
   size = volume.getXAttrSize(userCredentials, fileName, "doesnt-exist");
   assertEquals(-1, size);
   volume.setXAttr(userCredentials, fileName, "foo", "bar", XATTR_FLAGS.XATTR_FLAGS_CREATE);
   size = volume.getXAttrSize(userCredentials, fileName, "foo");
   assertEquals(3, size);
   size = volume.getXAttrSize(userCredentials, fileName, "doesnt-exist-in-cache");
   assertEquals(-1, size);
 }
예제 #27
0
  /** Usage : ... [-legacy=<port>] [-role=satellite|core] -- [<port>] <client options> */
  public LocationManager(String name, String args) throws CommandException, IOException {
    super(name, "System", args);

    this.args = getArgs();
    nucleus = getNucleus();
    coreDomains = new CoreDomains(getCellDomainName(), getCuratorFramework());

    if (this.args.hasOption("legacy")) {
      legacy = new LegacyServer(this.args.getIntOption("legacy"));
    } else {
      legacy = null;
    }

    if (this.args.hasOption("role")) {
      role = CellDomainRole.valueOf(this.args.getOption("role").toUpperCase());
      switch (role) {
        case CORE:
          checkArgument(this.args.argc() >= 1, "Listening port is required.");
          client = new CoreClient();
          coreDomains.onChange(event -> invokeOnMessageThread(() -> client.update(event)));
          break;
        default:
          client = new Client();
          coreDomains.onChange(event -> invokeOnMessageThread(() -> client.update(event)));
          break;
      }
    } else {
      role = null;
      client = null;
    }
  }
예제 #28
0
  @Test
  public void testCreateDirectoryRecursive() throws Exception {
    VOLUME_NAME = "testCreateDirectoryRecursive";
    client.createVolume(mrcAddress, auth, userCredentials, VOLUME_NAME);
    Volume volume = client.openVolume(VOLUME_NAME, null, options);

    final String directory1 = "/home/foo/bar/user/xtreemfs/test/bar/foo";
    final String directroy2 = "/home/foo/path/with/slash/at/end/";
    volume.createDirectory(userCredentials, directory1, 0777, true);
    volume.createDirectory(userCredentials, directroy2, 0777, true);

    final String[] dirs1 = directory1.split("/");
    final String[] dirs2 = directroy2.split("/");

    String tempdir = "";
    for (int i = 1; i < dirs1.length; i++) {
      tempdir = tempdir + "/" + dirs1[i];
      assertTrue(isDirectory(volume, tempdir));
    }

    tempdir = "";
    for (int i = 1; i < dirs2.length; i++) {
      tempdir = tempdir + "/" + dirs2[i];
      assertTrue(isDirectory(volume, tempdir));
    }
    volume.close();
  }
  // TODO The secret should be a char[].
  private Client validate(String clientId, String clientSecret) {
    Client client = clients.findById(clientId);
    getLogger().fine("Client = " + client);

    if (client == null) {
      sendError(
          OAuthError.invalid_client,
          "Could not find the correct client with id : " + clientId,
          null);
      setStatus(Status.CLIENT_ERROR_NOT_FOUND);
      return null;
    }

    if ((clientSecret == null) || !clientSecret.equals(client.getClientSecret())) {
      sendError(OAuthError.invalid_grant, "Client secret did not match", null);
      setStatus(Status.CLIENT_ERROR_UNAUTHORIZED);
      getLogger()
          .warning(
              "Could not find or match client secret "
                  + clientSecret
                  + " : "
                  + client.getClientSecret());
      return null;
    }

    return client;
  }
예제 #30
0
    public void actionPerformed(ActionEvent e) {
      String UCID = textField.getText();
      String Password = String.valueOf(passwordField.getPassword());
      if (!UCID.isEmpty() && !Password.isEmpty()) {
        Person p = new Person();
        p.UCID = UCID;
        p.Password = Password;
        Client cl = new Client();
        String Send = "start" + "|" + Person.ConvertToString(p);
        System.out.println(Send);
        String Receive = cl.login(Send);
        label.setText(p.UCID);
        System.out.println(Receive);
        String[] msg = Receive.split("\\|");
        if (msg[0].equalsIgnoreCase("confirm")) {
          CardLayout cards = (CardLayout) contentPane.getLayout();
          cards.show(contentPane, "student");

          i = 1;
          String j = String.valueOf(i);
          Question c = new Question();
          Send = "question" + "|" + i;
          System.out.println(Send);
          Receive = cl.login(Send);
          c = Question.ConverToObject(Receive);
          textPane.setText(c.Question);
          answerTF[i - 1] = c.Answer;
        }
      }
    }