Example #1
0
 private int getSendType() {
   int sendType = Attachments.SEND_TYPE_NOTSET;
   if ((msgContext != null) && (msgContext.getService() != null)) {
     sendType = msgContext.getService().getSendType();
   }
   return sendType;
 }
 @Test
 public void testGetProperty() {
   Message m = new MessageImpl();
   m.put("a", "b");
   MessageContext mc = new MessageContextImpl(m);
   assertEquals("b", mc.get("a"));
   assertNull(mc.get("b"));
 }
 @Test
 public void testServletConfig() {
   Message m = createMessage();
   MessageContext mc = new MessageContextImpl(m);
   ServletConfig request = EasyMock.createMock(ServletConfig.class);
   m.put(AbstractHTTPDestination.HTTP_CONFIG, request);
   assertSame(request.getClass(), mc.getServletConfig().getClass());
   assertSame(request.getClass(), mc.getContext(ServletConfig.class).getClass());
 }
 @Test
 public void testGetPropertyFromExchange() {
   Message m = new MessageImpl();
   Exchange ex = new ExchangeImpl();
   ex.put("a", "b");
   ex.setInMessage(m);
   MessageContext mc = new MessageContextImpl(m);
   assertEquals("b", mc.get("a"));
   assertNull(mc.get("b"));
 }
 @Test
 public void testHttpResponse() {
   Message m = createMessage();
   MessageContext mc = new MessageContextImpl(m);
   HttpServletResponse request = EasyMock.createMock(HttpServletResponse.class);
   m.put(AbstractHTTPDestination.HTTP_RESPONSE, request);
   HttpServletResponseFilter filter = (HttpServletResponseFilter) mc.getHttpServletResponse();
   assertSame(request.getClass(), filter.getResponse().getClass());
   filter = (HttpServletResponseFilter) mc.getContext(HttpServletResponse.class);
   assertSame(request.getClass(), filter.getResponse().getClass());
 }
  @Test
  public void testGetPropertyFromOtherMessage() {
    Message m1 = new MessageImpl();
    Message m2 = new MessageImpl();
    m2.put("a", "b");

    Exchange ex = new ExchangeImpl();
    ex.setInMessage(m1);
    ex.setOutMessage(m2);
    MessageContext mc = new MessageContextImpl(m1);
    assertEquals("b", mc.get("a"));
    assertNull(mc.get("b"));
  }
 private void fillAckMutation(MessageContext context, MutationBatch mb) {
   queue.stats.incAckMessageCount();
   Message message = context.getMessage();
   // Token refers to the timeout event.  If 0 (i.e. no) timeout was specified
   // then the token will not exist
   if (message.getToken() != null) {
     MessageQueueEntry entry = MessageQueueEntry.newBusyEntry(message);
     // Remove timeout entry from the queue
     mb.withRow(queue.queueColumnFamily, queue.getShardKey(message)).deleteColumn(entry);
     // Remove entry lookup from the key, if one exists
     if (message.hasKey()) {
       mb.withRow(
               queue.keyIndexColumnFamily,
               queue.getCompositeKey(queue.getName(), message.getKey()))
           .putEmptyColumn(
               MessageMetadataEntry.newMessageId(
                   queue.getCompositeKey(queue.getShardKey(message), entry.getMessageId())),
               queue.metadataDeleteTTL);
       if (message.isKeepHistory()) {
         MessageHistory history = context.getHistory();
         if (history.getStatus() == MessageStatus.RUNNING) {
           history.setStatus(MessageStatus.DONE);
         }
         history.setEndTime(
             TimeUnit.MICROSECONDS.convert(System.currentTimeMillis(), TimeUnit.MILLISECONDS));
         try {
           mb.withRow(queue.historyColumnFamily, message.getKey())
               .putColumn(
                   history.getToken(),
                   queue.serializeToString(context.getHistory()),
                   queue.metadata.getHistoryTtl()); // TTL
         } catch (Exception e) {
           LOG.warn("Error serializing message history for " + message.getKey(), e);
         }
       }
     }
     // Run hooks
     for (MessageQueueHooks hook : queue.hooks) {
       hook.beforeAckMessage(message, mb);
     }
   }
   if (context.getNextMessage() != null) {
     try {
       queue.fillMessageMutation(mb, context.getNextMessage());
     } catch (MessageQueueException e) {
       LOG.warn("Error filling nextMessage for " + message.getKey(), e);
     }
   }
 }
Example #8
0
  private static synchronized boolean isAttachmentSupportEnabled(MessageContext mc) {
    if (checkForAttachmentSupport) {
      // aviod testing and possibly failing everytime.
      checkForAttachmentSupport = false;
      try {
        // Get the default setting from AxisProperties
        String attachImpName =
            AxisProperties.getProperty(
                AxisEngine.PROP_ATTACHMENT_IMPLEMENTATION, AxisEngine.DEFAULT_ATTACHMENT_IMPL);
        // override the default with any changes specified in the engine configuration
        if (null != mc) {
          AxisEngine ae = mc.getAxisEngine();
          if (null != ae) {
            attachImpName = (String) ae.getOption(AxisEngine.PROP_ATTACHMENT_IMPLEMENTATION);
          }
        }

        /** Attempt to resolve class name, verify that these are present... */
        ClassUtils.forName("javax.activation.DataHandler");
        ClassUtils.forName("javax.mail.internet.MimeMultipart");

        attachImpl = ClassUtils.forName(attachImpName);

        attachmentSupportEnabled = true;
      } catch (ClassNotFoundException ex) {
        // no support for it, leave mAttachments null.
      } catch (java.lang.NoClassDefFoundError ex) {
        // no support for it, leave mAttachments null.
      } catch (java.lang.SecurityException ex) {
        // no support for it, leave mAttachments null.
      }
      log.debug(Messages.getMessage("attachEnabled") + "  " + attachmentSupportEnabled);
    }
    return attachmentSupportEnabled;
  }
  @Test
  public void testHttpRequest() {
    Message m = createMessage();
    MessageContext mc = new MessageContextImpl(m);
    HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class);
    m.put(AbstractHTTPDestination.HTTP_REQUEST, request);

    assertSame(
        request.getClass(),
        ((HttpServletRequestFilter) mc.getHttpServletRequest()).getRequest().getClass());
    assertSame(
        request.getClass(),
        ((HttpServletRequestFilter) mc.getContext(HttpServletRequest.class))
            .getRequest()
            .getClass());
  }
  @SuppressWarnings("unchecked")
  @Test
  public void testContextResolver() {
    ContextResolver<JAXBContext> resolver = new CustomContextResolver();
    ProviderFactory factory = ServerProviderFactory.getInstance();
    factory.registerUserProvider(resolver);

    Message m = new MessageImpl();
    Exchange ex = new ExchangeImpl();
    m.setExchange(ex);
    ex.setInMessage(m);
    Endpoint e = EasyMock.createMock(Endpoint.class);
    e.get(ServerProviderFactory.class.getName());
    EasyMock.expectLastCall().andReturn(factory);
    EasyMock.replay(e);
    ex.put(Endpoint.class, e);
    MessageContext mc = new MessageContextImpl(m);
    ContextResolver<JAXBContext> resolver2 =
        mc.getResolver(ContextResolver.class, JAXBContext.class);
    assertNotNull(resolver2);
    assertSame(resolver2, resolver);
  }
 @Override
 public IMessage onMessage(MessageSeedInfuser message, MessageContext ctx) {
   int x = message.x, y = message.y, z = message.z;
   if (ctx.side.isServer()) {
     TileEntity te = ctx.getServerHandler().playerEntity.worldObj.getTileEntity(x, y, z);
     if (te instanceof TileEntitySeedInfuser) {
       TileEntitySeedInfuser infuser = (TileEntitySeedInfuser) te;
       if (infuser.getStackInSlot(1) != null && infuser.getStackInSlot(1).stackSize > 0) {
         infuser.setInfusing(true);
       }
       int index = infuser.getRecipeIndex();
       if (index != -1) {
         return new MessageSeedInfuser(x, y, z, index);
       }
     }
   } else {
     TileEntity te = FluxedCrystals.proxy.getClientWorld().getTileEntity(x, y, z);
     if (te instanceof TileEntitySeedInfuser) {
       ((TileEntitySeedInfuser) te).setRecipeIndex(message.data);
       te.getWorldObj().markBlockForUpdate(x, y, z);
     }
   }
   return null;
 }
 @Test
 public void testGetRequest() {
   MessageContext mc = new MessageContextImpl(new MessageImpl());
   assertSame(RequestImpl.class, mc.getRequest().getClass());
   assertSame(RequestImpl.class, mc.getContext(Request.class).getClass());
 }
 @Test
 public void testGetHttpHeaders() {
   MessageContext mc = new MessageContextImpl(new MessageImpl());
   assertSame(HttpHeadersImpl.class, mc.getHttpHeaders().getClass());
   assertSame(HttpHeadersImpl.class, mc.getContext(HttpHeaders.class).getClass());
 }
 @Test
 public void testGetUriInfo() {
   MessageContext mc = new MessageContextImpl(new MessageImpl());
   assertSame(UriInfoImpl.class, mc.getUriInfo().getClass());
   assertSame(UriInfoImpl.class, mc.getContext(UriInfo.class).getClass());
 }
  private List<MessageContext> readMessagesInternal(
      String shardName,
      int itemsToPop,
      int lockColumnCount,
      MessageQueueEntry lockColumn,
      ColumnListMutation<MessageQueueEntry> rowMutation,
      MutationBatch m,
      long curTimeMicros)
      throws BusyLockException, MessageQueueException {

    try {
      List<MessageContext> entries = Lists.newArrayList();
      RangeEndpoint re =
          ShardedDistributedMessageQueue.entrySerializer
              .makeEndpoint((byte) MessageQueueEntryType.Message.ordinal(), Equality.EQUAL)
              .append((byte) 0, Equality.EQUAL);
      if (lockColumn != null) {
        re.append(lockColumn.getTimestamp(), Equality.LESS_THAN_EQUALS);
      } else {
        re.append(TimeUUIDUtils.getMicrosTimeUUID(curTimeMicros), Equality.LESS_THAN_EQUALS);
      }

      ColumnList<MessageQueueEntry> result =
          queue
              .keyspace
              .prepareQuery(queue.queueColumnFamily)
              .setConsistencyLevel(queue.consistencyLevel)
              .getKey(shardName)
              .withColumnRange(
                  new RangeBuilder()
                      .setLimit(itemsToPop + (lockColumn == null ? 0 : (lockColumnCount + 1)))
                      .setEnd(re.toBytes())
                      .build())
              .execute()
              .getResult();
      for (Column<MessageQueueEntry> column : result) {
        if (itemsToPop == 0) {
          break;
        }
        MessageQueueEntry entry = column.getName();
        switch (entry.getType()) {
          case Lock:
            // TODO: Track number of locks read and make sure we don't exceed itemsToPop
            // We have the lock
            if (lockColumn != null && entry.getState() == MessageQueueEntryState.Acquired) {
              if (!entry.getTimestamp().equals(lockColumn.getTimestamp())) {
                throw new BusyLockException("Someone else snuck in");
              }
            }
            break;
          case Message:
            {
              try {
                itemsToPop--;
                // First, we always want to remove the old item
                String messageId = queue.getCompositeKey(shardName, entry.getMessageId());
                rowMutation.deleteColumn(entry);
                // Next, parse the message metadata and add a timeout entry
                final Message message = queue.extractMessageFromColumn(column);
                // Update the message state
                if (message != null) {
                  MessageContext context = new MessageContext();
                  context.setMessage(message);
                  // Message has a trigger so we need to figure out if it is an
                  // unfinished repeating trigger and re-add it.
                  if (message.hasTrigger()) {
                    // Read back all messageIds associated with this key and check to see if we have
                    // duplicates.
                    String groupRowKey = queue.getCompositeKey(queue.getName(), message.getKey());
                    try {
                      // Use consistency level
                      ColumnList<MessageMetadataEntry> columns =
                          queue
                              .keyspace
                              .prepareQuery(queue.keyIndexColumnFamily)
                              .getRow(groupRowKey)
                              .withColumnRange(
                                  ShardedDistributedMessageQueue.metadataSerializer
                                      .buildRange()
                                      .greaterThanEquals(
                                          (byte) MessageMetadataEntryType.MessageId.ordinal())
                                      .lessThanEquals(
                                          (byte) MessageMetadataEntryType.MessageId.ordinal())
                                      .build())
                              .execute()
                              .getResult();
                      MessageMetadataEntry mostRecentMessageMetadata = null;
                      long mostRecentTriggerTime = 0;
                      for (Column<MessageMetadataEntry> currMessageEntry : columns) {
                        MessageQueueEntry pendingMessageEntry =
                            MessageQueueEntry.fromMetadata(currMessageEntry.getName());
                        if (currMessageEntry.getTtl() == 0) {
                          long currMessageTriggerTime =
                              pendingMessageEntry.getTimestamp(TimeUnit.MICROSECONDS);
                          // First message we found, so treat as the most recent
                          if (mostRecentMessageMetadata == null) {
                            mostRecentMessageMetadata = currMessageEntry.getName();
                            mostRecentTriggerTime = currMessageTriggerTime;
                          } else {
                            // This message's trigger time is after what we thought was the most
                            // recent.
                            // Discard the previous 'most' recent and accept this one instead
                            if (currMessageTriggerTime > mostRecentTriggerTime) {
                              LOG.warn(
                                  "Need to discard : "
                                      + entry.getMessageId()
                                      + " => "
                                      + mostRecentMessageMetadata.getName());
                              m.withRow(
                                      queue.keyIndexColumnFamily,
                                      queue.getCompositeKey(queue.getName(), message.getKey()))
                                  .putEmptyColumn(
                                      mostRecentMessageMetadata, queue.metadataDeleteTTL);
                              mostRecentTriggerTime = currMessageTriggerTime;
                              mostRecentMessageMetadata = currMessageEntry.getName();
                            } else {
                              LOG.warn(
                                  "Need to discard : "
                                      + entry.getMessageId()
                                      + " => "
                                      + currMessageEntry.getName());
                              m.withRow(
                                      queue.keyIndexColumnFamily,
                                      queue.getCompositeKey(queue.getName(), message.getKey()))
                                  .putEmptyColumn(
                                      currMessageEntry.getName(), queue.metadataDeleteTTL);
                            }
                          }
                        }
                      }
                      if (mostRecentMessageMetadata != null) {
                        if (!mostRecentMessageMetadata.getName().endsWith(entry.getMessageId())) {
                          throw new DuplicateMessageException("Duplicate trigger for " + messageId);
                        }
                      }
                    } catch (NotFoundException e) {
                    } catch (ConnectionException e) {
                      throw new MessageQueueException("Error fetching row " + groupRowKey, e);
                    }
                    // Update the trigger
                    final Message nextMessage;
                    Trigger trigger = message.getTrigger().nextTrigger();
                    if (trigger != null) {
                      nextMessage = message.clone();
                      nextMessage.setTrigger(trigger);
                      context.setNextMessage(nextMessage);
                      if (message.isAutoCommitTrigger()) {
                        queue.fillMessageMutation(m, nextMessage);
                      }
                    }
                  }
                  // Message has a key so we remove this item from the messages by key index.
                  // A timeout item will be added later
                  if (message.hasKey()) {
                    m.withRow(
                            queue.keyIndexColumnFamily,
                            queue.getCompositeKey(queue.getName(), message.getKey()))
                        .putEmptyColumn(
                            MessageMetadataEntry.newMessageId(messageId), queue.metadataDeleteTTL);
                    LOG.debug(
                        "Removing from key  :  "
                            + queue.getCompositeKey(queue.getName(), message.getKey())
                            + " : "
                            + messageId);
                    if (message.isKeepHistory()) {
                      MessageHistory history = context.getHistory();
                      history.setToken(entry.getTimestamp());
                      history.setStartTime(curTimeMicros);
                      history.setTriggerTime(message.getTrigger().getTriggerTime());
                      history.setStatus(MessageStatus.RUNNING);
                      try {
                        m.withRow(queue.historyColumnFamily, message.getKey())
                            .putColumn(
                                entry.getTimestamp(),
                                queue.serializeToString(history),
                                queue.metadata.getHistoryTtl());
                      } catch (Exception e) {
                        LOG.warn("Error serializing history for key '" + message.getKey() + "'", e);
                      }
                    }
                  }
                  // Message has a timeout so we add a timeout event.
                  if (message.getTimeout() > 0) {
                    MessageQueueEntry timeoutEntry =
                        MessageQueueEntry.newMessageEntry(
                            (byte) 0,
                            TimeUUIDUtils.getMicrosTimeUUID(
                                curTimeMicros
                                    + TimeUnit.MICROSECONDS.convert(
                                        message.getTimeout(), TimeUnit.SECONDS)
                                    + (queue.counter.incrementAndGet() % 1000)),
                            MessageQueueEntryState.Busy);
                    message.setToken(timeoutEntry.getTimestamp());
                    message.setRandom(timeoutEntry.getRandom());
                    m.withRow(queue.queueColumnFamily, queue.getShardKey(message))
                        .putColumn(
                            timeoutEntry,
                            column.getStringValue(),
                            queue.metadata.getRetentionTimeout());
                    MessageMetadataEntry messageIdEntry =
                        MessageMetadataEntry.newMessageId(
                            queue.getCompositeKey(
                                queue.getShardKey(message), timeoutEntry.getMessageId()));
                    // Add the timeout column to the key
                    if (message.hasKey()) {
                      m.withRow(
                              queue.keyIndexColumnFamily,
                              queue.getCompositeKey(queue.getName(), message.getKey()))
                          .putEmptyColumn(messageIdEntry, queue.metadata.getRetentionTimeout());
                    }
                    context.setAckMessageId(messageIdEntry.getName());
                  } else {
                    message.setToken(null);
                  }
                  // Update some stats
                  switch (entry.getState()) {
                    case Waiting:
                      queue.stats.incProcessCount();
                      break;
                    case Busy:
                      queue.stats.incReprocessCount();
                      break;
                    default:
                      LOG.warn("Unknown message state: " + entry.getState());
                      // TODO:
                      break;
                  }
                  entries.add(context);
                } else {
                  queue.stats.incInvalidMessageCount();
                  // TODO: Add to poison queue
                }
              } catch (DuplicateMessageException e) {
                // OK to ignore this error.  All the proper columns will have been deleted in the
                // batch.
              }
              break;
            }
          default:
            {
              // TODO: Error: Unknown type
              break;
            }
        }
      }
      return entries;
    } catch (BusyLockException e) {
      queue.stats.incLockContentionCount();
      throw e;
    } catch (Exception e) {
      throw new MessageQueueException("Error processing queue shard : " + shardName, e);
    } finally {
      try {
        m.execute();
      } catch (Exception e) {
        throw new MessageQueueException("Error processing queue shard : " + shardName, e);
      }
    }
  }
 @Test
 public void testGetSecurityContext() {
   MessageContext mc = new MessageContextImpl(new MessageImpl());
   assertSame(SecurityContextImpl.class, mc.getSecurityContext().getClass());
   assertSame(SecurityContextImpl.class, mc.getContext(SecurityContext.class).getClass());
 }
 @Test
 public void testProviders() {
   MessageContext mc = new MessageContextImpl(new MessageImpl());
   assertSame(ProvidersImpl.class, mc.getProviders().getClass());
   assertSame(ProvidersImpl.class, mc.getContext(Providers.class).getClass());
 }
 @Test
 public void testNoContext() {
   MessageContext mc = new MessageContextImpl(createMessage());
   assertNull(mc.getContext(Message.class));
 }