Exemplo n.º 1
0
 public long removeLeavers(MessageID messageID, Collection<Address> leavers) {
   MessageInfo messageInfo = sentMessages.get(messageID);
   if (messageInfo != null && messageInfo.removeLeavers(leavers)) {
     return messageInfo.getAndMarkFinalSent();
   }
   return NOT_READY;
 }
Exemplo n.º 2
0
  public static void main(String... args) throws Exception {
    jtreg = (System.getProperty("test.src") != null);
    File tmpDir;
    if (jtreg) {
      // use standard jtreg scratch directory: the current directory
      tmpDir = new File(System.getProperty("user.dir"));
    } else {
      tmpDir =
          new File(
              System.getProperty("java.io.tmpdir"),
              MessageInfo.class.getName()
                  + (new SimpleDateFormat("yyMMddHHmmss")).format(new Date()));
    }
    Example.setTempDir(tmpDir);
    Example.Compiler.factory = new ArgTypeCompilerFactory();

    MessageInfo mi = new MessageInfo();

    try {
      if (mi.run(args)) return;
    } finally {
      /* VERY IMPORTANT NOTE. In jtreg mode, tmpDir is set to the
       * jtreg scratch directory, which is the current directory.
       * In case someone is faking jtreg mode, make sure to only
       * clean tmpDir when it is reasonable to do so.
       */
      if (tmpDir.isDirectory() && tmpDir.getName().startsWith(MessageInfo.class.getName())) {
        if (clean(tmpDir)) tmpDir.delete();
      }
    }

    if (jtreg) throw new Exception(mi.errors + " errors occurred");
    else System.exit(1);
  }
Exemplo n.º 3
0
 /**
  * Add a propose from a member in destination set
  *
  * @param messageID the message ID
  * @param from the originator of the propose
  * @param sequenceNumber the proposed sequence number
  * @return NOT_READY if the final sequence number is not know, or the final sequence number
  */
 public long addPropose(MessageID messageID, Address from, long sequenceNumber) {
   MessageInfo messageInfo = sentMessages.get(messageID);
   if (messageInfo != null && messageInfo.addPropose(from, sequenceNumber)) {
     return messageInfo.getAndMarkFinalSent();
   }
   return NOT_READY;
 }
Exemplo n.º 4
0
 /**
  * Add a new message sent
  *
  * @param messageID the message ID
  * @param destinations the destination set
  * @param initialSequenceNumber the initial sequence number
  * @param deliverToMyself true if *this* member is in destination sent, false otherwise
  */
 public void addNewMessageToSend(
     MessageID messageID,
     Collection<Address> destinations,
     long initialSequenceNumber,
     boolean deliverToMyself) {
   MessageInfo messageInfo = new MessageInfo(destinations, initialSequenceNumber, deliverToMyself);
   if (deliverToMyself) {
     messageInfo.setProposeReceived(messageID.getAddress());
   }
   sentMessages.put(messageID, messageInfo);
 }
Exemplo n.º 5
0
 @Test
 public void testOutput() throws Exception {
   assertFalse(operationInfo.hasOutput());
   MessageInfo outputMessage =
       operationInfo.createMessage(
           new QName("http://apache.org/hello_world_soap_http", "testOutputMessage"),
           MessageInfo.Type.OUTPUT);
   operationInfo.setOutput("output", outputMessage);
   assertTrue(operationInfo.hasOutput());
   outputMessage = operationInfo.getOutput();
   assertEquals("testOutputMessage", outputMessage.getName().getLocalPart());
   assertEquals(
       "http://apache.org/hello_world_soap_http", outputMessage.getName().getNamespaceURI());
   assertEquals(operationInfo.getOutputName(), "output");
 }
  public void rollbackTx(Set<Long> acked) throws Exception {
    MessageInfo lastMi = null;

    MessageInfo mi = null;
    Iterator<MessageInfo> iter = deliveringRefs.iterator();
    while (iter.hasNext()) {
      mi = iter.next();
      if (mi.isLocalAcked()) {
        acked.add(mi.nativeId);
        lastMi = mi;
      }
    }

    if (lastMi != null) {
      session.getCoreSession().acknowledge(nativeId, lastMi.nativeId);
    }
  }
  // this is called before session commit a local tx
  public void finishTx() throws Exception {
    MessageInfo lastMi = null;

    MessageInfo mi = null;
    Iterator<MessageInfo> iter = deliveringRefs.iterator();
    while (iter.hasNext()) {
      mi = iter.next();
      if (mi.isLocalAcked()) {
        iter.remove();
        lastMi = mi;
      }
    }

    if (lastMi != null) {
      session.getCoreSession().acknowledge(nativeId, lastMi.nativeId);
    }
  }
    /**
     * Adds <tt>minfo</tt> into the list of collected messages.
     *
     * @param c Conversation
     * @param minfo MessageInfo
     */
    public void gotMessage(Conversation c, MessageInfo minfo) {

      logger.debug("Message: [" + minfo.getMessage() + "] received from: " + c.getBuddy());
      synchronized (this) {
        collectedMessageInfo.add(minfo);
        notifyAll();
      }
    }
Exemplo n.º 9
0
 public Object handleMessage(MessageInfo info, Object targetObj)
     throws ReflectiveOperationException {
   Object result = null;
   try {
     String cmd = info.getCmd();
     JSONArray args;
     // All the methods using BMI, should put the callback at last.
     if (info.getBinaryArgs() != null) {
       JSONArray newArgs = new JSONArray();
       newArgs.put(info.getBinaryArgs());
       newArgs.put(info.getCallbackId());
       args = newArgs;
     } else {
       args = info.getArgs();
     }
     String memberName = info.getJsName();
     XWalkExtensionClient ext = info.getExtension();
     int instanceId = info.getInstanceId();
     switch (cmd) {
       case "invokeNative":
         result = invokeMethod(ext, instanceId, targetObj, memberName, args);
         break;
       case "newInstance":
         BindingObject newObj =
             (BindingObject) (invokeMethod(ext, instanceId, targetObj, memberName, args));
         result = info.getInstanceHelper().addBindingObject(info.getObjectId(), newObj);
         break;
       case "getProperty":
         result = getProperty(targetObj, memberName);
         break;
       case "setProperty":
         setProperty(targetObj, memberName, args.get(0));
         break;
       default:
         Log.w(TAG, "Unsupported cmd: " + cmd);
         break;
     }
   } catch (Exception e) {
     Log.w(TAG, "Invalid message, error msg:\n" + e.toString());
     e.printStackTrace();
   }
   return result;
 }
Exemplo n.º 10
0
  /**
   * test json fill bean
   *
   * @throws JSONException
   */
  @Test
  public void testJsonFillBean() throws JSONException {
    MessageInfo fromMsg = BaseTest.getMessageInfo();
    JSONObject jsonObject = JsonUtil.toJSONObjectFromBean(fromMsg);
    Assert.assertEquals(55555555555555L, jsonObject.get("messageId"));
    Assert.assertEquals("some msg", jsonObject.get("messageSubject"));
    Assert.assertEquals((short) 8, jsonObject.get("messageSubjectLength"));
    // Assert.assertEquals(new JSONObject(new Content(1, "哈哈噢噢,who am i?")),
    // jsonObject.get("messageContent"));
    Assert.assertEquals(true, jsonObject.get("success"));
    Assert.assertEquals((Long) 10L, jsonObject.get("messageSize"));
    Assert.assertEquals((Short) (short) 20, jsonObject.get("messageSize2"));

    jsonObject = JsonUtil.toJSONObject(jsonObject.toString());
    MessageInfo msg = new MessageInfo();
    JsonUtil.fillBeanFromJSONObject(msg, jsonObject, true);
    Assert.assertEquals(55555555555555L, msg.getMessageId());
    Assert.assertEquals("some msg", msg.getMessageSubject());
    Assert.assertEquals((short) 8, msg.getMessageSubjectLength());
    Assert.assertEquals(new Content(1, "哈哈噢噢,who am i?"), msg.getMessageContent());
    Assert.assertEquals(true, msg.getSuccess());
    Assert.assertEquals((Long) 10L, msg.getMessageSize());
    Assert.assertEquals((Short) (short) 20, msg.getMessageSize2());
    Assert.assertEquals(2, msg.getRecipientList().size());
    Assert.assertEquals(BaseTest.getRecipient(), msg.getRecipientList().get(0));
    Assert.assertEquals(BaseTest.getRecipient2(), msg.getRecipientList().get(1));
  }
Exemplo n.º 11
0
  /**
   * @param outputTransportMessageConfiguration - topic name to publish messages
   * @param message - is and Object[]{Event, EventDefinition}
   * @param outputTransportAdaptorConfiguration
   * @param tenantId
   */
  public void publish(
      OutputTransportAdaptorMessageConfiguration outputTransportMessageConfiguration,
      Object message,
      OutputTransportAdaptorConfiguration outputTransportAdaptorConfiguration,
      int tenantId) {
    if (message instanceof Map) {

      ConcurrentHashMap<String, TransportAdaptorInfo> cassandraClusterCache =
          tenantedCassandraClusterCache.get(tenantId);
      if (null == cassandraClusterCache) {
        cassandraClusterCache = new ConcurrentHashMap<String, TransportAdaptorInfo>();
        if (null != tenantedCassandraClusterCache.putIfAbsent(tenantId, cassandraClusterCache)) {
          cassandraClusterCache = tenantedCassandraClusterCache.get(tenantId);
        }
      }

      TransportAdaptorInfo transportAdaptorInfo =
          cassandraClusterCache.get(outputTransportAdaptorConfiguration.getName());
      if (null == transportAdaptorInfo) {
        Map<String, String> properties = outputTransportAdaptorConfiguration.getOutputProperties();

        Map<String, String> credentials = new HashMap<String, String>();
        credentials.put(
            "username",
            properties.get(CassandraTransportAdaptorConstants.TRANSPORT_CASSANDRA_USER_NAME));
        credentials.put(
            "password",
            properties.get(CassandraTransportAdaptorConstants.TRANSPORT_CASSANDRA_PASSWORD));

        Cluster cluster =
            HFactory.createCluster(
                properties.get(CassandraTransportAdaptorConstants.TRANSPORT_CASSANDRA_CLUSTER_NAME),
                new CassandraHostConfigurator(
                    properties.get(CassandraTransportAdaptorConstants.TRANSPORT_CASSANDRA_HOSTNAME)
                        + ":"
                        + properties.get(
                            CassandraTransportAdaptorConstants.TRANSPORT_CASSANDRA_PORT)),
                credentials);

        String indexAllColumnsString =
            properties.get(
                CassandraTransportAdaptorConstants.TRANSPORT_CASSANDRA_INDEX_ALL_COLUMNS);
        boolean indexAllColumns = false;
        if (indexAllColumnsString != null && indexAllColumnsString.equals("true")) {
          indexAllColumns = true;
        }
        transportAdaptorInfo = new TransportAdaptorInfo(cluster, indexAllColumns);
        if (null
            != cassandraClusterCache.putIfAbsent(
                outputTransportAdaptorConfiguration.getName(), transportAdaptorInfo)) {
          transportAdaptorInfo =
              cassandraClusterCache.get(outputTransportAdaptorConfiguration.getName());
        } else {
          log.info("Initiated Cassandra Writer " + outputTransportAdaptorConfiguration.getName());
        }
      }

      String keySpaceName =
          outputTransportMessageConfiguration
              .getOutputMessageProperties()
              .get(CassandraTransportAdaptorConstants.TRANSPORT_CASSANDRA_KEY_SPACE_NAME);
      String columnFamilyName =
          outputTransportMessageConfiguration
              .getOutputMessageProperties()
              .get(CassandraTransportAdaptorConstants.TRANSPORT_CASSANDRA_COLUMN_FAMILY_NAME);
      MessageInfo messageInfo =
          transportAdaptorInfo.getMessageInfoMap().get(outputTransportMessageConfiguration);
      if (null == messageInfo) {
        Keyspace keyspace =
            HFactory.createKeyspace(keySpaceName, transportAdaptorInfo.getCluster());
        messageInfo = new MessageInfo(keyspace);
        if (null
            != transportAdaptorInfo
                .getMessageInfoMap()
                .putIfAbsent(outputTransportMessageConfiguration, messageInfo)) {
          messageInfo =
              transportAdaptorInfo.getMessageInfoMap().get(outputTransportMessageConfiguration);
        }
      }

      if (transportAdaptorInfo.getCluster().describeKeyspace(keySpaceName) == null) {
        BasicColumnFamilyDefinition columnFamilyDefinition = new BasicColumnFamilyDefinition();
        columnFamilyDefinition.setKeyspaceName(keySpaceName);
        columnFamilyDefinition.setName(columnFamilyName);
        columnFamilyDefinition.setComparatorType(ComparatorType.UTF8TYPE);
        columnFamilyDefinition.setDefaultValidationClass(ComparatorType.UTF8TYPE.getClassName());
        columnFamilyDefinition.setKeyValidationClass(ComparatorType.UTF8TYPE.getClassName());

        ColumnFamilyDefinition cfDef = new ThriftCfDef(columnFamilyDefinition);

        KeyspaceDefinition keyspaceDefinition =
            HFactory.createKeyspaceDefinition(
                keySpaceName,
                "org.apache.cassandra.locator.SimpleStrategy",
                1,
                Arrays.asList(cfDef));
        transportAdaptorInfo.getCluster().addKeyspace(keyspaceDefinition);
        KeyspaceDefinition fromCluster =
            transportAdaptorInfo.getCluster().describeKeyspace(keySpaceName);
        messageInfo.setColumnFamilyDefinition(
            new BasicColumnFamilyDefinition(fromCluster.getCfDefs().get(0)));
      } else {
        KeyspaceDefinition fromCluster =
            transportAdaptorInfo.getCluster().describeKeyspace(keySpaceName);
        for (ColumnFamilyDefinition columnFamilyDefinition : fromCluster.getCfDefs()) {
          if (columnFamilyDefinition.getName().equals(columnFamilyName)) {
            messageInfo.setColumnFamilyDefinition(
                new BasicColumnFamilyDefinition(columnFamilyDefinition));
            break;
          }
        }
      }

      Mutator<String> mutator = HFactory.createMutator(messageInfo.getKeyspace(), sser);
      String uuid = UUID.randomUUID().toString();
      for (Map.Entry<String, Object> entry : ((Map<String, Object>) message).entrySet()) {

        if (transportAdaptorInfo.isIndexAllColumns()
            && !messageInfo.getColumnNames().contains(entry.getKey())) {
          BasicColumnFamilyDefinition columnFamilyDefinition =
              messageInfo.getColumnFamilyDefinition();
          BasicColumnDefinition columnDefinition = new BasicColumnDefinition();
          columnDefinition.setName(StringSerializer.get().toByteBuffer(entry.getKey()));
          columnDefinition.setIndexType(ColumnIndexType.KEYS);
          columnDefinition.setIndexName(
              keySpaceName + "_" + columnFamilyName + "_" + entry.getKey() + "_Index");
          columnDefinition.setValidationClass(ComparatorType.UTF8TYPE.getClassName());
          columnFamilyDefinition.addColumnDefinition(columnDefinition);
          transportAdaptorInfo
              .getCluster()
              .updateColumnFamily(new ThriftCfDef(columnFamilyDefinition));
          messageInfo.getColumnNames().add(entry.getKey());
        }
        mutator.insert(
            uuid,
            columnFamilyName,
            HFactory.createStringColumn(entry.getKey(), entry.getValue().toString()));
      }

      mutator.execute();
    }
  }
Exemplo n.º 12
0
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    this.setTitle(getString(R.string.inbox));
    this.setContentView(R.layout.outbox);
    SettingManager.getInstance().init(this);
    NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    nm.cancelAll();

    mListView = (ListView) findViewById(R.id.list);
    mData = DatabaseOperator.getInstance().queryInbox();
    if (DEBUG) {
      if (mData == null) {
        return;
      }
      for (MessageInfo info : mData) {
        Log.d(TAG, "[[onCreate]] info = " + info.toString());
      }
    }

    mAdapter = new InfoAdapter(this, R.layout.list_item, mData);
    mListView.setAdapter(mAdapter);

    mListView.setOnItemLongClickListener(
        new AdapterView.OnItemLongClickListener() {
          @Override
          public boolean onItemLongClick(
              AdapterView<?> parent, View view, final int position, long id) {
            AlertDialog dialog =
                new AlertDialog.Builder(InboxActivity.this)
                    .setPositiveButton(
                        R.string.btn_delete,
                        new DialogInterface.OnClickListener() {
                          @Override
                          public void onClick(DialogInterface dialog, int which) {
                            if (mData != null && mData.size() > 0 && position < mData.size()) {
                              MessageInfo info = mData.get(position);
                              DatabaseOperator.getInstance().deleteInboxInfo(info);
                              mData = DatabaseOperator.getInstance().queryInbox();
                              mAdapter =
                                  new InfoAdapter(InboxActivity.this, R.layout.list_item, mData);
                              mListView.setAdapter(mAdapter);
                            }
                          }
                        })
                    .setNegativeButton(
                        R.string.btn_reply,
                        new DialogInterface.OnClickListener() {
                          @Override
                          public void onClick(DialogInterface dialog, int which) {
                            Intent reply = new Intent();
                            reply.setClass(getApplicationContext(), SendMessageActivity.class);
                            reply.putExtra(SendMessageActivity.RELAY_SMS, true);
                            startActivity(reply);
                          }
                        })
                    .create();
            dialog.show();

            return true;
          }
        });
  }
Exemplo n.º 13
0
  public void acknowledge(MessageAck ack) throws Exception {
    MessageId first = ack.getFirstMessageId();
    MessageId lastm = ack.getLastMessageId();
    TransactionId tid = ack.getTransactionId();
    boolean isLocalTx = (tid != null) && tid.isLocalTransaction();
    boolean single = lastm.equals(first);

    MessageInfo mi = null;
    int n = 0;

    if (ack.isIndividualAck()) {
      Iterator<MessageInfo> iter = deliveringRefs.iterator();
      while (iter.hasNext()) {
        mi = iter.next();
        if (mi.amqId.equals(lastm)) {
          n++;
          iter.remove();
          session.getCoreSession().individualAcknowledge(nativeId, mi.nativeId);
          session.getCoreSession().commit();
          break;
        }
      }
    } else if (ack.isRedeliveredAck()) {
      // client tells that this message is for redlivery.
      // do nothing until poisoned.
      n = 1;
    } else if (ack.isPoisonAck()) {
      // send to dlq
      Iterator<MessageInfo> iter = deliveringRefs.iterator();
      boolean firstFound = false;
      while (iter.hasNext()) {
        mi = iter.next();
        if (mi.amqId.equals(first)) {
          n++;
          iter.remove();
          session
              .getCoreSession()
              .moveToDeadLetterAddress(nativeId, mi.nativeId, ack.getPoisonCause());
          session.getCoreSession().commit();
          if (single) {
            break;
          }
          firstFound = true;
        } else if (firstFound || first == null) {
          n++;
          iter.remove();
          session
              .getCoreSession()
              .moveToDeadLetterAddress(nativeId, mi.nativeId, ack.getPoisonCause());
          session.getCoreSession().commit();
          if (mi.amqId.equals(lastm)) {
            break;
          }
        }
      }
    } else if (ack.isDeliveredAck() || ack.isExpiredAck()) {
      // ToDo: implement with tests
      n = 1;
    } else {
      Iterator<MessageInfo> iter = deliveringRefs.iterator();
      boolean firstFound = false;
      while (iter.hasNext()) {
        MessageInfo ami = iter.next();
        if (ami.amqId.equals(first)) {
          n++;
          if (!isLocalTx) {
            iter.remove();
          } else {
            ami.setLocalAcked(true);
          }
          if (single) {
            mi = ami;
            break;
          }
          firstFound = true;
        } else if (firstFound || first == null) {
          n++;
          if (!isLocalTx) {
            iter.remove();
          } else {
            ami.setLocalAcked(true);
          }
          if (ami.amqId.equals(lastm)) {
            mi = ami;
            break;
          }
        }
      }
      if (mi != null && !isLocalTx) {
        session.getCoreSession().acknowledge(nativeId, mi.nativeId);
      }
    }

    acquireCredit(n);
  }
  // Loosely based off net.oauth.OAuthServlet, and even more loosely related
  // to the OAuth specification
  private MessageInfo parseMessage(HttpRequest request) {
    MessageInfo info = new MessageInfo();
    info.request = request;
    String method = request.getMethod();
    ParsedUrl parsed = new ParsedUrl(request.getUri().toString());

    List<OAuth.Parameter> params = Lists.newArrayList();
    params.addAll(parsed.getParsedQuery());

    if (!validParamLocations.contains(OAuthParamLocation.URI_QUERY)) {
      // Make sure nothing OAuth related ended up in the query string
      for (OAuth.Parameter p : params) {
        if (p.getKey().contains("oauth_")) {
          throw new RuntimeException("Found unexpected query param " + p.getKey());
        }
      }
    }

    // Parse authorization header
    if (validParamLocations.contains(OAuthParamLocation.AUTH_HEADER)) {
      String aznHeader = request.getHeader("Authorization");
      if (aznHeader != null) {
        info.aznHeader = aznHeader;
        for (OAuth.Parameter p : OAuthMessage.decodeAuthorization(aznHeader)) {
          if (!p.getKey().equalsIgnoreCase("realm")) {
            params.add(p);
          }
        }
      }
    }

    // Parse body
    info.body = request.getPostBodyAsString();
    try {
      info.rawBody = IOUtils.toByteArray(request.getPostBody());
    } catch (IOException e) {
      throw new RuntimeException("Can't read post body bytes", e);
    }
    if (OAuth.isFormEncoded(request.getHeader("Content-Type"))) {
      params.addAll(OAuth.decodeForm(request.getPostBodyAsString()));
      // If we're not configured to pass oauth parameters in the post body, double check
      // that they didn't end up there.
      if (!validParamLocations.contains(OAuthParamLocation.POST_BODY)) {
        if (info.body.contains("oauth_")) {
          throw new RuntimeException("Found unexpected post body data" + info.body);
        }
      }
    }

    // Return the lot
    info.message = new OAuthMessage(method, parsed.getLocation(), params);

    // Check for trusted parameters
    if (checkTrustedParams) {
      if (!"foo".equals(OAuthUtil.getParameter(info.message, "oauth_magic"))) {
        throw new RuntimeException("no oauth_trusted=foo parameter");
      }
      if (!"bar".equals(OAuthUtil.getParameter(info.message, "opensocial_magic"))) {
        throw new RuntimeException("no opensocial_trusted=foo parameter");
      }
      if (!"quux".equals(OAuthUtil.getParameter(info.message, "xoauth_magic"))) {
        throw new RuntimeException("no xoauth_magic=quux parameter");
      }
      trustedParamCount += 3;
    }

    return info;
  }