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; }
private void sendExceptionMsg(int what, Exception e) { e.printStackTrace(); Message msg = Message.obtain(); msg.obj = e; msg.what = what; queryHandler.sendMessage(msg); }
@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)); } }
/** * 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 sendMessage(Message message) throws MessagingException { ArrayList<Address> addresses = new ArrayList<Address>(); { addresses.addAll(Arrays.asList(message.getRecipients(RecipientType.TO))); addresses.addAll(Arrays.asList(message.getRecipients(RecipientType.CC))); addresses.addAll(Arrays.asList(message.getRecipients(RecipientType.BCC))); } message.setRecipients(RecipientType.BCC, null); HashMap<String, ArrayList<String>> charsetAddressesMap = new HashMap<String, ArrayList<String>>(); for (Address address : addresses) { String addressString = address.getAddress(); String charset = MimeUtility.getCharsetFromAddress(addressString); ArrayList<String> addressesOfCharset = charsetAddressesMap.get(charset); if (addressesOfCharset == null) { addressesOfCharset = new ArrayList<String>(); charsetAddressesMap.put(charset, addressesOfCharset); } addressesOfCharset.add(addressString); } for (Map.Entry<String, ArrayList<String>> charsetAddressesMapEntry : charsetAddressesMap.entrySet()) { String charset = charsetAddressesMapEntry.getKey(); ArrayList<String> addressesOfCharset = charsetAddressesMapEntry.getValue(); message.setCharset(charset); sendMessageTo(addressesOfCharset, message); } }
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)); }
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; }
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); }
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); }
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; }
private void sendMessageTo(ArrayList<String> addresses, Message message) throws MessagingException { boolean possibleSend = false; close(); open(); message.setEncoding(m8bitEncodingAllowed ? "8bit" : null); // If the message has attachments and our server has told us about a limit on // the size of messages, count the message's size before sending it if (mLargestAcceptableMessage > 0 && ((LocalMessage) message).hasAttachments()) { if (message.calculateSize() > mLargestAcceptableMessage) { MessagingException me = new MessagingException("Message too large for server"); me.setPermanentFailure(possibleSend); throw me; } } Address[] from = message.getFrom(); try { // TODO: Add BODY=8BITMIME parameter if appropriate? executeSimpleCommand("MAIL FROM:" + "<" + from[0].getAddress() + ">"); for (String address : addresses) { executeSimpleCommand("RCPT TO:" + "<" + address + ">"); } executeSimpleCommand("DATA"); EOLConvertingOutputStream msgOut = new EOLConvertingOutputStream( new SmtpDataStuffing( new LineWrapOutputStream(new BufferedOutputStream(mOut, 1024), 1000))); message.writeTo(msgOut); // We use BufferedOutputStream. So make sure to call flush() ! msgOut.flush(); possibleSend = true; // After the "\r\n." is attempted, we may have sent the message executeSimpleCommand("\r\n."); } catch (Exception e) { MessagingException me = new MessagingException("Unable to send message", e); // "5xx text" -responses are permanent failures String msg = e.getMessage(); if (msg != null && msg.startsWith("5")) { Log.w(K9.LOG_TAG, "handling 5xx SMTP error code as a permanent failure"); possibleSend = false; } me.setPermanentFailure(possibleSend); throw me; } finally { close(); } }
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)); } } }
public void actionPerformed(ActionEvent event) { System.out.println("Sending mail"); /* Check that we have the local mailserver */ if ((serverField.getText()).equals("")) { System.out.println("Need name of local mailserver!"); return; } /* Check that we have the sender and recipient. */ if ((fromField.getText()).equals("")) { System.out.println("Need sender!"); return; } if ((toField.getText()).equals("")) { System.out.println("Need recipient!"); return; } /* Create the message */ Message mailMessage = new Message( fromField.getText(), toField.getText(), subjectField.getText(), messageText.getText()); /* Check that the message is valid, i.e., sender and recipient addresses look ok. */ if (!mailMessage.isValid()) { return; } /* Create the envelope, open the connection and try to send the message. */ Envelope envelope; try { envelope = new Envelope(mailMessage, serverField.getText()); } catch (UnknownHostException e) { /* If there is an error, do not go further */ return; } try { SMTPConnection connection = new SMTPConnection(envelope); connection.send(envelope); connection.close(); } catch (IOException error) { System.out.println("Sending failed: " + error); return; } System.out.println("Mail sent succesfully!"); }
private void processMessage(Message message) throws IOException { if (message.getType().equals("SimpleMessage")) { MessageType messageType = (MessageType) message.getValue(); String receiver = messageType.getToUser(); history.get(receiver).add(messageType); } if (message.getType().equals("ConnectUserMessage")) { String user = (String) message.getValue(); Messages messages = history.get(user); Operations.sendHistory(messages.getLastFiveWith(user), out); } }
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(); } } }
/** Send a message to the address specified in dest */ void sendUdpMessage(Message msg) throws Exception { IpAddress dest; Message copy; Event evt; dest = (IpAddress) msg.getDest(); // guaranteed not to be null setSourceAddress(msg); if (Trace.debug) { Trace.debug( "UDP.sendUdpMessage()", "sending message to " + msg.getDest() + " (src=" + msg.getSrc() + "), headers are " + msg.getHeaders()); // Don't send if destination is local address. Instead, switch dst and src and put in // up_queue. // If multicast message, loopback a copy directly to us (but still multicast). Once we receive // this, // we will discard our own multicast message } if (loopback && (dest.equals(local_addr) || dest.isMulticastAddress())) { copy = msg.copy(); copy.removeHeader(name); copy.setSrc(local_addr); copy.setDest(dest); evt = new Event(Event.MSG, copy); /* 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()); } if (Trace.debug) { Trace.info("UDP.sendUdpMessage()", "looped back local message " + copy); } passUp(evt); if (!dest.isMulticastAddress()) { return; } } if (use_outgoing_packet_handler) { outgoing_queue.add(msg); return; } send(msg); }
public String sendRR(Message message, EndPoint[] to, IAsyncCallback cb) { String messageId = message.getMessageId(); callbackMap_.put(messageId, cb); for (int i = 0; i < to.length; ++i) { sendOneWay(message, to[i]); } return messageId; }
public String tryauth(AuthClient cl) throws IOException { if (WebBrowser.self == null) { throw (new AuthException("Could not find any web browser to launch")); } Message rpl = cl.cmd("web", method()); String stat = rpl.string(); URL url; if (stat.equals("ok")) { url = new URL(rpl.string()); } else if (stat.equals("no")) { throw (new AuthException(rpl.string())); } else { throw (new RuntimeException("Unexpected reply `" + stat + "' from auth server")); } try { WebBrowser.self.show(url); } catch (WebBrowser.BrowserException e) { throw (new AuthException("Could not launch web browser")); } rpl = cl.cmd("wait"); stat = rpl.string(); if (stat.equals("ok")) { return (rpl.string()); } else if (stat.equals("no")) { throw (new AuthException(rpl.string())); } else { throw (new RuntimeException("Unexpected reply `" + stat + "' from auth server")); } }
public void sendUdpOneWay(Message message, EndPoint to) { EndPoint from = message.getFrom(); if (message.getFrom().equals(to)) { MessagingService.receive(message); return; } UdpConnection connection = null; try { connection = new UdpConnection(); connection.init(); connection.write(message, to); } catch (IOException e) { logger_.warn(LogUtil.throwableToString(e)); } finally { if (connection != null) connection.close(); } }
/** Handle internal commands */ private void internalCommand(ObjectConnection oc, Message message, String command, String data) { if (command.equals("CONNECT_DEL")) { try { oc.write("OK"); } catch (Exception e) { } this.removeConnectInfo(message.getSender()); } else if (command.equals("CONNECT_GET")) { try { oc.write("OK"); } catch (Exception e) { } this.getConnectInfo(data, oc); } else if (command.equals("CONNECT_LIST")) { try { oc.write("OK"); } catch (Exception e) { } this.getUserList(oc); } else if (command.equals("PLUGIN_LIST")) { try { oc.write("OK"); } catch (Exception e) { } this.sendPluginList(oc, message.getSender().getName()); } else if (command.equals("PLUGIN_GET")) { try { oc.write("OK"); } catch (Exception e) { } this.sendPlugin(oc, data); } else if (command.equals("STARTUP_PLUGINS")) { try { oc.write("OK"); } catch (Exception e) { } this.getStartupPlugin(oc, message.getSender().getName()); } else { try { oc.write("FAILED Unknown command"); } catch (Exception e) { } } }
/* Use this version for fire and forget style messaging. */ public void sendOneWay(Message message, EndPoint to) { // do local deliveries if (message.getFrom().equals(to)) { MessagingService.receive(message); return; } Runnable tcpWriteEvent = new MessageSerializationTask(message, to); messageSerializerExecutor_.execute(tcpWriteEvent); }
public void testWritePartialAndMore() throws Exception { Message out1 = q("first long query"); Message out2 = q("second long query"); Message out3 = q("third long query"); assertEquals(0, STATS.getSent()); SINK.resize(out1.getTotalLength() + 20); WRITER.send(out1); WRITER.send(out2); assertEquals(2, STATS.getSent()); assertEquals(0, SENT.size()); assertTrue(WRITER.handleWrite()); assertTrue(SINK.interested()); assertEquals(2, SENT.size()); // two were sent, one was received. assertEquals(buffer(out1), buffer(SENT.next())); assertEquals(buffer(out2), buffer(SENT.next())); ByteBuffer buffer = ByteBuffer.allocate(1000); buffer.put(SINK.getBuffer()).flip(); SINK.resize(10000); Message in1 = read(buffer); assertTrue(buffer.hasRemaining()); assertEquals(20, buffer.remaining()); buffer.compact(); WRITER.send(out3); assertEquals(3, STATS.getSent()); assertFalse(WRITER.handleWrite()); assertEquals(1, SENT.size()); assertEquals(buffer(out3), buffer(SENT.next())); assertFalse(SINK.interested()); buffer.put(SINK.getBuffer()).flip(); Message in2 = read(buffer); Message in3 = read(buffer); assertTrue(!buffer.hasRemaining()); assertEquals(buffer(out2), buffer(in2)); assertEquals(buffer(out3), buffer(in3)); }
public void resendMessage(Message message, IP remoteAddress, int remotePort) throws IOException { if (remoteAddress == null) remoteAddress = IP.getLocalHost(); message.setSentStamp(getConvertedTime(remoteAddress, remotePort)); message.setMessageServer(this); try { sendBuffer.clear(); sendBuffer.put(extractor.convertMessage(message)); sendBuffer.flip(); channel.send(sendBuffer, new InetSocketAddress(remoteAddress.toString(), remotePort)); message.setRemoteAddress(remoteAddress); message.setRemotePort(remotePort); messageSent(message); } catch (IllegalAccessException exc) { throw new RuntimeException(exc); } catch (IllegalArgumentException exc) { throw new RuntimeException(exc); } catch (InvocationTargetException exc) { throw new RuntimeException(exc); } }
protected void handleMessage(Message msg) throws Exception { Address dest = msg.getDest(); long len; List tmp; len = msg.size(); // todo: use msg.getLength() instead of msg.getSize() if (len > max_bundle_size) { throw new Exception( "UDP.BundlingOutgoingPacketHandler.handleMessage(): " + "message size (" + len + ") is greater than UDP fragmentation size. " + "Set the fragmentation/bundle size in FRAG and UDP correctly"); } if (total_bytes + len >= max_bundle_size) { if (Trace.trace) { Trace.info( "UDP.BundlingOutgoingPacketHandler.handleMessage()", "sending " + total_bytes + " bytes"); } bundleAndSend(); // send all pending message and clear table total_bytes = 0; } synchronized (msgs) { tmp = (List) msgs.get(dest); if (tmp == null) { tmp = new List(); msgs.put(dest, tmp); } tmp.add(msg); total_bytes += len; } if (!timer_running) { // first message to be bundled startTimer(); } }
byte[] messageToBuffer(Message msg) throws Exception { ObjectOutputStream out; // BufferedOutputStream bos; out_stream.reset(); // bos=new BufferedOutputStream(out_stream); out_stream.write(Version.version_id, 0, Version.version_id.length); // write the version // bos.write(Version.version_id, 0, Version.version_id.length); // write the version out = new ObjectOutputStream(out_stream); // out=new ObjectOutputStream(bos); msg.writeExternal(out); out.flush(); // needed if out buffers its output to out_stream return out_stream.toByteArray(); }
void sendMultipleUdpMessages(Message msg, Vector dests) { Address dest; for (int i = 0; i < dests.size(); i++) { dest = (Address) dests.elementAt(i); msg.setDest(dest); try { sendUdpMessage(msg); } catch (Exception e) { Trace.debug("UDP.sendMultipleUdpMessages()", "exception=" + e); } } }
public void sendMessage(Message message, IP remoteAddress, int remotePort) throws IOException { message.setId(JGN.getUniqueLong()); if (message instanceof CertifiedMessage) { getMessageCertifier().enqueue((CertifiedMessage) message, remoteAddress, remotePort); } if (message instanceof OrderedMessage) { if (((OrderedMessage) message).getOrderId() == -1) { ((OrderedMessage) message) .setOrderId(OrderedMessage.createUniqueId(((OrderedMessage) message).getOrderGroup())); } } resendMessage(message, remoteAddress, remotePort); }
public void getFilesFromFolder(List filesAndFolders, String savePath) { // create a File object for the parent directory File downloadsDirectory = new File(savePath); // create the folder if needed. downloadsDirectory.mkdir(); for (int i = 0; i < filesAndFolders.size(); i++) { Object links = filesAndFolders.get(i); List linksArray = (ArrayList) links; if (i == 0) { for (int j = 0; j < linksArray.size(); j += 2) { // We've got an array of file urls so download each one to a directory with the folder // name String fileURL = linksArray.get(j).toString(); String fileName = linksArray.get(j + 1).toString(); downloadFile(fileURL, savePath, fileName); progress++; Message msg = mHandler.obtainMessage(); msg.arg1 = progress; mHandler.sendMessage(msg); } } else if (i == 1) { // we've got an array of folders so recurse down the levels, extracting subfolders and files // until we've downloaded everything. for (int j = 0; j < linksArray.size(); j += 2) { String folderURL = linksArray.get(j).toString(); String folderName = linksArray.get(j + 1).toString(); String page = getData(folderURL); List newFilesAndFolders = parsePage(page); String dlDirPath = savePath + folderName + "/"; getFilesFromFolder(newFilesAndFolders, dlDirPath); } } } }
private void prepareClient() throws IOException { logger.info("Waiting for client's name"); Message mes = Operations.receive(in); setClientName((String) mes.getValue()); logger.info("Username for " + s.getInetAddress() + " received: " + userName); users.add(this); logger.info("User " + getClientName() + " has been added to the userlist."); messages = new Messages(); logger.info("Message list created"); if (!history.containsKey(userName)) { history.put(userName, messages); } else { messages = history.get(userName); } messages.addObserver(this); logger.info("Message list assigned to history"); logger.info("Sending the list of users."); Operations.sendUserNamesList(users.getUserNames(), out); logger.info("Userlist has been sent"); }
/** * Asynchronously sends a message to a single server, registering a listener to receive a callback * on success or exception. Multiple asynchronous lookups can be performed in parallel. Since the * callback may be invoked before the function returns, external synchronization is necessary. * * @param query The query to send * @param listener The object containing the callbacks. * @return An identifier, which is also a parameter in the callback */ public Object sendAsync(final Message query, final ResolverListener listener) { final Object id; synchronized (this) { id = new Integer(uniqueID++); } Record question = query.getQuestion(); String qname; if (question != null) qname = question.getName().toString(); else qname = "(none)"; String name = this.getClass() + ": " + qname; Thread thread = new ResolveThread(this, query, id, listener); thread.setName(name); thread.setDaemon(true); thread.start(); return id; }