You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@usergrid.apache.org by sn...@apache.org on 2014/02/07 03:21:35 UTC
[48/51] [abbrv] [partial] Package rename for usergrid/stack with 100%
tests passing.
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/b5d399b5/stack/core/src/main/java/org/apache/usergrid/locking/singlenode/SingleNodeLockManagerImpl.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/locking/singlenode/SingleNodeLockManagerImpl.java b/stack/core/src/main/java/org/apache/usergrid/locking/singlenode/SingleNodeLockManagerImpl.java
new file mode 100644
index 0000000..cb94fb3
--- /dev/null
+++ b/stack/core/src/main/java/org/apache/usergrid/locking/singlenode/SingleNodeLockManagerImpl.java
@@ -0,0 +1,93 @@
+/*******************************************************************************
+ * Copyright 2012 Apigee Corporation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ ******************************************************************************/
+package org.apache.usergrid.locking.singlenode;
+
+
+import java.util.UUID;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.ReentrantLock;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.apache.usergrid.locking.Lock;
+import org.apache.usergrid.locking.LockManager;
+import org.apache.usergrid.locking.LockPathBuilder;
+
+import com.google.common.cache.CacheBuilder;
+import com.google.common.cache.CacheLoader;
+import com.google.common.cache.LoadingCache;
+import com.google.common.cache.RemovalListener;
+import com.google.common.cache.RemovalNotification;
+
+
+/**
+ * Single Node implementation for {@link LockManager} Note that this implementation has not been used in a production
+ * environment.
+ * <p/>
+ * The hector based implementation is the preferred production locking system
+ */
+public class SingleNodeLockManagerImpl implements LockManager {
+
+ private static final Logger logger = LoggerFactory.getLogger( SingleNodeLockManagerImpl.class );
+
+ public static final long MILLI_EXPIRATION = 5000;
+
+ /** Lock cache that sill expire after 5 seconds of no use for a lock path */
+ private LoadingCache<String, ReentrantLock> locks =
+ CacheBuilder.newBuilder().expireAfterWrite( MILLI_EXPIRATION, TimeUnit.MILLISECONDS )
+ // use weakValues. We want want entries removed if they're not being
+ // referenced by another
+ // thread somewhere and GC occurs
+ .weakValues().removalListener( new RemovalListener<String, ReentrantLock>() {
+
+ @Override
+ public void onRemoval( RemovalNotification<String, ReentrantLock> notification ) {
+ logger.debug( "Evicting reentrant lock for {}", notification.getKey() );
+ }
+ } ).build( new CacheLoader<String, ReentrantLock>() {
+
+ @Override
+ public ReentrantLock load( String arg0 ) throws Exception {
+ return new ReentrantLock( true );
+ }
+ } );
+
+
+ /** Default constructor. */
+ public SingleNodeLockManagerImpl() {
+ }
+
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.apache.usergrid.locking.LockManager#createLock(java.util.UUID,
+ * java.lang.String[])
+ */
+ @Override
+ public Lock createLock( UUID applicationId, String... path ) {
+
+ String lockPath = LockPathBuilder.buildPath( applicationId, path );
+
+ try {
+ return new SingleNodeLockImpl( locks.get( lockPath ) );
+ }
+ catch ( ExecutionException e ) {
+ throw new RuntimeException( "Unable to create lock in cache", e );
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/b5d399b5/stack/core/src/main/java/org/apache/usergrid/locking/zookeeper/ZooKeeperLockManagerImpl.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/locking/zookeeper/ZooKeeperLockManagerImpl.java b/stack/core/src/main/java/org/apache/usergrid/locking/zookeeper/ZooKeeperLockManagerImpl.java
new file mode 100644
index 0000000..7c45e27
--- /dev/null
+++ b/stack/core/src/main/java/org/apache/usergrid/locking/zookeeper/ZooKeeperLockManagerImpl.java
@@ -0,0 +1,114 @@
+/*******************************************************************************
+ * Copyright 2012 Apigee Corporation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ ******************************************************************************/
+package org.apache.usergrid.locking.zookeeper;
+
+
+import java.util.UUID;
+
+import javax.annotation.PostConstruct;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.apache.usergrid.locking.Lock;
+import org.apache.usergrid.locking.LockManager;
+import org.apache.usergrid.locking.LockPathBuilder;
+
+import com.netflix.curator.RetryPolicy;
+import com.netflix.curator.framework.CuratorFramework;
+import com.netflix.curator.framework.CuratorFrameworkFactory;
+import com.netflix.curator.framework.recipes.locks.InterProcessMutex;
+import com.netflix.curator.retry.ExponentialBackoffRetry;
+
+
+/** Implementation for Zookeeper service that handles global locks. */
+public final class ZooKeeperLockManagerImpl implements LockManager {
+
+ private String hostPort;
+
+ private int sessionTimeout = 2000;
+
+ private int maxAttempts = 5;
+
+ private CuratorFramework client;
+
+
+ public ZooKeeperLockManagerImpl( String hostPort, int sessionTimeout, int maxAttemps ) {
+ this.hostPort = hostPort;
+ this.sessionTimeout = sessionTimeout;
+ this.maxAttempts = maxAttemps;
+ init();
+ }
+
+
+ public ZooKeeperLockManagerImpl() {
+ }
+
+
+ @PostConstruct
+ public void init() {
+ RetryPolicy retryPolicy = new ExponentialBackoffRetry( sessionTimeout, maxAttempts );
+ client = CuratorFrameworkFactory.newClient( hostPort, retryPolicy );
+ client.start();
+ }
+
+
+ protected static final Logger logger = LoggerFactory.getLogger( ZooKeeperLockManagerImpl.class );
+
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.apache.usergrid.locking.LockManager#createLock(java.util.UUID,
+ * java.lang.String[])
+ */
+ @Override
+ public Lock createLock( UUID applicationId, String... path ) {
+ String lockPath = LockPathBuilder.buildPath( applicationId, path );
+
+
+ return new ZookeeperLockImpl( new InterProcessMutex( client, lockPath ) );
+ }
+
+
+ public String getHostPort() {
+ return hostPort;
+ }
+
+
+ public void setHostPort( String hostPort ) {
+ this.hostPort = hostPort;
+ }
+
+
+ public int getSessionTimeout() {
+ return sessionTimeout;
+ }
+
+
+ public void setSessionTimeout( int sessionTimeout ) {
+ this.sessionTimeout = sessionTimeout;
+ }
+
+
+ public int getMaxAttempts() {
+ return maxAttempts;
+ }
+
+
+ public void setMaxAttempts( int maxAttemps ) {
+ this.maxAttempts = maxAttemps;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/b5d399b5/stack/core/src/main/java/org/apache/usergrid/locking/zookeeper/ZookeeperLockImpl.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/locking/zookeeper/ZookeeperLockImpl.java b/stack/core/src/main/java/org/apache/usergrid/locking/zookeeper/ZookeeperLockImpl.java
new file mode 100644
index 0000000..185f37c
--- /dev/null
+++ b/stack/core/src/main/java/org/apache/usergrid/locking/zookeeper/ZookeeperLockImpl.java
@@ -0,0 +1,87 @@
+/*******************************************************************************
+ * Copyright 2012 Apigee Corporation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ ******************************************************************************/
+package org.apache.usergrid.locking.zookeeper;
+
+
+import java.util.concurrent.TimeUnit;
+
+import org.apache.usergrid.locking.Lock;
+import org.apache.usergrid.locking.exception.UGLockException;
+
+import com.netflix.curator.framework.recipes.locks.InterProcessMutex;
+
+
+/**
+ * Wrapper for locks using curator
+ *
+ * @author tnine
+ */
+public class ZookeeperLockImpl implements Lock {
+
+
+ private InterProcessMutex zkMutex;
+
+
+ /**
+ *
+ */
+ public ZookeeperLockImpl( InterProcessMutex zkMutex ) {
+ this.zkMutex = zkMutex;
+ }
+
+
+ /* (non-Javadoc)
+ * @see org.apache.usergrid.locking.Lock#tryLock(long, java.util.concurrent.TimeUnit)
+ */
+ @Override
+ public boolean tryLock( long timeout, TimeUnit time ) throws UGLockException {
+
+ try {
+ return zkMutex.acquire( timeout, time );
+ }
+ catch ( Exception e ) {
+ throw new UGLockException( "Unable to obtain lock", e );
+ }
+ }
+
+
+ /* (non-Javadoc)
+ * @see org.apache.usergrid.locking.Lock#lock()
+ */
+ @Override
+ public void lock() throws UGLockException {
+ try {
+ zkMutex.acquire();
+ }
+ catch ( Exception e ) {
+ throw new UGLockException( "Unable to obtain lock", e );
+ }
+ }
+
+
+ /* (non-Javadoc)
+ * @see org.apache.usergrid.locking.Lock#unlock()
+ */
+ @Override
+ public void unlock() throws UGLockException {
+ try {
+ zkMutex.release();
+ }
+ catch ( Exception e ) {
+ throw new UGLockException( "Unable to obtain lock", e );
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/b5d399b5/stack/core/src/main/java/org/apache/usergrid/mq/CounterQuery.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/mq/CounterQuery.java b/stack/core/src/main/java/org/apache/usergrid/mq/CounterQuery.java
new file mode 100644
index 0000000..5504e22
--- /dev/null
+++ b/stack/core/src/main/java/org/apache/usergrid/mq/CounterQuery.java
@@ -0,0 +1,313 @@
+/*******************************************************************************
+ * Copyright 2012 Apigee Corporation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ ******************************************************************************/
+package org.apache.usergrid.mq;
+
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.apache.usergrid.mq.Query.CounterFilterPredicate;
+import org.apache.usergrid.persistence.CounterResolution;
+import org.apache.usergrid.utils.JsonUtils;
+import static org.apache.usergrid.utils.ClassUtils.cast;
+import static org.apache.usergrid.utils.ListUtils.firstBoolean;
+import static org.apache.usergrid.utils.ListUtils.firstInteger;
+import static org.apache.usergrid.utils.ListUtils.firstLong;
+import static org.apache.usergrid.utils.ListUtils.isEmpty;
+import static org.apache.usergrid.utils.MapUtils.toMapList;
+
+
+public class CounterQuery {
+
+ public static final Logger logger = LoggerFactory.getLogger( CounterQuery.class );
+
+ public static final int DEFAULT_MAX_RESULTS = 10;
+
+ private int limit = 0;
+ boolean limitSet = false;
+
+ private Long startTime;
+ private Long finishTime;
+ private boolean pad;
+ private CounterResolution resolution = CounterResolution.ALL;
+ private List<String> categories;
+ private List<CounterFilterPredicate> counterFilters;
+
+
+ public CounterQuery() {
+ }
+
+
+ public CounterQuery( CounterQuery q ) {
+ if ( q != null ) {
+ limit = q.limit;
+ limitSet = q.limitSet;
+ startTime = q.startTime;
+ finishTime = q.finishTime;
+ resolution = q.resolution;
+ pad = q.pad;
+ categories = q.categories != null ? new ArrayList<String>( q.categories ) : null;
+ counterFilters =
+ q.counterFilters != null ? new ArrayList<CounterFilterPredicate>( q.counterFilters ) : null;
+ }
+ }
+
+
+ public static CounterQuery newQueryIfNull( CounterQuery query ) {
+ if ( query == null ) {
+ query = new CounterQuery();
+ }
+ return query;
+ }
+
+
+ public static CounterQuery fromJsonString( String json ) {
+ Object o = JsonUtils.parse( json );
+ if ( o instanceof Map ) {
+ @SuppressWarnings({ "unchecked", "rawtypes" }) Map<String, List<String>> params =
+ cast( toMapList( ( Map ) o ) );
+ return fromQueryParams( params );
+ }
+ return null;
+ }
+
+
+ public static CounterQuery fromQueryParams( Map<String, List<String>> params ) {
+
+ CounterQuery q = null;
+ Integer limit = null;
+ Long startTime = null;
+ Long finishTime = null;
+ Boolean pad = null;
+ CounterResolution resolution = null;
+ List<CounterFilterPredicate> counterFilters = null;
+ List<String> categories = null;
+
+ List<String> l = null;
+
+ limit = firstInteger( params.get( "limit" ) );
+ startTime = firstLong( params.get( "start_time" ) );
+ finishTime = firstLong( params.get( "end_time" ) );
+
+ l = params.get( "resolution" );
+ if ( !isEmpty( l ) ) {
+ resolution = CounterResolution.fromString( l.get( 0 ) );
+ }
+
+ categories = params.get( "category" );
+
+ l = params.get( "counter" );
+ if ( !isEmpty( l ) ) {
+ counterFilters = CounterFilterPredicate.fromList( l );
+ }
+
+ pad = firstBoolean( params.get( "pad" ) );
+
+ if ( limit != null ) {
+ q = newQueryIfNull( q );
+ q.setLimit( limit );
+ }
+
+ if ( startTime != null ) {
+ q = newQueryIfNull( q );
+ q.setStartTime( startTime );
+ }
+
+ if ( finishTime != null ) {
+ q = newQueryIfNull( q );
+ q.setFinishTime( finishTime );
+ }
+
+ if ( resolution != null ) {
+ q = newQueryIfNull( q );
+ q.setResolution( resolution );
+ }
+
+ if ( categories != null ) {
+ q = newQueryIfNull( q );
+ q.setCategories( categories );
+ }
+
+ if ( counterFilters != null ) {
+ q = newQueryIfNull( q );
+ q.setCounterFilters( counterFilters );
+ }
+
+ if ( pad != null ) {
+ q = newQueryIfNull( q );
+ q.setPad( pad );
+ }
+
+ return q;
+ }
+
+
+ public int getLimit() {
+ return getLimit( DEFAULT_MAX_RESULTS );
+ }
+
+
+ public int getLimit( int defaultMax ) {
+ if ( limit <= 0 ) {
+ if ( defaultMax > 0 ) {
+ return defaultMax;
+ }
+ else {
+ return DEFAULT_MAX_RESULTS;
+ }
+ }
+ return limit;
+ }
+
+
+ public void setLimit( int limit ) {
+ limitSet = true;
+ this.limit = limit;
+ }
+
+
+ public CounterQuery withLimit( int limit ) {
+ limitSet = true;
+ this.limit = limit;
+ return this;
+ }
+
+
+ public boolean isLimitSet() {
+ return limitSet;
+ }
+
+
+ public Long getStartTime() {
+ return startTime;
+ }
+
+
+ public void setStartTime( Long startTime ) {
+ this.startTime = startTime;
+ }
+
+
+ public CounterQuery withStartTime( Long startTime ) {
+ this.startTime = startTime;
+ return this;
+ }
+
+
+ public Long getFinishTime() {
+ return finishTime;
+ }
+
+
+ public void setFinishTime( Long finishTime ) {
+ this.finishTime = finishTime;
+ }
+
+
+ public CounterQuery withFinishTime( Long finishTime ) {
+ this.finishTime = finishTime;
+ return this;
+ }
+
+
+ public boolean isPad() {
+ return pad;
+ }
+
+
+ public void setPad( boolean pad ) {
+ this.pad = pad;
+ }
+
+
+ public CounterQuery withPad( boolean pad ) {
+ this.pad = pad;
+ return this;
+ }
+
+
+ public void setResolution( CounterResolution resolution ) {
+ this.resolution = resolution;
+ }
+
+
+ public CounterResolution getResolution() {
+ return resolution;
+ }
+
+
+ public CounterQuery withResolution( CounterResolution resolution ) {
+ this.resolution = resolution;
+ return this;
+ }
+
+
+ public List<String> getCategories() {
+ return categories;
+ }
+
+
+ public CounterQuery addCategory( String category ) {
+ if ( categories == null ) {
+ categories = new ArrayList<String>();
+ }
+ categories.add( category );
+ return this;
+ }
+
+
+ public void setCategories( List<String> categories ) {
+ this.categories = categories;
+ }
+
+
+ public CounterQuery withCategories( List<String> categories ) {
+ this.categories = categories;
+ return this;
+ }
+
+
+ public List<CounterFilterPredicate> getCounterFilters() {
+ return counterFilters;
+ }
+
+
+ public CounterQuery addCounterFilter( String counter ) {
+ CounterFilterPredicate p = CounterFilterPredicate.fromString( counter );
+ if ( p == null ) {
+ return this;
+ }
+ if ( counterFilters == null ) {
+ counterFilters = new ArrayList<CounterFilterPredicate>();
+ }
+ counterFilters.add( p );
+ return this;
+ }
+
+
+ public void setCounterFilters( List<CounterFilterPredicate> counterFilters ) {
+ this.counterFilters = counterFilters;
+ }
+
+
+ public CounterQuery withCounterFilters( List<CounterFilterPredicate> counterFilters ) {
+ this.counterFilters = counterFilters;
+ return this;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/b5d399b5/stack/core/src/main/java/org/apache/usergrid/mq/Message.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/mq/Message.java b/stack/core/src/main/java/org/apache/usergrid/mq/Message.java
new file mode 100644
index 0000000..c011cfa
--- /dev/null
+++ b/stack/core/src/main/java/org/apache/usergrid/mq/Message.java
@@ -0,0 +1,512 @@
+/*******************************************************************************
+ * Copyright 2012 Apigee Corporation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ ******************************************************************************/
+package org.apache.usergrid.mq;
+
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.TreeMap;
+import java.util.UUID;
+
+import javax.xml.bind.annotation.XmlRootElement;
+
+import org.codehaus.jackson.annotate.JsonAnyGetter;
+import org.codehaus.jackson.annotate.JsonAnySetter;
+import org.codehaus.jackson.annotate.JsonIgnore;
+import org.codehaus.jackson.map.annotate.JsonSerialize;
+import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
+import org.apache.usergrid.utils.UUIDUtils;
+
+import com.fasterxml.uuid.UUIDComparator;
+
+import static org.apache.commons.collections.IteratorUtils.asEnumeration;
+import static org.apache.commons.collections.MapUtils.getBooleanValue;
+import static org.apache.commons.collections.MapUtils.getByteValue;
+import static org.apache.commons.collections.MapUtils.getDoubleValue;
+import static org.apache.commons.collections.MapUtils.getFloatValue;
+import static org.apache.commons.collections.MapUtils.getIntValue;
+import static org.apache.commons.collections.MapUtils.getLongValue;
+import static org.apache.commons.collections.MapUtils.getShortValue;
+import static org.apache.commons.collections.MapUtils.getString;
+import static org.apache.usergrid.utils.ClassUtils.cast;
+import static org.apache.usergrid.utils.ConversionUtils.bytes;
+import static org.apache.usergrid.utils.ConversionUtils.coerceMap;
+import static org.apache.usergrid.utils.ConversionUtils.getInt;
+import static org.apache.usergrid.utils.ConversionUtils.uuid;
+import static org.apache.usergrid.utils.MapUtils.hashMap;
+import static org.apache.usergrid.utils.UUIDUtils.getTimestampInMillis;
+import static org.apache.usergrid.utils.UUIDUtils.isTimeBased;
+import static org.apache.usergrid.utils.UUIDUtils.newTimeUUID;
+
+
+@XmlRootElement
+public class Message {
+
+ public static final String MESSAGE_CORRELATION_ID = "correlation_id";
+ public static final String MESSAGE_DESTINATION = "destination";
+ public static final String MESSAGE_ID = "uuid";
+ public static final String MESSAGE_REPLY_TO = "reply_to";
+ public static final String MESSAGE_TIMESTAMP = "timestamp";
+ public static final String MESSAGE_TYPE = "type";
+ public static final String MESSAGE_CATEGORY = "category";
+ public static final String MESSAGE_INDEXED = "indexed";
+ public static final String MESSAGE_PERSISTENT = "persistent";
+ public static final String MESSAGE_TRANSACTION = "transaction";
+
+ @SuppressWarnings("rawtypes")
+ public static final Map<String, Class> MESSAGE_PROPERTIES =
+ hashMap( MESSAGE_CORRELATION_ID, ( Class ) String.class ).map( MESSAGE_DESTINATION, String.class )
+ .map( MESSAGE_ID, UUID.class ).map( MESSAGE_REPLY_TO, String.class )
+ .map( MESSAGE_TIMESTAMP, Long.class ).map( MESSAGE_TYPE, String.class )
+ .map( MESSAGE_CATEGORY, String.class ).map( MESSAGE_INDEXED, Boolean.class )
+ .map( MESSAGE_PERSISTENT, Boolean.class ).map( MESSAGE_TRANSACTION, UUID.class );
+
+
+ public static int compare( Message m1, Message m2 ) {
+ if ( ( m1 == null ) && ( m2 == null ) ) {
+ return 0;
+ }
+ else if ( m1 == null ) {
+ return -1;
+ }
+ else if ( m2 == null ) {
+ return 1;
+ }
+ return UUIDComparator.staticCompare( m1.getUuid(), m2.getUuid() );
+ }
+
+
+ public static List<Message> fromList( List<Map<String, Object>> l ) {
+ List<Message> messages = new ArrayList<Message>( l.size() );
+ for ( Map<String, Object> properties : l ) {
+ messages.add( new Message( properties ) );
+ }
+ return messages;
+ }
+
+
+ public static List<Message> sort( List<Message> messages ) {
+ Collections.sort( messages, new Comparator<Message>() {
+ @Override
+ public int compare( Message m1, Message m2 ) {
+ return Message.compare( m1, m2 );
+ }
+ } );
+ return messages;
+ }
+
+
+ public static List<Message> sortReversed( List<Message> messages ) {
+ Collections.sort( messages, new Comparator<Message>() {
+ @Override
+ public int compare( Message m1, Message m2 ) {
+ return Message.compare( m2, m1 );
+ }
+ } );
+ return messages;
+ }
+
+
+ protected Map<String, Object> properties = new TreeMap<String, Object>( String.CASE_INSENSITIVE_ORDER );
+
+
+ public Message() {
+ }
+
+
+ @SuppressWarnings("unchecked")
+ public Message( Map<String, Object> properties ) {
+ this.properties.putAll( coerceMap( ( Map<String, Class<?>> ) cast( MESSAGE_PROPERTIES ), properties ) );
+ }
+
+
+ @SuppressWarnings("unchecked")
+ public void addCounter( String name, int value ) {
+ Map<String, Integer> counters = null;
+ if ( properties.get( "counters" ) instanceof Map ) {
+ counters = ( Map<String, Integer> ) properties.get( "counters" );
+ }
+ else {
+ counters = new HashMap<String, Integer>();
+ properties.put( "counters", counters );
+ }
+ counters.put( name, value );
+ }
+
+
+ public void clearBody() {
+ properties.clear();
+ }
+
+
+ public void clearProperties() {
+ properties.clear();
+ }
+
+
+ public boolean getBooleanProperty( String name ) {
+ return getBooleanValue( properties, name );
+ }
+
+
+ public byte getByteProperty( String name ) {
+ return getByteValue( properties, name );
+ }
+
+
+ @JsonIgnore
+ public String getCategory() {
+ return getString( properties, MESSAGE_CATEGORY );
+ }
+
+
+ @JsonIgnore
+ public String getCorrelationID() {
+ return getString( properties, MESSAGE_CORRELATION_ID );
+ }
+
+
+ @JsonIgnore
+ public byte[] getCorrelationIDAsBytes() {
+ return bytes( properties.get( MESSAGE_CORRELATION_ID ) );
+ }
+
+
+ @JsonIgnore
+ public Map<String, Integer> getCounters() {
+ Map<String, Integer> counters = new HashMap<String, Integer>();
+ if ( properties.get( "counters" ) instanceof Map ) {
+ @SuppressWarnings("unchecked") Map<String, Object> c = ( Map<String, Object> ) properties.get( "counters" );
+ for ( Entry<String, Object> e : c.entrySet() ) {
+ counters.put( e.getKey(), getInt( e.getValue() ) );
+ }
+ }
+ return counters;
+ }
+
+
+ @JsonIgnore
+ public int getDeliveryMode() {
+ return 2;
+ }
+
+
+ @JsonIgnore
+ public Queue getDestination() {
+ return Queue.getDestination( getString( properties, MESSAGE_DESTINATION ) );
+ }
+
+
+ public double getDoubleProperty( String name ) {
+ return getDoubleValue( properties, name );
+ }
+
+
+ @JsonIgnore
+ public long getExpiration() {
+ return 0;
+ }
+
+
+ public float getFloatProperty( String name ) {
+ return getFloatValue( properties, name );
+ }
+
+
+ public int getIntProperty( String name ) {
+ return getIntValue( properties, name );
+ }
+
+
+ public long getLongProperty( String name ) {
+ return getLongValue( properties, name );
+ }
+
+
+ @JsonIgnore
+ public String getMessageID() {
+ return getUuid().toString();
+ }
+
+
+ public Object getObjectProperty( String name ) {
+ return properties.get( name );
+ }
+
+
+ @JsonIgnore
+ public int getPriority() {
+ return 0;
+ }
+
+
+ @JsonAnyGetter
+ public Map<String, Object> getProperties() {
+ sync();
+ return properties;
+ }
+
+
+ @JsonIgnore
+ @SuppressWarnings("unchecked")
+ public Enumeration<String> getPropertyNames() {
+ return asEnumeration( properties.keySet().iterator() );
+ }
+
+
+ @JsonIgnore
+ public boolean getRedelivered() {
+ return false;
+ }
+
+
+ @JsonIgnore
+ public Queue getReplyTo() {
+ return Queue.getDestination( getString( properties, MESSAGE_REPLY_TO ) );
+ }
+
+
+ public short getShortProperty( String name ) {
+ return getShortValue( properties, name );
+ }
+
+
+ public String getStringProperty( String name ) {
+ return getString( properties, name );
+ }
+
+
+ @JsonIgnore
+ public synchronized long getTimestamp() {
+ if ( properties.containsKey( MESSAGE_TIMESTAMP ) ) {
+ long ts = getLongValue( properties, MESSAGE_TIMESTAMP );
+ if ( ts != 0 ) {
+ return ts;
+ }
+ }
+ long timestamp = getTimestampInMillis( getUuid() );
+ properties.put( MESSAGE_TIMESTAMP, timestamp );
+ return timestamp;
+ }
+
+
+ @JsonIgnore
+ public String getType() {
+ return getString( properties, MESSAGE_TYPE );
+ }
+
+
+ @JsonIgnore
+ public synchronized UUID getUuid() {
+ UUID uuid = uuid( properties.get( MESSAGE_ID ), null );
+ if ( uuid == null ) {
+ if ( properties.containsKey( MESSAGE_TIMESTAMP ) ) {
+ long ts = getLongValue( properties, MESSAGE_TIMESTAMP );
+ uuid = newTimeUUID( ts );
+ }
+ else {
+ uuid = newTimeUUID();
+ }
+
+ properties.put( MESSAGE_ID, uuid );
+ properties.put( MESSAGE_TIMESTAMP, getTimestampInMillis( uuid ) );
+ }
+ return uuid;
+ }
+
+
+ @JsonIgnore
+ public boolean isIndexed() {
+ return getBooleanValue( properties, MESSAGE_INDEXED );
+ }
+
+
+ @JsonIgnore
+ public boolean isPersistent() {
+ return getBooleanValue( properties, MESSAGE_PERSISTENT );
+ }
+
+
+ public boolean propertyExists( String name ) {
+ return properties.containsKey( name );
+ }
+
+
+ public void setBooleanProperty( String name, boolean value ) {
+ properties.put( name, value );
+ }
+
+
+ public void setByteProperty( String name, byte value ) {
+ properties.put( name, value );
+ }
+
+
+ public void setCategory( String category ) {
+ if ( category != null ) {
+ properties.put( MESSAGE_CATEGORY, category.toLowerCase() );
+ }
+ }
+
+
+ public void setCorrelationID( String correlationId ) {
+ properties.put( MESSAGE_CORRELATION_ID, correlationId );
+ }
+
+
+ public void setCorrelationIDAsBytes( byte[] correlationId ) {
+ properties.put( MESSAGE_CORRELATION_ID, correlationId );
+ }
+
+
+ public void setCounters( Map<String, Integer> counters ) {
+ if ( counters == null ) {
+ counters = new HashMap<String, Integer>();
+ }
+ properties.put( "counters", counters );
+ }
+
+
+ public void setDeliveryMode( int arg0 ) {
+ }
+
+
+ public void setDestination( Queue destination ) {
+ properties.put( MESSAGE_CORRELATION_ID, destination.toString() );
+ }
+
+
+ public void setDoubleProperty( String name, double value ) {
+ properties.put( name, value );
+ }
+
+
+ public void setExpiration( long expiration ) {
+ }
+
+
+ public void setFloatProperty( String name, float value ) {
+ properties.put( name, value );
+ }
+
+
+ public void setIndexed( boolean indexed ) {
+ properties.put( MESSAGE_INDEXED, indexed );
+ }
+
+
+ public void setIntProperty( String name, int value ) {
+ properties.put( name, value );
+ }
+
+
+ public void setLongProperty( String name, long value ) {
+ properties.put( name, value );
+ }
+
+
+ public void setMessageID( String id ) {
+ if ( UUIDUtils.isUUID( id ) ) {
+ properties.put( MESSAGE_ID, UUIDUtils.tryGetUUID( id ) );
+ }
+ else {
+ throw new RuntimeException( "Not a UUID" );
+ }
+ }
+
+
+ public void setObjectProperty( String name, Object value ) {
+ properties.put( name, value );
+ }
+
+
+ public void setPersistent( boolean persistent ) {
+ properties.put( MESSAGE_PERSISTENT, persistent );
+ }
+
+
+ public void setPriority( int priority ) {
+ }
+
+
+ @JsonAnySetter
+ public void setProperty( String key, Object value ) {
+ properties.put( key, value );
+ }
+
+
+ public void setRedelivered( boolean redelivered ) {
+ }
+
+
+ public void setReplyTo( Queue destination ) {
+ properties.put( MESSAGE_REPLY_TO, destination.toString() );
+ }
+
+
+ public void setShortProperty( String name, short value ) {
+ properties.put( name, value );
+ }
+
+
+ public void setStringProperty( String name, String value ) {
+ properties.put( name, value );
+ }
+
+
+ public void setTimestamp( long timestamp ) {
+ properties.put( MESSAGE_TIMESTAMP, timestamp );
+ }
+
+
+ public void setType( String type ) {
+ properties.put( MESSAGE_TYPE, type );
+ }
+
+
+ public void setUuid( UUID uuid ) {
+ if ( isTimeBased( uuid ) ) {
+ properties.put( MESSAGE_ID, uuid );
+ properties.put( MESSAGE_TIMESTAMP, getTimestampInMillis( uuid ) );
+ }
+ else {
+ throw new IllegalArgumentException( "Not a time-based UUID" );
+ }
+ }
+
+
+ public void setTransaction( UUID transaction ) {
+ properties.put( MESSAGE_TRANSACTION, transaction );
+ }
+
+
+ @JsonSerialize(include = Inclusion.NON_NULL)
+ public UUID getTransaction() {
+ return ( UUID ) properties.get( MESSAGE_TRANSACTION );
+ }
+
+
+ public void sync() {
+ getUuid();
+ getTimestamp();
+ }
+}