Exemplo n.º 1
1
  public Message send(Message query) {
    int q, r;
    Message best = null;
    byte rcode;

    for (q = 0; q < 20; q++) {
      boolean ok = false;
      for (r = 0; r < resolvers.length; r++) ok |= sendTo(query, r, q);
      if (!ok) break;
      Message m = null;
      synchronized (queue) {
        try {
          queue.wait((quantum + 1) * 1000);
        } catch (InterruptedException e) {
          System.out.println("interrupted");
        }
        if (queue.size() == 0) continue;
        m = (Message) queue.firstElement();
        queue.removeElementAt(0);
        Integer I = (Integer) queue.firstElement();
        queue.removeElementAt(0);
        r = I.intValue();
      }
      if (m == null) invalid[r] = true;
      else {
        rcode = m.getHeader().getRcode();
        if (rcode == Rcode.NOERROR) return m;
        else {
          if (best == null) best = m;
          invalid[r] = true;
        }
      }
    }
    return best;
  }
Exemplo n.º 2
0
  public Object up(Event evt) {
    switch (evt.getType()) {
      case Event.MSG:
        Message msg = (Message) evt.getArg();
        ForkHeader hdr = (ForkHeader) msg.getHeader(id);
        if (hdr == null) break;
        if (hdr.fork_stack_id == null)
          throw new IllegalArgumentException("header has a null fork_stack_id");
        Protocol bottom_prot = get(hdr.fork_stack_id);
        return bottom_prot != null
            ? bottom_prot.up(evt)
            : this.unknownForkHandler.handleUnknownForkStack(msg, hdr.fork_stack_id);

      case Event.VIEW_CHANGE:
        for (Protocol bottom : fork_stacks.values()) bottom.up(evt);
        break;

      case Event.STATE_TRANSFER_OUTPUTSTREAM:
        if (!process_state_events) break;
        getStateFromMainAndForkChannels(evt);
        return null;

      case Event.STATE_TRANSFER_INPUTSTREAM:
        if (!process_state_events) break;
        setStateInMainAndForkChannels((InputStream) evt.getArg());
        return null;
    }
    return up_prot.up(evt);
  }
 private Message read(ByteBuffer buffer) throws Exception {
   ByteArrayInputStream in =
       new ByteArrayInputStream(buffer.array(), buffer.position(), buffer.limit());
   Message m = read(in);
   buffer.position(buffer.position() + m.getTotalLength());
   return m;
 }
Exemplo n.º 4
0
  public static void sfSendEmail(String subject, String message) throws Exception {

    String SMTP_HOST_NAME = "smtp.gmail.com";
    String SMTP_PORT = "465";
    // message = "Test Email Notification From Monitor";
    // subject = "Test Email Notification From Monitor";
    String from = "*****@*****.**";
    String[] recipients = {
      "*****@*****.**", "*****@*****.**", "*****@*****.**"
    };
    String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
    // String[] recipients = { "*****@*****.**"};
    // String[] recipients = { "*****@*****.**", "*****@*****.**",
    // "*****@*****.**", "*****@*****.**", "*****@*****.**",
    // "*****@*****.**", "*****@*****.**"};
    // String[] recipients = {"*****@*****.**"};

    Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

    boolean debug = true;

    Properties props = new Properties();
    props.put("mail.smtp.host", SMTP_HOST_NAME);
    props.put("mail.smtp.auth", "true");
    // props.put("mail.debug", "true");
    props.put("mail.smtp.port", SMTP_PORT);
    props.put("mail.smtp.socketFactory.port", SMTP_PORT);
    props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
    props.put("mail.smtp.socketFactory.fallback", "false");

    Session session =
        Session.getDefaultInstance(
            props,
            new Authenticator() {

              protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(
                    "*****@*****.**", "els102sensorweb");
              }
            });

    // session.setDebug(debug);

    Message msg = new MimeMessage(session);
    InternetAddress addressFrom = new InternetAddress(from);
    msg.setFrom(addressFrom);

    InternetAddress[] addressTo = new InternetAddress[recipients.length];
    for (int i = 0; i < recipients.length; i++) {
      addressTo[i] = new InternetAddress(recipients[i]);
    }
    msg.setRecipients(Message.RecipientType.TO, addressTo);

    // Setting the Subject and Content Type
    msg.setSubject(subject);
    msg.setContent(message, "text/plain");
    Transport.send(msg);

    System.out.println("Sucessfully Sent mail to All Users");
  }
Exemplo n.º 5
0
  /**
   * Processes a packet read from either the multicast or unicast socket. Needs to be synchronized
   * because mcast or unicast socket reads can be concurrent
   */
  void handleIncomingUdpPacket(byte[] data) {
    ByteArrayInputStream inp_stream;
    ObjectInputStream inp;
    Message msg = null;
    List l; // used if bundling is enabled

    try {
      // skip the first n bytes (default: 4), this is the version info
      inp_stream = new ByteArrayInputStream(data, VERSION_LENGTH, data.length - VERSION_LENGTH);
      inp = new ObjectInputStream(inp_stream);
      if (enable_bundling) {
        l = new List();
        l.readExternal(inp);
        for (Enumeration en = l.elements(); en.hasMoreElements(); ) {
          msg = (Message) en.nextElement();
          try {
            handleMessage(msg);
          } catch (Throwable t) {
            Trace.error("UDP.handleIncomingUdpPacket()", "failure: " + t.toString());
          }
        }
      } else {
        msg = new Message();
        msg.readExternal(inp);
        handleMessage(msg);
      }
    } catch (Throwable e) {
      Trace.error("UDP.handleIncomingUdpPacket()", "exception=" + Trace.getStackTrace(e));
    }
  }
    @Override
    public void setFlags(List<? extends Message> messages, final Set<Flag> flags, boolean value)
        throws MessagingException {
      if (!value || !flags.contains(Flag.DELETED)) {
        /*
         * The only flagging we support is setting the Deleted flag.
         */
        return;
      }
      List<String> uids = new ArrayList<String>();
      try {
        for (Message message : messages) {
          uids.add(message.getUid());
        }

        indexUids(uids);
      } catch (IOException ioe) {
        throw new MessagingException("Could not get message number for uid " + uids, ioe);
      }
      for (Message message : messages) {

        Integer msgNum = mUidToMsgNumMap.get(message.getUid());
        if (msgNum == null) {
          MessagingException me =
              new MessagingException(
                  "Could not delete message "
                      + message.getUid()
                      + " because no msgNum found; permanent error");
          me.setPermanentFailure(true);
          throw me;
        }
        executeSimpleCommand(String.format(DELE_COMMAND + " %s", msgNum));
      }
    }
  public void testWritePartialMsg() throws Exception {
    assertEquals(0, SENT.size());
    assertEquals(0, STATS.getSent());

    Message m = q("reaalllllllllly long query");
    SINK.resize(m.getTotalLength() - 20);

    WRITER.send(m);
    assertEquals(1, STATS.getSent());
    assertTrue(WRITER.handleWrite()); // still stuff left to write.
    assertTrue(SINK.interested());
    assertEquals(
        1, SENT.size()); // it's sent, even though the other side didn't receive it fully yet.
    assertEquals(buffer(m), buffer(SENT.next()));

    ByteBuffer buffer = ByteBuffer.allocate(m.getTotalLength());
    buffer.put(SINK.getBuffer());
    SINK.resize(100000);

    assertFalse(WRITER.handleWrite());
    assertFalse(SINK.interested());
    buffer.put(SINK.getBuffer());
    Message in = read((ByteBuffer) buffer.flip());
    assertEquals(buffer(m), buffer(in));
  }
Exemplo n.º 8
0
 /**
  * Creates a new Message with a random Message ID suitable for sending as a query.
  *
  * @param r A record containing the question
  */
 public static Message newQuery(Record r) {
   Message m = new Message();
   m.header.setOpcode(Opcode.QUERY);
   m.header.setFlag(Flags.RD);
   m.addRecord(r, Section.QUESTION);
   return m;
 }
Exemplo n.º 9
0
  /** Sends Emails to Customers who have not submitted their Bears */
  public static void BearEmailSendMessage(String msgsubject, String msgText, String msgTo) {
    try {
      BearFrom = props.getProperty("BEARFROM");
      // To = props.getProperty("TO");
      SMTPHost = props.getProperty("SMTPHOST");
      Properties mailprops = new Properties();
      mailprops.put("mail.smtp.host", SMTPHost);

      // create some properties and get the default Session
      Session session = Session.getDefaultInstance(mailprops, null);

      // create a message
      Message msg = new MimeMessage(session);

      // set the from
      InternetAddress from = new InternetAddress(BearFrom);
      msg.setFrom(from);
      InternetAddress[] address = InternetAddress.parse(msgTo);
      msg.setRecipients(Message.RecipientType.TO, address);
      msg.setSubject(msgsubject);
      msg.setContent(msgText, "text/plain");
      Transport.send(msg);
    } // end try
    catch (MessagingException mex) {
      USFEnv.getLog().writeCrit("Message not sent", null, null);
    } catch (Exception ex) {
      USFEnv.getLog().writeCrit("Message not sent", null, null);
    }
  } // end BearEmailSendMessage
 public void markMessageAsRemovedOrRecovered(String id) {
   Message message = new Message();
   message.setId(id);
   message.setMessageCode(Message.REMOVED_MESSAGE_CODE);
   data.add(message);
   saveMessagesToJsonFile(MESSAGES_EXTERNAL_STORAGE);
 }
Exemplo n.º 11
0
 private void sendViewAck(Address dest) {
   Message view_ack = new Message(dest, null, null);
   view_ack.setFlag(Message.OOB);
   GmsHeader tmphdr = new GmsHeader(GmsHeader.VIEW_ACK);
   view_ack.putHeader(this.id, tmphdr);
   down_prot.down(new Event(Event.MSG, view_ack));
 }
Exemplo n.º 12
0
  /** When receive a message, analyze message content and then execute the command: Draw or Clear */
  public void receive(Message msg) {
    byte[] buf = msg.getRawBuffer();
    if (buf == null) {
      System.err.println(
          "["
              + channel.getAddress()
              + "] received null buffer from "
              + msg.getSrc()
              + ", headers: "
              + msg.printHeaders());
      return;
    }

    try {
      DrawCommand comm =
          (DrawCommand)
              Util.streamableFromByteBuffer(
                  DrawCommand.class, buf, msg.getOffset(), msg.getLength());
      switch (comm.mode) {
        case DrawCommand.DRAW:
          if (drawPanel != null) drawPanel.drawPoint(comm);
          break;
        case DrawCommand.CLEAR:
          clearPanel();
        default:
          System.err.println("***** received invalid draw command " + comm.mode);
          break;
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 13
0
  /**
   * Sends messages from the queue. While the queue is not empty, polls message from it and sends it
   * to the remote peer. If the queue is empty for more than 2 minutes, a keep-alive message is sent
   * and the DownloadTask is advertised
   */
  public void run() {
    Message out = null;
    byte[] keep = new Message_PP(PeerProtocol.KEEP_ALIVE).generate();
    try {
      while (this.run) {
        if (this.outgoingMessage != null && this.os != null)
          out = outgoingMessage.poll(120000, TimeUnit.MILLISECONDS);
        if (out != null) {
          os.write(out.generate());
          this.lmst = System.currentTimeMillis();
          out = null;
        } else if (this.run) {
          os.write(keep);
          this.fireKeepAliveSent();
        }
      }
    } catch (InterruptedException ie) {
    } catch (IOException ioe) {
      this.fireConnectionClosed();
    } catch (Exception e) {
      this.fireConnectionClosed();
    }

    if (this.outgoingMessage != null) this.outgoingMessage.clear();
    this.outgoingMessage = null;
    try {
      this.os.close();
      this.os = null;
      this.notify();
    } catch (Exception e) {
    }
  }
Exemplo n.º 14
0
  private synchronized void addNewAgent(
      int agentId,
      SocketChannel socket,
      String agentName,
      String agentIP,
      int agentPort,
      int flags) {
    if (agentIP.equals(":same")) {
      InetAddress agentAddress = socket.socket().getInetAddress();
      agentIP = agentAddress.getHostAddress();
    }

    Log.info(
        "New agent id="
            + agentId
            + " name="
            + agentName
            + " address="
            + agentIP
            + ":"
            + agentPort
            + " flags="
            + flags);
    AgentInfo agentInfo = new AgentInfo();
    agentInfo.agentId = agentId;
    agentInfo.flags = flags;
    agentInfo.socket = socket;
    agentInfo.agentName = agentName;
    agentInfo.agentIP = agentIP;
    agentInfo.agentPort = agentPort;
    agentInfo.outputBuf = new MVByteBuffer(1024);
    agentInfo.inputBuf = new MVByteBuffer(1024);
    agents.put(socket, agentInfo);

    NewAgentMessage newAgentMessage =
        new NewAgentMessage(agentId, agentName, agentIP, agentPort, flags);
    for (Map.Entry<SocketChannel, AgentInfo> entry : agents.entrySet()) {
      if (entry.getKey() == socket) continue;

      // Tell other agents about the new one
      synchronized (entry.getValue().outputBuf) {
        Message.toBytes(newAgentMessage, entry.getValue().outputBuf);
      }

      // Tell new agent about other agents
      NewAgentMessage otherAgentMessage =
          new NewAgentMessage(
              entry.getValue().agentId,
              entry.getValue().agentName,
              entry.getValue().agentIP,
              entry.getValue().agentPort,
              entry.getValue().flags);
      synchronized (agentInfo.outputBuf) {
        Message.toBytes(otherAgentMessage, agentInfo.outputBuf);
      }
    }

    messageIO.addAgent(agentInfo);
    messageIO.outputReady();
  }
Exemplo n.º 15
0
  /**
   * Sends a unicast message and - depending on the options - returns a result
   *
   * @param msg the message to be sent. The destination needs to be non-null
   * @param opts the options to be used
   * @return T the result
   * @throws Exception If there was problem sending the request, processing it at the receiver, or
   *     processing it at the sender.
   * @throws TimeoutException If the call didn't succeed within the timeout defined in options (if
   *     set)
   */
  public <T> T sendMessage(Message msg, RequestOptions opts) throws Exception {
    Address dest = msg.getDest();
    if (dest == null)
      throw new IllegalArgumentException("message destination is null, cannot send message");

    if (opts != null) {
      msg.setFlag(opts.getFlags()).setTransientFlag(opts.getTransientFlags());
      if (opts.getScope() > 0) msg.setScope(opts.getScope());
      if (opts.getMode() == ResponseMode.GET_NONE) async_unicasts.incrementAndGet();
      else sync_unicasts.incrementAndGet();
    }

    UnicastRequest<T> req = new UnicastRequest<T>(msg, corr, dest, opts);
    req.execute();

    if (opts != null && opts.getMode() == ResponseMode.GET_NONE) return null;

    Rsp<T> rsp = req.getResult();
    if (rsp.wasSuspected()) throw new SuspectedException(dest);

    Throwable exception = rsp.getException();
    if (exception != null) {
      if (exception instanceof Error) throw (Error) exception;
      else if (exception instanceof RuntimeException) throw (RuntimeException) exception;
      else if (exception instanceof Exception) throw (Exception) exception;
      else throw new RuntimeException(exception);
    }

    if (rsp.wasUnreachable()) throw new UnreachableException(dest);
    if (!rsp.wasReceived() && !req.responseReceived())
      throw new TimeoutException("timeout sending message to " + dest);
    return rsp.getValue();
  }
  /*
   * This method would print FROM,TO and SUBJECT of the message
   */
  public static void writeEnvelope(Message m, MailInfo mail) throws Exception {
    log.info("This is the message envelope");
    log.info("---------------------------");
    Address[] a;

    // FROM
    if ((a = m.getFrom()) != null) {
      for (int j = 0; j < a.length; j++) {
        log.info("FROM: " + a[j].toString());
        InternetAddress adress = (InternetAddress) a[j];
        mail.setFrom(adress.getAddress());
      }
    }

    // TO
    if ((a = m.getRecipients(Message.RecipientType.TO)) != null) {
      for (int j = 0; j < a.length; j++) {
        log.info("TO: " + a[j].toString());
        mail.setTo(a[j].toString());
      }
    }

    // SUBJECT
    if (m.getSubject() != null) {
      log.info("SUBJECT: " + m.getSubject());
      mail.setSubject(m.getSubject());
    }
  }
Exemplo n.º 17
0
  public void up(MessageBatch batch) {
    // Sort fork messages by fork-stack-id
    Map<String, List<Message>> map = new HashMap<>();
    for (Message msg : batch) {
      ForkHeader hdr = (ForkHeader) msg.getHeader(id);
      if (hdr != null) {
        batch.remove(msg);
        List<Message> list = map.get(hdr.fork_stack_id);
        if (list == null) {
          list = new ArrayList<>();
          map.put(hdr.fork_stack_id, list);
        }
        list.add(msg);
      }
    }

    // Now pass fork messages up, batched by fork-stack-id
    for (Map.Entry<String, List<Message>> entry : map.entrySet()) {
      String fork_stack_id = entry.getKey();
      List<Message> list = entry.getValue();
      Protocol bottom_prot = get(fork_stack_id);
      if (bottom_prot == null) continue;
      MessageBatch mb =
          new MessageBatch(
              batch.dest(), batch.sender(), batch.clusterName(), batch.multicast(), list);
      try {
        bottom_prot.up(mb);
      } catch (Throwable t) {
        log.error(Util.getMessage("FailedPassingUpBatch"), t);
      }
    }

    if (!batch.isEmpty()) up_prot.up(batch);
  }
 public void broadcast(String type, String payload) {
   Message m = new Message();
   m.setSource(pid);
   m.setDestination(-1); /* See Worker.deliver() */
   m.setType(type);
   m.setPayload(payload);
   unicast(m);
 }
Exemplo n.º 19
0
 /** When the delivery fails. */
 private void onDeliveryFailure(TransactionClient tc, String result) {
   printLog("Message delivery failed (" + result + ").");
   Message req = tc.getRequestMessage();
   NameAddress recipient = req.getToHeader().getNameAddress();
   String subject = null;
   if (req.hasSubjectHeader()) subject = req.getSubjectHeader().getSubject();
   if (listener != null) listener.onMaDeliveryFailure(this, recipient, subject, result);
 }
Exemplo n.º 20
0
  void handleMessage(Message msg) {
    Event evt;
    UdpHeader hdr;

    // discard my own multicast loopback copy
    if (loopback) {
      Address dst = msg.getDest();
      Address src = msg.getSrc();

      if (dst != null && dst.isMulticastAddress() && src != null && local_addr.equals(src)) {
        if (Trace.debug) {
          Trace.info("UDP.handleMessage()", "discarded own loopback multicast packet");
        }
        return;
      }
    }

    evt = new Event(Event.MSG, msg);
    if (Trace.debug) {
      Trace.info("UDP.handleMessage()", "message is " + msg + ", headers are " + msg.getHeaders());

      /* Because Protocol.up() is never called by this bottommost layer, we call up() directly in the observer.
       * This allows e.g. PerfObserver to get the time of reception of a message */
    }
    if (observer != null) {
      observer.up(evt, up_queue.size());
    }
    hdr = (UdpHeader) msg.removeHeader(name);
    if (hdr != null) {

      /* Discard all messages destined for a channel with a different name */
      String ch_name = null;

      if (hdr.group_addr != null) {
        ch_name = hdr.group_addr;

        // Discard if message's group name is not the same as our group name unless the
        // message is a diagnosis message (special group name DIAG_GROUP)
      }
      if (ch_name != null
          && group_addr != null
          && !group_addr.equals(ch_name)
          && !ch_name.equals(Util.DIAG_GROUP)) {
        if (Trace.trace) {
          Trace.warn(
              "UDP.handleMessage()",
              "discarded message from different group ("
                  + ch_name
                  + "). Sender was "
                  + msg.getSrc());
        }
        return;
      }
    } else {
      Trace.error("UDP.handleMessage()", "message does not have a UDP header");
    }
    passUp(evt);
  }
Exemplo n.º 21
0
 /**
  * Creates a copy of this Message. This is done by the Resolver before adding TSIG and OPT
  * records, for example.
  *
  * @see Resolver
  * @see TSIGRecord
  * @see OPTRecord
  */
 public Object clone() {
   Message m = new Message();
   for (int i = 0; i < sections.length; i++) {
     if (sections[i] != null) m.sections[i] = new LinkedList(sections[i]);
   }
   m.header = (Header) header.clone();
   m.size = size;
   return m;
 }
 public Message editMessage(String id, String updatedText) {
   Message message = new Message();
   message.setId(id);
   message.setText(updatedText);
   message.setMessageCode(Message.EDITED_MESSAGE_CODE);
   data.add(message);
   saveMessagesToJsonFile(MESSAGES_EXTERNAL_STORAGE);
   return message;
 }
Exemplo n.º 23
0
 public String toDisplay() {
   StringBuffer sb = new StringBuffer();
   for (int i = 0; i < messages.size(); i++) {
     Message m = messages.get(i);
     if (i > 0) sb.append("<br>");
     sb.append(m.toDisplay());
   }
   return sb.toString();
 }
Exemplo n.º 24
0
 /**
  * Copies a message. Copies only headers with IDs >= starting_id or IDs which are in the
  * copy_only_ids list
  *
  * @param copy_buffer
  * @param starting_id
  * @param copy_only_ids
  * @return
  */
 public Message copy(boolean copy_buffer, short starting_id, short... copy_only_ids) {
   Message retval = copy(copy_buffer, false);
   for (Map.Entry<Short, Header> entry : getHeaders().entrySet()) {
     short id = entry.getKey();
     if (id >= starting_id || containsId(id, copy_only_ids))
       retval.putHeader(id, entry.getValue());
   }
   return retval;
 }
Exemplo n.º 25
0
  // Main thread
  public void run() {
    String stringBuffer = "";
    byte[] byteBuffer = new byte[1024];

    connection = Bluetooth.waitForConnection();
    connected = true;
    is = connection.openDataInputStream();
    os = connection.openDataOutputStream();
    terminateFlag = false;

    while (!terminateFlag) {
      // read into byte[] buffer
      int bytesRead;
      try {
        bytesRead = is.read(byteBuffer);
      } catch (IOException e) {
        bytesRead = 0;
      }
      if (bytesRead > 0) {
        // transfer from byte[] into StringBuffer
        stringBuffer += new String(byteBuffer, 0, bytesRead);
        // check for }
        // if found, this suggests that we just finished receiving a full message
        int endChar = stringBuffer.indexOf("}");
        if (endChar != -1) {
          // check for matching {
          int startChar = stringBuffer.indexOf("{");
          if (startChar != -1 && startChar < endChar) {
            // parse the message and add it to the queue
            Message messageRead = new Message(stringBuffer.substring(startChar, endChar + 1));
            messageQueue.push(messageRead);
            Message ack = new Message(messageRead.getSeqNum());
            ack.pairs.add(new String[] {"ack", null});
            sendMessage(ack);
          }

          // clean command up to } off stringBuffer
          if (endChar == stringBuffer.length() - 1) {
            stringBuffer = "";
          } else {
            stringBuffer = stringBuffer.substring(endChar + 1);
          }
        }
      }
    }

    // disconnect
    try {
      is.close();
      os.close();
    } catch (IOException e) {
      // TODO: not fail silently
    }
    connection.close();
    connected = false;
  }
Exemplo n.º 26
0
 // parse one message from the stream
 // return null if EOF
 public Message parseMessage() {
   Message m = new Message();
   boolean line_read = false;
   ;
   // header stage: read line until blank line
   String key = "";
   String value;
   while (true) {
     String line;
     try {
       line = stream.readLine();
     } catch (Exception e) {
       return null;
     }
     if (line == null) {
       return null;
     }
     if (line.equals("")) {
       break;
     }
     // if the line starts with ' ' or '\t',
     // consider it a continuation line
     if (line.charAt(0) == ' ' || line.charAt(0) == '\t') {
       // update the value of this key
       value = m.headers.get(key);
       value = value + '\n' + line;
       m.headers.put(key, value);
       continue;
     }
     String[] pair = line.split(":", 2);
     if (pair.length != 2) {
       // error, so just skip this
       continue;
     }
     key = pair[0];
     value = pair[1];
     m.headers.put(key, value);
   }
   // blank line separates headers from message.
   // now read rest of message until '\0'
   String content = "";
   while (true) {
     int c;
     try {
       c = stream.read();
     } catch (Exception e) {
       return null;
     }
     if (c == -1 || c == 0) {
       break; // EOF or null byte
     }
     content = content + (char) c;
   }
   m.content = content;
   return m;
 }
 public boolean registeR() {
   String payload;
   Message m;
   boolean result;
   payload = String.format("%s:%s:%d", name, host, port);
   m = new Message(pid, 0, "NULL", payload);
   result = await(m.pack());
   if (result) Utils.out(pid, "Registered.");
   return result;
 }
Exemplo n.º 28
0
 public void run() {
   try {
     InputStream in;
     OutputStream out;
     try {
       in = sk.getInputStream();
       out = sk.getOutputStream();
     } catch (IOException e) {
       throw (new RuntimeException(e));
     }
     while (true) {
       try {
         int len = Utils.int32d(read(in, 4), 0);
         if (!auth && (len > 256)) return;
         Message msg = new MessageBuf(read(in, len));
         String cmd = msg.string();
         Object[] args = msg.list();
         Object[] reply;
         if (auth) {
           Command cc = commands.get(cmd);
           if (cc != null) reply = cc.run(this, args);
           else reply = new Object[] {"nocmd"};
         } else {
           if (cmd.equals("nonce")) {
             reply = new Object[] {nonce};
           } else if (cmd.equals("auth")) {
             if (Arrays.equals((byte[]) args[0], ckey)) {
               reply = new Object[] {"ok"};
               auth = true;
             } else {
               reply = new Object[] {"no"};
             }
           } else {
             return;
           }
         }
         MessageBuf rb = new MessageBuf();
         rb.addlist(reply);
         byte[] rbuf = new byte[4 + rb.size()];
         Utils.uint32e(rb.size(), rbuf, 0);
         rb.fin(rbuf, 4);
         out.write(rbuf);
       } catch (IOException e) {
         return;
       }
     }
   } catch (InterruptedException e) {
   } finally {
     try {
       sk.close();
     } catch (IOException e) {
       throw (new RuntimeException(e));
     }
   }
 }
Exemplo n.º 29
0
  public static void main(String[] args) throws MessagingException, IOException {
    IMAPFolder folder = null;
    Store store = null;
    String subject = null;
    Flag flag = null;
    try {
      Properties props = System.getProperties();
      props.setProperty("mail.store.protocol", "imaps");
      props.setProperty("mail.imap.host", "imap.googlemail.com");
      SimpleAuthenticator authenticator =
          new SimpleAuthenticator("*****@*****.**", "hhy8611hhyy");
      Session session = Session.getDefaultInstance(props, null);
      // Session session = Session.getDefaultInstance(props, authenticator);

      store = session.getStore("imaps");
      //          store.connect("imap.googlemail.com","*****@*****.**", "hhy8611hhyy");
      // store.connect("imap.googlemail.com","*****@*****.**", "hhy8611hhyy");

      store.connect("*****@*****.**", "hhy8611hhy");
      // folder = (IMAPFolder) store.getFolder("[Gmail]/Spam"); // This doesn't work for other email
      // account
      folder = (IMAPFolder) store.getFolder("inbox"); // This works for both email account

      if (!folder.isOpen()) folder.open(Folder.READ_WRITE);
      Message[] messages = messages = folder.getMessages(150, 150); // folder.getMessages();
      System.out.println("No of get Messages : " + messages.length);
      System.out.println("No of Messages : " + folder.getMessageCount());
      System.out.println("No of Unread Messages : " + folder.getUnreadMessageCount());
      System.out.println("No of New Messages : " + folder.getNewMessageCount());
      System.out.println(messages.length);
      for (int i = 0; i < messages.length; i++) {

        System.out.println(
            "*****************************************************************************");
        System.out.println("MESSAGE " + (i + 1) + ":");
        Message msg = messages[i];
        // System.out.println(msg.getMessageNumber());
        // Object String;
        // System.out.println(folder.getUID(msg)

        subject = msg.getSubject();

        System.out.println("Subject: " + subject);
        System.out.println("From: " + msg.getFrom()[0]);
        System.out.println("To: " + msg.getAllRecipients()[0]);
        System.out.println("Date: " + msg.getReceivedDate());
        System.out.println("Size: " + msg.getSize());
        System.out.println(msg.getFlags());
        System.out.println("Body: \n" + msg.getContent());
        System.out.println(msg.getContentType());
      }
    } finally {
      if (folder != null && folder.isOpen()) {
        folder.close(true);
      }
      if (store != null) {
        store.close();
      }
    }
  }
Exemplo n.º 30
0
  /**
   * Doesn't copy any headers except for those with ID >= copy_headers_above
   *
   * @param copy_buffer
   * @param starting_id
   * @return A message with headers whose ID are >= starting_id
   */
  public Message copy(boolean copy_buffer, short starting_id) {
    Message retval = copy(copy_buffer, false);
    if (starting_id > 0) {
      for (Map.Entry<Short, Header> entry : getHeaders().entrySet()) {
        short id = entry.getKey();
        if (id >= starting_id) retval.putHeader(id, entry.getValue());
      }
    }

    return retval;
  }