private void callFunctionByMessage(Message m) {
   int id = m.getId();
   BluetoothGatt gatt = gatts.get(m.getAddress());
   System.out.println("Call Function: " + id);
   switch (id) {
     case 10:
       turnOnService(gatt, UUID_HUM_SERV, UUID_HUM_CONF);
       break;
     case 11:
       turnOnService(gatt, UUID_ACC_SERV, UUID_ACC_CONF);
       break;
     case 20:
       enableNotifications(gatt, UUID_HUM_SERV, UUID_HUM_DATA);
       break;
     case 21:
       enableNotifications(gatt, UUID_ACC_SERV, UUID_ACC_DATA);
       break;
     case 30:
       enableNotifications(gatt, UUID_SENSI_HUM_SERV, UUID_SENSI_HUM_DATA);
       break;
     case 31:
       enableNotifications(gatt, UUID_SENSI_TEMP_SERV, UUID_SENSI_TEMP_DATA);
       break;
     default:
       break;
   }
 }
 @Override
 public boolean onMessage(final Message message) {
   if (message instanceof ClockMessage) {
     final ClockMessage clockMessage = (ClockMessage) message;
     MessageScheduler.getInstance().removeClock(clockMessage.getClockId());
     if (this.m_cancelTimedPop) {
       return false;
     }
     this.popup();
     return false;
   } else {
     switch (message.getId()) {
       case 19301:
         {
           final UIShowPopupInfosMessage msg = (UIShowPopupInfosMessage) message;
           boolean ok = false;
           if (this.m_popupDialog == null || this.m_fieldProvider == null) {
             MessageScheduler.getInstance().removeAllClocks(this);
             return false;
           }
           if (this.m_fieldProvider instanceof SpellLevel
               && msg.getContent() instanceof SpellLevel) {
             final SpellLevel spellLevel1 = (SpellLevel) this.m_fieldProvider;
             final SpellLevel spellLevel2 = (SpellLevel) msg.getContent();
             ok = (spellLevel1.getSpell().getId() == spellLevel2.getSpell().getId());
           } else {
             ok = this.m_fieldProvider.equals(msg.getContent());
           }
           if (ok) {
             this.m_cancelTimedPop = !XulorActions.closePopup(null, this.m_popupDialog);
             PropertiesProvider.getInstance().removeProperty(this.m_property);
           }
           return false;
         }
       case 19300:
         {
           final UIShowPopupInfosMessage msg = (UIShowPopupInfosMessage) message;
           this.m_fieldProvider = msg.getContent();
           if (this.m_fieldProvider == null) {
             return false;
           }
           if (msg.getIntValue() > 0) {
             this.m_cancelTimedPop = false;
             MessageScheduler.getInstance().addClock(this, msg.getIntValue(), -1, 1);
           } else {
             this.popup();
           }
           return false;
         }
       default:
         {
           return true;
         }
     }
   }
 }
 public void addMessage(Message message) {
   data.add(message);
   Message last = data.get(data.size() - 1);
   if (last.getText().length() > MESSAGE_LENGTH) {
     System.out.println(RED + "WARNING: long message (more than 140 symbols)." + END);
   }
   System.out.println("Successfully added: " + last.getFormattedMessage());
   log("ADD " + last.getId() + " " + last.getAuthor() + " " + last.getText());
   saveMessagesToJsonFile(MESSAGES_EXTERNAL_STORAGE);
 }
        @Override
        public void onCharacteristicWrite(
            BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {

          if (messageQueue.size() > 0) {
            Message m = messageQueue.getFirst();
            messageQueue.removeFirst();
            callFunctionByMessage(m);
            System.out.println("Activate Function on Write: " + m.getId());
          }
        }
  public void runHibernate() {
    // ############################################################################
    Session session = HibernateUtil.getSessionFactory().openSession();
    Transaction tx = session.beginTransaction();
    Message message = new Message("Hello World");
    session.save(message);
    tx.commit();
    session.close();
    // ############################################################################
    Session secondSession = HibernateUtil.getSessionFactory().openSession();
    Transaction secondTransaction = secondSession.beginTransaction();
    List messages = secondSession.createQuery("from Message m order by m.text asc").list();
    System.out.println(messages.size() + " message(s) found:");
    for (Iterator iter = messages.iterator(); iter.hasNext(); ) {
      Message loadedMsg = (Message) iter.next();
      System.out.println(loadedMsg.getText());
    }
    secondTransaction.commit();
    secondSession.close();
    // ############################################################################
    Session thirdSession = HibernateUtil.getSessionFactory().openSession();
    Transaction thirdTransaction = thirdSession.beginTransaction();
    // message.getId() holds the identifier value of the first message
    Message loadedMessage = (Message) thirdSession.get(Message.class, message.getId());
    loadedMessage.setText("Greetings Earthling");
    loadedMessage.setNextMessage(new Message("Take me to your leader (please)"));
    thirdTransaction.commit();
    thirdSession.close();
    // ############################################################################
    // Final unit of work (just repeat the query)
    // TODO: You can move this query into the thirdSession before the
    // commit, makes more sense!
    Session fourthSession = HibernateUtil.getSessionFactory().openSession();
    Transaction fourthTransaction = fourthSession.beginTransaction();
    messages = fourthSession.createQuery("from Message m order by m.text asc").list();
    System.out.println(messages.size() + " message(s) found:");
    for (Iterator iter = messages.iterator(); iter.hasNext(); ) {
      Message loadedMsg = (Message) iter.next();
      System.out.println(loadedMsg.getText());
    }
    fourthTransaction.commit();
    fourthSession.close();

    // Shutting down the application
    HibernateUtil.shutdown();
  }
Exemple #6
0
  public void announce(long anId) {
    //
    // Announcement an = announcementMgr.getAnnouncementById(anId);

    try {
      String tweet = "";

      Message msg = msgMgr.generateMessageForAnnouncement(anId);
      tweet = msg.getTextWithParametersAdded();
      announcementMgr.updateSetMessage(anId, tweet, msg.getId());
      logger.info(getScreenName() + " is tweeting :" + tweet);
      tweet(tweet);
    } catch (TwitterException e) {
      ExceptionUtil.getInstance().handleError(e);
    } catch (Exception e) {
      logger.error("Error", e);
    }
  }
Exemple #7
0
  public void reply(long anId, long statusId) throws Exception {

    Announcement an = announcementMgr.getAnnouncementById(anId);

    Announcer customer = announcerMgr.getAnnouncer(an.getCustomerId());

    if (customer == null) {

      throw new Exception("Customer not found for announcement: " + an.getId());
    }
    // Product product = productMgr.getProductById(an.getProductId());
    String cause = announcementMgr.getAnnouncementReasonStatusText(anId);

    // tweey check
    String customerName = customer.getName();
    String tweet = "";
    Message msg = msgMgr.generateMessageForAnnouncement(an.getId());
    tweet = msg.getTextWithParametersAdded();
    announcementMgr.updateSetMessage(an.getId(), tweet, msg.getId());
    //
    // logger.info(getScreenName() + " is following " + customerName +
    // " before replying...");
    // follow(an.getCustomerId());

    try {

      long tweetId = -1;
      logger.info(
          getScreenName()
              + " is replying "
              + customerName
              + " : "
              + tweet
              + "\nBecause of: @"
              + customerName
              + ":"
              + cause);
      tweetId = reply(tweet, statusId);
      announcementMgr.updateSetTweetId(anId, tweetId);

    } catch (TwitterException e) {
      ExceptionUtil.getInstance().handleError(e);
    }
  }
 @Override
 public boolean onMessage(final Message message) {
   switch (message.getId()) {
     case 5240:
       {
         final WalletUpdateMessage updateMessage = (WalletUpdateMessage) message;
         WakfuGameEntity.getInstance()
             .getLocalPlayer()
             .getOwnedDimensionalBag()
             .getWallet()
             .setAmountOfCash(updateMessage.getAmountOfCash());
         return false;
       }
     default:
       {
         return true;
       }
   }
 }
 @Override
 public boolean onMessage(final Message message) {
   switch (message.getId()) {
     case 2050:
       {
         final boolean success =
             NetCharacterChoiceFrame.onCharacterSelectionResult(
                 (CharacterSelectionResultMessage) message, this);
         if (!success) {
           WakfuProgressMonitorManager.getInstance().done();
           WakfuGameEntity.getInstance().removeFrame(this);
           NetCharacterChoiceFrame.getInstance().enableLoadUI(true);
           WakfuGameEntity.getInstance().pushFrame(NetCharacterChoiceFrame.getInstance());
         }
         return false;
       }
     case 2054:
       {
         final CharacterCreationResultMessage msg = (CharacterCreationResultMessage) message;
         NetCharacterCreationFrame.m_logger.info(
             (Object)
                 ("R\u00e9sultat de la cr\u00e9ation de perso : succes="
                     + msg.isCreationSuccessful()
                     + ", code="
                     + msg.getCreationCode()));
         if (msg.isCreationSuccessful()) {
           WakfuProgressMonitorManager.getInstance()
               .getProgressMonitor(true)
               .beginTask(WakfuTranslator.getInstance().getString("loadingWorld.progress"), 0);
         } else {
           WakfuProgressMonitorManager.getInstance().done();
           displayNameError(msg.getCreationCode());
           CharacterCreationDialogActions.setCreateCharacterFlag(false);
         }
         return false;
       }
     default:
       {
         return true;
       }
   }
 }
 @Override
 public void onCharacteristicChanged(
     BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic) {
   // this will get called anytime you perform a read or write characteristic operation
   if (characteristic.getUuid().equals(UUID_HUM_DATA)) {
     calculateHumidity(characteristic, gatt);
   } else if (characteristic.getUuid().equals(UUID_ACC_DATA)) {
     calculateAcceleration(characteristic, gatt);
   } else if (characteristic.getUuid().equals(UUID_SENSI_HUM_DATA)) {
     calculateHumSensi(characteristic, gatt);
   } else if (characteristic.getUuid().equals(UUID_SENSI_TEMP_DATA)) {
     calculateTempSensi(characteristic, gatt);
   }
   if (messageQueue.size() > 0) {
     Message m = messageQueue.getFirst();
     messageQueue.removeFirst();
     callFunctionByMessage(m);
     System.out.println("Activate Function on Change: " + m.getId());
   }
 }
 @Override
 public boolean onMessage(final Message message) {
   switch (message.getId()) {
     case 19070:
       {
         this.askToCloseRequest();
         return false;
       }
     case 19071:
       {
         final AbstractUIMessage msg = (AbstractUIMessage) message;
         final byte closedReason = msg.getByteValue();
         final int idPrivate = ChatWindowManager.getInstance().getModeratorWindowId();
         String translatorKey = "contactModerator.closed";
         switch (closedReason) {
           case 4:
             {
               translatorKey = "contactModerator.closed";
               break;
             }
           case 5:
             {
               translatorKey = "contactModerator.disconnected";
               break;
             }
         }
         final ChatMessage chatMessage =
             new ChatMessage(WakfuTranslator.getInstance().getString(translatorKey));
         chatMessage.setPipeDestination(3);
         chatMessage.setWindowId(idPrivate);
         ChatManager.getInstance().pushMessage(chatMessage);
         return this.m_isRunning = false;
       }
     default:
       {
         return true;
       }
   }
 }
 @Override
 public void onServicesDiscovered(final BluetoothGatt gatt, final int status) {
   // this will get called after the client initiates a
   // BluetoothGatt.discoverServices() call
   System.out.println("Services Discovered!");
   services = gatt.getServices();
   System.out.println("Anzahl Services: " + services.size());
   for (int i = 0; i < services.size(); i++) {
     BluetoothGattService s = services.get(i);
     if (s.getUuid().equals(UUID_HUM_SERV)) {
       Message m10 = new Message(10, gatt.getDevice().getAddress());
       Message m20 = new Message(20, gatt.getDevice().getAddress());
       messageQueue.add(m10);
       messageQueue.add(m20);
     } else if (s.getUuid().equals(UUID_ACC_SERV)) {
       Message m11 = new Message(11, gatt.getDevice().getAddress());
       Message m21 = new Message(21, gatt.getDevice().getAddress());
       messageQueue.add(m11);
       messageQueue.add(m21);
     } else if (s.getUuid().equals(UUID_SENSI_HUM_SERV)) {
       Message m30 = new Message(30, gatt.getDevice().getAddress());
       messageQueue.add(m30);
     } else if (s.getUuid().equals(UUID_SENSI_TEMP_SERV)) {
       Message m31 = new Message(31, gatt.getDevice().getAddress());
       messageQueue.add(m31);
     }
   }
   /**
    * This is a self-contained function for turning on the magnetometer sensor. It must be
    * called AFTER the onServicesDiscovered callback is received.
    */
   if (messageQueue.size() > 0) {
     Message m = messageQueue.getFirst();
     messageQueue.removeFirst();
     callFunctionByMessage(m);
     System.out.println("Activate Function on Services: " + m.getId());
   }
 }
Exemple #13
0
  /**
   * Updates the unread state of all messages in the conversation. Persists the change to the
   * database and cache, and also updates the unread counts for the affected items' {@link Folder}s
   * and {@link Tag}s appropriately.
   *
   * <p>Messages in the conversation are omitted from this operation if one or more of the following
   * applies:
   *
   * <ul>
   *   <li>The caller lacks {@link ACL#RIGHT_WRITE} permission on the <code>Message</code>.
   *   <li>The caller has specified a {@link MailItem.TargetConstraint} that explicitly excludes the
   *       <code>Message</code>.
   *   <li>The caller has specified the maximum change number they know about, and the
   *       (modification/content) change number on the <code>Message</code> is greater.
   * </ul>
   *
   * As a result of all these constraints, no messages may actually be marked read/unread.
   *
   * @perms {@link ACL#RIGHT_WRITE} on all the messages
   */
  @Override
  void alterUnread(boolean unread) throws ServiceException {
    markItemModified(Change.MODIFIED_UNREAD);

    boolean excludeAccess = false;

    // Decrement the in-memory unread count of each message.  Each message will
    // then implicitly decrement the unread count for its conversation, folder
    // and tags.
    TargetConstraint tcon = mMailbox.getOperationTargetConstraint();
    List<Integer> targets = new ArrayList<Integer>();
    for (Message msg : getMessages()) {
      // skip messages that don't need to be changed, or that the client can't modify, doesn't know
      // about, or has explicitly excluded
      if (msg.isUnread() == unread) {
        continue;
      } else if (!msg.canAccess(ACL.RIGHT_WRITE)) {
        excludeAccess = true;
        continue;
      } else if (!msg.checkChangeID() || !TargetConstraint.checkItem(tcon, msg)) {
        continue;
      }

      int delta = unread ? 1 : -1;
      msg.updateUnread(delta, msg.isTagged(Flag.ID_FLAG_DELETED) ? delta : 0);
      msg.mData.metadataChanged(mMailbox);
      targets.add(msg.getId());
    }

    // mark the selected messages in this conversation as read in the database
    if (targets.isEmpty()) {
      if (excludeAccess)
        throw ServiceException.PERM_DENIED("you do not have sufficient permissions");
    } else {
      DbMailItem.alterUnread(mMailbox, targets, unread);
    }
  }
 @Override
 public void run() {
   sending: // Label so that, if needed, we can completely kill the while loop from inside the
            // nested loop.
   while (sender.alive) {
     Queue<Task> queue = sender.getQueue();
     while (sender.alive && !queue.isEmpty()) {
       Long messageLimit = sender.api.getMessageLimit(sender.ratelimitIdentifier);
       if (messageLimit != null) {
         try {
           Thread.sleep(messageLimit - System.currentTimeMillis());
         } catch (InterruptedException e) {
           JDAImpl.LOG.log(e);
         }
       }
       Task task = queue.peek();
       Message msg = task.message;
       Requester.Response response;
       if (sender.api.getTextChannelById(msg.getChannelId()) == null
           && sender.api.getPrivateChannelById(msg.getChannelId()) == null) {
         // We no longer have access to the MessageChannel that this message is queued to
         // send to. This is most likely because it was deleted.
         AsyncMessageSender.stop(sender.api, sender.ratelimitIdentifier);
         break sending;
       }
       if (task.isEdit) {
         response =
             sender
                 .api
                 .getRequester()
                 .patch(
                     Requester.DISCORD_API_PREFIX
                         + "channels/"
                         + msg.getChannelId()
                         + "/messages/"
                         + msg.getId(),
                     new JSONObject().put("content", msg.getRawContent()));
       } else {
         response =
             sender
                 .api
                 .getRequester()
                 .post(
                     Requester.DISCORD_API_PREFIX
                         + "channels/"
                         + msg.getChannelId()
                         + "/messages",
                     new JSONObject()
                         .put("content", msg.getRawContent())
                         .put("tts", msg.isTTS()));
       }
       if (response.responseText == null) {
         JDAImpl.LOG.debug(
             "Error sending async-message (returned null-text)... Retrying after 1s");
         sender.api.setMessageTimeout(sender.ratelimitIdentifier, 1000);
       } else if (!response.isRateLimit()) // success/unrecoverable error
       {
         queue.poll(); // remove from queue
         try {
           if (response.isOk()) {
             if (task.callback != null)
               task.callback.accept(
                   new EntityBuilder(sender.api).createMessage(response.getObject()));
           } else {
             // if response didn't have id, sending failed (due to permission/blocked pm,...
             JDAImpl.LOG.fatal(
                 "Could not send/update async message to channel: "
                     + msg.getChannelId()
                     + ". Discord-response: "
                     + response.toString());
             if (task.callback != null) task.callback.accept(null);
           }
         } catch (JSONException ex) {
           // could not generate message from json
           JDAImpl.LOG.log(ex);
         } catch (IllegalArgumentException ex) {
           JDAImpl.LOG.log(ex);
         }
       } else {
         sender.api.setMessageTimeout(
             sender.ratelimitIdentifier, response.getObject().getLong("retry_after"));
       }
       if (queue.isEmpty()) {
         queue = sender.getQueue();
       }
     }
     sender.waitNew();
   }
 }
Exemple #15
0
  public static void main(String[] args) {
    try {
      // connect to mongoDB, ip and port number
      Mongo mongo = new Mongo("127.0.0.1", 27017);

      // get database from MongoDB,
      // if database doesn't exists, mongoDB will create it automatically
      DB db = mongo.getDB("yourdb");

      // Getting A List Of Collections
      Set<String> collections = db.getCollectionNames();

      for (String s : collections) {
        System.out.println(s);
      }

      // Get collection from MongoDB, database named "yourDB"
      // if collection doesn't exists, mongoDB will create it automatically
      DBCollection collection = db.getCollection("yourCollection");

      // create a document to store key and value
      DBObject document = new BasicDBObject();
      document.put("id", 1001);
      document.put("msg", "hello world mongoDB in Java");

      // save it into collection named "yourCollection"
      collection.insert(document);

      // search query
      DBObject searchQuery = new BasicDBObject();
      searchQuery.put("id", 1001);

      // query it
      DBCursor cursor = collection.find(searchQuery);

      // loop over the cursor and display the retrieved result
      while (cursor.hasNext()) {
        System.out.println("Our collection after putting document here: " + cursor.next());
      }

      // Counting Documents in Collection
      System.out.println("Elements in collection " + collection.getCount());

      // update document (just replase exist - it is normal practise)
      DBObject updatedDocument = new BasicDBObject();
      updatedDocument.put("id", 1001);
      updatedDocument.put("msg", "hello world mongoDB in Java updated");
      collection.update(new BasicDBObject().append("id", 1001), updatedDocument);

      // query it
      DBCursor cursorAfterUpdate = collection.find(searchQuery);

      // loop over the cursor and display the retrieved result
      while (cursorAfterUpdate.hasNext()) {
        System.out.println("Our collection after update: " + cursorAfterUpdate.next());
      }

      // Counting Documents in Collection
      System.out.println("Elements in collection " + collection.getCount());

      // Map to object
      Message message = new Message();
      message.setId((Integer) document.get("id"));
      message.setMessage((String) document.get("msg"));

      System.out.println("Id putted in object: " + message.getId());
      System.out.println("Message putted in object: " + message.getMessage());

      // Remove document from collection
      DBObject doc = collection.findOne(); // get first document
      collection.remove(doc);

      // query it
      DBCursor cursorAfterDelete = collection.find(searchQuery);

      // loop over the cursor and display the retrieved result
      while (cursorAfterDelete.hasNext()) {
        System.out.println("Our collection after delete: " + cursorAfterDelete.next());
      }

      // Counting Documents in Collection
      System.out.println("Elements in collection " + collection.getCount());

      // Close connection to db
      mongo.close();

      System.out.println("Done");

    } catch (UnknownHostException e) {
      e.printStackTrace();
    } catch (MongoException e) {
      e.printStackTrace();
    }
  }
  private void vanish(MessageContext context, String args) {
    Message message = context.getMessage();
    if (args.isEmpty()) {
      return;
    }

    try {
      final int cap = 100;
      final int capPages = 10;
      String[] vals = args.split(" ");
      String userId;
      int numMsgs;
      if (vals.length == 2) {
        User user = findUser(context, vals[0]);
        userId = user.getId();
        if (user == NO_USER) {
          userId = vals[0];
        }
        numMsgs = Math.max(1, Math.min(cap, Integer.parseInt(vals[1])));
      } else if (vals.length == 1) {
        userId = "";
        numMsgs = Math.max(1, Math.min(cap, Integer.parseInt(vals[0])));
      } else {
        userId = "";
        numMsgs = 10;
      }

      int limit = numMsgs;
      String before = message.getId();
      //  Limit search to 10 pages (500 msgs)
      //  Instead of deleting them when we find them, we build a list instead
      List<String> messagesToDelete = new ArrayList<>(limit);
      for (int k = 0; k < capPages && limit > 0; k++) {
        Map<String, String> headers = new HashMap<>();
        headers.put(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType());
        headers.put(HttpHeaders.AUTHORIZATION, apiClient.getToken());
        Map<String, Object> queryParams = new HashMap<>();
        queryParams.put("limit", 50);
        queryParams.put("before", before);
        HttpResponse<JsonNode> response =
            Unirest.get(ApiConst.CHANNELS_ENDPOINT + message.getChannelId() + "/messages")
                .headers(headers)
                .queryString(queryParams)
                .asJson();
        JSONArray ret = response.getBody().getArray();
        if (userId.isEmpty()) {
          for (int i = 0; i < ret.length() && limit > 0; i++) {
            JSONObject msg = ret.getJSONObject(i);
            String mid = msg.getString("id");
            before = mid;
            messagesToDelete.add(mid);
            limit--;
          }
        } else {
          for (int i = 0; i < ret.length() && limit > 0; i++) {
            JSONObject msg = ret.getJSONObject(i);
            String mid = msg.getString("id");
            JSONObject msgUsr = msg.getJSONObject("author");
            String uid = msgUsr.getString("id");
            before = mid;
            if (userId.equals(uid)) {
              messagesToDelete.add(mid);
              limit--;
            }
          }
        }
      }
      LOGGER.info("Deleting {} messages", messagesToDelete.size());
      //  Using bulk delete endpoint
      apiClient.bulkDeleteMessages(
          context.getChannel().getId(),
          messagesToDelete.toArray(new String[messagesToDelete.size()]));
    } catch (Exception e) {
      LOGGER.warn("Unable to get messages", e);
    }
  }
Exemple #17
0
  /**
   * Tags or untags all messages in the conversation. Persists the change to the database and cache.
   * If the conversation includes at least one unread {@link Message} whose tagged state is
   * changing, updates the {@link Tag}'s unread count appropriately.
   *
   * <p>Messages in the conversation are omitted from this operation if one or more of the following
   * applies:
   *
   * <ul>
   *   <li>The caller lacks {@link ACL#RIGHT_WRITE} permission on the <code>Message</code>.
   *   <li>The caller has specified a {@link MailItem.TargetConstraint} that explicitly excludes the
   *       <code>Message</code>.
   *   <li>The caller has specified the maximum change number they know about, and the
   *       (modification/content) change number on the <code>Message</code> is greater.
   * </ul>
   *
   * As a result of all these constraints, no messages may actually be tagged/untagged.
   *
   * @perms {@link ACL#RIGHT_WRITE} on all the messages
   */
  @Override
  void alterTag(Tag tag, boolean add) throws ServiceException {
    if (tag == null) throw ServiceException.FAILURE("missing tag argument", null);
    if (!add && !isTagged(tag)) return;
    if (tag.getId() == Flag.ID_FLAG_UNREAD)
      throw ServiceException.FAILURE("unread state must be set with alterUnread", null);
    // don't let the user tag things as "has attachments" or "draft"
    if (tag instanceof Flag && (tag.getBitmask() & Flag.FLAG_SYSTEM) != 0)
      throw MailServiceException.CANNOT_TAG(tag, this);

    markItemModified(tag instanceof Flag ? Change.MODIFIED_FLAGS : Change.MODIFIED_TAGS);

    TargetConstraint tcon = mMailbox.getOperationTargetConstraint();
    boolean excludeAccess = false;

    List<Message> msgs = getMessages();
    List<Integer> targets = new ArrayList<Integer>(msgs.size());
    for (Message msg : msgs) {
      // skip messages that don't need to be changed, or that the client can't modify, doesn't know
      // about, or has explicitly excluded
      if (msg.isTagged(tag) == add) {
        continue;
      } else if (!msg.canAccess(ACL.RIGHT_WRITE)) {
        excludeAccess = true;
        continue;
      } else if (!msg.checkChangeID() || !TargetConstraint.checkItem(tcon, msg)) {
        continue;
      } else if (add && !tag.canTag(msg)) {
        throw MailServiceException.CANNOT_TAG(tag, this);
      }

      targets.add(msg.getId());
      msg.tagChanged(tag, add);

      // since we're adding/removing a tag, the tag's unread count may change
      int delta = add ? 1 : -1;
      if (tag.trackUnread() && msg.isUnread())
        tag.updateUnread(delta, isTagged(Flag.ID_FLAG_DELETED) ? delta : 0);

      // if we're adding/removing the \Deleted flag, update the folder and tag "deleted" and
      // "deleted unread" counts
      if (tag.getId() == Flag.ID_FLAG_DELETED) {
        getFolder().updateSize(0, delta, 0);
        // note that Message.updateUnread() calls updateTagUnread()
        if (msg.isUnread()) msg.updateUnread(0, delta);
      }
    }

    if (targets.isEmpty()) {
      if (excludeAccess)
        throw ServiceException.PERM_DENIED("you do not have sufficient permissions");
    } else {
      if (ZimbraLog.mailop.isDebugEnabled()) {
        String operation = add ? "Setting" : "Unsetting";
        ZimbraLog.mailop.debug(
            "%s %s for %s.  Affected ids: %s",
            operation,
            getMailopContext(tag),
            getMailopContext(this),
            StringUtil.join(",", targets));
      }
      recalculateCounts(msgs);
      DbMailItem.alterTag(tag, targets, add);
    }
  }
Exemple #18
0
  /**
   * Moves all the conversation's {@link Message}s to a different {@link Folder}. Persists the
   * change to the database and the in-memory cache. Updates all relevant unread counts, folder
   * sizes, etc.
   *
   * <p>Messages moved to the Trash folder are automatically marked read. Conversations moved to the
   * Junk folder will not receive newly-delivered messages.
   *
   * <p>Messages in the conversation are omitted from this operation if one or more of the following
   * applies:
   *
   * <ul>
   *   <li>The caller lacks {@link ACL#RIGHT_WRITE} permission on the <code>Message</code>.
   *   <li>The caller has specified a {@link MailItem.TargetConstraint} that explicitly excludes the
   *       <code>Message</code>.
   *   <li>The caller has specified the maximum change number they know about, and the
   *       (modification/content) change number on the <code>Message</code> is greater.
   * </ul>
   *
   * As a result of all these constraints, no messages may actually be moved.
   *
   * @perms {@link ACL#RIGHT_INSERT} on the target folder, {@link ACL#RIGHT_DELETE} on the messages'
   *     source folders
   */
  @Override
  boolean move(Folder target) throws ServiceException {
    if (!target.canContain(TYPE_MESSAGE)) throw MailServiceException.CANNOT_CONTAIN();
    markItemModified(Change.UNMODIFIED);

    List<Message> msgs = getMessages();
    TargetConstraint tcon = mMailbox.getOperationTargetConstraint();
    boolean toTrash = target.inTrash();
    int oldUnread = 0;
    for (Message msg : msgs) if (msg.isUnread()) oldUnread++;
    // if mData.unread is wrong, what to do?  right now, always use the calculated value
    mData.unreadCount = oldUnread;

    boolean excludeAccess = false;

    List<Integer> markedRead = new ArrayList<Integer>();
    List<Message> moved = new ArrayList<Message>();
    List<Message> indexUpdated = new ArrayList<Message>();

    for (Message msg : msgs) {
      Folder source = msg.getFolder();

      // skip messages that don't need to be moved, or that the client can't modify, doesn't know
      // about, or has explicitly excluded
      if (source.getId() == target.getId()) {
        continue;
      } else if (!source.canAccess(ACL.RIGHT_DELETE)) {
        excludeAccess = true;
        continue;
      } else if (target.getId() != Mailbox.ID_FOLDER_TRASH
          && target.getId() != Mailbox.ID_FOLDER_SPAM
          && !target.canAccess(ACL.RIGHT_INSERT)) {
        excludeAccess = true;
        continue;
      } else if (!msg.checkChangeID() || !TargetConstraint.checkItem(tcon, msg)) {
        continue;
      }

      boolean isDeleted = msg.isTagged(Flag.ID_FLAG_DELETED);
      if (msg.isUnread()) {
        if (!toTrash || msg.inTrash()) {
          source.updateUnread(-1, isDeleted ? -1 : 0);
          target.updateUnread(1, isDeleted ? 1 : 0);
        } else {
          // unread messages moved from Mailbox to Trash need to be marked read:
          //   update cached unread counts (message, conversation, folder, tags)
          msg.updateUnread(-1, isDeleted ? -1 : 0);
          //   note that we need to update this message in the DB
          markedRead.add(msg.getId());
        }
      }

      // moved an item out of the spam folder, need to index it
      if (msg.inSpam() && !target.inSpam()) {
        if (msg.isIndexed() && msg.getIndexId() != -1) {
          msg.indexIdChanged(msg.getId());
          indexUpdated.add(msg);
        }
      }

      // if a draft is being moved to Trash then remove any "send-later" info from it
      if (toTrash && msg.isDraft()) msg.setDraftAutoSendTime(0);

      // handle folder message counts
      source.updateSize(-1, isDeleted ? -1 : 0, -msg.getTotalSize());
      target.updateSize(1, isDeleted ? 1 : 0, msg.getTotalSize());

      moved.add(msg);
      msg.folderChanged(target, 0);
    }

    // mark unread messages moved from Mailbox to Trash/Spam as read in the DB
    if (!markedRead.isEmpty()) DbMailItem.alterUnread(target.getMailbox(), markedRead, false);

    if (moved.isEmpty()) {
      if (excludeAccess)
        throw ServiceException.PERM_DENIED("you do not have sufficient permissions");
    } else {
      // moving a conversation to spam closes it
      if (target.inSpam()) detach();
      if (ZimbraLog.mailop.isInfoEnabled()) {
        StringBuilder ids = new StringBuilder();
        for (int i = 0; i < moved.size(); i++) {
          if (i > 0) {
            ids.append(',');
          }
          ids.append(moved.get(i).getId());
        }
        ZimbraLog.mailop.info(
            "Moving %s to %s.  Affected message ids: %s.",
            getMailopContext(this), getMailopContext(target), ids);
      }
      DbMailItem.setFolder(moved, target);

      if (!indexUpdated.isEmpty()) {
        DbMailItem.setIndexIds(mMailbox, indexUpdated);
        for (Message msg : indexUpdated) {
          mMailbox.queueForIndexing(msg, false, null);
        }
      }
    }

    return !moved.isEmpty();
  }
Exemple #19
0
 /**
  * Deletes a Message from the queue.
  *
  * @param msg The message to delete.
  * @throws HTTPException If the IronMQ service returns a status other than 200 OK.
  * @throws IOException If there is an error accessing the IronMQ server.
  */
 public void deleteMessage(Message msg) throws IOException {
   deleteMessage(msg.getId());
 }