Esempio n. 1
0
 public void searchAll() {
   boolean thereIsMessage = false;
   System.out.println("search for:");
   String forSearch;
   forSearch = "";
   boolean incorrectExpression = false;
   try {
     forSearch = reader.readLine();
   } catch (IOException e) {
     System.out.println("Can't read this");
   }
   for (Message it : messageList) {
     if (it.getAuthor().equals(forSearch)) {
       System.out.println(it.toString());
       thereIsMessage = true;
       continue;
     }
     if (it.getMessage().contains(forSearch)) {
       System.out.println(it.toString());
       thereIsMessage = true;
       continue;
     }
     try {
       Pattern p = Pattern.compile(forSearch);
       Matcher m = p.matcher(it.getMessage());
       if (m.find()) {
         thereIsMessage = true;
         System.out.println(it.toString());
       }
     } catch (PatternSyntaxException e) {
       if (!incorrectExpression) {
         System.out.println("Incorrect expression: \n" + e.getMessage());
         incorrectExpression = true;
       }
     }
   }
   if (!thereIsMessage) {
     System.out.println("There isn't any message from this author");
     logWriter.write(
         (new Date()).toString()
             + " | "
             + "Search by all: "
             + forSearch
             + " |Nothing was found "
             + ""
             + "\n");
   } else {
     logWriter.write(
         (new Date()).toString()
             + " | "
             + "Search by all: "
             + forSearch
             + " |Successfully "
             + ""
             + "\n");
   }
 }
  public void messageReceived(int to, Message message) {
    Date date = Calendar.getInstance().getTime();

    if (message instanceof RadioSignalResultsMsg) {
      RadioSignalResultsMsg resultMsg = (RadioSignalResultsMsg) message;
      log(
          date
              + "\t"
              + date.getTime()
              + "\t"
              + "RADIO15.4_RESULT_MSG"
              + "\t"
              + resultMsg.get_idReceiver()
              + "\t"
              + resultMsg.get_idSender()
              + "\t"
              + resultMsg.get_seqno()
              + "\t"
              + resultMsg.get_rssi()
              + "\t"
              + resultMsg.get_lqi()
              + "\t"
              + resultMsg.get_timestamp());
    } else {
      log(date + "\t" + date.getTime() + "\t UNKNOWN_MSG" + "\t" + message.toString());
    }
  }
Esempio n. 3
0
 // Send message to base station
 public void sendMessage(Message m) {
   try {
     os.write(m.toString().getBytes());
     os.flush();
   } catch (IOException e) {
     System.out.println("Failed to send message!");
   }
 }
Esempio n. 4
0
 @Override
 public String toString() {
   StringBuffer sb = new StringBuffer();
   for (int i = 0; i < messages.size(); i++) {
     Message m = messages.get(i);
     if (i > 0) sb.append(",");
     sb.append(m.toString());
   }
   return sb.toString();
 }
  /**
   * Sends a broadcast message (TAG EPOCH_TIME message). Opens a new socket in case it's closed.
   *
   * @param message the message to send (multicast). It can't be null or 0-characters long.
   * @return
   * @throws IllegalArgumentException
   */
  public boolean sendMessage(String message) throws IllegalArgumentException {
    if (message == null || message.length() == 0) throw new IllegalArgumentException();

    // Check for WiFi connectivity
    ConnectivityManager connManager =
        (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    if (mWifi == null || !mWifi.isConnected()) {
      Log.d(
          DEBUG_TAG,
          "Sorry! You need to be in a WiFi network in order to send UDP multicast packets. Aborting.");
      return false;
    }

    // Check for IP address
    WifiManager wim = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    int ip = wim.getConnectionInfo().getIpAddress();

    // Create the send socket
    if (socket == null) {
      try {
        socket = new DatagramSocket();
      } catch (SocketException e) {
        Log.d(DEBUG_TAG, "There was a problem creating the sending socket. Aborting.");
        e.printStackTrace();
        return false;
      }
    }

    // Build the packet
    DatagramPacket packet;
    Message msg = new Message(TAG, message);
    byte data[] = msg.toString().getBytes();

    try {
      packet =
          new DatagramPacket(
              data, data.length, InetAddress.getByName(ipToString(ip, true)), MULTICAST_PORT);
    } catch (UnknownHostException e) {
      Log.d(DEBUG_TAG, "It seems that " + ipToString(ip, true) + " is not a valid ip! Aborting.");
      e.printStackTrace();
      return false;
    }

    try {
      socket.send(packet);
    } catch (IOException e) {
      Log.d(DEBUG_TAG, "There was an error sending the UDP packet. Aborted.");
      e.printStackTrace();
      return false;
    }

    return true;
  }
Esempio n. 6
0
 public boolean acceptMsg(Message msg) {
   logRecvMsg(msg);
   TestChatServer.logUserMsgRecvd(username, msg.toString(), new Date());
   TransportObject toSend =
       new TransportObject(
           ServerReply.receive,
           msg.getSource(),
           msg.getDest(),
           msg.getContent(),
           msg.getTimestamp(),
           msg.getSQN());
   if (!queueReply(toSend)) return false;
   msgReceived(
       msg.getSource() + "\t" + msg.getDest() + "\t" + msg.getSQN() + "\t" + msg.getContent());
   return true;
 }
Esempio n. 7
0
 public void run() {
   while (keeprunning) {
     try {
       Message m = outqueue.take();
       if (!keeprunning) break;
       // synchronized (out) { // shouldn't need to synchronize here, there's only one thread
       // running this
       out.println(m.toString());
       // }
     } catch (InterruptedException e) {
     } catch (Exception e) {
       System.err.println("unexpected exception in OuputHandler");
       e.printStackTrace();
     }
   }
 }
Esempio n. 8
0
  public void searchByRegularExpression() {
    boolean thereIsMessage = false;
    boolean incorrectExpression = false;
    System.out.println("Input: regular expression");

    String expression;
    expression = "";
    try {
      expression = reader.readLine();
    } catch (IOException e) {
      System.out.println("Can't read this");
    }

    for (Message it : messageList) {
      try {
        Pattern p = Pattern.compile(expression);
        Matcher m = p.matcher(it.getMessage());
        if (m.find()) {
          thereIsMessage = true;
          System.out.println(it.toString());
        }
      } catch (PatternSyntaxException e) {
        System.out.println("Incorrect expression: \n" + e.getMessage());
        incorrectExpression = true;
      }
    }
    if ((!thereIsMessage) && (!incorrectExpression)) {
      System.out.println("There isn't any message with this regular expression");
      logWriter.write(
          (new Date()).toString()
              + " | "
              + "Search By Regular Expression: "
              + expression
              + " |There isn't any message with this regular expression "
              + ""
              + "\n");
    } else {
      logWriter.write(
          (new Date()).toString()
              + " | "
              + "Search By Regular Expression: "
              + expression
              + " |Successfully "
              + ""
              + "\n");
    }
  }
  /**
   * Stellt die Nachricht an alle Consumer zu.
   *
   * @param consumers die Message-Consumer.
   * @param msg
   */
  private void deliver(Message msg) {
    if (pool.isTerminating() || pool.isTerminated()) {
      Logger.warn("shutdown in progress, no more messages accepted");
      return; // wir nehmen keine Nachrichten mehr entgegen.
    }

    // BUGZILLA 1413 Wir koennen leider doch nicht auf einer Kopie der Liste arbeiten, weil
    // diese waehrend der Zustellung erweitert werden kann. Z.bsp. der "AutoRegisterMessageConsumer"
    // erhaelt die SYSTEM_STARTED-Message und registriert daraufhin neue Consumer. Unter anderem
    // den DeployMessageConsumer aus jameica.webadmin, der ebenfalls auf die SYSTEM_STARTED-Message
    // lauscht.
    Logger.debug("deliver message " + msg.toString());
    MessageConsumer consumer = null;
    for (int i = 0; i < this.consumers.size(); ++i) {
      consumer = this.consumers.get(i);
      Class[] expected = consumer.getExpectedMessageTypes();
      boolean send = expected == null;
      if (expected != null) {
        for (int j = 0; j < expected.length; ++j) {
          if (expected[j].isInstance(msg)) {
            send = true;
            break;
          }
        }
      }
      try {
        if (send) consumer.handleMessage(msg);
      } catch (ApplicationException ae) {
        Application.getMessagingFactory()
            .sendSyncMessage(new StatusBarMessage(ae.getMessage(), StatusBarMessage.TYPE_ERROR));
      } catch (OperationCanceledException oce) {
        Logger.debug("consumer " + consumer.getClass().getName() + " cancelled message " + msg);
      } catch (Throwable t) {
        Logger.error(
            "consumer "
                + consumer.getClass().getName()
                + " produced an error ("
                + t.getClass().getName()
                + ": "
                + t
                + ") while consuming message "
                + msg);
        Logger.write(Level.INFO, "error while processing message", t);
      }
    }
  }
  /** {@inheritDoc} */
  @Override
  public void loadLocale(Locale l) throws NoSuchLocalizationException {
    messages.remove(l);

    InputStream resstream = null;
    InputStream filestream = null;

    try {
      filestream = new FileInputStream(new File(plugin.getDataFolder(), l.getLanguage() + ".yml"));
    } catch (FileNotFoundException e) {
    }

    try {
      resstream =
          plugin.getResource(
              new StringBuilder(LOCALIZATION_FOLDER_NAME)
                  .append("/")
                  .append(l.getLanguage())
                  .append(".yml")
                  .toString());
    } catch (Exception e) {
    }

    if ((resstream == null) && (filestream == null)) throw new NoSuchLocalizationException(l);

    messages.put(l, new HashMap<Message, List<String>>(Message.values().length));

    FileConfiguration resconfig =
        (resstream == null) ? null : YamlConfiguration.loadConfiguration(resstream);
    FileConfiguration fileconfig =
        (filestream == null) ? null : YamlConfiguration.loadConfiguration(filestream);
    for (Message m : Message.values()) {
      List<String> values = m.getDefault();

      if (resconfig != null) {
        if (resconfig.isList(m.toString())) {
          values = resconfig.getStringList(m.toString());
        } else {
          values.add(resconfig.getString(m.toString(), values.get(0)));
        }
      }
      if (fileconfig != null) {
        if (fileconfig.isList(m.toString())) {
          values = fileconfig.getStringList(m.toString());
        } else {
          values.add(fileconfig.getString(m.toString(), values.get(0)));
        }
      }

      messages.get(l).put(m, values);
    }
  }
Esempio n. 11
0
  /**
   * Add a new {@link Message} to this conversation.
   *
   * @param message being added
   */
  public void newChatMessage(Message message) {
    // TODO: Refactor this,ChatDocumentBuilder, etc into cleaner/clearer, way to display msgs
    LOG.debugf("Message: from {0} text: {1}", message.getSenderName(), message.toString());
    messages.add(message);
    Type type = message.getType();

    if (type != Type.SENT) {
      currentChatState = ChatState.active;
    }

    if (message instanceof MessageFileOffer) {
      MessageFileOffer msgWithFileOffer = (MessageFileOffer) message;
      addFileOfferMessage(msgWithFileOffer);
    } else if (message instanceof NoSaveStatusMessage) {
      updateNoSaveLink(((NoSaveStatusMessage) message).getStatus());
    }

    displayMessages();
  }
 public void showMessages(boolean isFormatted) {
   try {
     Collections.sort(data);
     if (isFormatted) {
       System.out.println("FORMATTED LIST OF MESSAGES:");
       log("QUERY formatted list");
       for (Message i : data) {
         System.out.println(i.getFormattedMessage());
       }
     } else {
       System.out.println("FULL LIST OF MESSAGES:");
       log("QUERY full list");
       for (Message i : data) {
         System.out.println(i.toString());
       }
     }
   } catch (Exception e) {
     System.out.println(RED + "Failed on your query. Try another one." + END);
     log("QUERY failed");
   }
 }
Esempio n. 13
0
  public void searchByKeyWord() {
    boolean thereIsMessage = false;
    System.out.println("Input: key word");

    String keyWord;
    keyWord = "";
    try {
      keyWord = reader.readLine();
    } catch (IOException e) {
      System.out.println("Can't read this");
    }
    logWriter.write("Search By Key Word: " + keyWord + " |Successfully " + "" + "\n");
    for (Message it : messageList) {
      if (it.getMessage().contains(keyWord)) {
        System.out.println(it.toString());
        thereIsMessage = true;
      }
    }
    if (!thereIsMessage) {
      System.out.println("There isn't any message with this word");
      logWriter.write(
          (new Date()).toString()
              + " | "
              + "Search By Key Word: "
              + keyWord
              + " |There isn't any message with this word "
              + ""
              + "\n");
    } else {
      logWriter.write(
          (new Date()).toString()
              + " | "
              + "Search By Key Word: "
              + keyWord
              + " |Successfully "
              + ""
              + "\n");
    }
  }
Esempio n. 14
0
  public void searchByAuthor() {
    boolean thereIsMessage = false;
    System.out.println("Input: author name");
    String nameForSearch;
    nameForSearch = "";
    try {
      nameForSearch = reader.readLine();
    } catch (IOException e) {
      System.out.println("Can't read this");
    }

    for (Message it : messageList) {
      if (it.getAuthor().equals(nameForSearch)) {
        System.out.println(it.toString());
        thereIsMessage = true;
      }
    }
    if (!thereIsMessage) {
      System.out.println("There isn't any message from this author");
      logWriter.write(
          (new Date()).toString()
              + " | "
              + "Search By Author: "
              + nameForSearch
              + " |There isn't any message from this author "
              + ""
              + "\n");
    } else {
      logWriter.write(
          (new Date()).toString()
              + " | "
              + "Search By Author: "
              + nameForSearch
              + " |Successfully "
              + ""
              + "\n");
    }
  }
  /**
   * The implementation for pushMessageSync() function.
   *
   * @param msg
   * @return 1 for success, 0 for failure
   * @throws TException
   */
  @Override
  public int pushMessageSync(Message msg) throws org.apache.thrift.TException {

    if (msg == null) {
      log.error("Error, pushMessageSync: empty message ");
      return 0;
    }

    List<String> sessionids = msg.getSessionIDs();
    for (String sid : sessionids) {
      SessionQueue pQueue = null;

      if (!msgQueues.containsKey(sid)) {
        pQueue = new SessionQueue();
        msgQueues.put(sid, pQueue);
      } else {
        pQueue = msgQueues.get(sid);
      }

      log.debug(
          "pushMessageSync: SessionId: " + sid + " Receive a message, " + msg.toString() + "\n");
      ByteBuffer bb = ByteBuffer.wrap(msg.getPacket().getData());
      // ByteBuffer dst = ByteBuffer.wrap(msg.getPacket().toString().getBytes());
      BlockingQueue<ByteBuffer> queue = pQueue.getQueue();
      if (queue != null) {
        if (!queue.offer(bb)) {
          log.error("Failed to queue message for session: " + sid);
        } else {
          log.debug("insert a message to session: " + sid);
        }
      } else {
        log.error("queue for session {} is null", sid);
      }
    }

    return 1;
  }
Esempio n. 16
0
 /**
  * @see
  *     uk.ac.imperial.presage2.core.network.NetworkConnector#deliverMessage(uk.ac.imperial.presage2.core.network.Message)
  */
 @Override
 public synchronized void deliverMessage(Message<?> m) {
   if (logger.isDebugEnabled()) logger.debug("Received message: " + m.toString());
   this.receivedMessages.add(m);
 }
  public synchronized void receive(Message m) {

    Utils.out(pid, m.toString()); /* The default action. */
  }
Esempio n. 18
0
    public void run() {
      String messageString;
      long lastActivity = System.currentTimeMillis();
      while (keeprunning) {
        try {
          if (in.ready()) {
            messageString = in.readLine();

            if (messageString == null) continue;
            Message m = new Message(messageString);

            if (m.getCommand().matches("\\d+"))
              try {
                int intcommand = Integer.parseInt(m.getCommand());
                if (intcommand == Constants.RPL_ENDOFMOTD) {
                  System.err.println("MOTD SEEN, must be connected.");
                  if (connected) joinChannels();
                  connected = true;
                } else if (intcommand == Constants.ERR_NICKNAMEINUSE) {
                  System.err.println("NICKNAMEINUSE");
                  namecount++;
                  BotStats.getInstance().setBotname(botdefaultname + namecount);
                  new Message("", "NICK", BotStats.getInstance().getBotname(), "").send();
                  new Message(
                          "",
                          "USER",
                          BotStats.getInstance().getBotname()
                              + " nowhere.com "
                              + BotStats.getInstance().getServername(),
                          BotStats.getInstance().getClientName()
                              + " v."
                              + BotStats.getInstance().getVersion())
                      .send();
                  System.err.println("Setting nick to:" + botdefaultname + namecount);
                }
              } catch (NumberFormatException nfe) {
                // we ignore this
                System.err.println("Unknown command:" + m.getCommand());
              }

            if (m.getCommand().equals("PING")) {
              outqueue.add(new Message("", "PONG", "", m.getTrailing()));
              if (debug) System.out.println("PUNG at " + new Date());
            } else if (BotStats.getInstance().containsIgnoreName(m.getSender())) {
              if (debug) System.out.println("Ignored: " + m);
            } else {
              inqueue.add(m); // add to inqueue
              if (debug) System.out.println(m.toString());
              // System.out.println("Inbuffer: prefix: " + m.prefix + " params: " + m.params + "
              // trailing:"
              // + m.trailing + " command:" + m.command + " sender: " + m.sender + "\n    "
              // + "isCTCP:" + m.isCTCP + " isPrivate:" + m.isPrivate + " CTCPCommand:" +
              // m.CTCPCommand
              // + " CTCPMessage:" + m.CTCPMessage);
            }

            lastActivity = System.currentTimeMillis();
          } else {
            if (System.currentTimeMillis() - lastActivity > 400000) {
              System.err.println("400 seconds since last activity! Attempting reconnect");
              in.close();
              oh.disconnect();
              keeprunning = false;
              reconnect();
              return;
            }
            sleep(100);
          }
        } catch (IOException ioe) {
          System.out.println("EOF on connection: " + ioe.getMessage());
        } catch (InterruptedException ie) {
          System.out.println("Interrupted: " + ie.getMessage());
        } catch (Exception e) {
          System.err.println("Unexpected exception in InputHandler :");
          e.printStackTrace();
        }
      }
    }
Esempio n. 19
0
 @Test
 public void logSend() {
   Message message = new Message(1, new Card(2), 3, 4, 5, new Money(6));
   log.logSend(message);
   assertTrue(mock_simulator.getLastLog().equals("Message:   " + message.toString()));
 }
Esempio n. 20
0
 /**
  * @see
  *     uk.ac.imperial.presage2.core.network.NetworkConnector#sendMessage(uk.ac.imperial.presage2.core.network.Message)
  */
 @Override
 public void sendMessage(Message<?> m) {
   if (logger.isDebugEnabled()) logger.debug("Sending message: " + m.toString());
   this.controller.deliverMessage(m);
 }
Esempio n. 21
0
 /**
  * Prepends a MultiMessage to the Text.
  *
  * @param prefix The MultiMessage to be prepended.
  * @return Returns the Message instance (for in-line use).
  */
 public MultiMessage prepend(Message prefix) {
   for (String t : text) {
     text.set(text.indexOf(t), prefix.toString() + t);
   }
   return this;
 }
Esempio n. 22
0
 /**
  * Appends a MultiMessage to the text.
  *
  * @param suffix The MultiMessage to be appended.
  * @return Returns the Message instance (for in-line use).
  */
 public MultiMessage append(Message suffix) {
   for (String t : text) {
     text.set(text.indexOf(t), t + suffix.toString());
   }
   return this;
 }