Commit b8a6ea54 by amir

initial

parents
Pipeline #76 skipped in 0 seconds
/build/
/bin/
.gradle
.settings
.idea
.lck
.project
.classpath
gradle/
group 'com.ipgallery.common'
version '1.0.0'
apply plugin: 'java'
apply plugin: 'maven-publish'
sourceCompatibility = 1.8
repositories {
//mavenCentral()
maven { url "http://172.16.1.132:8081/repository/internal" }
maven { url "http://mandubian-mvn.googlecode.com/svn/trunk/mandubian-mvn/repository" }
}
dependencies {
compile 'com.rabbitmq:amqp-client:3.6.0' //'com.rabbitmq:rabbitmq-client:1.3.0'
compile 'com.fasterxml.jackson.core:jackson-databind:2.2.3'
compile 'com.ipgallery.common:utils:1.0.0'
compile 'com.ipgallery.common:itc:1.0.0'
testCompile group: 'junit', name: 'junit', version: '4.11'
}
publishing {
publications {
repositories.maven {
url 'http://172.16.1.132:8081/repository/internal'
credentials {
username "admin"
password "giptmgr1"
}
}
mavenJava(MavenPublication) {
//artifactId 'group-service'
from components.java
}
}
}
\ No newline at end of file
#!/usr/bin/env bash
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn ( ) {
echo "$*"
}
die ( ) {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
esac
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
function splitJvmOpts() {
JVM_OPTS=("$@")
}
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windowz variants
if not "%OS%" == "Windows_NT" goto win9xME_args
if "%@eval[2+2]" == "4" goto 4NT_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
goto execute
:4NT_args
@rem Get arguments from the 4NT Shell from JP Software
set CMD_LINE_ARGS=%$
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
rootProject.name = 'rabbitmq'
package rabbitmq.client;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.util.concurrent.TimeoutException;
import com.rabbitmq.client.ShutdownSignalException;
import rabbitmq.common.RMQMessage;
import rabbitmq.common.RMQSender;
import rabbitmq.common.RMConnectionPool;
import rabbitmq.common.RMQId;
import rabbitmq.common.RMQBinaryMessage;
import rabbitmq.common.RMQReciever;
import rabbitmq.common.RMQTextMessage;
public class RMQClient {
protected RMConnectionPool connectionPool = null;
protected RMQSender rmqSender = null;
protected RMQReciever rmqReciever = null;
protected RMQId originId = null;
public RMQClient(RMQId originId, boolean useWaitForReply) throws IOException, TimeoutException {
this.originId = originId;
this.connectionPool= new RMConnectionPool();
if (useWaitForReply)
this.rmqReciever = new RMQReciever(originId);
}
public boolean connectTo(String targetHost, String targetQueue) {
RMQId rmqId = new RMQId(targetHost, targetQueue);
return connectTo(rmqId);
}
public boolean connectTo(RMQId rmqId) {
this.rmqSender = connectionPool.getOpenedConnection(rmqId);
if (this.rmqSender != null) {
return true;
}
else {
this.rmqSender = connectionPool.connect(rmqId);
if (this.rmqSender != null )
return true;
}
return false;
}
public void disconnect() {
if (rmqSender != null) {
try {
connectionPool.closeConnection(this.rmqSender.getQueueId());
} catch (Exception e) {
e.printStackTrace();
}
}
}
public boolean isConnected() {
return rmqSender.isOpen();
}
public boolean sendMessage(RMQMessage request) {
try {
rmqSender.sendMessage(request, this.originId);
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
public boolean sendTextMessage(String message) {
try {
rmqSender.sendMessage(message, this.originId);
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
public RMQMessage waitForReply(long timeout) throws ShutdownSignalException, IOException, InterruptedException, ClassNotFoundException {
if (rmqReciever != null ) {
// wait for response
RMQBinaryMessage rmqMsg = rmqReciever.recieveMessageWithProps(timeout);
RMQMessage respMsg = (RMQMessage)deserializeObject(rmqMsg.getMessage());
return respMsg;
}
else
return null;
}
public RMQTextMessage waitForTextReply(long timeout) throws ShutdownSignalException, IOException, InterruptedException, ClassNotFoundException {
RMQTextMessage textMessage = new RMQTextMessage();
if (rmqReciever != null ) {
// wait for response
String textResponse = rmqReciever.recieveTextMessage(timeout);
textMessage.setMessage(textResponse);
return textMessage;
}
else
return null;
}
protected static RMQMessage deserializeObject(byte[] objectToSerialize) throws IOException, ClassNotFoundException {
ByteArrayInputStream bis = new ByteArrayInputStream(objectToSerialize);
ObjectInput in = new ObjectInputStream(bis);
Object readObject;
try {
readObject = in.readObject();
}
finally
{
}
return (RMQMessage) readObject;
}
}
package rabbitmq.client;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.ShutdownSignalException;
import rabbitmq.common.RMQId;
import rabbitmq.common.RMQKeyGenerator;
import rabbitmq.common.RMQMessage;
import rabbitmq.common.RMQRestRequest;
import rabbitmq.common.RMQTextMessage;
import utils.http.simpleHttpClient.SimpleHttpRequest.Method;
import utils.http.simpleRestClient.SimpleRestResponse;
public class RMQRestClient extends RMQClient {
private static final String EMPTY_RESPONSE = "Empty response";
protected String app = null;
protected int port = 0;
protected ObjectMapper objMapper = new ObjectMapper();
public RMQRestClient(RMQId originId, String app, boolean useWaitForReply) throws IOException , TimeoutException{
super(originId, useWaitForReply);
this.app = app;
}
public String doGet(String entity, String params[], String requestParams, String key) {
return doGet(entity, buildParamPath(params), requestParams, key);
}
public String doGet(String entity, String paramsPath, String requestParams, String key) {
return sendRequest(Method.GET, entity, paramsPath, requestParams, null, key);
}
public String doPost(String entity, String params[], String requestParams, String content, String key) {
return doPost(entity, buildParamPath(params), requestParams, content, key);
}
public String doPost(String entity, String paramsPath, String requestParams, String content, String key) {
return sendRequest(Method.POST, entity, paramsPath, requestParams, content, key);
}
public String doDelete(String entity, String params[], String requestParams, String key) {
return doDelete(entity, buildParamPath(params), requestParams, key);
}
public String doDelete(String entity, String paramsPath, String requestParams, String key) {
return sendRequest(Method.DELETE, entity, paramsPath, requestParams, null, key);
}
public SimpleRestResponse waitForRestReply(long timeout) throws ShutdownSignalException, IOException, InterruptedException, ClassNotFoundException {
RMQMessage resp = waitForReply(timeout);
if (resp != null) {
String respStr = resp.getParameterByName("response");
if (respStr != null)
return getResponseHandler(respStr);
else {
SimpleRestResponse r = new SimpleRestResponse();
r.success = false;
r.error = "";
r.objectNode = null;
return r;
}
}
return null;
}
public SimpleRestResponse waitForTextRestReply(long timeout) throws ShutdownSignalException, IOException, InterruptedException, ClassNotFoundException {
RMQTextMessage resp = waitForTextReply(timeout);
if (resp != null) {
return getResponseHandler(resp.getMessage());
}
else {
SimpleRestResponse r = new SimpleRestResponse();
r.success = false;
r.error = "Received null reply";
r.objectNode = null;
return r;
}
}
/************************************************************************
*
* helper methods
* @throws IOException
*
***********************************************************************/
protected String sendRequest(Method method,
String entity,
String paramsPath,
String requestParams,
String content,
String key) {
RMQRestRequest request = new RMQRestRequest();
if (isConnected() == false)
return null;
if (key == null)
key = RMQKeyGenerator.generateBasicKey();
request.setKey(key);
request.setOrigin(this.originId);
request.setApp(this.app);
request.setMethod(method);
request.setEntity(entity);
if (paramsPath != null)
request.setParams(paramsPath);
if (requestParams != null)
request.setRequestParams(requestParams);
if (content != null)
request.setContent(content);
try {
if (super.sendTextMessage(request.toJson()))
return key;
else
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
protected String buildServiceId(String app, String entity) {
String serviceId = "service." + app;
for (String et: entity.split("/", 3)) {
serviceId += "." + et;
}
return serviceId;
}
protected String buildParamPath(String[] params) {
// build params-path
String paramPath = null;
if (params != null) {
paramPath = new String();
for (int i=0; i<params.length; i++) {
paramPath += "/" +params[i];
}
return paramPath;
}
else
return null;
}
protected SimpleRestResponse getResponseHandler(String respString)
{
SimpleRestResponse rr = null;
if (respString != null && !respString.isEmpty())
{
try
{
rr = objMapper.readValue(respString, SimpleRestResponse.class);
if (rr != null)
rr.prepare(objMapper);
} catch (Exception e)
{
rr = new SimpleRestResponse(false, e.toString(),null);
e.printStackTrace();
}
}
else
{
rr = new SimpleRestResponse(false, EMPTY_RESPONSE, null);
}
return rr;
}
}
package rabbitmq.common;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
public class ConnectionWrapper
{
private final Connection connection;
private final Channel channel;
private final String queueName;
public ConnectionWrapper(final String queueName, final String hostName) throws IOException, TimeoutException
{
this.queueName = queueName;
this.connection = createConnection(hostName);
this.channel = createChannel(queueName, connection);
}
public String getQueueName()
{
return queueName;
}
private Connection createConnection(final String hostName) throws IOException, TimeoutException
{
ConnectionFactory factory = new ConnectionFactory();
factory.setHost(hostName);
Connection connection = factory.newConnection();
return connection;
}
private Channel createChannel(final String queueName, final Connection connection) throws IOException
{
Channel channel = connection.createChannel();
channel.queueDeclare(queueName, false, false, false, null);
return channel;
}
public Channel getChannel()
{
return this.channel;
}
public void close() throws IOException, TimeoutException
{
this.channel.close();
}
}
\ No newline at end of file
package rabbitmq.common;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.TimeoutException;
import rabbitmq.common.RMQSender;
public class RMConnectionPool {
private Map<String, RMQSender> conns = null;
public RMConnectionPool() {
conns = new HashMap<String, RMQSender>();
}
public RMQSender connect(RMQId rmqId) {
RMQSender con = null;
con = conns.get(rmqId.getDescriptor());
if (con != null && con.isOpen())
return con;
// try to create a new connection
if (con != null)
conns.remove(con.getQueueId().getDescriptor());
try {
con = new RMQSender(rmqId.getQueue(), rmqId.getHost());
conns.put(rmqId.getDescriptor(), con);
return con;
}
catch (Exception e) {
return null;
}
}
public void closeConnection(RMQId rmqId) throws IOException, TimeoutException {
RMQSender con = conns.get(rmqId.getDescriptor());
if (con != null) {
con.closeConnection();
conns.remove(con.getQueueId().getDescriptor());
}
}
public void clear() throws IOException, TimeoutException {
for(Entry<String, RMQSender> entry : conns.entrySet()) {
RMQSender con = entry.getValue();
if (con.isOpen())
con.closeConnection();
conns.remove(con.getQueueId().getDescriptor());
}
}
public RMQSender getOpenedConnection(RMQId rmqId) {
RMQSender con = conns.get(rmqId.getDescriptor());
if (con != null && con.isOpen())
return con;
else
return null;
}
}
package rabbitmq.common;
import com.rabbitmq.client.AMQP.BasicProperties;
public class RMQBinaryMessage {
private byte[] message = null;
private BasicProperties properties = null;
public byte[] getMessage() {
return message;
}
public void setMessage(byte[] message) {
this.message = message;
}
public BasicProperties getProperties() {
return properties;
}
public void setProperties(BasicProperties properties) {
this.properties = properties;
}
}
package rabbitmq.common;
public class RMQId {
private String host = null;
private String queue = null;
public RMQId(String host, String queue) {
this.host = host;
this.queue = queue;
}
public RMQId(String descriptor) {
String[] tokens = new String[2];
tokens = descriptor.split("@");
if (tokens.length == 2) {
this.queue = tokens[0];
this.host = tokens[1];
}
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getQueue() {
return queue;
}
public void setQueue(String queue) {
this.queue = queue;
}
public String getDescriptor() { return queue + "@" + host; }
}
package rabbitmq.common;
public class RMQKeyGenerator {
private static long counter = 0;
public RMQKeyGenerator() {
}
public static String generateBasicKey() {
StringBuilder sb = new StringBuilder();
counter++;
sb.append(System.currentTimeMillis());
sb.append(";");
sb.append(counter);
return sb.toString();
}
public static String generateServiceBasedKey(String Service) {
StringBuilder sb = new StringBuilder();
counter++;
sb.append(Service);
sb.append(";");
sb.append(System.currentTimeMillis());
sb.append(";");
sb.append(counter);
return sb.toString();
}
public static String generateUserBasedKey(String Service, String userName) {
StringBuilder sb = new StringBuilder();
counter++;
sb.append(Service);
sb.append(";");
sb.append(userName);
sb.append(";");
sb.append(System.currentTimeMillis());
sb.append(";");
sb.append(counter);
return sb.toString();
}
}
package rabbitmq.common;
import java.io.IOException;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import rabbitmq.common.RMQId;
import utils.itm.ITMMessage;
public class RMQMessage extends ITMMessage implements Serializable {
private static final long serialVersionUID = 1L;
private RMQId origin = null;
protected Map<String, String> parameters = null;
public RMQMessage()
{
super();
}
public RMQMessage(int opCOde, String key)
{
super(opCOde, key);
}
public RMQId getOrigin() {
return origin;
}
public void setOrigin(RMQId origin) {
this.origin = origin;
}
public boolean parse(String textMessage) throws JsonParseException, IOException {
JsonFactory factory = new JsonFactory();
JsonParser parser = factory.createParser(textMessage);
return doParse(parser);
}
protected boolean doParse(JsonParser parser) throws JsonParseException, IOException {
JsonToken token = null;
if (parser.isClosed())
return false;
// get start object
token = parser.nextToken();
if ((token==null) || (token != null && JsonToken.START_OBJECT.equals(token)==false))
return false;
String[] field = getNextField(parser);
while (field != null) {
if (field[0].equalsIgnoreCase("oc"))
setOpCode(Integer.parseInt(field[1]));
else if (field[0].equalsIgnoreCase("key"))
setKey(field[1]);
else if (field[0].equalsIgnoreCase("oId"))
setOrigin(new RMQId(field[1]));
else
addParameter(field[0], field[1]);
field = getNextField(parser);
}
// check for the existence of the mandatory parameters
if (getOpCode() == 0 || getKey() == null)
return false;
return true;
}
protected void addParameter(String name, String value) {
if (parameters == null) {
parameters = new HashMap<String, String>();
}
parameters.put(name, value);
}
public String getParameterByName(String name) {
if (parameters != null)
return parameters.get(name);
else
return null;
}
protected String[] getNextField(JsonParser parser) throws JsonParseException, IOException {
String[] result = new String[2];
JsonToken token = null;
token = parser.nextToken();
if (token != null && token.name().equals("FIELD_NAME")) {
token = parser.nextToken();
if (token != null && (token.name().equals("VALUE_STRING") || token.name().equals("VALUE_NUMBER_INT"))) {
result[0] = parser.getCurrentName();
result[1] = parser.getValueAsString();
return result;
}
}
return null;
}
protected String[] getNextObjectField(JsonParser parser) throws JsonParseException, IOException {
String[] result = new String[2];
JsonToken token = null;
// get {
token = parser.nextToken();
if (token != null && token.name().equals("START_OBJECT")) {
// get field name
token = parser.nextToken();
if (token != null && token.name().equals("FIELD_NAME")) {
result[0] = parser.getCurrentName();
// get field value
token = parser.nextToken();
if (token != null && (token.name().equals("VALUE_STRING") || token.name().equals("VALUE_NUMBER_INT"))) {
result[1] = parser.getValueAsString();
// get }
token = parser.nextToken();
if (token != null && token.name().equals("END_OBJECT")) {
return result;
}
}
}
}
return null;
}
}
package rabbitmq.common;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
import rabbitmq.common.ConnectionWrapper;
import rabbitmq.common.RMQBinaryMessage;
import rabbitmq.common.RMQId;
import rabbitmq.common.RMQTextMessage;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.QueueingConsumer;
import com.rabbitmq.client.ShutdownSignalException;
public class RMQReciever {
private final String mQueueName;
private final String mHostName;
private final ConnectionWrapper mConnectionWrapper;
private Channel mChannel;
private QueueingConsumer mConsumer;
public RMQReciever(RMQId rmqId) throws IOException, TimeoutException
{
this.mQueueName = rmqId.getQueue();
this.mHostName = rmqId.getHost();
this.mConnectionWrapper = new ConnectionWrapper(this.mQueueName, this.mHostName);
this.mChannel = this.mConnectionWrapper.getChannel();
this.mConsumer = new QueueingConsumer(mChannel);
this.mChannel.basicConsume(this.mQueueName, true, mConsumer);
}
public RMQReciever(String queueName, String hostName) throws IOException, TimeoutException
{
this.mQueueName = queueName;
this.mHostName = hostName;
this.mConnectionWrapper = new ConnectionWrapper(queueName, hostName);
this.mChannel = this.mConnectionWrapper.getChannel();
this.mConsumer = new QueueingConsumer(mChannel);
this.mChannel.basicConsume(this.mQueueName, true, mConsumer);
}
public byte[] recieveMessage() throws IOException, ShutdownSignalException, InterruptedException {
QueueingConsumer.Delivery delivery = this.mConsumer.nextDelivery();
return delivery.getBody();
}
public RMQBinaryMessage recieveMessageWithProps(long timeout) throws IOException, ShutdownSignalException, InterruptedException {
QueueingConsumer.Delivery delivery = null;
RMQBinaryMessage rmqMsg = new RMQBinaryMessage();
if (timeout != 0)
delivery = this.mConsumer.nextDelivery(timeout);
else
delivery = this.mConsumer.nextDelivery();
if (delivery != null) {
rmqMsg.setProperties(delivery.getProperties());
rmqMsg.setMessage(delivery.getBody());
return rmqMsg;
}
else
return null;
}
public String recieveTextMessage (long timeout) throws IOException, ShutdownSignalException, InterruptedException
{
QueueingConsumer.Delivery delivery = null;
if (timeout != 0)
delivery = mConsumer.nextDelivery(timeout);
else
delivery = mConsumer.nextDelivery();
if (delivery != null) {
String txtMsg = new String(delivery.getBody(), "UTF-8");
return txtMsg;
}
else
return null;
}
public RMQTextMessage recieveTextMessageWithProps(long timeout) throws IOException, ShutdownSignalException, InterruptedException
{
QueueingConsumer.Delivery delivery = null;
RMQTextMessage textMessage = new RMQTextMessage();
if (timeout != 0)
delivery = mConsumer.nextDelivery(timeout);
else
delivery = mConsumer.nextDelivery();
if (delivery != null) {
textMessage.setProperties(delivery.getProperties());
String txtMsg = new String(delivery.getBody(), "UTF-8");
textMessage.setMessage(txtMsg);
return textMessage;
}
else
return null;
}
public void purge() throws IOException {
this.mChannel.queuePurge(this.mQueueName);
}
}
package rabbitmq.common;
import java.io.IOException;
import java.io.Serializable;
import java.io.StringWriter;
import java.util.Map.Entry;
import utils.http.simpleHttpClient.SimpleHttpRequest.Method;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
public class RMQRestRequest extends RMQMessage implements Serializable {
private static final long serialVersionUID = 1L;
public static final int OC_REST_REQUEST = 1000;
public static final String METHOD = "METHOD";
public static final String APP = "APP";
public static final String ENTITY = "ENTITY";
public static final String PARAMS = "PARAMS";
public static final String REQUEST_PARAMS = "REQUEST_PARAMS";
public static final String CONTENT = "CONTENT";
public RMQRestRequest() {
setOpCode(OC_REST_REQUEST);
}
public void setMethod(Method method) {
addParameter(METHOD, method.toString());
}
public void setApp(String app) {
addParameter(APP, app);
}
public void setEntity(String entity) {
addParameter(ENTITY, entity);
}
public void setParams(String params) {
addParameter(PARAMS, params);
}
public void setRequestParams(String requestParams) {
addParameter(REQUEST_PARAMS, requestParams);
}
public void setContent(String content) {
addParameter(CONTENT, content);
}
@SuppressWarnings("deprecation")
public String toJson() throws IOException {
StringWriter sw = new StringWriter();
JsonGenerator generator = new JsonFactory().createJsonGenerator(sw);
generator.writeStartObject();
basicParametersToJson(generator);
// add parameters
if (parameters != null && parameters.size() > 0) {
for(Entry<String, String> param : parameters.entrySet()) {
generator.writeStringField(param.getKey(), param.getValue());
}
}
generator.writeEndObject();
generator.close();
return sw.toString();
}
protected void basicParametersToJson(JsonGenerator generator) throws IOException {
// oc
generator.writeNumberField("oc", getOpCode());
// key
generator.writeStringField("key", getKey());
// origin id
RMQId oId = getOrigin();
if (oId != null)
generator.writeStringField("oid", oId.getDescriptor());
}
}
package rabbitmq.common;
import java.io.Serializable;
public class RMQRestResponse extends RMQMessage implements Serializable {
private static final long serialVersionUID = 1L;
public static final int OC_REST_RESPONSE = 1001;
public static final String CONTENT = "CONTENT";
public RMQRestResponse() {
setOpCode(OC_REST_RESPONSE);
}
public void setContent(String content) {
addParameter(CONTENT, content);
}
}
package rabbitmq.common;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.AMQP.BasicProperties;
import rabbitmq.common.ConnectionWrapper;
import rabbitmq.common.RMQId;
public class RMQSender
{
private final ConnectionWrapper connectionWrapper;
private final String queueName;
private final String hostName;
public RMQSender(String queueName, String hostName) throws IOException, TimeoutException
{
this.queueName = queueName;
this.hostName = hostName;
this.connectionWrapper = new ConnectionWrapper(queueName, hostName);
}
public RMQSender(RMQId rmqId) throws IOException, TimeoutException
{
this(rmqId.getQueue(), rmqId.getHost());
}
public void sendMessage(String textMessage, RMQId originId) throws IOException
{
BasicProperties basicProps = null;
if (originId != null)
basicProps = CreateMessageProperites(originId);
connectionWrapper.getChannel().basicPublish("", this.queueName, basicProps, textMessage.getBytes());
}
public void sendMessage(byte[] bytesMessage, RMQId originId) throws IOException
{
BasicProperties basicProps = null;
if (originId != null)
basicProps = CreateMessageProperites(originId);
connectionWrapper.getChannel().basicPublish("", this.queueName, basicProps, bytesMessage);
}
public void sendMessage(Object objMessage, RMQId originId) throws IOException
{
byte[] bytesMsg = serializeObject(objMessage);
BasicProperties basicProps = null;
if (originId != null)
basicProps = CreateMessageProperites(originId);
connectionWrapper.getChannel().basicPublish("", this.queueName, basicProps, bytesMsg);
}
public void closeConnection() throws IOException , TimeoutException{
connectionWrapper.close();
}
public boolean isOpen() {
return connectionWrapper.getChannel().isOpen();
}
public RMQId getQueueId() {
return new RMQId(this.hostName, this.queueName);
}
protected byte[] serializeObject(Object msg) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = null;
try {
out = new ObjectOutputStream(bos);
out.writeObject(msg);
byte[] bytesArr = bos.toByteArray();
return bytesArr;
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException ex) {
// ignore close exception
}
try {
bos.close();
} catch (IOException ex) {
// ignore close exception
}
}
}
protected BasicProperties CreateMessageProperites(RMQId originId) {
// add to message 2 headers containing the originating host & queue
AMQP.BasicProperties.Builder propsBuilder = new AMQP.BasicProperties().builder();
Map<String,Object> headers = new HashMap<String,Object>();
headers.put("OriginHost", originId.getHost());
headers.put("OriginQueue", originId.getQueue());
propsBuilder.headers(headers);
return propsBuilder.build();
}
}
\ No newline at end of file
package rabbitmq.common;
import com.rabbitmq.client.AMQP.BasicProperties;
public class RMQTextMessage {
private String message = null;
private BasicProperties properties = null;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public BasicProperties getProperties() {
return properties;
}
public void setProperties(BasicProperties properties) {
this.properties = properties;
}
}
package rabbitmq.server;
import rabbitmq.common.RMQId;
import rabbitmq.common.RMQMessage;
public abstract class RMQHandler {
protected RMQId listenerRmqId = null;
protected String apiContextPath = null;
public RMQHandler()
{
}
public RMQHandler(RMQId listenerRmqId, String apiContextPath)
{
this.listenerRmqId = listenerRmqId;
this.apiContextPath = apiContextPath;
}
public void setListenerRmqId(RMQId listenerRmqId) {
this.listenerRmqId = listenerRmqId;
}
public void setApiContextPath(String apiContextPath) {
this.apiContextPath = apiContextPath;
}
public RMQId getListenerRmqId() {
return listenerRmqId;
}
public String getApiContextPath() {
return apiContextPath;
}
public abstract void handleRequest(RMQMessage message) throws Exception;
}
package rabbitmq.server;
/*
* MDSThreadManager
* a thread manager with a support a rabbit queue interface to outside world
*/
import java.io.IOException;
import java.io.ByteArrayInputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;
import java.util.logging.Level;
import rabbitmq.common.RMQSender;
import rabbitmq.common.RMQMessage;
import rabbitmq.common.RMQId;
import itc.ItcMessage;
import itc.ItcMessageQueue;
import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.ShutdownSignalException;
//import rabbitmq.reciever.RMQMessage;
import rabbitmq.common.RMQReciever;
import rabbitmq.common.RMQTextMessage;
import utils.common.SimpleLogger;
import utils.itm.ITMManager;
import utils.itm.ITMThread;
public class RMQServer extends ITMManager {
protected RMQReciever mRMQReciever = null;
protected RMQId listenRMQId = null;
protected SimpleLogger logger = null;
protected int numOfWorkerThreads = 0;
protected int maxRMQSize = 0;
protected String logPath = null;
protected Map<String, RMQHandler> rmqHandlers = new HashMap<String, RMQHandler>();
public boolean Init(String appName,
String logPath,
String rmqId,
int numOfWorkerThreads,
int maxRMQSize) {
this.moduleName = appName;
this.listenRMQId = new RMQId(rmqId);
this.numOfWorkerThreads = numOfWorkerThreads;
this.maxQueueSize = maxRMQSize;
// logger
if (createLogger(appName, logPath) == false) {
logger.log(Level.SEVERE, " Failed to create logger");
return false;
}
return super.Init(numOfWorkerThreads, maxQueueSize, 0, moduleName, logger);
}
public boolean Init(RMQId listenRMQId,
int numOfWorkerThreads,
int maxQueueSize,
String moduleName,
SimpleLogger logger) {
this.listenRMQId = listenRMQId;
return super.Init(numOfWorkerThreads, maxQueueSize, 0, moduleName, logger);
}
/*
* override the super class InitListenQ and implement a rabbitMQ listener
*/
@Override
public boolean InitListenQ() {
try {
// empty queue on init if configured to do so
boolean isEmptyQueueOnLoad = false;
String strEmptyQueueOnLoad = System.getProperty("rmqServer.emptyQueueOnLoad");
if (strEmptyQueueOnLoad == null) {
logSevere("RMQServer::InitListenQ", "failed to read 'EmptyQueueOnLoad' from config file", null);
return false;
}
isEmptyQueueOnLoad = Boolean.parseBoolean(strEmptyQueueOnLoad);
// create the queue
mRMQReciever = new RMQReciever(listenRMQId.getQueue(), listenRMQId.getHost());
if (isEmptyQueueOnLoad) {
mRMQReciever.purge();
}
} catch (IOException e) {
e.printStackTrace();
logSevere("RMQServer::InitListenQ", "InitListenQ() failed", e);
return false;
}
catch (TimeoutException e) {
e.printStackTrace();
logSevere("RMQServer::InitListenQ", "InitListenQ() failed on timeout", e);
return false;
}
return true;
}
private boolean createLogger(String appName,
String logPath) {
logName = appName;
logger = new SimpleLogger();
return logger.Initialize(logName, logPath, Level.ALL);
}
@Override
public ITMThread CreateThread() {
return new RMQThread(rmqHandlers);
}
@Override
public byte[] ReceiveMsg() {
// TODO Auto-generated method stub
return null;
}
@Override
public void HandleMsg() throws ClassNotFoundException, IOException
{
try {
// wait for message to arrive
RMQTextMessage rmqMsg = mRMQReciever.recieveTextMessageWithProps(0);
// parse the message, but only the basic fields needed for routing
// the message to a worker thread
RMQMessage baseMsg = new RMQMessage();
if (baseMsg.parse(rmqMsg.getMessage()) == false)
{
String logMsg = "Failed to parse message: " + rmqMsg.getMessage();
logSevere("RMQServer.HandleMsg - ", logMsg, null);
}
// log msg
String logMsg = "Received message. code: " + baseMsg.getOpCode();
logMsg += " key: " + baseMsg.getKey();
if (baseMsg.getOrigin() != null)
logMsg += " from: " + baseMsg.getOrigin().getDescriptor();
logInfo("RMQServer.HandleMsg - auto reply", logMsg);
DispatchMsgToThread(baseMsg.getKey(), baseMsg.getOpCode(), rmqMsg.getMessage());
}
catch (Exception e)
{
logSevere("RMQServer.HandleMsg", "mRMQServer.recieveMessageWithProps() failed", e);
return;
}
}
public void setHandler(RMQHandler handler) {
rmqHandlers.put(handler.getApiContextPath(), handler);
}
protected void DispatchMsgToThread(String key, int opCode, String txtMessage) throws ClassNotFoundException, IOException
{
// validate mandatory parameters
if (key == null) {
logSevere("RMQServer:DispatchMsgToThread", "DispatchMsgToThread - Failed. key is NULL. opCode: " + opCode, null);
return;
}
int thrdIndex = getThreadNumber(key);
if (thrdIndex >= 0 && thrdIndex < numOfThreads)
{
// get the thread's queue
ItcMessageQueue thrdQ = thrdQList.get(thrdIndex);
if (thrdQ != null)
{
ItcMessage itcMsg = new ItcMessage(opCode, txtMessage, null, false);
thrdQ.forwardMsg(itcMsg);
String logMsg = "msg dispatched to thread: " + thrdIndex + " key: " + key;
logInfo("RMQServer:DispatchMsgToThread", logMsg);
}
else
logSevere("RMQServer:DispatchMsgToThread", "DispatchMsgToThread - Failed to find Q for thrdIndex: " + thrdIndex, null);
}
else
logSevere("RMQServer:DispatchMsgToThread", "Thread index out of range", null);
}
}
package rabbitmq.server;
import java.io.IOException;
import java.util.Map;
import java.util.logging.Level;
import com.fasterxml.jackson.core.JsonParseException;
import rabbitmq.common.*;
import utils.itm.ITMThread;
public class RMQThread extends ITMThread
{
protected Map<String, RMQHandler> rmqHandlers = null;
public RMQThread(Map<String, RMQHandler> rmqHandlers) {
this.rmqHandlers = rmqHandlers;
}
@Override
public void HandleMsg(int opCode, Object msg) throws InterruptedException, JsonParseException, IOException {
String txtMessage = (String)msg;
RMQMessage rmqMessage = new RMQMessage();
if (rmqMessage.parse(txtMessage)) {
try {
String appName = rmqMessage.getParameterByName(RMQRestRequest.APP);
if (appName != null) {
RMQHandler handler = findHandler(appName);
if (handler != null)
handler.handleRequest(rmqMessage);
else
logger.log(Level.SEVERE, "RMQThread.HandleMsg - failed to find handler for: " + appName);
}
else
logger.log(Level.SEVERE, "RMQThread.HandleMsg - failed to find APP parameres request");
} catch (Exception e) {
e.printStackTrace();
}
}
}
private RMQHandler findHandler(String appContextApi) {
RMQHandler handler = rmqHandlers.get(appContextApi);
if (handler == null) {
// check the opposite option for /
String firstChar = appContextApi.substring(0, 1);
if (firstChar.equals("/")) {
// remove the /
StringBuilder sb = new StringBuilder(appContextApi);
appContextApi = sb.deleteCharAt(0).toString();
}
else {
// add /
StringBuilder sb = new StringBuilder(appContextApi);
appContextApi = sb.insert(0, '/').toString();
}
// now try again
handler = rmqHandlers.get(appContextApi);
}
return handler;
}
}
/**
* @author adi
*
*/
package rabbitmq.server;
\ No newline at end of file
package rabbitmq.impl;
public class Receiver {
// public static void main(String[] args) throws IOException, ClassNotFoundException, ShutdownSignalException, ConsumerCancelledException, InterruptedException {
//
//// RMQServerWrapper server = new RMQServerWrapper("MyQueue", "localhost");
//// byte[] recieveMessage = server.recieveMessage();
////
//// ByteArrayInputStream bis = new ByteArrayInputStream(recieveMessage);
////
//// ObjectInput in = new ObjectInputStream(bis);
//// Object readObject;
//// try {
//// readObject = in.readObject();
//// } finally {
//// }
////
//// ModelHierarchy deserializedCar = (ModelHierarchy)readObject;
// }
}
package rabbitmq.impl;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.util.concurrent.TimeoutException;
import org.junit.Test;
import rabbitmq.common.RMQSender;
import rabbitmq.model.ModelHierarchy;
public class Sender {
// uncomment to test
//@Test
public void testSender() throws IOException, TimeoutException {
ModelHierarchy model = new ModelHierarchy();
RMQSender rmqClient = new RMQSender("MyQueue", "localhost");
byte[] serializedObject = serializeObject(model);
rmqClient.sendMessage(serializedObject, null);
}
private static byte[] serializeObject(ModelHierarchy model) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = null;
try {
out = new ObjectOutputStream(bos);
out.writeObject(model);
byte[] bytesArr = bos.toByteArray();
return bytesArr;
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException ex) {
// ignore close exception
}
try {
bos.close();
} catch (IOException ex) {
// ignore close exception
}
}
}
}
\ No newline at end of file
package rabbitmq.impl;
import static org.junit.Assert.*;
import org.junit.Test;
public class testRMQRestClient {
@Test
public void test() {
fail("Not yet implemented");
}
}
package rabbitmq.model;
import java.io.Serializable;
public class Car implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private String mdoel;
private Wheel wheel;
public Car() {
}
public String getMdoel() {
return mdoel;
}
public void setMdoel(String mdoel) {
this.mdoel = mdoel;
}
public Wheel getWheel() {
return wheel;
}
public void setWheel(Wheel wheel) {
this.wheel = wheel;
}
}
package rabbitmq.model;
import java.io.Serializable;
public class ModelHierarchy implements Serializable{
private static final long serialVersionUID = 1L;
private Car car;
public ModelHierarchy() {
car = new Car();
car.setMdoel("Volvo");
final Wheel wheel = new Wheel();
wheel.setDiameter(5);
car.setWheel(wheel);
}
}
package rabbitmq.model;
import java.io.Serializable;
public class Wheel implements Serializable{
private static final long serialVersionUID = 1L;
private int diameter;
public Wheel() {
}
public int getDiameter() {
return diameter;
}
public void setDiameter(int diameter) {
this.diameter = diameter;
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment