@SuppressLint("ResourceAsColor") @Override public View getView(int position, View convertView, ViewGroup parent) { View view = convertView; ViewHolder holder = new ViewHolder(); // Setting image for stamp if (view == null) { holder = new ViewHolder(); view = mLayoutInflater.inflate(R.layout.item, null); holder.txtSender = (TextView) view.findViewById(R.id.txt_sender); holder.txtMessage = (TextView) view.findViewById(R.id.txt_message); holder.wrapper = (LinearLayout) view.findViewById(R.id.wrapper); view.setTag(holder); } else { holder = (ViewHolder) view.getTag(); } Message message = mMessages.get(position); if (message == null) return view; holder.txtMessage.setText(""); // holder.txtSender.setText(""); holder.txtSender.setText(message.getSender() + ":"); if (message.isMine()) { holder.txtSender.setVisibility(View.INVISIBLE); } else { holder.txtSender.setVisibility(View.VISIBLE); } holder.txtMessage.setText(message.getMessage()); holder.txtMessage.setBackgroundResource( message.isMine() ? R.drawable.bubble_green : R.drawable.bubble_yellow); holder.wrapper.setGravity(message.isMine() ? Gravity.RIGHT : Gravity.LEFT); return view; }
/** * if this method return null the message is rejected and should be dumped. * * @param currentMessage * @return */ public final Message setCurrentMessage(Message currentMessage) { this.currentMessage = currentMessage; if (!controller.isControlling(currentMessage.getSender()) && !SYS_TERMINATION_MESSAGE.equals(currentMessage.getName())) { messageCount[controller.pid()]++; } return beforeMessageProcessing(currentMessage); }
/** 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) { } } }
/** * The format looks as follows: * * <p>32bit p2p version - 32bit id - 4bit message type - 4bit message name - 160bit sender id - * 16bit tcp port - 16bit udp port - 160bit recipient id - 16bit (4x4)content type - 8bit network * address information. It total, the header is of size 56 bytes. * * @param buffer The Netty buffer to fill * @param message The message with the header that will be serialized * @return The buffer passed as an argument */ public static ChannelBuffer encodeHeader(final ChannelBuffer buffer, final Message message) { buffer.writeInt(message.getVersion()); // 4 buffer.writeInt(message.getMessageId()); // 8 buffer.writeByte((message.getType().ordinal() << 4) | message.getCommand().ordinal()); // 9 buffer.writeBytes(message.getSender().getID().toByteArray()); // 29 buffer.writeShort((short) message.getSender().portTCP()); // 31 buffer.writeShort((short) message.getSender().portUDP()); // 33 buffer.writeBytes(message.getRecipient().getID().toByteArray()); // 53 final int content = ((message.getContentType4().ordinal() << 12) | (message.getContentType3().ordinal() << 8) | (message.getContentType2().ordinal() << 4) | message.getContentType1().ordinal()); buffer.writeShort((short) content); // 55 // options int options = (message.getSender().getOptions() << 4) | message.getOptions(); buffer.writeByte(options); // 56 return buffer; }
public String insertMessage(Message message) throws SQLException { String r = "New message inserted!"; if (isFriend( message.getSender(), message.getReceiver())) { // Check if the sender and receiver are friends try { // creates a SQL Statement object in order to execute the SQL insert command stmt = conn.createStatement(); stmt.execute( "INSERT INTO MESSAGES (Sender, Receiver, Text, DateMsg, TimeMsg, IsDelivered ) " + "VALUES (" + getProfileID(message.getSender()) + ", " + getProfileID(message.getReceiver()) + ", '" + message.getText() + "' , '" + message.getDateMsg() + "' , '" + message.getTimeMsg() + "'," + message.isDelivered() + ")"); stmt.close(); // System.out.println("Requête executée"); } catch (SQLException e) { // System.err.println(e.toString()); r = e.toString(); throw e; } return r; } else { return "WARNING : Can't insert message in database : the sender and receiver are not friends !"; } }
/** Tests Message class. */ @Test public void messageTest() { Message message = new Message(); message = new Message("xml", this, MessageDirection.OUTBOUND); message.setCreationTime(new LocalDateTime()); message.setSender("sender"); message.setReceiver("receiver"); message.setContentHash(null); assertNotNull(message.getCreationTime()); assertEquals("sender", message.getSender()); assertEquals("receiver", message.getReceiver()); assertEquals(0, message.getContentHash().length); message.setContentHash(new byte[0]); assertEquals(0, message.getContentHash().length); }
/** * Deletes the message with the given ID if the user has the rights * * @param id message id * @return String containing the status of the deletion */ public String delete_message(int id) { try { Query q = em.createQuery("SELECT m FROM Message m where m.msgID = :id"); q.setParameter("id", id); Message m = (Message) q.getSingleResult(); if (!(dm.lookupRights().compareTo("admin") == 0)) { if (!(dm.lookupUserName().compareTo(m.getSender()) == 0) && m.getStatus().compareTo("bcast") == 0) return "You do not have the rights to delete"; if (!(dm.lookupUserName().compareTo(m.getReceiver()) == 0) && !(m.getStatus().compareTo("bcast") == 0)) return "You do not have the rights to delete"; } Query q1 = em.createQuery("DELETE FROM Message x where x.msgID = :id"); q1.setParameter("id", id); q1.executeUpdate(); return "Message deleted successfuly"; } catch (Exception e) { return "WRONG MESSAGE ID"; } }
/** * Handles a message. Knows type "collectiveUpdate-"+name only. It is the responsibility of the * owner to propagate messages of this type using this method. */ public boolean handleMessage(Message m, Object o) { if (!shouldLive || !m.getType().equals("collectiveUpdate-" + name)) return false; final String logSender = observer + "#collectiveUpdate"; Logger.debug(logSender, "Update from " + m.getSender()); /**/ if (!m.getRecipient().name.equals(contributor.getName())) Logger.warning( logSender, "Recipient and my contributor are not the same:\n" + "Recipient: " + m.getRecipient().name + "\n" + "Contributor: " + contributor.getName(), null); /**/ Collective c = (Collective) o; // --- reset array representations cacheCollection = null; commandCollection = null; // --- remove possible garbage cache.remove(m.getRecipient().name); c.cache.remove(m.getRecipient().name); cache.remove(m.getSender().name); c.cache.remove(m.getSender().name); // --- sending our contributions if (contributor == null) Logger.warning(logSender, "Non-contributor observer is known by " + m.getSender(), null); updateLocalInfo(); m.setReply(this); // --- update containers repairSenderAddress(c, m.getSender()); merge(c); observer.collectiveUpdated((ContributionBox) cache.get(m.getSender().name)); return true; }
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(); } } }
/** * Creates a message Id. If the message is a request, the peer address is the sender, otherwise * its the recipient. This is due to the fact that depending on the direction, peer address may * change, but its still considered the same message. * * @param message The message */ public MessageID(final Message message) { this( message.getMessageId(), message.isRequest() ? message.getSender() : message.getRecipient()); }
/** * Decodes the payload from a Netty buffer in a big switch * * @param content The content type * @param buffer The buffer to read from * @param message The message to store the results * @throws IndexOutOfBoundsException If a buffer is read beyond its limits * @throws NoSuchAlgorithmException * @throws SignatureException * @throws InvalidKeyException * @throws InvalidKeySpecException * @throws InvalidKeySpecException * @throws IOException * @throws DecoderException * @throws ASN1Exception * @throws UnsupportedEncodingException If UTF-8 is not there */ public static boolean decodePayload( final Content content, final ChannelBuffer buffer, final Message message) throws InvalidKeyException, SignatureException, NoSuchAlgorithmException, InvalidKeySpecException, IOException, DecoderException { final int len; byte[] me; switch (content) { case KEY: if (buffer.readableBytes() < 20) return false; message.setKey0(readID(buffer)); return true; case KEY_KEY: if (buffer.readableBytes() < 40) return false; message.setKeyKey0(readID(buffer), readID(buffer)); return true; case MAP_KEY_DATA: if (buffer.readableBytes() < 4) return false; int size = buffer.readInt(); Map<Number160, Data> result = new HashMap<Number160, Data>(size); for (int i = 0; i < size; i++) { if (buffer.readableBytes() < 20) return false; Number160 key = readID(buffer); final Data data = decodeData(new ChannelDecoder(buffer), message.getSender()); if (data == null) return false; if (message.isRequest()) { if (data.isProtectedEntry() && message.getPublicKey() == null) throw new DecoderException( "You indicated that you want to protect the data, but you did not provide or provided too late a public key."); data.setPublicKey(message.getPublicKey()); } result.put(key, data); } message.setDataMap0(result); return true; case MAP_KEY_KEY: if (buffer.readableBytes() < 4) return false; len = buffer.readInt(); if (buffer.readableBytes() < ((20 + 20) * len)) return false; final Map<Number160, Number160> keyMap = new HashMap<Number160, Number160>(); for (int i = 0; i < len; i++) { final Number160 key1 = readID(buffer); final Number160 key2 = readID(buffer); keyMap.put(key1, key2); } message.setKeyMap0(keyMap); return true; case SET_KEYS: // can be 31bit long ~ 2GB if (buffer.readableBytes() < 4) return false; len = buffer.readInt(); if (buffer.readableBytes() < (20 * len)) return false; final Collection<Number160> tmp = new ArrayList<Number160>(len); for (int i = 0; i < len; i++) { Number160 key = readID(buffer); tmp.add(key); } message.setKeys0(tmp); return true; case SET_NEIGHBORS: if (buffer.readableBytes() < 1) return false; len = buffer.readUnsignedByte(); if (buffer.readableBytes() < (len * PeerAddress.SIZE_IPv4)) return false; final Collection<PeerAddress> neighbors = new ArrayList<PeerAddress>(len); for (int i = 0; i < len; i++) { PeerAddress peerAddress = readPeerAddress(buffer); if (peerAddress == null) return false; neighbors.add(peerAddress); } message.setNeighbors0(neighbors); return true; case SET_TRACKER_DATA: if (buffer.readableBytes() < 1) return false; len = buffer.readUnsignedByte(); if (buffer.readableBytes() < (len * (PeerAddress.SIZE_IPv4 + 1))) return false; final Collection<TrackerData> trackerDatas = new ArrayList<TrackerData>(len); for (int i = 0; i < len; i++) { PeerAddress peerAddress = readPeerAddress(buffer); if (peerAddress == null) return false; byte[] attachment = null; int offset = 0; int length = 0; if (buffer.readableBytes() < 1) return false; byte miniHeader = buffer.readByte(); if (miniHeader != 0) { if (buffer.readableBytes() < 4) return false; length = buffer.readInt(); if (buffer.readableBytes() < length) return false; attachment = new byte[length]; buffer.readBytes(attachment); } trackerDatas.add( new TrackerData(peerAddress, message.getSender(), attachment, offset, length)); } message.setTrackerData0(trackerDatas); return true; case CHANNEL_BUFFER: if (buffer.readableBytes() < 4) return false; len = buffer.readInt(); if (buffer.readableBytes() < len) return false; // you can only use slice if no execution handler is in place, // otherwise, you will overwrite stuff final ChannelBuffer tmpBuffer = buffer.slice(buffer.readerIndex(), len); buffer.skipBytes(len); message.setPayload0(tmpBuffer); return true; case LONG: if (buffer.readableBytes() < 8) return false; message.setLong0(buffer.readLong()); return true; case INTEGER: if (buffer.readableBytes() < 4) return false; message.setInteger0(buffer.readInt()); return true; case PUBLIC_KEY: case PUBLIC_KEY_SIGNATURE: if (buffer.readableBytes() < 2) return false; len = buffer.readUnsignedShort(); me = new byte[len]; if (buffer.readableBytes() < len) return false; message.setPublicKey0(decodePublicKey(new ChannelDecoder(buffer), me)); if (content == Content.PUBLIC_KEY_SIGNATURE) { message.setHintSign(true); } return true; case EMPTY: case RESERVED1: case RESERVED2: case RESERVED3: default: return true; } }
/** {@inheritDoc} */ @Override public void send(Message msg) throws IllegalArgumentException, IOException { // Sanity checks if (msg.getTo() == null || msg.getSubject() == null || msg.getBody() == null) { throw new IllegalArgumentException("Message has no destination or no subject"); } ArrayList<String> cmd = new ArrayList<String>(); // mailx -b bcc -c cc -s subj to-addr to-addr cmd.add(mailer); if (msg.getBcc() != null) { cmd.add("-b"); cmd.add(join(msg.getBcc(), ",")); } if (msg.isHtml()) { cmd.add("-a"); cmd.add("Content-type: text/html;"); } if (msg.getCc() != null) { cmd.add("-c"); cmd.add(join(msg.getCc(), ",")); } cmd.add("-s"); cmd.add(msg.getSubject()); cmd.addAll(msg.getTo()); if (msg.getSender() != null) { // Sender in the headers: cmd.add("-a"); cmd.add(String.format("From: %s", msg.getSender())); // sendmail options are denoted with a double-hyphen cmd.add("--"); // Envelope Sender cmd.add("-f"); cmd.add(msg.getSender()); } Log.i(LOG_TAG, String.format("About to send email with command: %s", cmd)); String[] strArray = new String[cmd.size()]; Process mailerProc = run(cmd.toArray(strArray)); BufferedOutputStream mailerStdin = new BufferedOutputStream(mailerProc.getOutputStream()); /* There is no such thing as a "character" in the land of the shell; there are only bytes. * Here, we convert the body from a Java string (consisting of characters) to a byte array * encoding each character with UTF-8. Each character will be represented as between one * and four bytes apiece. */ mailerStdin.write(msg.getBody().getBytes("UTF-8")); mailerStdin.flush(); mailerStdin.close(); int retValue; try { retValue = mailerProc.waitFor(); } catch (InterruptedException e) { // ignore, but set retValue to something bogus retValue = -12345; } if (retValue != 0) { Log.e(LOG_TAG, String.format("Mailer finished with non-zero return value: %d", retValue)); BufferedInputStream mailerStdout = new BufferedInputStream(mailerProc.getInputStream()); StringBuilder stdout = new StringBuilder(); int theByte; while ((theByte = mailerStdout.read()) != -1) { stdout.append((char) theByte); } Log.e(LOG_TAG, "Mailer output was: " + stdout.toString()); } else { Log.v(LOG_TAG, "Mailer returned successfully."); } }
public void onMessage(Message message) { String text = new String(message.getData(), message.getOffset(), message.getLength()); System.err.println("received message from " + message.getSender() + " : " + text); }
/** * Authenticate users * * @param oc the streams * @param ci the ConnectInfo */ private void authentification(ObjectConnection oc, Message message, String data) { String passwd = null; String name = null; String authenticationServer = null; String hostname = null; int port = 0; StringTokenizer stk = new StringTokenizer(data, " "); try { passwd = stk.nextToken(); hostname = stk.nextToken(); port = Integer.parseInt(stk.nextToken()); } catch (Exception ex) { Logging.getLogger().warning("#Err > Incorrect authentication message."); try { oc.write("BAD_MESSAGE"); } catch (Exception e) { } return; } name = message.getSender().getName(); authenticationServer = message.getSender().getAuthenticationServer(); UserConcept user = null; try { user = store.getUserStore().getUser(message.getSender().getName()); } catch (Exception e) { e.printStackTrace(); } // password ok if (user != null && store.getUserStore().checkUserPassword(user, passwd)) { // disconnect already connected user if (isAlreadyKnown(message.getSender())) { ConnectInfo oldUser = getCompleteConnectInfo(message.getSender()); try { ObjectConnection myoc = this.sendMessageTo(oldUser, "Client", "DISCONNECT"); myoc.close(); } catch (Exception e) { // we can't do much here, the client might have crashed } this.removeConnectInfo(oldUser); } connections.add( new ConnectInfo( name, authenticationServer, hostname, port, user.getPublicKey(), "Client")); try { oc.write("AUTH_ACCEPTED " + user.getPrivateKey()); } catch (Exception e) { e.printStackTrace(); } this.sendUserList(); } else { try { oc.write("NOT_VALID_USER"); } catch (Exception e) { } } }
/** * Reads messages from the network. A message is either a command for the server or for an * internal Service. * * @param sock the Socket */ private void getMessage(Socket sock) { int i; boolean alreadyConnected; boolean isAuthentication; Message message; byte[] signature; String cmd; String cmdData; StringTokenizer stk; ObjectConnection oc = null; try { /* streams initialization */ oc = new ObjectConnection(sock); message = (Message) oc.read(); signature = (byte[]) oc.read(); } catch (Exception ex) { ex.printStackTrace(); Logging.getLogger().warning("#Err > Unable to read message."); return; } // check wether a user is known or not alreadyConnected = isAlreadyKnown(message.getSender()); // check if command is authentication isAuthentication = message.getApplication().equals("Server") && ((String) message.getData()).startsWith("AUTH"); // signature check if (alreadyConnected && !isAuthentication) { boolean sigok = false; try { ConnectInfo ci = message.getSender(); if (ci.verifier == null) ci = this.getCompleteConnectInfo(ci); sigok = ci.verifier.verify(message, signature); } catch (Exception e) { e.printStackTrace(); } if (!sigok) { try { oc.write("FAILED bad signature"); } catch (Exception e) { } Logging.getLogger().warning("#Err > bad signature: " + message.getSender()); return; } } if (message.getApplication().equals("Server")) { cmd = null; try { stk = new StringTokenizer((String) message.getData()); cmd = stk.nextToken(); cmdData = stk.nextToken("\0").substring(1); } catch (Exception ex) { if (cmd == null) cmd = ""; cmdData = ""; } /* if the user asks for authentication, we try to do it and exits this method */ if (cmd.equals("AUTH")) { try { oc.write("OK"); } catch (Exception e) { e.printStackTrace(); } authentification(oc, message, cmdData); } else if (!alreadyConnected) { Logging.getLogger().info("Access denied to " + message.getSender()); try { oc.write("FAILED No Connection"); } catch (Exception e) { } } else { internalCommand(oc, message, cmd, cmdData); } } else if (!alreadyConnected) { Logging.getLogger().info("Access denied to " + message.getSender()); try { oc.write("FAILED No Connection"); } catch (Exception e) { } } else { Service s; /* seek the destination service */ boolean serviceFound = false; for (i = 0; i < this.services.size(); i++) { s = (Service) services.get(i); if (s.getName().equalsIgnoreCase(message.getApplication())) { serviceFound = true; UserConcept user = null; ServiceConcept service = null; try { user = store.getUserStore().getUser(message.getSender().getName()); service = store.getServiceStore().getService(message.getReceiver().getName()); } catch (Exception e) { } /* tests serviceManager for permissions */ boolean isAutorizedService = false; try { isAutorizedService = store.getServiceStore().isAuthorizedService(user, service); } catch (Exception e) { } if (!isAutorizedService) { Logging.getLogger() .info( "#Err > " + message.getSender() + " : Service denied to " + message.getReceiver().getName()); try { oc.write("FAILED You don't have acces to this service"); } catch (Exception e) { } } else { try { oc.write("OK"); } catch (Exception e) { } serviceFound = true; s.process(oc, message); } break; } } if (!serviceFound) { try { oc.write("FAILED unknown"); } catch (Exception e) { } Logging.getLogger() .warning("#Err > Service " + message.getReceiver().getName() + " unknown"); } } oc.close(); }