how to create NexmoClient object? - vonage

I tried to get NexmoClient object without success.
I Fill in API_KEY and API_SECRET with the values I copied from the Nexmo Dashboard.
import com.nexmo.client.NexmoClient;
import com.nexmo.client.auth.AuthMethod;
import com.nexmo.client.auth.TokenAuthMethod;
import com.nexmo.client.sms.SmsSubmissionResult;
import com.nexmo.client.sms.messages.TextMessage;
public class SendSMS {
public static void main(String[] args) throws Exception {
AuthMethod auth = new TokenAuthMethod(1111,22222);
NexmoClient client = new NexmoClient(auth);
}
}
"
After the Gradle run, I was expected to NexmoClient object as they wrote in the docs https://www.nexmo.com/blog/2017/05/03/send-sms-messages-with-java-dr/
for continue to the next step, but I didn't know where to insert the following info
TextMessage message = new TextMessage(FROM_NUMBER, TO_NUMBER, "Hello from
Nexmo!");
SmsSubmissionResult[] responses =
client.getSmsClient().submitMessage(message);
for (SmsSubmissionResult response : responses) {
System.out.println(response);
}

You can put that code below where you initialize the client. Your whole class will then look like this:
import com.nexmo.client.NexmoClient;
import com.nexmo.client.auth.AuthMethod;
import com.nexmo.client.auth.TokenAuthMethod;
import com.nexmo.client.sms.messages.TextMessage;
public class SendSMS {
private static final String FROM_NUMBER = "";
private static final String TO_NUMBER = "";
public static void main(String[] args) throws Exception {
AuthMethod auth = new TokenAuthMethod(1111, 22222);
NexmoClient client = new NexmoClient(auth);
TextMessage message = new TextMessage(FROM_NUMBER, TO_NUMBER, "Hello from Nexmo !");
SmsSubmissionResult[] responses = client.getSmsClient().submitMessage(message);
for (SmsSubmissionResult response : responses) {
System.out.println(response);
}
}
}
This blog post is actually a bit old and suggests using an older version of the server SDK. There's an updated example on the developer portal as some things have changed in the newer versions of the SDK: https://developer.nexmo.com/messaging/sms/code-snippets/send-an-sms

Related

How to configure Message Bus In Liferay 7?

I want to use Liferay Message bus in DXP. I have written the following code.
DemoSender.java
package demo.sender.portlet;
import demo.sender.constants.DemoSenderPortletKeys;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.messaging.Message;
import com.liferay.portal.kernel.messaging.MessageBus;
import com.liferay.portal.kernel.messaging.MessageBusUtil;
import com.liferay.portal.kernel.portlet.bridges.mvc.MVCPortlet;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.Portlet;
import org.osgi.framework.BundleContext;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
/**
* #author parth.ghiya
*/
#Component(
immediate = true,
property = {
"com.liferay.portlet.display-category=category.sample",
"com.liferay.portlet.instanceable=true",
"javax.portlet.display-name=demo-sender Portlet",
"javax.portlet.init-param.template-path=/",
"javax.portlet.init-param.view-template=/view.jsp",
"javax.portlet.name=" + DemoSenderPortletKeys.DemoSender,
"javax.portlet.resource-bundle=content.Language",
"javax.portlet.security-role-ref=power-user,user"
},
service = Portlet.class
)
public class DemoSenderPortlet extends MVCPortlet {
#Activate
protected void activate(BundleContext bundleContext) {
_bundleContext = bundleContext;
}
public void sendMessage(
ActionRequest actionRequest, ActionResponse actionResponse) {
if (_log.isInfoEnabled()) {
_log.info("Sending message to DE Echo service");
}
Message message = new Message();
message.setDestinationName("MyEchoDestination");
message.setPayload("Hello World!");
message.setResponseDestinationName("MyEchoResponse");
_messageBus.sendMessage(message.getDestinationName(), message);
}
private static final Log _log = LogFactoryUtil.getLog(DemoSenderPortlet.class);
private BundleContext _bundleContext;
#Reference
private MessageBus _messageBus;
}
DemoReceiver.java
package demo.receiver.portlet;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.messaging.BaseMessageListener;
import com.liferay.portal.kernel.messaging.Message;
import com.liferay.portal.kernel.messaging.MessageBus;
import com.liferay.portal.kernel.messaging.MessageListener;
#Component(
immediate = true, property = {"destination.name=MyEchoDestination"},
service = MessageListener.class
)
public class DemoReceiverPortlet extends BaseMessageListener {
#Override
protected void doReceive(Message message) throws Exception {
if (_log.isInfoEnabled()) {
_log.info("Received: " + message);
}
String payload = (String)message.getPayload();
if (_log.isInfoEnabled()) {
_log.info("Message payload: " + payload);
}
/*
String responseDestinationName = message.getResponseDestinationName();
if ((responseDestinationName != null) &&
(responseDestinationName.length() > 0)) {
Message responseMessage = new Message();
responseMessage.setDestinationName(responseDestinationName);
responseMessage.setResponseId(message.getResponseId());
//This is just for demo purposes
responseMessage.setPayload(payload);
_messageBus.sendMessage(
message.getResponseDestinationName(), responseMessage);
}
*/
}
private static final Log _log = LogFactoryUtil.getLog(DemoReceiverPortlet.class);
#Reference
private volatile MessageBus _messageBus;
}
The problem is that my doReceive method is never getting called.
What configuration needs to be further added?
Regards
P.S : in DemoSender, i send some message on click of button
Edit # 1
I did added configurator code as follows.
package demo.receiver.portlet;
import java.util.Dictionary;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Deactivate;
import org.osgi.service.component.annotations.Reference;
import com.liferay.portal.kernel.concurrent.DiscardOldestPolicy;
import com.liferay.portal.kernel.concurrent.RejectedExecutionHandler;
import com.liferay.portal.kernel.concurrent.ThreadPoolExecutor;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.messaging.Destination;
import com.liferay.portal.kernel.messaging.DestinationConfiguration;
import com.liferay.portal.kernel.messaging.DestinationFactory;
import com.liferay.portal.kernel.messaging.MessageBus;
import com.liferay.portal.kernel.util.HashMapDictionary;
#Component(
enabled = false, immediate = true,
service = DemoReceiverConfigurator.class
)
public class DemoReceiverConfigurator {
#Activate
protected void activate(ComponentContext componentContext) {
_bundleContext = componentContext.getBundleContext();
System.out.println("===demo===");
Dictionary<String, Object> properties =
componentContext.getProperties();
DestinationConfiguration destinationConfiguration =
new DestinationConfiguration(DestinationConfiguration.DESTINATION_TYPE_PARALLEL,"MyEchoDestination");
destinationConfiguration.setMaximumQueueSize(200);
RejectedExecutionHandler rejectedExecutionHandler =
new DiscardOldestPolicy() {
#Override
public void rejectedExecution(
Runnable runnable, ThreadPoolExecutor threadPoolExecutor) {
if (_log.isWarnEnabled()) {
_log.warn(
"The current thread will handle the request " +
"because the audit router's task queue is at " +
"its maximum capacity");
}
super.rejectedExecution(runnable, threadPoolExecutor);
}
};
destinationConfiguration.setRejectedExecutionHandler(
rejectedExecutionHandler);
Destination destination = _destinationFactory.createDestination(
destinationConfiguration);
Dictionary<String, Object> destinationProperties =
new HashMapDictionary<>();
destinationProperties.put("destination.name", destination.getName());
_destinationServiceRegistration = _bundleContext.registerService(
Destination.class, destination, destinationProperties);
}
#Deactivate
protected void deactivate() {
if (_destinationServiceRegistration != null) {
Destination destination = _bundleContext.getService(
_destinationServiceRegistration.getReference());
_destinationServiceRegistration.unregister();
destination.destroy();
}
_bundleContext = null;
}
#Reference(unbind = "-")
protected void setMessageBus(MessageBus messageBus) {
}
private static final Log _log = LogFactoryUtil.getLog(
DemoReceiverConfigurator.class);
private volatile BundleContext _bundleContext;
#Reference
private DestinationFactory _destinationFactory;
private volatile ServiceRegistration<Destination>
_destinationServiceRegistration;
}
But my Activate method aint getting called, i have enabledfalse in my message listener class and enabled = false, immediate = true in my Configurator class.
Dont know what i am missing.
Often in OSGi, this seemingly obvious configuration is enough. In this case though, it obviously isn't, because Liferay now knows about the message you're sending and that you're interested to receive, but the Messagebus doesn't know about this destination to be created.
It seems obvious - if there is a listener to a particular message, there probably needs to be a destination. But what type will it be? Parallel processing? How many parallel handlers? Synchronous? Queued? This is what you'll need to do.
While a quick search didn't find a documentation on how to do this, you can use this configurator as an example for creating the missing link.
MessageBus documentation was improved a few days ago, have a look to following page https://dev.liferay.com/develop/tutorials/-/knowledge_base/7-0/message-bus

Unable to set multiple expectation with MockWebServiceServer

I am using a MockWebServiceServer to test the REST APIs. I am passing the values to it using #Runwith(Parameterized.class).
#RunWith(Parameterized.class)
public class MyAPITest {
protected static MockWebServiceServer mockServer;
private Message message;
public MyAPITest(Message messageIn) {
this.message = messageIn;
}
#BeforeClass
public static void setup(){
mockServer = MockWebServiceServer.createServer(applicationContext);
}
#Test
public final void testMethod() throws Throwable {
Source reqPayload1 = new StringSource("...");
Source reqPayload2 = new StringSource("...");
Source resPayload1 = new StringSource("...");
Source resPayload2 = new StringSource("...");
mockServer.expect(RequestMatchers.payload(reqPayload1 )).andRespond(ResponseCreators.withPayload(resPayload1 ));
//Unable to add below line as it throws exception. Unable to set multiple expectation
//mockServer.expect(RequestMatchers.payload(reqPayload2 )).andRespond(ResponseCreators.withPayload(resPayload2 ));
myClass.onMessage(this.message);
mockServer.verify();
}
#Parameters
public static Collection<Object[]> getParameters() {
//Read input data from file
}
}
Code works fine when I've only 1 input.
But it throws exception when I've more than one input.
java.lang.IllegalStateException: Can not expect another connection, the test is already underway
at org.springframework.util.Assert.state(Assert.java:385)
at org.springframework.ws.test.client.MockWebServiceMessageSender.expectNewConnection(MockWebServiceMessageSender.java:64)
at org.springframework.ws.test.client.MockWebServiceServer.expect(MockWebServiceServer.java:162)
at com.rakuten.gep.newsletter.batch.ExacttargetMQJobTest.testOnMessage(ExacttargetMQJobTest.java:82)
I'm using Spring 3.2. I want to test my api with multiple inputs.

Commons Configuration2 ReloadingFileBasedConfiguration

I am trying to implement the Apache Configuration 2 in my codebase
import java.io.File;
import java.util.concurrent.TimeUnit;
import org.apache.commons.configuration2.PropertiesConfiguration;
import org.apache.commons.configuration2.builder.ConfigurationBuilderEvent;
import org.apache.commons.configuration2.builder.ReloadingFileBasedConfigurationBuilder;
import org.apache.commons.configuration2.builder.fluent.Parameters;
import org.apache.commons.configuration2.convert.DefaultListDelimiterHandler;
import org.apache.commons.configuration2.event.EventListener;
import org.apache.commons.configuration2.ex.ConfigurationException;
import org.apache.commons.configuration2.reloading.PeriodicReloadingTrigger;
import org.apache.commons.configuration2.CompositeConfiguration;
public class Test {
private static final long DELAY_MILLIS = 10 * 60 * 5;
public static void main(String[] args) {
// TODO Auto-generated method stub
CompositeConfiguration compositeConfiguration = new CompositeConfiguration();
PropertiesConfiguration props = null;
try {
props = initPropertiesConfiguration(new File("/tmp/DEV.properties"));
} catch (ConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
compositeConfiguration.addConfiguration( props );
compositeConfiguration.addEventListener(ConfigurationBuilderEvent.ANY,
new EventListener<ConfigurationBuilderEvent>()
{
#Override
public void onEvent(ConfigurationBuilderEvent event)
{
System.out.println("Event:" + event);
}
});
System.out.println(compositeConfiguration.getString("property1"));
try {
Thread.sleep(14*1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Have a script which changes the value of property1 in DEV.properties
System.out.println(compositeConfiguration.getString("property1"));
}
protected static PropertiesConfiguration initPropertiesConfiguration(File propsFile) throws ConfigurationException {
if(propsFile.exists()) {
final ReloadingFileBasedConfigurationBuilder<PropertiesConfiguration> builder =
new ReloadingFileBasedConfigurationBuilder<PropertiesConfiguration>(PropertiesConfiguration.class)
.configure(new Parameters().fileBased()
.setFile(propsFile)
.setReloadingRefreshDelay(DELAY_MILLIS)
.setThrowExceptionOnMissing(false)
.setListDelimiterHandler(new DefaultListDelimiterHandler(';')));
final PropertiesConfiguration propsConfiguration = builder.getConfiguration();
PeriodicReloadingTrigger trigger = new PeriodicReloadingTrigger(builder.getReloadingController(),
null, 1, TimeUnit.SECONDS);
trigger.start();
return propsConfiguration;
} else {
return new PropertiesConfiguration();
}
}
}
Here is a sample code that I using to check whether the Automatic Reloading works or not. However when the underlying property file is updated, the configuration doesn't reflect it.
As per the documentation :
One important point to keep in mind when using this approach to reloading is that reloads are only functional if the builder is used as central component for accessing configuration data. The configuration instance obtained from the builder will not change automagically! So if an application fetches a configuration object from the builder at startup and then uses it throughout its life time, changes on the external configuration file become never visible. The correct approach is to keep a reference to the builder centrally and obtain the configuration from there every time configuration data is needed.
https://commons.apache.org/proper/commons-configuration/userguide/howto_reloading.html#Reloading_File-based_Configurations
This is different from what the old implementation was.
I was able to successfully execute your sample code by making 2 changes :
make the builder available globally and access the configuration from the builder :
System.out.println(builder.getConfiguration().getString("property1"));
add the listener to the builder :
`builder.addEventListener(ConfigurationBuilderEvent.ANY, new EventListener() {
public void onEvent(ConfigurationBuilderEvent event) {
System.out.println("Event:" + event);
}
});
Posting my sample program, where I was able to successfully demonstrate it
import java.io.File;
import java.util.concurrent.TimeUnit;
import org.apache.commons.configuration2.PropertiesConfiguration;
import org.apache.commons.configuration2.builder.ConfigurationBuilderEvent;
import org.apache.commons.configuration2.builder.ReloadingFileBasedConfigurationBuilder;
import org.apache.commons.configuration2.builder.fluent.Parameters;
import org.apache.commons.configuration2.event.EventListener;
import org.apache.commons.configuration2.reloading.PeriodicReloadingTrigger;
public class TestDynamicProps {
public static void main(String[] args) throws Exception {
Parameters params = new Parameters();
ReloadingFileBasedConfigurationBuilder<PropertiesConfiguration> builder =
new ReloadingFileBasedConfigurationBuilder<PropertiesConfiguration>(PropertiesConfiguration.class)
.configure(params.fileBased()
.setFile(new File("src/main/resources/override.properties")));
PeriodicReloadingTrigger trigger = new PeriodicReloadingTrigger(builder.getReloadingController(),
null, 1, TimeUnit.SECONDS);
trigger.start();
builder.addEventListener(ConfigurationBuilderEvent.ANY, new EventListener<ConfigurationBuilderEvent>() {
public void onEvent(ConfigurationBuilderEvent event) {
System.out.println("Event:" + event);
}
});
while (true) {
Thread.sleep(1000);
System.out.println(builder.getConfiguration().getString("property1"));
}
}
}
The problem with your implementation is, that the reloading is done on the ReloadingFileBasedConfigurationBuilder Object and is not being returned to the PropertiesConfiguration Object.

How to write an NLog target using Signalr

I'm trying to write a target for NLog to send messages out to connected clients using SignalR.
Here's what I have now. What I'm wondering is should I be using resolving the ConnectionManager like this -or- somehow obtain a reference to the hub (SignalrTargetHub) and call a SendMessage method on it?
Are there performance ramifications for either?
[Target("Signalr")]
public class SignalrTarget:TargetWithLayout
{
public SignalR.IConnectionManager ConnectionManager { get; set; }
public SignalrTarget()
{
ConnectionManager = AspNetHost.DependencyResolver.Resolve<IConnectionManager>();
}
protected override void Write(NLog.LogEventInfo logEvent)
{
dynamic clients = GetClients();
var logEventObject = new
{
Message = this.Layout.Render(logEvent),
Level = logEvent.Level.Name,
TimeStamp = logEvent.TimeStamp.ToString("yyyy-MM-dd HH:mm:ss.fff")
};
clients.onLoggedEvent(logEventObject);
}
private dynamic GetClients()
{
return ConnectionManager.GetClients<SignalrTargetHub>();
}
}
I ended up with the basic the same basic structure that I started with. Just a few tweaks to get the information I needed.
Added exception details.
Html encoded the final message.
[Target("Signalr")]
public class SignalrTarget:TargetWithLayout
{
protected override void Write(NLog.LogEventInfo logEvent)
{
var sb = new System.Text.StringBuilder();
sb.Append(this.Layout.Render(logEvent));
if (logEvent.Exception != null)
sb.AppendLine().Append(logEvent.Exception.ToString());
var message = HttpUtility.HtmlEncode(sb.ToString());
var logEventObject = new
{
Message = message,
Logger = logEvent.LoggerName,
Level = logEvent.Level.Name,
TimeStamp = logEvent.TimeStamp.ToString("HH:mm:ss.fff")
};
GetClients().onLoggedEvent(logEventObject);
}
private dynamic GetClients()
{
return AspNetHost.DependencyResolver.Resolve<IConnectionManager>().GetClients<SignalrTargetHub>();
}
}
In my simple testing it's working well. Still remains to be seen if this adds any significant load when under stress.

twitter4j: getting credential errors even though i had set them?

package twitter4j.examples.tweets;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.conf.*;
import java.io.IOException;
public final class UpdateStatus {
public static void main(String[] args) throws IOException {
String testPost = "hello from otc";
String consumerKey = "key";
String consumerSecret = "secret";
String accessToken = "access";
String accessSecret = "access_secret";
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey(consumerKey)
.setOAuthConsumerSecret(consumerSecret)
.setOAuthAccessToken(accessToken)
.setOAuthAccessTokenSecret(accessSecret);
try {
TwitterFactory factory = new TwitterFactory();
Twitter twitter = factory.getInstance();
AccessToken accestoken = new AccessToken(accessToken, accessSecret);
twitter.setOAuthAccessToken(accestoken);
Status status = twitter.updateStatus(testPost);
System.out.println("it worked!");
if (status.getId() == 0) {
System.out
.println("Error occured while posting tweets to twitter");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
why do i keep getting this error:
401:Authentication credentials (http://dev.twitter.com/pages/auth) were missing or incorrect. Ensure that you have set valid conumer key/secret, access token/secret, and the system clock in in sync.
error - Could not authenticate with OAuth.
request - /1/statuses/update.json
Relevant discussions can be on the Internet at:
http://www.google.co.jp/search?q=e06d87a8 or
http://www.google.co.jp/search?q=5851cbdb
TwitterException{exceptionCode=[e06d87a8-5851cbdb], statusCode=401, retryAfter=-1, rateLimitStatus=null, featureSpecificRateLimitStatus=null, version=2.2.3}
at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:189)
at twitter4j.internal.http.HttpClientWrapper.request(HttpClientWrapper.java:65)
at twitter4j.internal.http.HttpClientWrapper.post(HttpClientWrapper.java:102)
at twitter4j.TwitterImpl.post(TwitterImpl.java:1871)
at twitter4j.TwitterImpl.updateStatus(TwitterImpl.java:459)
at twitter4j.examples.tweets.UpdateStatus.main(UpdateStatus.java:35)
i have set the credentials in the file already, have i not?
i figured it out heres a working code:
package twitter4j.examples.tweets;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import java.io.IOException;
public final class UpdateStatus {
public static void main(String[] args) throws IOException {
String tweet = "your first tweet via java";
String accessToken = "your access token";
String accessSecret = "your access token secret";
try {
TwitterFactory factory = new TwitterFactory();
Twitter twitter = factory.getInstance();
AccessToken accestoken = new AccessToken(accessToken, accessSecret);
twitter.setOAuthAccessToken(accestoken);
Status status = twitter.updateStatus(tweet);
System.out.println("it worked!");
if (status.getId() == 0) {
System.out
.println("Error occured while posting tweets to twitter");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
note: for this to work you MUST create an application on twitter
you must have a twitter4j.properties file which contain the following
debug set to true
oauth.consumerKey
oauth.consumerSecret
oauth.accessToken
oauth.accessTokenSecret
all the keys and tokens are from the twitter application
make sure your application access level all say "read and write"

Resources