public void handleUpdatePacket(Packet p, String from) {
    // dont update packets that came from this device
    if (p.getSource().equals(localDevice.getBluetoothAddress())) return;

    // get the md5 of the payload of the packet and store it
    // if the previous md5 is the same with the new one
    // then this packet is redundant
    String hash = md5(p.getPayload());
    if (history.containsKey(p.getSource())) {
      String old = history.get(p.getSource());
      if (old.equals(hash)) return;
    }

    ByteBuffer buffer = ByteBuffer.allocate(p.getPayload().length);
    buffer.put(p.getPayload());
    routingTable.remove(p.getSource());
    routingTable.add(p.getSource());
    byte[] tmp = new byte[12];
    while (buffer.hasRemaining()) {
      buffer.get(tmp, 0, 12);
      routingTable.add(p.getSource(), new String(tmp));
    }

    for (String address : connections.keySet()) {
      if (!address.equals(from)) {
        connections.get(address).offer(p);
      }
    }
    history.put(p.getSource(), hash);
  }
Exemple #2
0
  /**
   * Updates the CRC value based on Packet p.
   *
   * @param p The packet which is used to update the CRC.
   */
  public void updateCRC(Packet p) {
    List<Integer> data = p.getData();
    if (data.size() == 0) { // If there isn't any data, we don't need to update the CRC
      return;
    }

    int regAddress;
    if (p.getPacketType() == PacketType.ONE) {
      RegisterType regType = p.getRegType();
      if (regType == RegisterType.NONE) { // Invalid register type
        return;
      } else if (regType == RegisterType.CMD && data.get(0) == 0x00000007) { // RCRC command
        crcValue = 0;
        return;
      }
      regAddress = regType.Address();
    } else regAddress = 0x00000002; // If type 2, we will assume FDRI

    for (int d : data) {
      for (int i = 0; i < 32; i++) { // Shift in the data one bit at a time
        shiftIn_OneBit(d >> i);
      }
      for (int i = 0; i < 5; i++) { // Shift in the reg address one bit at a time
        shiftIn_OneBit(regAddress >> i);
      }
    }
  } // end UpdateCRC
Exemple #3
0
  @Override
  public void send(Packet<byte[]> packet) throws ChannelException {
    final byte[] data = packet.unpack();

    if (data.length > MAX_DATA_LENGTH) {
      throw new ChannelException("too much data for a datagram packet");
    }

    // use socket address from packet when possible
    SocketAddress socketAddress = packet.getRemoteAddress();
    if (socketAddress == null) {
      socketAddress = socket.getRemoteSocketAddress();
    }

    final DatagramPacket datagramPacket;
    try {
      datagramPacket = new DatagramPacket(data, data.length, socketAddress);
    } catch (SocketException e) {
      throw new ChannelException("could not generate datagram packet", e);
    }

    try {
      socket.send(datagramPacket);
    } catch (IOException e) {
      throw new ChannelException("could not send datagram packet", e);
    }
  }
Exemple #4
0
 public Cookie sendPacket(Packet packet) throws IOException {
   Cookie cookie = new Cookie(packet.type);
   packet.send(connection);
   packet.dump(System.out);
   time = System.currentTimeMillis();
   return cookie;
 }
  public void run() {
    // Parse all packets
    Pattern p = Pattern.compile(".*IN=.* OUT=.* SRC=.* DST=.* LEN=.*");
    Packet lastPkt = null;
    for (LogLine ll : mLogs) {
      if (p.matcher(ll.msg).matches()) {
        Packet pkt = parse(ll);
        if (pkt.ok) {
          mPackets.add(pkt);
          // NOTE: sometimes the same packet is logged twice, so lets keep only the last one
          if (pkt.isSame(lastPkt)) {
            mPackets.remove(lastPkt);
          }
          lastPkt = pkt;
        }
      }
    }

    if (mPackets.isEmpty()) {
      return;
    }

    // Analyze packets
    new SimpleStats(this).run();
    new ResendStats(this).run();
    new ConnectionGrouping(this).run();
  }
Exemple #6
0
 /**
  * Reads a packet from the given buffer
  *
  * @param buf The buffer to read from
  * @return The packet that was read
  */
 @Override
 public Packet read(PacketBuffer buf) {
   PacketSpec spec = getSpec(buf.readInt());
   Packet packet = new Packet(new PacketBuilder(this, spec));
   packet.read(buf);
   return packet;
 }
 @Test
 public void testEncodeWithEndpoint() throws IOException {
   Packet packet = new Packet(PacketType.ERROR);
   packet.setEndpoint("/woot");
   ChannelBuffer result = encoder.encodePacket(packet);
   Assert.assertEquals("7::/woot", result.toString(CharsetUtil.UTF_8));
 }
Exemple #8
0
  public void request(Session session, Channel channel) throws Exception {
    super.request(session, channel);

    Buffer buf = new Buffer();
    Packet packet = new Packet(buf);

    // byte      SSH_MSG_CHANNEL_REQUEST(98)
    // uint32 recipient channel
    // string request type        // "x11-req"
    // boolean want reply         // 0
    // boolean   single connection
    // string    x11 authentication protocol // "MIT-MAGIC-COOKIE-1".
    // string    x11 authentication cookie
    // uint32    x11 screen number
    packet.reset();
    buf.putByte((byte) Session.SSH_MSG_CHANNEL_REQUEST);
    buf.putInt(channel.getRecipient());
    buf.putString(Util.str2byte("x11-req"));
    buf.putByte((byte) (waitForReply() ? 1 : 0));
    buf.putByte((byte) 0);
    buf.putString(Util.str2byte("MIT-MAGIC-COOKIE-1"));
    buf.putString(ChannelX11.getFakedCookie(session));
    buf.putInt(0);
    write(packet);

    session.x11_forwarding = true;
  }
 /**
  * Non-SYN packets with a zero SendStreamID may also be queued here so that they don't get thrown
  * away while the SYN packet before it is queued.
  *
  * <p>Additional overload protection may be required here... We don't have a 3-way handshake, so
  * the SYN fully opens a connection. Does that make us more or less vulnerable to SYN flooding?
  */
 public void receiveNewSyn(Packet packet) {
   if (!_active) {
     if (packet.isFlagSet(Packet.FLAG_SYNCHRONIZE)) {
       if (_log.shouldLog(Log.WARN)) _log.warn("Dropping new SYN request, as we're not listening");
       sendReset(packet);
     } else {
       if (_log.shouldLog(Log.WARN)) _log.warn("Dropping non-SYN packet - not listening");
     }
     return;
   }
   if (_manager.wasRecentlyClosed(packet.getSendStreamId())) {
     if (_log.shouldLog(Log.WARN))
       _log.warn("Dropping packet for recently closed stream: " + packet);
     return;
   }
   if (_log.shouldLog(Log.INFO))
     _log.info("Receive new SYN: " + packet + ": timeout in " + _acceptTimeout);
   // also check if expiration of the head is long past for overload detection with peek() ?
   boolean success = _synQueue.offer(packet); // fail immediately if full
   if (success) {
     _context.simpleScheduler().addEvent(new TimeoutSyn(packet), _acceptTimeout);
   } else {
     if (_log.shouldLog(Log.WARN)) _log.warn("Dropping new SYN request, as the queue is full");
     if (packet.isFlagSet(Packet.FLAG_SYNCHRONIZE)) sendReset(packet);
   }
 }
  /* 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();
  }
    /**
     * 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());
        }
      }
    }
  public byte[] BuildMovementPacket(byte flags, boolean down, byte speed) {
    byte[] tmp = new byte[4];
    Packet pkt = new Packet(ProtocolMgr.QUORRA_SET_POWER, tmp, (byte) 4);
    int[] data = null;
    if (down) {
      int targetSpeed = m_maxSpeed;
      switch (speed) {
        case 50:
          targetSpeed = m_maxSpeed / 3;
          break;
        case 100:
          targetSpeed = m_maxSpeed / 2;
          break;
        case 127:
        default:
          break;
      }
      data = controlAPI.MoveFlagsToQuorra(targetSpeed, flags, getTurnDiv());
      if (data != null) {
        pkt.writeUInt16(data[0]);
        pkt.writeUInt16(data[1]);
      }
    }

    if (data == null) {
      pkt.writeUInt16(0);
      pkt.writeUInt16(0);
    }
    pkt.CountOpcode(true);
    return pkt.getSendData();
  }
  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);
        }
      }
    }
  }
 private void receivePing(Packet packet) {
   boolean ok = packet.verifySignature(_context, packet.getOptionalFrom(), null);
   if (!ok) {
     if (_log.shouldLog(Log.WARN)) {
       if (packet.getOptionalFrom() == null)
         _log.warn(
             "Ping with no from (flagged? " + packet.isFlagSet(Packet.FLAG_FROM_INCLUDED) + ")");
       else if (packet.getOptionalSignature() == null)
         _log.warn(
             "Ping with no signature (flagged? "
                 + packet.isFlagSet(Packet.FLAG_SIGNATURE_INCLUDED)
                 + ")");
       else
         _log.warn(
             "Forged ping, discard (from="
                 + packet.getOptionalFrom().calculateHash().toBase64()
                 + " sig="
                 + packet.getOptionalSignature().toBase64()
                 + ")");
     }
   } else {
     PacketLocal pong = new PacketLocal(_context, packet.getOptionalFrom());
     pong.setFlag(Packet.FLAG_ECHO, true);
     pong.setFlag(Packet.FLAG_SIGNATURE_INCLUDED, false);
     pong.setReceiveStreamId(packet.getSendStreamId());
     _manager.getPacketQueue().enqueue(pong);
   }
 }
 @Test
 public void testEncodeWithReason() throws IOException {
   Packet packet = new Packet(PacketType.ERROR);
   packet.setReason(ErrorReason.TRANSPORT_NOT_SUPPORTED);
   ChannelBuffer result = encoder.encodePacket(packet);
   Assert.assertEquals("7:::0", result.toString(CharsetUtil.UTF_8));
 }
Exemple #16
0
  /**
   * build packet from raw data
   *
   * @param rawdata Packet data, received as a byte[]
   * @param sourceIP IP from which the data originated
   * @return Packet (Advert, Bid, BidWin or Data) built from given data
   */
  @Override
  public Packet buildPacket(byte[] rawdata, Inet4Address sourceIP) {
    char type = (char) rawdata[0];
    Packet packet;
    switch (type) {
      case 'A':
        packet = new Advert(rawdata);
        packet.setSourceIP(sourceIP);
        break;
      case 'B':
        packet = new Bid(rawdata);
        packet.setSourceIP(sourceIP);
        break;
      case 'W':
        packet = new BidWin(rawdata);
        packet.setSourceIP(sourceIP);
        break;
      case 'D':
        packet = new Data(rawdata);
        break;
        // case 'C':
        // packet = new Check(rawdata);
        // break;
      default:
        packet = null;
    }

    return packet;
  }
  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);
    }
  }
 @Test
 public void testDecodeWithMessageIdAndAck() throws IOException {
   Packet packet = decoder.decodePacket("5:1+::{\"name\":\"tobi\"}", null);
   Assert.assertEquals(PacketType.EVENT, packet.getType());
   Assert.assertEquals(1, (long) packet.getId());
   Assert.assertEquals(Packet.ACK_DATA, packet.getAck());
   Assert.assertEquals("tobi", packet.getName());
 }
 public byte[] BuildReelPacket(boolean up) {
   byte[] tmp = new byte[2];
   Packet pkt = new Packet(ProtocolMgr.QUORRA_REEL, tmp, (byte) 2);
   pkt.writeByte(up ? (byte) 1 : (byte) 0);
   pkt.writeByte((byte) 100);
   pkt.CountOpcode(true);
   return pkt.getSendData();
 }
 @Test
 public void ack() {
   Packet packet = new Packet(Parser.ACK);
   packet.data = new JsonParser().parse("[\"a\", 1, {}]");
   packet.id = 123;
   packet.nsp = "/";
   test(packet);
 }
 @Test
 public void testEncodeWithReasonAndAdvice() throws IOException {
   Packet packet = new Packet(PacketType.ERROR);
   packet.setReason(ErrorReason.UNAUTHORIZED);
   packet.setAdvice(ErrorAdvice.RECONNECT);
   ChannelBuffer result = encoder.encodePacket(packet);
   Assert.assertEquals("7:::2+0", result.toString(CharsetUtil.UTF_8));
 }
  public synchronized void handlePacket(Connection c, Packet p) {
    Address address = c.getAddress();
    System.out.println(p.toString());

    // silently ignore packets from a connection if we haven't received a version packet

    if (!c.hasReceivedVersion() && p.packetType() != PacketType.VERSION) {
      return;
    }

    switch (p.packetType()) {
      case VERSION:
        VersionPacket v = (VersionPacket) p;
        long ourVersion = ProtocolVersion.version(),
            theirVersion = v.getVersion(),
            negotiatedVersion;
        negotiatedVersion = theirVersion < ourVersion ? theirVersion : ourVersion;
        c.setVersion(negotiatedVersion);
        c.hasReceivedVersion(true);
        addressBook.justSeen(address);
        if (negotiatedVersion >= 209) {
          Packet verack = c.createPacket(PacketType.VERACK);
          c.sendPacket(verack);
        }
        break;
      case VERACK:
        c.hasRecievedVerack(true);
        addressBook.justSeen(address);
        break;
      case HEADERS:
        // primitive headers function
        HeadersPacket h = (HeadersPacket) p;
        if (h.headers().size() == 0) {
          break;
        }
        for (Block header : h.headers()) {
          try {
            blockChain.addBlock(header);

          } catch (InvalidBlockException e) {
            // TODO actually handle
            e.printStackTrace();
            continue;
          } catch (OrphanBlockException e) {
            // TODO actually handle
            e.printStackTrace();
            continue;
          } catch (BlockExistsException e) {
            // TODO actually handle
            e.printStackTrace();
            continue;
          }
        }
        GetHeadersPacket gh = (GetHeadersPacket) c.createPacket(PacketType.GETHEADERS);
        gh.startHashes().add(blockChain.topBlock().hash());
        c.sendPacket(gh);
    }
  }
Exemple #24
0
  public void handleCustomPayload(Packet250CustomPayload par1Packet250CustomPayload) {
    DataInputStream var2;
    ItemStack var3;
    ItemStack var4;

    if ("MC|BEdit".equals(par1Packet250CustomPayload.channel)) {
      try {
        var2 = new DataInputStream(new ByteArrayInputStream(par1Packet250CustomPayload.data));
        var3 = Packet.readItemStack(var2);

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

        var4 = this.playerEntity.inventory.getCurrentItem();

        if (var3 != null
            && var3.itemID == Item.writableBook.shiftedIndex
            && var3.itemID == var4.itemID) {
          var4.setTagCompound(var3.getTagCompound());
        }
      } catch (Exception var7) {
        var7.printStackTrace();
      }
    } else if ("MC|BSign".equals(par1Packet250CustomPayload.channel)) {
      try {
        var2 = new DataInputStream(new ByteArrayInputStream(par1Packet250CustomPayload.data));
        var3 = Packet.readItemStack(var2);

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

        var4 = this.playerEntity.inventory.getCurrentItem();

        if (var3 != null
            && var3.itemID == Item.field_77823_bG.shiftedIndex
            && var4.itemID == Item.writableBook.shiftedIndex) {
          var4.setTagCompound(var3.getTagCompound());
          var4.itemID = Item.field_77823_bG.shiftedIndex;
        }
      } catch (Exception var6) {
        var6.printStackTrace();
      }
    } else if ("MC|TrSel".equals(par1Packet250CustomPayload.channel)) {
      try {
        var2 = new DataInputStream(new ByteArrayInputStream(par1Packet250CustomPayload.data));
        int var8 = var2.readInt();
        Container var9 = this.playerEntity.craftingInventory;

        if (var9 instanceof ContainerMerchant) {
          ((ContainerMerchant) var9).func_75175_c(var8);
        }
      } catch (Exception var5) {
        var5.printStackTrace();
      }
    }
  }
  // Starts the simulation. It will end when no more packets are in the
  // medium
  public void runSimulator() {
    Event next;
    Packet p;

    while (true) {
      next = eventList.removeNext();

      if (next == null) {
        break;
      }

      if (traceLevel > 1) {
        System.out.println();
        System.out.println(
            "main(): event received.  t=" + next.getTime() + ", node=" + next.getEntity());
        if (next.getType() == FROMLAYER2) {
          p = next.getPacket();
          System.out.print("  src=" + p.getSource() + ", ");
          System.out.print("dest=" + p.getDest() + ", ");
          System.out.print("contents=[");
          for (int i = 0; i < NUMENTITIES - 1; i++) {
            System.out.print(p.getMincost(i) + ", ");
          }
          System.out.println(p.getMincost(NUMENTITIES - 1) + "]");
        } else if (next.getType() == LINKCHANGE) {
          System.out.println("  Link cost change.");
        }
      }

      time = next.getTime();

      if (next.getType() == FROMLAYER2) {
        p = next.getPacket();
        if ((next.getEntity() < 0) || (next.getEntity() >= NUMENTITIES)) {
          System.out.println("main(): Panic. Unknown event entity.");
        } else {
          entity[next.getEntity()].update(p);
        }
      } else if (next.getType() == LINKCHANGE) {
        if (time < 10001.0) {
          cost[0][1] = 20;
          cost[1][0] = 20;
          entity[0].linkCostChangeHandler(1, 20);
          entity[1].linkCostChangeHandler(0, 20);
        } else {
          cost[0][1] = 1;
          cost[1][0] = 1;
          entity[0].linkCostChangeHandler(1, 1);
          entity[1].linkCostChangeHandler(0, 1);
        }
      } else {
        System.out.println("main(): Panic.  Unknown event type.");
      }
    }

    System.out.println("Simulator terminated at t=" + time + ", no packets in medium.");
  }
 public RegisterHandler(UserIndex index) {
   userIndex = index;
   required = new Packet("iq");
   required.setFrom(Server.SERVER_NAME);
   required.setType("result");
   new Packet("username").setParent(required);
   new Packet("password").setParent(required);
   new Packet("hash").setParent(required);
 }
  // Handle updates when a packet is received.
  // Students will need to call NetworkSimulator.toLayer2()
  // with new packets based upon what they
  // send to update.  Be careful to construct
  // the source and destination of the packet
  // correctly.  Read the warning in NetworkSimulator.java
  // for more details.
  public void update(Packet p) {
    /* When the update function is called with a packet, we update the destination node with the
     		routing information in the given packet.
     The packet methods used in this function are explained in the file Packet.java
     Initialize the new cost as INF, get the origin of the packet and set the "changed" FLAG to false.
     If the "changed" FLAG becomes true, we will know an update has been used and new packets are sent to
    		the neighbors of the updated node to continue the iteration.
    */
    int newCost = 999;
    int src = p.getSource();
    int[] nextDistanceVector = new int[NetworkSimulator.NUMENTITIES];
    boolean changeHandler = false;
    boolean linkchange = p.getLinkChange();
    System.out.println("heyy " + p.getLinkChange());
    /*
     * This is the crucial loop of the update function. i represents
     *   the newCost variable is initially set to be equal to the combination of
     *   the cost of getting from the node to source, plus getting from source to node i.
     *
     *  Later on, the new value for the distance table is the minimum of either the newcost or the
     *  already given value at the distanceTable.
     *
     * The new distance vector is saved as the nextDistanceVector, for updating purposes.
     */
    for (int i = 0; i < NetworkSimulator.NUMENTITIES; i++) {
      newCost = distanceVector[src] + p.getMincost(i);
      distanceTable[i][src] = newCost < distanceTable[i][src] ? newCost : distanceTable[i][src];
      nextDistanceVector[i] = Math.min(newCost, distanceVector[i]);

      // If any one of the values of the distance vector is updated, the FLAG becomes
      // 		true, which means a packet has to be sent to direct neighbors of this node.
      if (nextDistanceVector[i] != distanceVector[i]) changeHandler = true;
    }

    // The distanceVector is updated with the "next distance vector.
    distanceVector = nextDistanceVector;

    System.out.println(
        "LOG--------Entity " + thisNode + " says: Node " + thisNode + " is updated.");
    printDT();

    if (changeHandler || (linkchange && !IsMyLinkChanged)) {
      Packet packet;
      for (int j = 0; j < NetworkSimulator.NUMENTITIES; j++) {
        if (j != thisNode && NetworkSimulator.cost[thisNode][j] != 999) {
          packet = new Packet(thisNode, j, distanceVector);
          NetworkSimulator.toLayer2(packet);
          System.out.println(
              "LOG--------At Node " + thisNode + ", the distance vector has been updated.");
          System.out.println("LOG--------Packet sent from " + thisNode + " to " + j);
        }
      }
    }
    // Read the NetworkSimulator.java
    // for more details.
  }
 public byte[] BuildPawPacket(float percent) {
   byte[] tmp = new byte[4];
   Packet pkt = new Packet(ProtocolMgr.QUORRA_PAWS, tmp, (byte) 4);
   int pos = (int) ((2000 * (percent / 100)) - 1000);
   int pos2 = (int) ((2000 * ((100 - percent) / 100)) - 1000);
   pkt.writeUInt16(pos);
   pkt.writeUInt16(pos2);
   pkt.CountOpcode(true);
   return pkt.getSendData();
 }
 /** @deprecated http://java.net/jira/browse/JAX_WS-1077 */
 @Deprecated
 public com.oracle.webservices.internal.api.message.MessageContext createContext(
     InputStream in, MimeHeaders headers) throws IOException {
   String contentType = getHeader(headers, "Content-Type");
   Packet packet = (Packet) createContext(in, contentType);
   packet.acceptableMimeTypes = getHeader(headers, "Accept");
   packet.soapAction = fixQuotesAroundSoapAction(getHeader(headers, "SOAPAction"));
   //      packet.put(Packet.INBOUND_TRANSPORT_HEADERS, toMap(headers));
   return packet;
 }
Exemple #30
0
 /**
  * The method sendPlayerIcon sends the path to the icon to the other player that he is playing
  * against if the game is online if the game is online of not his method is skipped
  */
 public void sendPlayerIcon() {
   try {
     Packet packet = new Packet();
     packet.setPlayerIconPath(playerIconPath);
     bridge.getOutputStream().writeObject(packet);
     bridge.getOutputStream().flush();
   } catch (Exception e) {
     JOptionPane.showMessageDialog(this, e.toString());
   }
 }