Could Not autowire an object in Mule component - eclipse

I am trying to autowire an object of a service class in mule flow. The code is:
public class SignatureValidator implements Callable
{
#Autowired
private TriggerHostServiceImpl triggerHostServiceImpl;
#Override
public Object onCall(MuleEventContext eventContext) throws Exception
{
MuleMessage message = eventContext.getMessage();
message = fetchPropertiesAndValidateMessageSignature(message);
return message.getPayload();
}
private MuleMessage fetchPropertiesAndValidateMessageSignature(MuleMessage message) throws GeneralSecurityException, IOException
{
String muleWSTriggerLabel = message.getInboundProperty("triggerLabel");
String muleWSSignature = message.getInboundProperty("signature");
String muleWSExpiresOn = message.getInboundProperty("expiresOn");
String xmlData = message.getInboundProperty("xmlData");
String appHostName = InitConfigurationLoader.getConfigSetting("applicationHostingName");
Trigger triggerJaxbObject = (Trigger) message.getPayload();
String applicationIdentifier = triggerJaxbObject.getApplicationIdentifier();
TriggerMapper triggerMapper = FetchConfigurationEntities.getTriggerMapper(applicationIdentifier, muleWSTriggerLabel);
String reportEmail = FetchConfigurationEntities.getReportEmail(triggerMapper);
ImportDetails importInstance = FetchConfigurationEntities.getImport(triggerMapper);
String importInstanceURL = importInstance.getWebserviceURL();
message.setInvocationProperty("triggerJaxbObject", triggerJaxbObject);
message.setInvocationProperty("importInstance", importInstance);
message.setInvocationProperty("reportEmail", reportEmail);
message.setInvocationProperty("appIdentifier", applicationIdentifier);
message.setInvocationProperty("importHost", importInstanceURL.substring(importInstanceURL.lastIndexOf('/')+1, importInstanceURL.length()));
setPayloadAfterValidation(message, muleWSTriggerLabel, xmlData, muleWSSignature, appHostName, muleWSExpiresOn);
return message;
}
My service class is:
package com.catalystone.csi.service;
import java.util.Map;
import java.util.Map.Entry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.catalystone.csi.core.cache.UpdateCacheable;
import com.catalystone.csi.dao.TriggerHostDao;
import com.catalystone.csi.model.TriggerHost;
#Service
public class TriggerHostServiceImpl implements TriggerHostService
{
#Autowired
private TriggerHostDao triggerHostDao;
#Autowired
private UpdateCacheable updateCacheable;
/**
* Method to save mule configurations i.e. TriggerHosts
*/
#Override
#Transactional
public boolean saveTriggerHost(TriggerHost triggerHost)
{
if(triggerHostDao.saveTriggerHost(triggerHost))
{
Map<String, TriggerHost> allTriggerHosts = getAllTriggerHosts();
allTriggerHosts.put(triggerHost.getTriggerIdentifier(), triggerHost);
updateCacheable.updateAllTriggerHostCache(allTriggerHosts);
return true;
}
else
return false;
}
/**
* Method to fetch all the configurations
*/
#Override
#Transactional//this annotation is used to maintain transaction
public Map<String, TriggerHost> getAllTriggerHosts()
{
return triggerHostDao.getAllTriggerHosts();
}
/**
* Method to delete mule configuration for triggerHost
* #return - true if delete configuration is successfully done
*/
#Override
#Transactional//this annotation is used to maintain transaction
public Boolean deleteConfiguration(TriggerHost triggerHost, boolean isMultipleImportOccurrence)
{
Boolean isDeleteSuccessful = triggerHostDao.deleteConfiguration(triggerHost, isMultipleImportOccurrence);
//Getting all the configurations from cache
Map<String, TriggerHost> allTriggerHosts = getAllTriggerHosts();
//check if delete configuration successful then remove that configuration from cache
if(isDeleteSuccessful)
{
for(Entry<String, TriggerHost> triggerHostEntry : allTriggerHosts.entrySet())
{
if(triggerHostEntry.getValue().getTriggerIdentifier().equals(triggerHost.getTriggerIdentifier()))
{
allTriggerHosts.remove(triggerHostEntry.getKey());
break;
}
}
//update cache
updateCacheable.updateAllTriggerHostCache(allTriggerHosts);
return true;
}
return false;
}
#Override
#Transactional
public Boolean updateConfiguration(TriggerHost triggerHost)
{
if(triggerHostDao.updateConfiguration(triggerHost))
{
Map<String, TriggerHost> allTriggerHosts = getAllTriggerHosts();
allTriggerHosts.put(triggerHost.getTriggerIdentifier(), triggerHost);
updateCacheable.updateAllTriggerHostCache(allTriggerHosts);
return true;
}
return false;
}
#Override
#Transactional
public Boolean deleteConfiguration(String existingImportIdentifier)
{
return triggerHostDao.deleteConfiguration(existingImportIdentifier);
}
}
when I run this code then value of triggerHostServiceImpl is always null. How to autowire? I have also tried a link Dependency Injection is working at Mule application startup. Objects are getting null, when a request received and Failing by throwing NullEx
and
Spring3 Dependency Injection not working with mule
but then it is giving me so many exception that I couldn't get.

you have to Autowire the Interface not the Implementation
#Autowired
private TriggerHostService triggerHostService;
and add the setter and getter of triggerHostService

Related

How to abandon rollout with Rollout Config Action Class on a specific target page in MSM in AEM 6.4

I want to control rollout on a target on the basis of some condition matched in a page. If condition fails, the rollout should not happen.
I have create a rollout config class using BaseActionFactory and BaseAction. Can we abandon rollout on specific target if the condition fails.
#Component(metatype=false)
#Service
public class FilterRoleActionFactory extends BaseActionFactory<BaseAction>{
private static final Logger LOG = LoggerFactory.getLogger(FilterRoleActionFactory.class);
#Property(name="liveActionName", propertyPrivate=true)
private static final String[] LIVE_ACTION_NAME = {FilterRoleAction.class.getSimpleName(), "filterRoleAction"};
#Reference
private RolloutManager rolloutManager;
protected void bindRolloutManager(RolloutManager rolloutManager) {
this.rolloutManager = rolloutManager;
}
protected void unbindRolloutManager(RolloutManager rolloutManager) {
if(this.rolloutManager == rolloutManager) {
this.rolloutManager = null;
}
}
#Override
public String createsAction() {
return LIVE_ACTION_NAME[0];
}
#Override
protected BaseAction newActionInstance(ValueMap config) throws WCMException {
return new FilterRoleAction(config, this);
}
private static final class FilterRoleAction extends BaseAction{
private static final Logger LOG = LoggerFactory.getLogger(FilterRoleAction.class);
private static Map<String, List<String>> roleMap = new HashMap<>();
static {
roleMap.put("master-ip",Arrays.asList("enterprise:role/investment-professional/non-us-investment-professional","enterprise:role/investment-professional/us-investment-professional"));
roleMap.put("master-insti", Arrays.asList("enterprise:role/institutional/non-us-institutional", "enterprise:role/institutional/us-institutional"));
roleMap.put("master-inv", Arrays.asList("enterprise:role/public/public-non-us", "enterprise:role/public/public-us"));
};
protected FilterRoleAction(ValueMap config, BaseActionFactory<? extends LiveAction> liveActionFactory) {
super(config, liveActionFactory);
}
#Override
protected boolean handles(Resource resource, Resource target, LiveRelationship relation, boolean resetRollout)
throws RepositoryException, WCMException {
return target != null && relation.getStatus().isPage();
}
#Override
protected void doExecute(Resource resource, Resource target, LiveRelationship relation, boolean resetRollout)
throws RepositoryException, WCMException {
ValueMap valueMap = resource.getValueMap();
Object tags = valueMap.get(MFSConstants.CQ_COLON_TAGS);
LOG.debug("Tags {} ", tags);
String targetPath = StringUtils.replaceFirst(target.getPath(), "/content/mfs-enterprise/mfscom/masters/", "");
String targetRole = StringUtils.substringBefore(targetPath, "/");
boolean isRolloutAllowed = false;
if(tags != null) {
String[] tagArray = (String[])tags;
for(String tag : tagArray) {
List<String> roles = roleMap.get(targetRole);
if(roles.contains(tag)) {
isRolloutAllowed = true;
break;
}
}
}
if(!isRolloutAllowed) {
LOG.debug("Throwing an Exception, as Role is not allowed. Page Path: {} ",target.getPath());
throw new WCMException("Rollout is not allowed on this page: "+target.getPath()) ;
}
}
}
if isRolloutAllowed is false then i need to abandon the rollout for the target while it should continue processing for other target pages.

xtext parameterized xtext runner

Purpose: Run parameterized tests within xtext/xtend context.
Progress: So far I have achieved getting it to run, but it is appearing wrong in the junit window.
Issues:
The failure trace and results of both tests appear in the last test, as shown in the figure below.
The first test, marked by the red pen, is sort of unresolved and does not contain any failure trace.
Here is the test class:
#RunWith(typeof(Parameterized))
#InjectWith(SemanticAdaptationInjectorProvider)
#Parameterized.UseParametersRunnerFactory(XtextParametersRunnerFactory)
class CgCppAutoTest extends AbstractSemanticAdaptationTest {
new (List<File> files)
{
f = files;
}
#Inject extension ParseHelper<SemanticAdaptation>
#Inject extension ValidationTestHelper
#Parameters(name = "{index}")
def static Collection<Object[]> data() {
val files = new ArrayList<List<File>>();
listf("test_input", files);
val test = new ArrayList();
test.add(files.get(0));
return Arrays.asList(test.toArray(), test.toArray());
}
def static void listf(String directoryName, List<List<File>> files) {
...
}
var List<File> f;
#Test def allSemanticAdaptations() {
System.out.println("fail");
assertTrue(false);
}
}
ParameterizedXtextRunner (Inspiration from here: https://www.eclipse.org/forums/index.php?t=msg&th=1075706&goto=1726802&):
class ParameterizedXtextRunner extends XtextRunner {
val Object[] parameters;
val String annotatedName;
new(TestWithParameters test) throws InitializationError {
super(test.testClass.javaClass)
parameters = test.parameters;
annotatedName = test.name;
}
override protected getName() {
return super.name + annotatedName;
}
override protected createTest() throws Exception {
val object = testClass.onlyConstructor.newInstance(parameters)
val injectorProvider = getOrCreateInjectorProvider
if (injectorProvider != null) {
val injector = injectorProvider.injector
if (injector != null)
injector.injectMembers(object)
}
return object;
}
override protected void validateConstructor(List<Throwable> errors) {
validateOnlyOneConstructor(errors)
}
And finally XtextParametersRunnerFactory:
class XtextParametersRunnerFactory implements ParametersRunnerFactory {
override createRunnerForTestWithParameters(TestWithParameters test) throws InitializationError {
new ParameterizedXtextRunner(test)
}
}
By looking at the XtextRunner class it inherits from BlockJUnit4ClassRunner.
Parameterized does not extend this runner, but
ParentRunner. However, so does BlockJUnit4ClassRunner
Therefore we implemented it as below:
public class XtextParametersRunnerFactory implements ParametersRunnerFactory {
#Override
public Runner createRunnerForTestWithParameters(TestWithParameters test) throws InitializationError {
return new XtextRunnerWithParameters(test);
}
}
And used the code from XtextRunner and put it into the new runner -- it is necessary to extract InjectorProviders from Xtext as well
public class XtextRunnerWithParameters extends BlockJUnit4ClassRunnerWithParameters {
public XtextRunnerWithParameters(TestWithParameters test) throws InitializationError {
super(test);
}
#Override
public Object createTest() throws Exception {
Object object = super.createTest();
IInjectorProvider injectorProvider = getOrCreateInjectorProvider();
if (injectorProvider != null) {
Injector injector = injectorProvider.getInjector();
if (injector != null)
injector.injectMembers(object);
}
return object;
}
#Override
protected Statement methodBlock(FrameworkMethod method) {
IInjectorProvider injectorProvider = getOrCreateInjectorProvider();
if (injectorProvider instanceof IRegistryConfigurator) {
final IRegistryConfigurator registryConfigurator = (IRegistryConfigurator) injectorProvider;
registryConfigurator.setupRegistry();
final Statement methodBlock = superMethodBlock(method);
return new Statement() {
#Override
public void evaluate() throws Throwable {
try {
methodBlock.evaluate();
} finally {
registryConfigurator.restoreRegistry();
}
}
};
}else{
return superMethodBlock(method);
}
}
protected Statement superMethodBlock(FrameworkMethod method) {
return super.methodBlock(method);
}
protected IInjectorProvider getOrCreateInjectorProvider() {
return InjectorProviders.getOrCreateInjectorProvider(getTestClass());
}
protected IInjectorProvider getInjectorProvider() {
return InjectorProviders.getInjectorProvider(getTestClass());
}
protected IInjectorProvider createInjectorProvider() {
return InjectorProviders.createInjectorProvider(getTestClass());
}
}
Creating a test:
#RunWith(typeof(Parameterized))
#InjectWith(SemanticAdaptationInjectorProvider)
#Parameterized.UseParametersRunnerFactory(XtextParametersRunnerFactory)
class xxx
{
#Inject extension ParseHelper<SemanticAdaptation>
#Inject extension ValidationTestHelper
// Here goes standard parameterized stuff
}
due to OSGi import package constraits and deprecation I use this adoption of the original code:
package de.uni_leipzig.pkr.handparser.tests.runners;
import org.eclipse.xtext.testing.IInjectorProvider;
import org.eclipse.xtext.testing.IRegistryConfigurator;
import org.eclipse.xtext.testing.XtextRunner;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.InitializationError;
import org.junit.runners.model.Statement;
import org.junit.runners.parameterized.BlockJUnit4ClassRunnerWithParameters;
import org.junit.runners.parameterized.TestWithParameters;
import com.google.inject.Injector;
public class XtextRunnerWithParameters extends BlockJUnit4ClassRunnerWithParameters {
public static class MyXtextRunner extends XtextRunner {
public MyXtextRunner(Class<?> testClass) throws InitializationError {
super(testClass);
}
public IInjectorProvider getOrCreateInjectorProvider() {
return super.getOrCreateInjectorProvider();
}
}
private MyXtextRunner xtextRunner;
public XtextRunnerWithParameters(TestWithParameters test) throws InitializationError {
super(test);
xtextRunner = new MyXtextRunner(test.getTestClass().getJavaClass());
}
#Override
public Object createTest() throws Exception {
Object object = super.createTest();
IInjectorProvider injectorProvider = xtextRunner.getOrCreateInjectorProvider();
if (injectorProvider != null) {
Injector injector = injectorProvider.getInjector();
if (injector != null)
injector.injectMembers(object);
}
return object;
}
#Override
protected Statement methodBlock(FrameworkMethod method) {
IInjectorProvider injectorProvider = xtextRunner.getOrCreateInjectorProvider();
if (injectorProvider instanceof IRegistryConfigurator) {
final IRegistryConfigurator registryConfigurator = (IRegistryConfigurator) injectorProvider;
registryConfigurator.setupRegistry();
final Statement methodBlock = superMethodBlock(method);
return new Statement() {
#Override
public void evaluate() throws Throwable {
try {
methodBlock.evaluate();
} finally {
registryConfigurator.restoreRegistry();
}
}
};
} else {
return superMethodBlock(method);
}
}
protected Statement superMethodBlock(FrameworkMethod method) {
return super.methodBlock(method);
}
}

GCM XMPP Server using Smack 4.1.0

I'm trying to adapt the example provided here for Smack 4.1.0. and getting a little confused.
Specifically I'm struggling to understand what the GcmPacketExtension should now extend, how the constructor should work and how the Providermanager.addExtensionProvider should be updated to tie in with it.
I'm sure someone must have done this before but I can't find any examples
and I seem to be going round in circles using just the documentation.
Any help would be much appreciated, I'm sure the answer is very simple!
Current Code (is compiling but not running):
static {
ProviderManager.addExtensionProvider(GCM_ELEMENT_NAME, GCM_NAMESPACE, new ExtensionElementProvider<ExtensionElement>() {
#Override
public DefaultExtensionElement parse(XmlPullParser parser,int initialDepth) throws org.xmlpull.v1.XmlPullParserException,
IOException {
String json = parser.nextText();
return new GcmPacketExtension(json);
}
});
}
and:
private static final class GcmPacketExtension extends DefaultExtensionElement {
private final String json;
public GcmPacketExtension(String json) {
super(GCM_ELEMENT_NAME, GCM_NAMESPACE);
this.json = json;
}
public String getJson() {
return json;
}
#Override
public String toXML() {
return String.format("<%s xmlns=\"%s\">%s</%s>",
GCM_ELEMENT_NAME, GCM_NAMESPACE,
StringUtils.escapeForXML(json), GCM_ELEMENT_NAME);
}
public Stanza toPacket() {
Message message = new Message();
message.addExtension(this);
return message;
}
}
Current exception:
Exception in thread "main" java.lang.NoClassDefFoundError: de/measite/minidns/DNSCache
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at org.jivesoftware.smack.SmackInitialization.loadSmackClass(SmackInitialization.java:213)
at org.jivesoftware.smack.SmackInitialization.parseClassesToLoad(SmackInitialization.java:193)
at org.jivesoftware.smack.SmackInitialization.processConfigFile(SmackInitialization.java:163)
at org.jivesoftware.smack.SmackInitialization.processConfigFile(SmackInitialization.java:148)
at org.jivesoftware.smack.SmackInitialization.<clinit>(SmackInitialization.java:116)
at org.jivesoftware.smack.SmackConfiguration.getVersion(SmackConfiguration.java:96)
at org.jivesoftware.smack.provider.ProviderManager.<clinit>(ProviderManager.java:121)
at SmackCcsClient.<clinit>(SmackCcsClient.java:58)
Caused by: java.lang.ClassNotFoundException: de.measite.minidns.DNSCache
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 10 more
OK, so I managed to get it working after much reading and pain, so here is a VERY crude server implementation that actually works. Obviously not for production and feel free to correct anything that's wrong. I'm not saying this is the best way to do it but it does work. It will send a message and receive messages but only shows them in the log.
import org.jivesoftware.smack.ConnectionConfiguration.SecurityMode;
import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.SmackException.NotConnectedException;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.DefaultExtensionElement;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Stanza;
import org.jivesoftware.smack.filter.StanzaFilter;
import org.jivesoftware.smack.provider.ProviderManager;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;
import org.jivesoftware.smack.util.StringUtils;
import org.json.simple.JSONValue;
import org.json.simple.parser.ParseException;
import org.xmlpull.v1.XmlPullParser;
import org.jivesoftware.smack.*;
import org.jivesoftware.smack.packet.ExtensionElement;
import org.jivesoftware.smack.provider.ExtensionElementProvider;
import org.jivesoftware.smack.roster.Roster;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.SSLSocketFactory;
/**
* Sample Smack implementation of a client for GCM Cloud Connection Server. This
* code can be run as a standalone CCS client.
*
* <p>For illustration purposes only.
*/
public class SmackCcsClient {
private static final Logger logger = Logger.getLogger("SmackCcsClient");
private static final String GCM_SERVER = "gcm.googleapis.com";
private static final int GCM_PORT = 5235;
private static final String GCM_ELEMENT_NAME = "gcm";
private static final String GCM_NAMESPACE = "google:mobile:data";
private static final String YOUR_PROJECT_ID = "<your ID here>";
private static final String YOUR_API_KEY = "<your API Key here>"; // your API Key
private static final String YOUR_PHONE_REG_ID = "<your test phone's registration id here>";
static {
ProviderManager.addExtensionProvider(GCM_ELEMENT_NAME, GCM_NAMESPACE, new ExtensionElementProvider<ExtensionElement>() {
#Override
public DefaultExtensionElement parse(XmlPullParser parser,int initialDepth) throws org.xmlpull.v1.XmlPullParserException,
IOException {
String json = parser.nextText();
return new GcmPacketExtension(json);
}
});
}
private XMPPTCPConnection connection;
/**
* Indicates whether the connection is in draining state, which means that it
* will not accept any new downstream messages.
*/
protected volatile boolean connectionDraining = false;
/**
* Sends a downstream message to GCM.
*
* #return true if the message has been successfully sent.
*/
public boolean sendDownstreamMessage(String jsonRequest) throws
NotConnectedException {
if (!connectionDraining) {
send(jsonRequest);
return true;
}
logger.info("Dropping downstream message since the connection is draining");
return false;
}
/**
* Returns a random message id to uniquely identify a message.
*
* <p>Note: This is generated by a pseudo random number generator for
* illustration purpose, and is not guaranteed to be unique.
*/
public String nextMessageId() {
return "m-" + UUID.randomUUID().toString();
}
/**
* Sends a packet with contents provided.
*/
protected void send(String jsonRequest) throws NotConnectedException {
Stanza request = new GcmPacketExtension(jsonRequest).toPacket();
connection.sendStanza(request);
}
/**
* Handles an upstream data message from a device application.
*
* <p>This sample echo server sends an echo message back to the device.
* Subclasses should override this method to properly process upstream messages.
*/
protected void handleUpstreamMessage(Map<String, Object> jsonObject) {
// PackageName of the application that sent this message.
String category = (String) jsonObject.get("category");
String from = (String) jsonObject.get("from");
#SuppressWarnings("unchecked")
Map<String, String> payload = (Map<String, String>) jsonObject.get("data");
payload.put("ECHO", "Application: " + category);
// Send an ECHO response back
String echo = createJsonMessage(from, nextMessageId(), payload,
"echo:CollapseKey", null, false);
try {
sendDownstreamMessage(echo);
} catch (NotConnectedException e) {
logger.log(Level.WARNING, "Not connected anymore, echo message is not sent", e);
}
}
/**
* Handles an ACK.
*
* <p>Logs a INFO message, but subclasses could override it to
* properly handle ACKs.
*/
protected void handleAckReceipt(Map<String, Object> jsonObject) {
String messageId = (String) jsonObject.get("message_id");
String from = (String) jsonObject.get("from");
logger.log(Level.INFO, "handleAckReceipt() from: " + from + ",messageId: " + messageId);
}
/**
* Handles a NACK.
*
* <p>Logs a INFO message, but subclasses could override it to
* properly handle NACKs.
*/
protected void handleNackReceipt(Map<String, Object> jsonObject) {
String messageId = (String) jsonObject.get("message_id");
String from = (String) jsonObject.get("from");
logger.log(Level.INFO, "handleNackReceipt() from: " + from + ",messageId: " + messageId);
}
protected void handleControlMessage(Map<String, Object> jsonObject) {
logger.log(Level.INFO, "handleControlMessage(): " + jsonObject);
String controlType = (String) jsonObject.get("control_type");
if ("CONNECTION_DRAINING".equals(controlType)) {
connectionDraining = true;
} else {
logger.log(Level.INFO, "Unrecognized control type: %s. This could happen if new features are " + "added to the CCS protocol.",
controlType);
}
}
/**
* Creates a JSON encoded GCM message.
*
* #param to RegistrationId of the target device (Required).
* #param messageId Unique messageId for which CCS sends an
* "ack/nack" (Required).
* #param payload Message content intended for the application. (Optional).
* #param collapseKey GCM collapse_key parameter (Optional).
* #param timeToLive GCM time_to_live parameter (Optional).
* #param delayWhileIdle GCM delay_while_idle parameter (Optional).
* #return JSON encoded GCM message.
*/
public static String createJsonMessage(String to, String messageId,
Map<String, String> payload, String collapseKey, Long timeToLive,
Boolean delayWhileIdle) {
Map<String, Object> message = new HashMap<String, Object>();
message.put("to", to);
if (collapseKey != null) {
message.put("collapse_key", collapseKey);
}
if (timeToLive != null) {
message.put("time_to_live", timeToLive);
}
if (delayWhileIdle != null && delayWhileIdle) {
message.put("delay_while_idle", true);
}
message.put("message_id", messageId);
message.put("data", payload);
return JSONValue.toJSONString(message);
}
/**
* Creates a JSON encoded ACK message for an upstream message received
* from an application.
*
* #param to RegistrationId of the device who sent the upstream message.
* #param messageId messageId of the upstream message to be acknowledged to CCS.
* #return JSON encoded ack.
*/
protected static String createJsonAck(String to, String messageId) {
Map<String, Object> message = new HashMap<String, Object>();
message.put("message_type", "ack");
message.put("to", to);
message.put("message_id", messageId);
return JSONValue.toJSONString(message);
}
/**
* Connects to GCM Cloud Connection Server using the supplied credentials.
*
* #param senderId Your GCM project number
* #param apiKey API Key of your project
*/
public void connect(String senderId, String apiKey)
throws XMPPException, IOException, SmackException {
XMPPTCPConnectionConfiguration config =
XMPPTCPConnectionConfiguration.builder()
.setServiceName(GCM_SERVER)
.setHost(GCM_SERVER)
.setCompressionEnabled(false)
.setPort(GCM_PORT)
.setConnectTimeout(30000)
.setSecurityMode(SecurityMode.disabled)
.setSendPresence(false)
.setSocketFactory(SSLSocketFactory.getDefault())
.build();
connection = new XMPPTCPConnection(config);
//disable Roster as I don't think this is supported by GCM
Roster roster = Roster.getInstanceFor(connection);
roster.setRosterLoadedAtLogin(false);
logger.info("Connecting...");
connection.connect();
connection.addConnectionListener(new LoggingConnectionListener());
// Handle incoming packets
connection.addAsyncStanzaListener(new MyStanzaListener() , new MyStanzaFilter() );
// Log all outgoing packets
connection.addPacketInterceptor(new MyStanzaInterceptor(), new MyStanzaFilter() );
connection.login(senderId + "#gcm.googleapis.com" , apiKey);
}
private class MyStanzaFilter implements StanzaFilter
{
#Override
public boolean accept(Stanza arg0) {
// TODO Auto-generated method stub
if(arg0.getClass() == Stanza.class )
return true;
else
{
if(arg0.getTo()!= null)
if(arg0.getTo().startsWith(YOUR_PROJECT_ID) )
return true;
}
return false;
}
}
private class MyStanzaListener implements StanzaListener{
#Override
public void processPacket(Stanza packet) {
logger.log(Level.INFO, "Received: " + packet.toXML());
Message incomingMessage = (Message) packet;
GcmPacketExtension gcmPacket =
(GcmPacketExtension) incomingMessage.
getExtension(GCM_NAMESPACE);
String json = gcmPacket.getJson();
try {
#SuppressWarnings("unchecked")
Map<String, Object> jsonObject =
(Map<String, Object>) JSONValue.
parseWithException(json);
// present for "ack"/"nack", null otherwise
Object messageType = jsonObject.get("message_type");
if (messageType == null) {
// Normal upstream data message
handleUpstreamMessage(jsonObject);
// Send ACK to CCS
String messageId = (String) jsonObject.get("message_id");
String from = (String) jsonObject.get("from");
String ack = createJsonAck(from, messageId);
send(ack);
} else if ("ack".equals(messageType.toString())) {
// Process Ack
handleAckReceipt(jsonObject);
} else if ("nack".equals(messageType.toString())) {
// Process Nack
handleNackReceipt(jsonObject);
} else if ("control".equals(messageType.toString())) {
// Process control message
handleControlMessage(jsonObject);
} else {
logger.log(Level.WARNING,
"Unrecognized message type (%s)",
messageType.toString());
}
} catch (ParseException e) {
logger.log(Level.SEVERE, "Error parsing JSON " + json, e);
} catch (Exception e) {
logger.log(Level.SEVERE, "Failed to process packet", e);
}
}
}
private class MyStanzaInterceptor implements StanzaListener
{
#Override
public void processPacket(Stanza packet) {
logger.log(Level.INFO, "Sent: {0}", packet.toXML());
}
}
public static void main(String[] args) throws Exception {
SmackCcsClient ccsClient = new SmackCcsClient();
ccsClient.connect(YOUR_PROJECT_ID, YOUR_API_KEY);
// Send a sample hello downstream message to a device.
String messageId = ccsClient.nextMessageId();
Map<String, String> payload = new HashMap<String, String>();
payload.put("Message", "Ahha, it works!");
payload.put("CCS", "Dummy Message");
payload.put("EmbeddedMessageId", messageId);
String collapseKey = "sample";
Long timeToLive = 10000L;
String message = createJsonMessage(YOUR_PHONE_REG_ID, messageId, payload,
collapseKey, timeToLive, true);
ccsClient.sendDownstreamMessage(message);
logger.info("Message sent.");
//crude loop to keep connection open for receiving messages
while(true)
{;}
}
/**
* XMPP Packet Extension for GCM Cloud Connection Server.
*/
private static final class GcmPacketExtension extends DefaultExtensionElement {
private final String json;
public GcmPacketExtension(String json) {
super(GCM_ELEMENT_NAME, GCM_NAMESPACE);
this.json = json;
}
public String getJson() {
return json;
}
#Override
public String toXML() {
return String.format("<%s xmlns=\"%s\">%s</%s>",
GCM_ELEMENT_NAME, GCM_NAMESPACE,
StringUtils.escapeForXML(json), GCM_ELEMENT_NAME);
}
public Stanza toPacket() {
Message message = new Message();
message.addExtension(this);
return message;
}
}
private static final class LoggingConnectionListener
implements ConnectionListener {
#Override
public void connected(XMPPConnection xmppConnection) {
logger.info("Connected.");
}
#Override
public void reconnectionSuccessful() {
logger.info("Reconnecting..");
}
#Override
public void reconnectionFailed(Exception e) {
logger.log(Level.INFO, "Reconnection failed.. ", e);
}
#Override
public void reconnectingIn(int seconds) {
logger.log(Level.INFO, "Reconnecting in %d secs", seconds);
}
#Override
public void connectionClosedOnError(Exception e) {
logger.info("Connection closed on error.");
}
#Override
public void connectionClosed() {
logger.info("Connection closed.");
}
#Override
public void authenticated(XMPPConnection arg0, boolean arg1) {
// TODO Auto-generated method stub
}
}
}
I also imported the following external JARs:
(they might not all be required but most are!)
json-simple-1.1.1.jar
jxmpp-core-0.4.1.jar
jxmpp-util-cache-0.5.0-alpha2.jar
minidns-0.1.3.jar
commons-logging-1.2.jar
httpclient-4.3.4.jar
xpp3_xpath-1.1.4c.jar
xpp3-1.1.4c.jar
For the Client I used the GCM sample project here. (Scroll to the bottom of the page for the source link)
Hope this helps someone!
[23-Oct-2015] I'm editing this answer for others who are using Gradle ... below is all the dependencies that I needed to get this to compile (add to the bottom of your build.gradle file).
dependencies {
compile 'com.googlecode.json-simple:json-simple:1.1.1'
compile 'org.igniterealtime.smack:smack-java7:4.1.4'
compile 'org.igniterealtime.smack:smack-tcp:4.1.4'
compile 'org.igniterealtime.smack:smack-im:4.1.4'
compile 'org.jxmpp:jxmpp-core:0.5.0-alpha6'
compile 'org.jxmpp:jxmpp-util-cache:0.5.0-alpha6'
}
There are two reference implementations provided by Google for the GCM Cloud Connection Server (XMPP endpoint).
Both are here:
https://github.com/googlesamples/friendlyping/tree/master/server
The Java server uses the Smack XMPP library.
The Go server uses Google's own go-gcm library - https://github.com/google/go-gcm
The Go server is also used in the GCM Playground example - https://github.com/googlesamples/gcm-playground - so it seems like the Go server may be preferred by Google. Being Go, it can be deployed without any dependencies, which is an advantage over the Java server.

spring data mongodb converter

I am using spring data mongo-db 1.4.1.RELEASE.
My entity 'Event' has a getter method which is calculated based on other properties:
public int getStatus() {
return (getMainEventId() == null) ? (elapseTimeInMin() < MINIMUM_TIME ? CANDIDATE :
VALID) : POINTER;
}
I wanted the property 'status' to be persisted only through the getter ,so I wrote converters:
#WritingConverter
public class EventWriteConverter implements Converter<Event ,BasicDBObject > {
static final Logger logger = LoggerFactory.getLogger(EventWriteConverter.class.getCanonicalName());
public BasicDBObject convert(Event event) {
logger.info("converting " +event );
if (event.getMainEventId() != null)
return new BasicDBObject("mainEventId", event.getMainEventId() );
BasicDBObject doc = new BasicDBObject("status",event.getStatus()).
append("updated_date",new Date()).
append("start",event.getS0()).
append("end",event.getS1()).
append("location",event.getLocation()).
;
BasicDBList list = new BasicDBList();
doc.append("access_points",event.getHotPoints());
return doc;
}
#ReadingConverter
public class EventReadConverter implements Converter<BasicDBObject, Event> {
#Inject
HotPointRepositry hotRepositry;
static final Logger logger = LoggerFactory.getLogger(EventReadConverter.class.getCanonicalName());
public Event convert(BasicDBObject doc) {
logger.info(" converting ");
Event event = new Event();
event.setId(doc.getObjectId("_id"));
event.setS0(doc.getDate("start"));
event.setS1(doc.getDate("end"));
BasicDBList dblist = (BasicDBList) doc.get("hot_points");
if (dblist != null) {
for (Object obj : dblist) {
ObjectId hotspotId = ((BasicDBObject) obj).getObjectId("_id");
event.addHot(hotRepositry.findOne(hotId));
}
}
dblist = (BasicDBList) doc.get("devices");
if (dblist != null) {
for (Object obj : dblist)
event.addDevice(obj.toString());
}
event.setMainEventId(doc.getObjectId("mainEventId"));
return event;
}
}
My test mongo configuration is
#Profile("test")
#Configuration
#EnableMongoRepositories(basePackages = "com.echo.spring.data.mongo")
#ComponentScan(basePackages = "com.echo.spring.data.mongo" )
public class MongoDbTestConfig extends AbstractMongoConfiguration {
static final Logger logger = LoggerFactory.getLogger(MongoDbTestConfig.class.getCanonicalName());
#Override
protected String getDatabaseName() {
return "echo";
}
#Override
public Mongo mongo() {
return new Fongo("echo-test").getMongo();
}
#Override
protected String getMappingBasePackage() {
return "com.echo.spring.data.mongo";
}
#Bean
#Override
public CustomConversions customConversions() {
logger.info("loading custom converters");
List<Converter<?, ?>> converterList = new ArrayList<Converter<?, ?>>();
converterList.add(new EventReadConverter());
converterList.add(new EventWriteConverter());
CustomConversions cus = new CustomConversions(converterList);
return new CustomConversions(converterList);
}
}
And my test (using fongo) is
ActiveProfiles("test")
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = MongoDbTestConfig.class )
public class SampleMongoApplicationTests {
#Test
#ShouldMatchDataSet(location = "/MongoJsonData/events.json")
public void shouldSaveEvent() throws IOException {
URL url = Resources.getResource("MongoJsonData/events.json");
List<String> lines = Resources.readLines(url,Charsets.UTF_8);
for (String line : lines) {
Event event = objectMapper.readValue(line.getBytes(),Event.class);
eventRepository.save(event);
}
}
I can see the converters are loaded when the configuration customConversions() is called
I added logging and breakpoints in the convert methods but they do not seems to be
called when I run or debug, though they are loaded .
What am I doing wrong ?
I had a similar situation, I followed Spring -Mongodb storing/retrieving enums as int not string
and I need both the converter AND converterFactory wired to get it working.

ServletRequestListener - Getting the userprincipal returns null

I'm having a web-application that is secured with HTTP-Basic auth.
I also implemented a filter using the ServletRequestListener interface. Now when the filter calls the requestInitialized method, the getUserPrincipal-Method of the request returns null. But when I check the request headers, the authorization-header is set with the encrypted value. Here's the code:
#Override
public void requestInitialized(ServletRequestEvent e) {
HttpServletRequest request = (HttpServletRequest) e.getServletRequest();
//p is null
Principal p = request.getUserPrincipal();
Enumeration<String> enH = request.getHeaders("Authorization");
while (enH.hasMoreElements()) {
String s = enH.nextElement();
System.out.println(s);
//prints.
//Basic c3RhY2tvdmVyZmxvdzpteXBhc3N3b3Jk
}
}
Why is the userprincipal not initialized?
You are likely not setting up the needed security layers for embedded-jetty.
Here's an example found in the Jetty embedded examples source tree.
package org.eclipse.jetty.embedded;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.eclipse.jetty.security.ConstraintMapping;
import org.eclipse.jetty.security.ConstraintSecurityHandler;
import org.eclipse.jetty.security.HashLoginService;
import org.eclipse.jetty.security.LoginService;
import org.eclipse.jetty.security.authentication.BasicAuthenticator;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.util.security.Constraint;
public class SecuredHelloHandler
{
public static void main(String[] args) throws Exception
{
Server server = new Server(8080);
LoginService loginService = new HashLoginService("MyRealm","src/test/resources/realm.properties");
server.addBean(loginService);
ConstraintSecurityHandler security = new ConstraintSecurityHandler();
server.setHandler(security);
Constraint constraint = new Constraint();
constraint.setName("auth");
constraint.setAuthenticate( true );
constraint.setRoles(new String[]{"user", "admin"});
ConstraintMapping mapping = new ConstraintMapping();
mapping.setPathSpec( "/*" );
mapping.setConstraint( constraint );
Set<String> knownRoles = new HashSet<String>();
knownRoles.add("user");
knownRoles.add("admin");
security.setConstraintMappings(Collections.singletonList(mapping), knownRoles);
security.setAuthenticator(new BasicAuthenticator());
security.setLoginService(loginService);
security.setStrict(false);
// Your Handler (or Servlet) that should be secured
HelloHandler hh = new HelloHandler();
security.setHandler(hh);
server.start();
server.join();
}
}
I solved it by using a Filter instead of a Listener..
#WebFilter(urlPatterns = { "/*" })
public class RequestFilter implements Filter {
#Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain fChain) throws IOException, ServletException {
HttpServletRequest hReq = (HttpServletRequest) req;
//p is not null anymore
Principal p = hReq.getUserPrincipal();
fChain.doFilter(hReq, res);
}
#Override
public void destroy() {
}
#Override
public void init(FilterConfig config) throws ServletException {
}
}