@Test public void tooLongSender() throws Exception { Mailbox mbox = MailboxManager.getInstance().getMailboxByAccountId(MockProvisioning.DEFAULT_ACCOUNT_ID); Map<String, Object> fields = new HashMap<String, Object>(); fields.put(ContactConstants.A_firstName, Strings.repeat("F", 129)); Contact contact = mbox.createContact(null, new ParsedContact(fields), Mailbox.ID_FOLDER_CONTACTS, null); DbConnection conn = DbPool.getConnection(mbox); Assert.assertEquals( Strings.repeat("F", 128), DbUtil.executeQuery( conn, "SELECT sender FROM mboxgroup1.mail_item WHERE mailbox_id = ? AND id = ?", mbox.getId(), contact.getId()) .getString(1)); fields.put(ContactConstants.A_firstName, null); fields.put(ContactConstants.A_lastName, Strings.repeat("L", 129)); mbox.modifyContact(null, contact.getId(), new ParsedContact(fields)); Assert.assertEquals( Strings.repeat("L", 128), DbUtil.executeQuery( conn, "SELECT sender FROM mboxgroup1.mail_item WHERE mailbox_id = ? AND id = ?", mbox.getId(), contact.getId()) .getString(1)); conn.closeQuietly(); }
/** * This method looks up a MailboxAddress that has been registered with the system, and implicitly * opens the connection to the remote Mailbox. It also opens the reply address for the remote * mailbox, so it may send responses back to this Isolate. * * @param name the name of the Mailbox to lookup. * @param replyMailbox the address of a local mailbox that the remote isolate can send replies to. * @return an open address to the remote mailbox named <code>name</code>. * @throws NoSuchMailboxException if there is no mailbox named <code>name</code>. */ public static MailboxAddress lookupMailbox(String name, Mailbox replyMailbox) throws NoSuchMailboxException { Mailbox box = VM.lookupMailbox(name); if (box == null) { throw new NoSuchMailboxException(name); } MailboxAddress replyAddress = new MailboxAddress(replyMailbox); MailboxAddress startingAddress = new MailboxAddress(box); MailboxAddress finalAddress = box.callHandleOpen(startingAddress, replyAddress); if (finalAddress == null) { // something fell apart in callHandleOpen throw new NoSuchMailboxException(name); } // record the address of the remote mailbox with this isolate: finalAddress.recordAddress(Isolate.currentIsolate(), replyAddress); // also, tell the isolate containing the remote mailbox about the // reply address that it will use to send replies back to this isolate. replyAddress.recordAddress(box.getOwner(), finalAddress); return finalAddress; }
public void forceDeleteMailbox(Mailbox mbox) throws ServiceException { DeleteMailbox redoRecorder = new DeleteMailbox(mbox.getId()); boolean success = false; try { beginTransaction("deleteMailbox", null, redoRecorder); redoRecorder.log(); try { // remove all the relevant entries from the database DbConnection conn = getOperationConnection(); ZimbraLog.mailbox.info( "attempting to remove the zimbra.mailbox row for id " + mbox.getId()); DbOfflineMailbox.forceDeleteMailbox(conn, mbox.getId()); success = true; } finally { // commit the DB transaction before touching the store! (also ends the operation) endTransaction(success); } if (success) { // remove all traces of the mailbox from the Mailbox cache // (so anyone asking for the Mailbox gets NO_SUCH_MBOX or creates a fresh new empty one // with a different id) MailboxManager.getInstance().markMailboxDeleted(mbox); } } finally { if (success) { redoRecorder.commit(); } else { redoRecorder.abort(); } } }
public void run() { if (!player.isOnline()) { return; } Mailbox mb = plugin.getMailbox(player.getName(), false); if (mb != null) { int numUnread = mb.numUnread(); if (numUnread > 0) { String s1 = numUnread == 1 ? "" : "s"; String s2 = numUnread == 1 ? "it" : "them"; player.sendMessage( ChatColor.YELLOW + "You have " + ChatColor.GREEN + Integer.toString(numUnread) + ChatColor.YELLOW + " unread message" + s1 + "."); player.sendMessage( ChatColor.YELLOW + "Type " + ChatColor.DARK_RED + "/kmail read next" + ChatColor.YELLOW + " to begin reading " + s2 + "."); } } plugin.saveMailbox(player.getName()); }
@Test public void createAutoContact() throws Exception { Mailbox mbox = MailboxManager.getInstance().getMailboxByAccountId(MockProvisioning.DEFAULT_ACCOUNT_ID); List<Contact> contacts = mbox.createAutoContact( null, ImmutableList.of( new InternetAddress("Test 1", "*****@*****.**"), new InternetAddress("Test 2", "*****@*****.**"))); Assert.assertEquals(2, contacts.size()); Assert.assertEquals("1, Test", contacts.get(0).getFileAsString()); Assert.assertEquals( "*****@*****.**", contacts.get(0).getFields().get(ContactConstants.A_email)); Assert.assertEquals("2, Test", contacts.get(1).getFileAsString()); Assert.assertEquals( "*****@*****.**", contacts.get(1).getFields().get(ContactConstants.A_email)); Collection<javax.mail.Address> newAddrs = mbox.newContactAddrs( ImmutableList.of( (javax.mail.Address) new javax.mail.internet.InternetAddress("*****@*****.**", "Test 1"), (javax.mail.Address) new javax.mail.internet.InternetAddress("*****@*****.**", "Test 2"))); Assert.assertEquals(0, newAddrs.size()); }
public Mailbox build() { try { String tmpName = name; String path = name; String parent = null; int lastIndexOf = name.lastIndexOf("."); if (lastIndexOf != -1) { tmpName = name.substring(lastIndexOf + 1); parent = name.substring(0, lastIndexOf); } Mailbox mailbox = new Mailbox(); mailbox.name = tmpName; mailbox.address = new InternetAddress(address); mailbox.path = path; mailbox.parent = parent; mailbox.subscribed = subscribed; mailbox.exists = exists; mailbox.addAll(messages); mailbox.error = error; MailboxHolder.add(mailbox); return mailbox; } catch (AddressException e) { throw new RuntimeException(e.getMessage(), e); } }
/** * This version is used internally by ServerChannel to call send using a temporory mailAddress * that is unowned. * * @param env the message to send * @throws IllegateStateException if the address is not in the open state, or if the caller is not * the "owner" of this MailboxAddress. */ void send0(Envelope env) throws AddressClosedException { if (state == CLOSED) { throw new AddressClosedException(this); } else if (!mailbox.isOpen()) { closeLocalState(); throw new AddressClosedException(this); } env.setAddresses(this); mailbox.handleMessage(env); }
/** {@inheritDoc} */ public String toString() { switch (state) { case UNOWNED: return "MailboxAddress (UNOWNED) of " + mailbox.toString(); case OPEN: return "MailboxAddress of " + mailbox.toString(); case CLOSED: return "MailboxAddress (CLOSED)"; default: throw Assert.shouldNotReachHere(); } }
public void testSimple() throws Exception { HostMessenger msg1 = new HostMessenger(getConfig()); msg1.start(); HostMessenger msg2 = new HostMessenger(getConfig()); msg2.start(); System.out.println("Waiting for socketjoiners..."); msg1.waitForGroupJoin(2); System.out.println("Finished socket joiner for msg1"); msg2.waitForGroupJoin(2); System.out.println("Finished socket joiner for msg2"); assertEquals(msg1.getHostId(), 0); assertEquals(msg2.getHostId(), 1); Mailbox mb1 = msg1.createMailbox(); Mailbox mb2 = msg2.createMailbox(); long siteId2 = mb2.getHSId(); MsgTest.initWithSize(16); MsgTest mt = new MsgTest(); mt.setValues(); mb1.send(siteId2, mt); MsgTest mt2 = null; while (mt2 == null) { mt2 = (MsgTest) mb2.recv(); } assertTrue(mt2.verify()); // Do it again MsgTest.initWithSize(32); mt = new MsgTest(); mt.setValues(); mb1.send(siteId2, mt); mt2 = null; while (mt2 == null) { mt2 = (MsgTest) mb2.recv(); } assertTrue(mt2.verify()); // Do it a final time with a message that should block on write. // spin on a complete network message here - maybe better to write // the above cases this way too? for (int i = 0; i < 3; ++i) { MsgTest.initWithSize(4280034); mt = new MsgTest(); mt.setValues(); mb1.send(siteId2, mt); mt2 = null; while (mt2 == null) { mt2 = (MsgTest) mb2.recv(); } assertTrue(mt.verify()); } msg1.shutdown(); msg2.shutdown(); }
@Test public void spaceInFirstName() throws Exception { Mailbox mbox = MailboxManager.getInstance().getMailboxByAccountId(MockProvisioning.DEFAULT_ACCOUNT_ID); Map<String, Object> fields = new HashMap<String, Object>(); fields.put(ContactConstants.A_firstName, "First Second Third Forth"); fields.put(ContactConstants.A_lastName, "Last"); fields.put(ContactConstants.A_email, "*****@*****.**"); mbox.createContact(null, new ParsedContact(fields), Mailbox.ID_FOLDER_CONTACTS, null); ContactAutoComplete autocomplete = new ContactAutoComplete(mbox.getAccount(), new OperationContext(mbox)); Assert.assertEquals( 1, autocomplete.query("first second third forth", null, 100).entries.size()); }
void blameBroadcastShuffleMessages() throws TimeoutException, Matrix, IOException, InterruptedException, FormatException { phase.set(Phase.Blame); log.warn("Player " + me + " enters blame phase and sends broadcast messages."); // Collect all packets from phase 2 and 3. Queue<Packet> evidence = mailbox.getPacketsByPhase(Phase.Shuffling); evidence.addAll(mailbox.getPacketsByPhase(Phase.BroadcastOutput)); // Send them all with the decryption key. mailbox.broadcast( messages.make().attach(Blame.ShuffleAndEquivocationFailure(dk, evidence)), phase.get()); throw fillBlameMatrix(); }
// Check for players with insufficient funds. private void blameInsufficientFunds() throws CoinNetworkException, TimeoutException, Matrix, IOException, InterruptedException, FormatException, AddressFormatException { List<VerificationKey> offenders = new LinkedList<>(); // Check that each participant has the required amounts. for (VerificationKey player : players.values()) { if (!coin.sufficientFunds(player.address(), amount + fee)) { // Enter the blame phase. offenders.add(player); } } // If they do, return. if (offenders.isEmpty()) return; // If not, enter blame phase and find offending transactions. phase.set(Phase.Blame); Message blameMessage = messages.make(); for (VerificationKey offender : offenders) { blameMessage = blameMessage.attach(Blame.InsufficientFunds(offender)); } // Broadcast offending transactions. mailbox.broadcast(blameMessage, phase.get()); // Get all subsequent blame messages. throw fillBlameMatrix(); }
// In the shuffle phase, we have to receive a set of strings from the previous player and // decrypt them all. final Message decryptAll(Message message, DecryptionKey key, int expected) throws IOException, InterruptedException, FormatException { Message decrypted = messages.make(); int count = 0; Set<String> addrs = new HashSet<>(); // Used to check that all addresses are different. while (!message.isEmpty()) { String encrypted = message.readString(); message = message.rest(); addrs.add(encrypted); count++; decrypted = decrypted.attach(key.decrypt(encrypted)); } if (addrs.size() != count || count != expected) { phase.set(Phase.Blame); mailbox.broadcast( messages.make().attach(Blame.ShuffleFailure(players.get(N))), phase.get()); return null; } return decrypted; }
/** * Sends a message to the Mailbox. Does not wait for acknowledgment. The MailboxAddress must have * been opened by #lookup, must not have been closed, and caller must by the owning isolate of * this MailboxAddress, or an IllegateStateException will be thrown. * * @param env the message to send * @throws IllegateStateException if the address is not in the open state, or if the caller is not * the "owner" of this MailboxAddress. */ public void send(Envelope env) throws AddressClosedException { if (state == CLOSED) { throw new AddressClosedException(this); } else if (!mailbox.isOpen()) { closeLocalState(); throw new AddressClosedException(this); } else if (state == UNOWNED) { throw new IllegalStateException(this + " has not been opened for sending."); } else if (Isolate.currentIsolate() != owner && !(env instanceof AddressClosedEnvelope)) { throw new IllegalStateException( "Attempted send on " + this + " by " + Isolate.currentIsolate()); } env.setAddresses(this); mailbox.handleMessage(env); }
// In the broadcast phase, we have to either receive all the // new addresses or send them all out. This is set off in its own function so that the // malicious machine can override it. Deque<Address> readAndBroadcastNewAddresses(Message shuffled) throws IOException, InterruptedException, TimeoutException, BlameException, FormatException { Deque<Address> newAddresses; if (me == N) { // The last player adds his own new address in without // encrypting anything and shuffles the result. newAddresses = readNewAddresses(shuffled); mailbox.broadcast(shuffled, phase.get()); } else { // All other players just receive their addresses from the last one. newAddresses = readNewAddresses(mailbox.receiveFrom(players.get(N), phase.get())); } return newAddresses; }
/** Confirms that locator is not set for contacts. */ @Test public void locator() throws Exception { // Create contact. Map<String, String> attrs = Maps.newHashMap(); attrs.put(ContactConstants.A_fullName, "Volume Id"); Mailbox mbox = MailboxManager.getInstance().getMailboxByAccountId(MockProvisioning.DEFAULT_ACCOUNT_ID); mbox.createContact(null, new ParsedContact(attrs), Mailbox.ID_FOLDER_CONTACTS, null); // Check volume id in database. String sql = String.format( "SELECT COUNT(*) FROM %s WHERE type = %d AND blob_digest IS NULL AND locator IS NOT NULL", DbMailItem.getMailItemTableName(mbox), MailItem.Type.CONTACT.toByte()); DbResults results = DbUtil.executeQuery(sql); Assert.assertEquals("Found non-null locator values for contacts", 0, results.getInt(1)); }
@Test public void reservedQueryTerm() throws Exception { Mailbox mbox = MailboxManager.getInstance().getMailboxByAccountId(MockProvisioning.DEFAULT_ACCOUNT_ID); Map<String, Object> fields = new HashMap<String, Object>(); fields.put(ContactConstants.A_firstName, "not and or"); fields.put(ContactConstants.A_lastName, "subject: from:"); fields.put(ContactConstants.A_email, "*****@*****.**"); mbox.createContact(null, new ParsedContact(fields), Mailbox.ID_FOLDER_CONTACTS, null); ContactAutoComplete autocomplete = new ContactAutoComplete(mbox.getAccount(), new OperationContext(mbox)); Assert.assertEquals(1, autocomplete.query("not", null, 100).entries.size()); Assert.assertEquals(1, autocomplete.query("not and", null, 100).entries.size()); Assert.assertEquals(1, autocomplete.query("not and or", null, 100).entries.size()); Assert.assertEquals(1, autocomplete.query("subject:", null, 100).entries.size()); Assert.assertEquals(1, autocomplete.query("subject: from:", null, 100).entries.size()); }
@Test public void testSingleHost() throws Exception { HostMessenger hm = createHostMessenger(0); Mailbox m1 = hm.createMailbox(); SiteMailbox sm = new SiteMailbox(hm, (-2L << 32)); hm.createMailbox(sm.getHSId(), sm); sm.send(m1.getHSId(), new LocalObjectMessage(null)); m1.send(sm.getHSId(), new LocalObjectMessage(null)); LocalObjectMessage lom = (LocalObjectMessage) m1.recv(); assertEquals(lom.m_sourceHSId, sm.getHSId()); lom = (LocalObjectMessage) sm.recv(); assertEquals(lom.m_sourceHSId, m1.getHSId()); }
/** * Bug 77746 Test that VCARD formatting escapes ';' and ',' chars which are part of name * components */ @Test public void semiColonAndCommaInName() throws Exception { Mailbox mbox = MailboxManager.getInstance().getMailboxByAccountId(MockProvisioning.DEFAULT_ACCOUNT_ID); Map<String, Object> fields = new HashMap<String, Object>(); fields.put(ContactConstants.A_lastName, "Last"); fields.put(ContactConstants.A_firstName, "First ; SemiColon"); fields.put(ContactConstants.A_middleName, "Middle , Comma"); fields.put(ContactConstants.A_namePrefix, "Ms."); Contact contact = mbox.createContact(null, new ParsedContact(fields), Mailbox.ID_FOLDER_CONTACTS, null); VCard vcard = VCard.formatContact(contact); String vcardAsString = vcard.getFormatted(); String expectedPattern = "N:Last;First \\; SemiColon;Middle \\, Comma;Ms.;"; String assertMsg = String.format("Vcard\n%s\nshould contain string [%s]", vcardAsString, expectedPattern); Assert.assertTrue(assertMsg, vcardAsString.contains(expectedPattern)); }
@Test public void existsInContacts() throws Exception { Mailbox mbox = MailboxManager.getInstance().getMailboxByAccountId(MockProvisioning.DEFAULT_ACCOUNT_ID); mbox.createContact( null, new ParsedContact(Collections.singletonMap(ContactConstants.A_email, "*****@*****.**")), Mailbox.ID_FOLDER_CONTACTS, null); MailboxTestUtil.index(mbox); Assert.assertTrue( mbox.index.existsInContacts( ImmutableList.of( new InternetAddress("Test <*****@*****.**>"), new InternetAddress("Test <*****@*****.**>")))); Assert.assertFalse( mbox.index.existsInContacts( ImmutableList.of( new InternetAddress("Test <*****@*****.**>"), new InternetAddress("Test <*****@*****.**>")))); }
static Conversation create(Mailbox mbox, int id, Message[] msgs) throws ServiceException { if (ZimbraLog.mailop.isDebugEnabled()) { StringBuilder msgIds = new StringBuilder(); for (int i = 0; i < msgs.length; i++) msgIds.append(i > 0 ? "," : "").append(msgs[i].getId()); ZimbraLog.mailop.debug("Adding Conversation: id=%d, message(s): %s.", id, msgIds); } assert (id != Mailbox.ID_AUTO_INCREMENT && msgs.length > 0); Arrays.sort(msgs, new Message.SortDateAscending()); int date = 0, unread = 0, flags = 0; long tags = 0; CustomMetadataList extended = null; for (int i = 0; i < msgs.length; i++) { Message msg = msgs[i]; if (msg == null) throw ServiceException.FAILURE("null Message in list", null); date = Math.max(date, msg.mData.date); unread += msg.mData.unreadCount; flags |= msg.mData.flags; tags |= msg.mData.tags; extended = MetadataCallback.duringConversationAdd(extended, msg); } UnderlyingData data = new UnderlyingData(); data.id = id; data.type = TYPE_CONVERSATION; data.folderId = Mailbox.ID_FOLDER_CONVERSATIONS; data.subject = msgs.length > 0 ? DbMailItem.truncateSubjectToMaxAllowedLength(msgs[0].getSubject()) : ""; data.date = date; data.size = msgs.length; data.unreadCount = unread; data.flags = flags; data.tags = tags; data.metadata = encodeMetadata(DEFAULT_COLOR_RGB, 1, extended, new SenderList(msgs)); data.contentChanged(mbox); DbMailItem.create(mbox, data, null); Conversation conv = new Conversation(mbox, data); conv.finishCreation(null); DbMailItem.setParent(msgs, conv); for (int i = 0; i < msgs.length; i++) { mbox.markItemModified(msgs[i], Change.MODIFIED_PARENT); msgs[i].mData.parentId = id; msgs[i].mData.metadataChanged(mbox); } return conv; }
private void destroy() throws IOException { for (IOThread it : ioThreads) { it.stop(); } for (IOThread it : ioThreads) { it.close(); } if (reaper != null) { reaper.close(); } termMailbox.close(); tag = 0xdeadbeef; }
// Everyone except player 1 creates a new keypair and sends it around to everyone else. DecryptionKey broadcastNewKey(Map<VerificationKey, Address> changeAddresses) throws TimeoutException, InterruptedException, IOException, FormatException { DecryptionKey dk = null; dk = crypto.makeDecryptionKey(); // Broadcast the public key and store it in the set with everyone else's. encryptionKeys.put(vk, dk.EncryptionKey()); changeAddresses.put(vk, change); Message message = messages.make().attach(dk.EncryptionKey()); if (change != null) { message = message.attach(change); } mailbox.broadcast(message, phase.get()); return dk; }
/** Tests Invalid image attachment (bug 71868). */ @Test public void modifyInvalidImageAttachment() throws Exception { // Create a contact with an attachment. Map<String, String> attrs = new HashMap<String, String>(); attrs.put("fullName", "Contact Initial Content"); byte[] attachData = "attachment 1".getBytes(); Attachment attachment1 = new Attachment(attachData, "image/png", "customField", "image.png"); Mailbox mbox = MailboxManager.getInstance().getMailboxByAccountId(MockProvisioning.DEFAULT_ACCOUNT_ID); Contact contact = mbox.createContact( null, new ParsedContact(attrs, Lists.newArrayList(attachment1)), Mailbox.ID_FOLDER_CONTACTS, null); Attachment attachment2 = new Attachment(attachData, "image/png", "image", "image2.png"); try { ParsedContact pc = new ParsedContact(contact) .modify(new ParsedContact.FieldDeltaList(), Lists.newArrayList(attachment2)); } catch (ServiceException se) { Assert.assertEquals("check the INVALID_IMAGE exception", "mail.INVALID_IMAGE", se.getCode()); } }
/** Tests {@link Attachment#getContent()} (bug 36974). */ @Test public void getAttachmentContent() throws Exception { // Create a contact with an attachment. Map<String, String> attrs = new HashMap<String, String>(); attrs.put("fullName", "Get Attachment Content"); byte[] attachData = "attachment 1".getBytes(); Attachment textAttachment = new Attachment(attachData, "text/plain", "customField", "text.txt"); Mailbox mbox = MailboxManager.getInstance().getMailboxByAccountId(MockProvisioning.DEFAULT_ACCOUNT_ID); mbox.createContact( null, new ParsedContact(attrs, Lists.newArrayList(textAttachment)), Mailbox.ID_FOLDER_CONTACTS, null); // Call getContent() on all attachments. for (Contact contact : mbox.getContactList(null, Mailbox.ID_FOLDER_CONTACTS)) { List<Attachment> attachments = contact.getAttachments(); for (Attachment attach : attachments) { attach.getContent(); } } }
/** Modify Contact having an attachment (bug 70488). */ @Test public void modifyContactHavingAttachment() throws Exception { // Create a contact with an attachment. Map<String, String> attrs = new HashMap<String, String>(); attrs.put("fullName", "Contact Initial Content"); byte[] attachData = "attachment 1".getBytes(); Attachment textAttachment = new Attachment(attachData, "text/plain", "customField", "file.txt"); Mailbox mbox = MailboxManager.getInstance().getMailboxByAccountId(MockProvisioning.DEFAULT_ACCOUNT_ID); Contact contact = mbox.createContact( null, new ParsedContact(attrs, Lists.newArrayList(textAttachment)), Mailbox.ID_FOLDER_CONTACTS, null); ParsedContact pc = new ParsedContact(contact) .modify(new ParsedContact.FieldDeltaList(), new ArrayList<Attachment>()); MimeMessage mm = new Mime.FixedMimeMessage(JMSession.getSession(), pc.getContentStream()); MimePart mp = Mime.getMimePart(mm, "1"); Assert.assertEquals("text/plain", mp.getContentType()); Assert.assertEquals("attachment 1", mp.getContent()); }
@Test public void nestedTxn() throws Exception { Account acct = Provisioning.getInstance().getAccount("*****@*****.**"); Mailbox mbox = MailboxManager.getInstance().getMailboxByAccount(acct); useMVCC(mbox); DeliveryOptions dopt = new DeliveryOptions().setFolderId(Mailbox.ID_FOLDER_INBOX); mbox.lock.lock(); try { OperationContext octx = new OperationContext(acct); mbox.beginTransaction("outer", octx); mbox.beginTransaction("inner1", octx); mbox.addMessage( octx, new ParsedMessage("From: [email protected]".getBytes(), false), dopt, null); // nothing committed yet Assert.assertEquals(0, countInboxMessages(mbox)); mbox.endTransaction(true); // inner 1 // nothing committed yet Assert.assertEquals(0, countInboxMessages(mbox)); mbox.beginTransaction("inner2", null); mbox.addMessage( null, new ParsedMessage("From: [email protected]".getBytes(), false), dopt, null); // nothing committed yet Assert.assertEquals(0, countInboxMessages(mbox)); mbox.endTransaction(true); // inner 2 // nothing committed yet Assert.assertEquals(0, countInboxMessages(mbox)); mbox.endTransaction(true); // outer // committed Assert.assertEquals(2, countInboxMessages(mbox)); } finally { mbox.lock.release(); } }
public void terminate() { tag = 0xdeadbeef; if (!starting.get()) { slotSync.lock(); try { // Check whether termination was already underway, but interrupted and now // restarted. boolean restarted = terminating; terminating = true; // First attempt to terminate the context. if (!restarted) { // First send stop command to sockets so that any blocking calls // can be interrupted. If there are no sockets we can ask reaper // thread to stop. for (SocketBase socket : sockets) { socket.stop(); } if (sockets.isEmpty()) { reaper.stop(); } } } finally { slotSync.unlock(); } // Wait till reaper thread closes all the sockets. Command cmd = termMailbox.recv(-1); if (cmd == null) { throw new IllegalStateException(); } assert (cmd.type() == Command.Type.DONE); slotSync.lock(); try { assert (sockets.isEmpty()); } finally { slotSync.unlock(); } } // Deallocate the resources. try { destroy(); } catch (IOException e) { throw new RuntimeException(e); } }
void checkDoubleSpending(Transaction t) throws InterruptedException, IOException, FormatException, TimeoutException, Matrix, CoinNetworkException, AddressFormatException { // Check for double spending. Message doubleSpend = messages.make(); for (VerificationKey key : players.values()) { Transaction o = coin.getConflictingTransaction(t, key.address(), amount); if (o != null) { doubleSpend = doubleSpend.attach(Blame.DoubleSpend(key, o)); } } if (!doubleSpend.isEmpty()) { phase.set(Phase.Blame); mailbox.broadcast(doubleSpend, phase.get()); throw fillBlameMatrix(); } }
private int countInboxMessages(Mailbox mbox) throws ServiceException, SQLException { PreparedStatement stmt = null; ResultSet rs = null; DbConnection conn = DbPool.getConnection(mbox); try { stmt = conn.prepareStatement( "SELECT COUNT(*) FROM mboxgroup1.mail_item WHERE mailbox_id = ? and folder_id = ?"); stmt.setInt(1, mbox.getId()); stmt.setInt(2, Mailbox.ID_FOLDER_INBOX); rs = stmt.executeQuery(); if (rs.next()) { return rs.getInt(1); } return 0; } finally { DbPool.closeResults(rs); DbPool.quietCloseStatement(stmt); DbPool.quietClose(conn); } }