/* This test has been moved to jaxws-unit harness to use tag 2.1.5

  public void testHeadersInStreamMessage() throws Exception {
  	String requestStr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
              "<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\" " +
              "xmlns:wsa=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\" xmlns:user=\"http://foo.bar\">" +
              "<S:Header>" +
              "<user:foo>bar</user:foo>" +
              "</S:Header>" +
              "<S:Body>" +
              "<addNumbers xmlns=\"http://example.com/\">" +
              "<number1>10</number1>" +
              "<number2>10</number2>" +
              "</addNumbers>" +
              "</S:Body></S:Envelope>";
      Message message = useStreamCodec(requestStr);
      HeaderList hl = message.getHeaders();
      ByteArrayBuffer baos = new ByteArrayBuffer();
      XMLStreamWriter writer = XMLStreamWriterFactory.create(baos);
      writer.writeStartDocument();
      for(Header h: hl) {
          h.writeTo(writer);
      }
      writer.writeEndDocument();
      writer.flush();
      //baos.writeTo(System.out);

      XMLInputFactory readerFactory = XMLInputFactory.newInstance();
      XMLStreamReader reader = readerFactory.createXMLStreamReader(baos.newInputStream());
      reader.next();// go to start element
      Header h = Headers.create(SOAPVersion.SOAP_11,reader);
      assertEquals(h.getNamespaceURI(),"http://foo.bar");
  }

  */
  Message useStreamCodec(String msg) throws IOException {
    Codec codec = Codecs.createSOAPEnvelopeXmlCodec(SOAPVersion.SOAP_11);
    Packet packet = new Packet();
    ByteArrayInputStream in = new ByteArrayInputStream(msg.getBytes());
    codec.decode(in, "text/xml", packet);
    return packet.getMessage();
  }
示例#2
0
  private void listen() throws Exception {
    System.out.println("Listening on port: " + serverPort);
    // Initialize socket
    socket = new DatagramSocket(serverPort);

    // While running
    while (run) {

      // Wait for handshake
      packet = new DatagramPacket(response, response.length);
      socket.receive(packet); // Blocking
      // System.out.println("RT: got packet");
      Packet p = new Packet(packet.getData());

      if (p.isHandshake()) {
        // System.out.println("RT: is handshake");
        // Get client connection info
        InetAddress IPAddress = packet.getAddress();
        int port = packet.getPort();

        // Process handshake
        processHandshake(p, IPAddress, port);

        // Get message
        MyMessage message = getMessage();

        if (message != null) {
          rc.rreceive(message);
        }
      }
    }
  }
示例#3
0
    /**
     * Handles incoming presence packets and maps jids to node#ver strings.
     *
     * @param packet the incoming presence <tt>Packet</tt> to be handled
     * @see PacketListener#processPacket(Packet)
     */
    public void processPacket(Packet packet) {
      CapsPacketExtension ext =
          (CapsPacketExtension)
              packet.getExtension(CapsPacketExtension.ELEMENT_NAME, CapsPacketExtension.NAMESPACE);

      /*
       * Before Version 1.4 of XEP-0115: Entity Capabilities, the 'ver'
       * attribute was generated differently and the 'hash' attribute was
       * absent. The 'ver' attribute in Version 1.3 represents the
       * specific version of the client and thus does not provide a way to
       * validate the DiscoverInfo sent by the client. If
       * EntityCapsManager receives no 'hash' attribute, it will assume
       * the legacy format and will not cache it because the DiscoverInfo
       * to be received from the client later on will not be trustworthy.
       */
      String hash = ext.getHash();

      /* Google Talk web does not set hash but we need it to be cached */
      if (hash == null) hash = "";

      if (hash != null) {
        // Check it the packet indicates  that the user is online. We
        // will use this information to decide if we're going to send
        // the discover info request.
        boolean online = (packet instanceof Presence) && ((Presence) packet).isAvailable();

        if (online) {
          addUserCapsNode(
              packet.getFrom(), ext.getNode(), hash, ext.getVersion(), ext.getExtensions(), online);
        } else {
          removeUserCapsNode(packet.getFrom());
        }
      }
    }
示例#4
0
  public void run() {
    boolean gotByePacket = false;

    try {
      /* stream to read from client */
      ObjectInputStream fromClient = new ObjectInputStream(socket.getInputStream());
      Packet packetFromClient;

      /* stream to write back to client */
      ObjectOutputStream toClient = new ObjectOutputStream(socket.getOutputStream());

      // writer to the disk
      // String file = "list";

      // while (( packetFromClient = (Packet) fromClient.readObject()) != null) {
      /* create a packet to send reply back to client */

      packetFromClient = (Packet) fromClient.readObject();
      Packet packetToClient = new Packet();
      packetToClient.type = Packet.LOOKUP_REPLY;
      packetToClient.data = new ArrayList<String>();

      if (packetFromClient.type == Packet.LOOKUP_REQUEST) {
        // called by client
        System.out.println("Request from Client:" + packetFromClient.type);

        packetToClient.type = Packet.LOOKUP_REPLY;
        long start = packetFromClient.start;
        long length = packetFromClient.length;

        if (start > dict.size()) {
          // set the error field, return
          packetToClient.error_code = Packet.ERROR_OUT_OF_RANGE;
        } else {
          for (int i = (int) start; i < start + length && i < dict.size(); i++) {
            packetToClient.data.add(dict.get(i));
          }
        }

        toClient.writeObject(packetToClient);
        // continue;
      }

      // }

      /* cleanup when client exits */
      fromClient.close();
      toClient.close();
      socket.close();

      // close the filehandle

    } catch (IOException e) {
      if (!gotByePacket) {
        e.printStackTrace();
      }
    } catch (ClassNotFoundException e) {
      if (!gotByePacket) e.printStackTrace();
    }
  }
  public void handleCustomPayload(Packet250CustomPayload par1Packet250CustomPayload) {
    if ("MC|BEdit".equals(par1Packet250CustomPayload.channel)) {
      try {
        DataInputStream datainputstream =
            new DataInputStream(new ByteArrayInputStream(par1Packet250CustomPayload.data));
        ItemStack itemstack = Packet.readItemStack(datainputstream);

        if (!ItemWritableBook.validBookTagPages(itemstack.getTagCompound())) {
          throw new IOException("Invalid book tag!");
        }

        ItemStack itemstack2 = playerEntity.inventory.getCurrentItem();

        if (itemstack != null
            && itemstack.itemID == Item.writableBook.shiftedIndex
            && itemstack.itemID == itemstack2.itemID) {
          itemstack2.setTagCompound(itemstack.getTagCompound());
        }
      } catch (Exception exception) {
        exception.printStackTrace();
      }
    } else if ("MC|BSign".equals(par1Packet250CustomPayload.channel)) {
      try {
        DataInputStream datainputstream1 =
            new DataInputStream(new ByteArrayInputStream(par1Packet250CustomPayload.data));
        ItemStack itemstack1 = Packet.readItemStack(datainputstream1);

        if (!ItemEditableBook.validBookTagContents(itemstack1.getTagCompound())) {
          throw new IOException("Invalid book tag!");
        }

        ItemStack itemstack3 = playerEntity.inventory.getCurrentItem();

        if (itemstack1 != null
            && itemstack1.itemID == Item.writtenBook.shiftedIndex
            && itemstack3.itemID == Item.writableBook.shiftedIndex) {
          itemstack3.setTagCompound(itemstack1.getTagCompound());
          itemstack3.itemID = Item.writtenBook.shiftedIndex;
        }
      } catch (Exception exception1) {
        exception1.printStackTrace();
      }
    } else if ("MC|TrSel".equals(par1Packet250CustomPayload.channel)) {
      try {
        DataInputStream datainputstream2 =
            new DataInputStream(new ByteArrayInputStream(par1Packet250CustomPayload.data));
        int i = datainputstream2.readInt();
        Container container = playerEntity.craftingInventory;

        if (container instanceof ContainerMerchant) {
          ((ContainerMerchant) container).setCurrentRecipeIndex(i);
        }
      } catch (Exception exception2) {
        exception2.printStackTrace();
      }
    } else {
      ModLoader.serverCustomPayload(this, par1Packet250CustomPayload);
    }
  }
示例#6
0
  public void testBasicPacket() {
    Packet packet;

    packet = new Packet("c", "a");
    assertEquals("message_", packet.message_, "c");
    assertEquals("destination_", packet.destination_, "a");
    assertEquals("origin_", packet.origin_, "");
    packet.origin_ = "o";
    assertEquals("origin_ (after setting)", packet.origin_, "o");
  }
示例#7
0
  public static List readWatchableObjects(DataInputStream par0DataInputStream) throws IOException {
    ArrayList arraylist = null;

    for (byte byte0 = par0DataInputStream.readByte();
        byte0 != 127;
        byte0 = par0DataInputStream.readByte()) {
      if (arraylist == null) {
        arraylist = new ArrayList();
      }

      int i = (byte0 & 0xe0) >> 5;
      int j = byte0 & 0x1f;
      WatchableObject watchableobject = null;

      switch (i) {
        case 0:
          watchableobject = new WatchableObject(i, j, Byte.valueOf(par0DataInputStream.readByte()));
          break;

        case 1:
          watchableobject =
              new WatchableObject(i, j, Short.valueOf(par0DataInputStream.readShort()));
          break;

        case 2:
          watchableobject =
              new WatchableObject(i, j, Integer.valueOf(par0DataInputStream.readInt()));
          break;

        case 3:
          watchableobject =
              new WatchableObject(i, j, Float.valueOf(par0DataInputStream.readFloat()));
          break;

        case 4:
          watchableobject = new WatchableObject(i, j, Packet.readString(par0DataInputStream, 64));
          break;

        case 5:
          short word0 = par0DataInputStream.readShort();
          byte byte1 = par0DataInputStream.readByte();
          short word1 = par0DataInputStream.readShort();
          watchableobject = new WatchableObject(i, j, new ItemStack(word0, byte1, word1));
          break;

        case 6:
          int k = par0DataInputStream.readInt();
          int l = par0DataInputStream.readInt();
          int i1 = par0DataInputStream.readInt();
          watchableobject = new WatchableObject(i, j, new ChunkCoordinates(k, l, i1));
          break;
      }

      arraylist.add(watchableobject);
    }

    return arraylist;
  }
 public void registerPacket(Packet par1Packet) {
   logger.warning(
       (new StringBuilder())
           .append(getClass())
           .append(" wasn't prepared to deal with a ")
           .append(par1Packet.getClass())
           .toString());
   kickPlayerFromServer("Protocol error, unexpected packet");
 }
示例#9
0
  private boolean sendAck(Packet p, DatagramPacket dp) {

    // Respond
    // System.out.println("RT: Sending ack for packet w/ seqnum: " + p.getSeqNum());
    Packet hsp = new Packet(p.getSeqNum());
    hsp.assembleHandshakePacket();
    packet =
        new DatagramPacket(hsp.getPacketData(), hsp.getPacketSize(), dp.getAddress(), dp.getPort());

    try {
      socket.send(packet);
    } catch (Exception e) {
      System.out.println("RT: Could not send ack packet:\n" + e.getMessage());
      return false;
    }

    return true;
  }
示例#10
0
  private MyMessage getMessage() throws Exception {
    int dataRecieved = 0;
    String m = new String();
    String t;

    // FIXME needs to get multiple packets and messages
    // System.out.println("RT: Now waiting for message data");

    while (dataRecieved < totalDataSize) {
      // Get message data
      response = new byte[65000];
      DatagramPacket packet = new DatagramPacket(response, response.length);
      socket.receive(packet);
      Packet p = new Packet(packet.getData());
      // System.out.println("RT: Got message with seqnum: "+p.getSeqNum());

      // If we have a handshake packet something broke
      if (p.isHandshake()) {
        return null;
      }

      // If next in-order packet grab data and is not corrupt
      // XXX
      if (p.getSeqNum() == seqNum + 1 && p.checkChecksum()) {
        // Get the message ( part? )
        // System.out.println("RT: Is correct seqnum");
        t = p.getMessages().get(0).getMessageContents();
        // System.out.println("RT: Got message packet: " + t);
        m += t;

        // Send ack
        sendAck(p, packet);

        // Increment counters
        dataRecieved += t.length();
        seqNum++;
      } else {
        System.out.println("RT: Is NOT correct seqnum");
      }
    }
    MyMessage result = new MyMessage();
    result.setMessageContents(m);
    return result;
  }
示例#11
0
 private String getFriendsMessage(Packet packet) {
   ArrayList<String> friends = new ArrayList<String>();
   friends = server.getfriendlist(packet.getSender());
   String friendsMessage = "";
   // Prepare delimited list to send to sender
   for (int i = 0; i < friends.size(); i++) {
     friendsMessage = friendsMessage + friends.get(i) + ":";
   }
   return friendsMessage;
 }
示例#12
0
  private static void writeWatchableObject(
      DataOutputStream par0DataOutputStream, WatchableObject par1WatchableObject)
      throws IOException {
    int i =
        (par1WatchableObject.getObjectType() << 5 | par1WatchableObject.getDataValueId() & 0x1f)
            & 0xff;
    par0DataOutputStream.writeByte(i);

    switch (par1WatchableObject.getObjectType()) {
      case 0:
        par0DataOutputStream.writeByte(((Byte) par1WatchableObject.getObject()).byteValue());
        break;

      case 1:
        par0DataOutputStream.writeShort(((Short) par1WatchableObject.getObject()).shortValue());
        break;

      case 2:
        par0DataOutputStream.writeInt(((Integer) par1WatchableObject.getObject()).intValue());
        break;

      case 3:
        par0DataOutputStream.writeFloat(((Float) par1WatchableObject.getObject()).floatValue());
        break;

      case 4:
        Packet.writeString((String) par1WatchableObject.getObject(), par0DataOutputStream);
        break;

      case 5:
        ItemStack itemstack = (ItemStack) par1WatchableObject.getObject();
        par0DataOutputStream.writeShort(itemstack.getItem().shiftedIndex);
        par0DataOutputStream.writeByte(itemstack.stackSize);
        par0DataOutputStream.writeShort(itemstack.getItemDamage());
        break;

      case 6:
        ChunkCoordinates chunkcoordinates = (ChunkCoordinates) par1WatchableObject.getObject();
        par0DataOutputStream.writeInt(chunkcoordinates.posX);
        par0DataOutputStream.writeInt(chunkcoordinates.posY);
        par0DataOutputStream.writeInt(chunkcoordinates.posZ);
        break;
    }
  }
示例#13
0
  private int processHandshake(Packet p, InetAddress ip, int port) throws Exception {
    // System.out.println("Got handshake");
    // Get connection information
    this.numMessages = p.getNumMessages();
    this.totalDataSize = p.getTotalDataLength();
    this.seqNum = p.getSeqNum();

    // Respond
    // System.out.println("RT: Sending handshake response");
    Packet hsp = new Packet(seqNum);
    hsp.assembleHandshakePacket();
    packet = new DatagramPacket(hsp.getPacketData(), hsp.getPacketSize(), ip, port);
    socket.send(packet);

    // System.out.println("RT: Done with handshake:\n\tStarting seqnum: "+seqNum+"\n\tTotal datalen:
    // "+totalDataSize);
    return 1; // FIXME p.getNumMessages();
  }
示例#14
0
文件: Manager.java 项目: JCortz/SD
  /*
   * Cria uma nova Tarefa.
   * Retorna true se foi criada com sucesso false caso contrário
   */
  public boolean newTask(String type, Packet objects) {
    if (type.equals("")) return false;
    lock.lock();
    try {
      if (this.tasks.containsKey(type)) {
        return false;
      } else {
        HashMap<String, String> aux = objects.getArgs();
        HashMap<String, Integer> objs = new HashMap<>();
        for (Map.Entry<String, String> entry : aux.entrySet()) {
          objs.put(entry.getKey(), Integer.parseInt((entry.getValue())));
        }
        Task t = new Task(type, objs, lock);

        this.tasks.put(type, t);

        return true;
      }
    } finally {
      lock.unlock();
    }
  }
示例#15
0
 public void send(Packet aPacket, InetSocketAddress aNodeId) {
   synchronized (_messages) {
     _messages.add(aPacket.getMessage());
   }
 }
示例#16
0
  public void run() {
    ObjectInputStream din = null;
    try {
      din = new ObjectInputStream(socket.getInputStream());
      Packet packet = (Packet) din.readObject();
      username = packet.getSender();

      server.usernameSocketMapping.put(username, socket);
      server.isAlive.add(username);
      // Sh: Login validation message
      if (packet.getType() == 0) {
        try {
          String password = packet.getMessage();
          Statement st = Server.conn.createStatement();
          ResultSet rs =
              st.executeQuery(
                  "SELECT * FROM user_info where username='******' and password='******'");
          if (!rs.next()) { // User does not exist
            server.forwardToReceiver(new Packet(0, "Server", username, "Invalid"));
            synchronized (server.usernameSocketMapping) {
              server.usernameSocketMapping.remove(username);
            }
            synchronized (server.isAlive) {
              server.isAlive.remove(username);
            }
            return;
          } else { // Authentic user
            server.forwardToReceiver(new Packet(0, "Server", username, "Authentic"));
          }
        } catch (SQLException e1) {
          e1.printStackTrace();
        }
      }
      // Sh: Signup message
      if (packet.getType() == 2) {
        try {
          String[] message = packet.getMessage().split(":");
          String name = message[0];
          String password = message[1];
          // String sex=message[2];
          String username = message[2];
          Statement st = Server.conn.createStatement();
          ResultSet rs =
              st.executeQuery("SELECT * FROM user_info where username='******'");
          if (rs.next()) { // Username already present
            server.forwardToReceiver(new Packet(2, "Server", username, "Username present"));
            synchronized (server.usernameSocketMapping) {
              server.usernameSocketMapping.remove(username);
            }
            synchronized (server.isAlive) {
              server.isAlive.remove(username);
            }
            return;
          } else { // Register user
            String query =
                "INSERT INTO user_info VALUES('"
                    + name
                    + "','"
                    + password
                    + "',"
                    + "NULL,'"
                    + username
                    + "')";
            System.out.println(query);
            st.executeUpdate(query);
            server.forwardToReceiver(new Packet(2, "Server", username, "User Registererd"));
          }

        } catch (SQLException e1) {
          e1.printStackTrace();
        }
      }
      System.out.println("State of isAlive map is: " + server.isAlive);

      try {
        Statement st = Server.conn.createStatement();
        ResultSet rs =
            st.executeQuery(
                "SELECT sender,message,status FROM msg_buffer where receiver='"
                    + username
                    + "' order by sender,sno");
        String sendflag = null;
        String sender = null;
        while (rs.next()) {

          sender = rs.getString("sender");
          int status = rs.getInt("status");
          String message = rs.getString("message");
          System.out.println("sender: " + sender);
          System.out.println("receiver: " + username);
          System.out.println("message: " + message);
          server.forwardToReceiver(new Packet(status, sender, username, message));
          System.out.println("Sending " + packet);
          if (!sender.equals(sendflag)) {
            server.forwardToReceiver(new Packet(6, username, sender, "Message Received"));
            sendflag = sender;
          }
        }

        st.executeUpdate("DELETE FROM msg_buffer where receiver='" + username + "'");
      } catch (SQLException e1) {
        e1.printStackTrace();
      }

      while (true) {
        packet = (Packet) din.readObject();

        if (packet.getType() == 3) // is an OK message
        {
          try {
            packet.setSender(username);
            System.out.println("Is OK message");
            Statement st = Server.conn.createStatement();
            ResultSet rs =
                st.executeQuery(
                    "SELECT * FROM user_info where username='******'");
            if (rs.next()) {

              if (server.addFriend(packet.getSender(), packet.getReceiver(), true) == 1) {
                // packet.setMessage("Already in friend list");
                server.forwardToReceiver(
                    new Packet(1, "Server", packet.getSender(), "Already in friend list"));
                System.out.println("ALready in list");
              } else {
                System.out.println("Sending " + packet);
                server.forwardToReceiver(
                    new Packet(1, "Server", packet.getReceiver(), packet.getMessage()));
                server.forwardToReceiver(
                    new Packet(1, "Server", packet.getSender(), packet.getMessage()));
              }
            } else {
              server.forwardToReceiver(
                  new Packet(1, "Server", packet.getSender(), "User does not exist"));
            }
          } catch (SQLException e1) {
            e1.printStackTrace();
          }
        } else if ((packet.getType() == 8)) // is a getFriends message
        {
          packet.setSender(username);
          System.out.println("Type 8");
          /*
           * try { //Thread.sleep(3000); } catch (InterruptedException
           * e) { // TODO Auto-generated catch block
           * e.printStackTrace(); }
           */
          String FriendsMessage = getFriendsMessage(packet);
          server.forwardToReceiver(
              new Packet(8, "Server", packet.getSender(), "Friends|" + FriendsMessage));
        } else if (packet.getType() == 16) // Random conversation.
        {
          packet.setSender(username);
          String receiver = server.getRandomPerson(packet.getSender());
          if (!receiver.equals("No One Online")) {
            server.forwardToReceiver(
                new Packet(1, "Server", packet.getSender(), receiver + "| will talk to you now."));
            server.forwardToReceiver(
                new Packet(1, "Server", receiver, packet.getSender() + "| will talk to you now."));
          } else {
            System.out.println("No one online");
            server.forwardToReceiver(new Packet(16, "Server", packet.getSender(), "No One Online"));
            server.forwardToReceiver(new Packet(1, "Server", packet.getSender(), "No One Online"));
          }
        } else if (packet.getType() == 13) { // Webcam of live is started
          synchronized (server.webcamAliveMapping) {
            server.webcamAliveMapping.put(packet.getSender(), packet.getMessage());
          }
          System.out.println("State of webcamAliveMapping is: " + server.webcamAliveMapping);

        } else if (packet.getType() == 14) { // Webcam of client is
          // closed
          if (server.webcamAliveMapping.containsKey(packet.getSender())) {
            synchronized (server.webcamAliveMapping) {
              server.webcamAliveMapping.remove(packet.getSender());
            }
          }
        } else if (packet.getType() == 15) { // Client requested for
          // another client's webcam
          if (server.webcamAliveMapping.containsKey(
              packet.getReceiver())) { // User Webcam is available
            server.forwardToReceiver(
                new Packet(
                    15,
                    "Server",
                    packet.getSender(),
                    server.webcamAliveMapping.get(packet.getReceiver())));
          } else { // User Webcam not available
            server.forwardToReceiver(
                new Packet(15, "Server", packet.getSender(), "Webcam Not Found"));
            server.forwardToReceiver(
                new Packet(
                    1,
                    "Server",
                    packet.getSender(),
                    "Webcam for " + packet.getReceiver() + " is not available"));
          }
        } else if (packet.getType() == 17) {
          ArrayList<String> friends = new ArrayList<String>();
          friends = server.getfriendlist(packet.getSender());
          if (friends.isEmpty()) {
            server.forwardToReceiver(
                new Packet(1, "Server", packet.getSender(), "Your friendlist is empty."));
          } else {
            for (int i = 0; i < friends.size(); i++) {
              server.forwardToReceiver(
                  new Packet(1, packet.getSender(), friends.get(i), packet.getMessage()));
            }
          }

        } else {
          packet.setSender(username);
          System.out.println("Sending " + packet);
          server.forwardToReceiver(packet);
        }
      }
    } catch (EOFException ie) {
    } catch (IOException ie) {
      ie.printStackTrace();
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    } finally {
      try {
        din.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
      synchronized (server.isAlive) {
        server.isAlive.remove(username);
      }
      synchronized (server.usernameSocketMapping) {
        server.usernameSocketMapping.remove(username);
      }
      System.out.println("State of isAlive map is: " + server.isAlive);
      server.removeConnection(socket);
    }
  }
 /**
  * Write a given packet to the stream and then flushes it.
  *
  * @throws IOException if there was a problem writing to the stream.
  * @throws AlgorithmException if there was a problem encoding the packet data.
  */
 public void writePacket(Packet packet) throws IOException, AlgorithmException {
   outputStream.write(packet.encodePacket());
   outputStream.flush();
 }