Code Monkey home page Code Monkey logo

vonage-java-sdk's Introduction

Vonage Server SDK for Java

Java Maven Release Build Status codecov SLOC Contributor Covenant License Snyk

Nexmo is now known as Vonage

This Java SDK allows you to use Vonage APIs in any JVM-based application. You'll need to have created a Vonage account.

Supported APIs

Other SDKs

We also provide server SDKs in other languages:

We also offer client-side SDKs for iOS, Android and JavaScript. See all of our SDKs and integrations on the Vonage Developer portal.

Installation

Releases are published to Maven Central. Instructions for your build system can be found in the snippets section. They're also available from here. Release notes can be found in the changelog.

Build It Yourself

Alternatively you can clone the repo and build the JAR file yourself:

git clone [email protected]:vonage/vonage-java-sdk.git
mvn install

Download everything in a ZIP file

Note: We strongly recommend that you use a tool that supports dependency management, such as Maven, Gradle or Ivy.

We provide a ZIP file for each release, containing the Java Server SDK JAR, along with all the dependencies. Download the file, unzip it, and add the JAR files to your project's classpath.

Usage

Configuration

Typical Instantiation

For default configuration, you just need to specify your Vonage account credentials using API key and secret, private key and application ID or both. For maximum compatibility with all APIs, it is recommended that you specify both authentication methods, like so:

VonageClient client = VonageClient.builder()
        .applicationId(APPLICATION_ID)
        .privateKeyPath(PRIVATE_KEY_PATH)
        .apiKey(API_KEY)
        .apiSecret(API_SECRET)
        .build();

Customize the Base URI

By default, the client will use https://api.nexmo.com, https://rest.nexmo.com, https://api-eu.vonage.com and https://video.api.vonage.com as base URIs for the various endpoints. To customize these you can instantiate VonageClient with an HttpConfig object.

HttpConfig.Builder has been created to assist in building this object. Usage is as follows:

HttpConfig httpConfig = HttpConfig.builder()
        .apiBaseUri("https://api.example.com")
        .restBaseUri("https://rest.example.com")
        .apiEuBaseUri("https://api-eu.example.com")
        .videoBaseUri("https://video.example.com")
        .build();

VonageClient client = VonageClient.builder()
        .apiKey(API_KEY).apiSecret(API_SECRET)
        .httpConfig(httpConfig)
        .build();

If you do not specify a property, it will take on whatever the default value is. You can also set all three with a single method:

HttpConfig httpConfig = HttpConfig.builder().baseUri("http://example.com").build();

VonageClient client = VonageClient.builder()
        .apiKey(API_KEY).apiSecret(API_SECRET)
        .httpConfig(httpConfig)
        .build();

Custom Timeout

By default, the SDK has a 1-minute timeout for requests. You can change this to be longer or shorter using HttpConfig. The following example sets this to 12 seconds:

VonageClient client = VonageClient.builder()
        .applicationId(APPLICATION_ID)
        .privateKeyPath(PRIVATE_KEY_PATH)
        .httpConfig(HttpConfig.builder().timeoutMillis(12_000).build())
        .build();

Frequently Asked Questions

Q: What happened to com.vonage:client?

A: To avoid confusion with our various client-side SDKs, this server-side SDK has been moved from the com.vonage:client coordinates to com.vonage:server-sdk. The old artifactId (com.vonage:client) will not receive further updates. All users should migrate to the new artifactId. Please note that the SDK is functionally the same, it is just a namespace change on Maven Central.

Q: What is your policy on thread safety?

A: The current architecture of the SDK means that only one thread should use the client at a time. If you would like to use the SDK in a multithreaded environment, create a separate instance of VonageClient for each thread.

Q: Does this SDK support asynchronous request / response processing?

A: Currently no, but it is on the roadmap.

Q: How do I migrate from TokBox to Vonage?

A: See the OpenTok migration guide.

Contribute!

We ❤️ contributions to this library!

It is a good idea to talk to us first if you plan to add any new functionality. Otherwise, bug reports, bug fixes and feedback on the library are always appreciated.

Contact

Slack Twitter

vonage-java-sdk's People

Contributors

andrewtlu avatar aryanrawlani28 avatar berry120 avatar chrisguzman avatar code0987 avatar cr0wst avatar daniele-athome avatar dolphincodes avatar henry398 avatar ilgo0413 avatar imabhinavagarwal avatar jackshirazi avatar judy2k avatar jwalter avatar keenal avatar lornajane avatar maesealex avatar malakar-soham avatar malakar-swastik avatar mend-for-github-com[bot] avatar mheap avatar nexmodev avatar nikgil avatar prassud avatar slorello89 avatar smadani avatar timotheel avatar tjlytle avatar vyj7 avatar yallen011 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

vonage-java-sdk's Issues

Local build failes

I just cloned the repo and tried to build master via ./gradlew build but the build failed because the examples didn't compile.

$ git rev-parse HEAD
6d35a6f175de3c8564e558dcb14a6ef5ac67d9b3

$ ./gradlew build
...
:compileExamplesJava
warning: [options] bootstrap class path not set in conjunction with -source 1.7
warning: unknown enum constant Include.NON_NULL
  reason: class file for com.fasterxml.jackson.annotation.JsonInclude$Include not found
warning: unknown enum constant Include.NON_NULL
warning: unknown enum constant Id.NAME
  reason: class file for com.fasterxml.jackson.annotation.JsonTypeInfo$Id not found
warning: unknown enum constant As.EXISTING_PROPERTY
  reason: class file for com.fasterxml.jackson.annotation.JsonTypeInfo$As not found
/Users/stefanscheidt/Code/REWE-Vendor/nexmo-java/src/examples/java/com/nexmo/client/examples/FlierCode.java:64: error: constructor VerifyClient in class VerifyClient cannot be applied to given types;
        VerifyClient verifyClient = new VerifyClient(apiKey, apiSecret);
                                    ^
  required: HttpWrapper
  found: String,String
  reason: actual and formal argument lists differ in length
/Users/stefanscheidt/Code/REWE-Vendor/nexmo-java/src/examples/java/com/nexmo/client/verify/examples/CheckNumber.java:46: error: constructor VerifyClient in class VerifyClient cannot be applied to given types;
            client = new VerifyClient(API_KEY, API_SECRET);
                     ^
  required: HttpWrapper
  found: String,String
  reason: actual and formal argument lists differ in length
/Users/stefanscheidt/Code/REWE-Vendor/nexmo-java/src/examples/java/com/nexmo/client/verify/examples/SearchVerify.java:45: error: constructor VerifyClient in class VerifyClient cannot be applied to given types;
            client = new VerifyClient(API_KEY, API_SECRET);
                     ^
  required: HttpWrapper
  found: String,String
  reason: actual and formal argument lists differ in length
/Users/stefanscheidt/Code/REWE-Vendor/nexmo-java/src/examples/java/com/nexmo/client/verify/examples/VerifyNumber.java:47: error: constructor VerifyClient in class VerifyClient cannot be applied to given types;
            client = new VerifyClient(API_KEY, API_SECRET);
                     ^
  required: HttpWrapper
  found: String,String
  reason: actual and formal argument lists differ in length
4 errors
5 warnings
:compileExamplesJava FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':compileExamplesJava'.
> Compilation failed; see the compiler error output for details.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 0.84 secs

Disable https requirement via configuration

right now, the nexmo client expects only a https endpoint which makes totally sense in the context of a production environment but is a bit costly when trying to use and configure a mock for testing purposes.

Therefore, it would be really neat, if the client can by configured to use a plain http endpoint instead. This could be achieved by having an environment variable, system property or even an additional constructor argument or maybe make it implicit by directly checking the protocol in the given URI.

Possible bug when running under Tomcat

The following stack trace has been observed when using nexmo-java under Tomcat 8.

java.lang.RuntimeException: java.lang.IllegalStateException: Can't overwrite cause with java.lang.IllegalStateException: Illegal access: this web application instance has been stopped already.  Could not load com.auth0.jwt.internal.org.bouncycastle.jcajce.provider.asymmetric.rsa.DigestSignatureSpi$SHA256.  The eventual following stack trace is caused by an error thrown for debugging purposes as well as to attempt to terminate the thread which cause...```

new JWTAuthMethod throws java.security.InvalidKeyException: Private key should be provided in PEM format!

Steps to reproduce:

  1. create a new application using the Nexmo CLI
  2. Execute code: new JWTAuthMethod(applicationId, pathToPrivateKey);

Digging a bit deeper there seems to be something potentially going on with the contents of the file as stored by the CLI. If you output it to stdout then it looks fine. If you copy and past the content into a string the PEM regexp works fine. But reading directly from the file and running the regexp against it fails.

Here's a basic example of a test for this after digging in to the code for JWTAuthMethod:

            Pattern pemPattern = Pattern.compile("-----BEGIN PRIVATE KEY-----.*-----END PRIVATE KEY-----", Pattern.MULTILINE | Pattern.DOTALL);

            Path path = Paths.get("private.key");
            byte[] privateKey = Files.readAllBytes(path);
            String s = new String(privateKey, StandardCharsets.UTF_8);
            System.out.println(s);

            StringBuilder sb = new StringBuilder("-----BEGIN PRIVATE KEY-----\n" +
                    "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC/5SukrAilz/F4\n" +
                    "/0KBTFQD47ErblpgjxtfLPc=\n" +
                    "-----END PRIVATE KEY-----");

            Matcher fileExtracter = pemPattern.matcher(s);
            Matcher hardCodedExtracter = pemPattern.matcher(sb.toString());

            System.out.println("fileExtracter.matches(): " + fileExtracter.matches());
            System.out.println("hardCodedExtracter.matches(): " + hardCodedExtracter.matches());

Where the output is:

-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC/5SukrAilz/F4
/0KBTFQD47ErblpgjxtfLPc=
-----END PRIVATE KEY-----

fileExtracter.matches(): false
hardCodedExtracter.matches(): true

missing special characters in sms

using 2.0.1 when sending a unicode SMS message, e.g.

new NexmoClient().getSmsClient().submitMessage(new TextMessage(from, to, "text with umlaut öäü", true))

I don't see those special charactes in the SMS -- and logs show that HttpClient is POST-ing with header

Content-Type: application/x-www-form-urlencoded; charset=ISO-8859-1

using setEventUrl for Voice Call returns an invalid parameter Bad Request

When calling setEventUrl on a Call object, and then calling the VoiceClient createCall function using this object, the returned CallEvent has no set objects and no call is made. Output shows:

Received: {"type":400,"title":"Bad Request","invalid_parameters":[{"reason":"Invalid type parameter provided","name":"event_url"}]}

If setEventUrl is not called, then the CallEvent is correctly set and a call is made.

Add support for proxies

Please provide a means for clients to set the hostname and port for a proxy, as the hardcoded direct connection to nexmo servers is not allowed in certain environments.

Allow injecting HttpClient for NexmoClient

HttpClient is strongly coupled in Nexmo's clients, and there isn't a a setter which allows to configure and plugin a HttpClient of my choice. My use case being I want to plugin a proxy for httpClient.

I am in urgent need for this functionality, so kindly let me know if any existing contributors is going to work on this or you would require me to fix it and send a PR.

Missing values in CallStatus?

Hi,

How come the CallStatus class does not contain values like BUSY, FAILED, UNANSWERED, TIMEOUT, REJECTED?

Calling getCallDetails on an call with status : busy will result in an error:

com.nexmo.client.NexmoUnexpectedException: Failed to produce json from CallInfo object.
	at com.nexmo.client.voice.CallInfo.fromJson(CallInfo.java:182)
	at com.nexmo.client.voice.endpoints.ReadCallMethod.parseResponse(ReadCallMethod.java:62)
	at com.nexmo.client.voice.endpoints.ReadCallMethod.parseResponse(ReadCallMethod.java:36)
	at com.nexmo.client.voice.endpoints.AbstractMethod.execute(AbstractMethod.java:107)
	at com.nexmo.client.voice.endpoints.CallsEndpoint.get(CallsEndpoint.java:88)
	at com.nexmo.client.voice.VoiceClient.getCallDetails(VoiceClient.java:108)
	at lu.test.actions.TestAction.events(TestAction.java:323)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
...
	at org.mortbay.jetty.Server.handle(Server.java:326)
	at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
	at org.mortbay.jetty.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:923)
	at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
	at com.google.tracing.TraceContext$TraceContextRunnable.runInContext(TraceContext.java:453)
	at com.google.tracing.TraceContext$TraceContextRunnable$1.run(TraceContext.java:460)
	at com.google.tracing.CurrentContext.runInContext(CurrentContext.java:293)
	at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContextNoUnref(TraceContext.java:319)
	at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContext(TraceContext.java:311)
	at com.google.tracing.TraceContext$TraceContextRunnable.run(TraceContext.java:457)
	at java.lang.Thread.run(Thread.java:745)
Caused by: com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of com.nexmo.client.voice.CallStatus, problem: No enum constant com.nexmo.client.voice.CallStatus.BUSY
 at [Source: {"uuid":"1ee08cfb-4f49-4882-b028-e450ac7cc758","status":"busy","direction":"outbound","rate":"0","price":"0.00000000","duration":"0","network":"27001","conversation_uuid":"CON-358257a8-7033-4d81-b2c8-ff3a1c54cc4b","to":{"type":"phone","number":"********"},"from":{"type":"phone","number":"********"},"_links":{"self":{"href":"/v1/calls/1ee08cfb-4f49-4882-b028-e450ac7cc758"}}}; line: 1, column: 57] (through reference chain: com.nexmo.client.voice.CallInfo["status"])
	at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:277)
	at com.fasterxml.jackson.databind.DeserializationContext.instantiationException(DeserializationContext.java:1441)
	at com.fasterxml.jackson.databind.DeserializationContext.handleInstantiationProblem(DeserializationContext.java:1055)
	at com.fasterxml.jackson.databind.deser.std.FactoryBasedEnumDeserializer.deserialize(FactoryBasedEnumDeserializer.java:136)
	at com.fasterxml.jackson.databind.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:499)
	at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:101)
	at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:276)
	at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:140)
	at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3798)
	at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2842)
	at com.nexmo.client.voice.CallInfo.fromJson(CallInfo.java:180)
	... 129 more
Caused by: java.lang.IllegalArgumentException: No enum constant com.nexmo.client.voice.CallStatus.BUSY
	at java.lang.Enum.valueOf(Enum.java:236)
	at com.nexmo.client.voice.CallStatus.valueOf(CallStatus.java:27)
	at com.nexmo.client.voice.CallStatus.fromString(CallStatus.java:43)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:42)
	at com.fasterxml.jackson.databind.introspect.AnnotatedMethod.callOnWith(AnnotatedMethod.java:130)
	at com.fasterxml.jackson.databind.deser.std.FactoryBasedEnumDeserializer.deserialize(FactoryBasedEnumDeserializer.java:133)

Thanks

GAE support

Hi,

Is there a way to make this lib work on a standard GAE environment?

I tried setting the httpClient like this

NexmoClient client = new NexmoClient(auth);
client.setHttpClient(new DefaultHttpClient(myGAEConnectionManager));

but I'm still getting

Caused by: java.lang.ClassNotFoundException: org.apache.http.conn.HttpClientConnectionManager

looks like setHttpClient does not have the desired effect, since the NexmoClient constructor initializes the httpClient before setHttpClient is called.

Any help would be very much appreciated! Thanks

new JWTAuthMethod throws "java.lang.NoClassDefFoundError: com/auth0/jwt/JWTSigner"

With the following code:

Path path = Paths.get(PRIVATE_KEY);
JWTAuthMethod auth = new JWTAuthMethod(APPLICATION_ID, path);

I see the following stacktrace:

Exception in thread "main" java.lang.NoClassDefFoundError: com/auth0/jwt/JWTSigner
	at com.nexmo.client.auth.JWTAuthMethod.<init>(JWTAuthMethod.java:63)
	at com.nexmo.client.auth.JWTAuthMethod.<init>(JWTAuthMethod.java:68)
	at App.main(App.java:26)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: java.lang.ClassNotFoundException: com.auth0.jwt.JWTSigner
	at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
	at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
	at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
	at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
	... 8 more

My build.gradle looks as follows:

// Apply the java plugin to add support for Java
apply plugin: 'java'

apply plugin: 'eclipse'

// Apply the application plugin to add support for building an application
apply plugin: 'application'

// In this section you declare where to find the dependencies of your project
repositories {
    // Use jcenter for resolving your dependencies.
    // You can declare any Maven/Ivy/file repository here.
    jcenter()
    
    maven {
        url 'https://oss.sonatype.org/content/repositories/snapshots/'
    }

    mavenCentral()
}

dependencies {
    // Use JUnit test framework
    testCompile 'junit:junit:4.12'
    
    compile 'com.nexmo:client:2.0.0-SNAPSHOT'
}

// Define the main class for the application
mainClassName = 'App'

This looks like a dependency hasn't been found. What steps should I undertake to insure this dependency is installed?

Missing a proper release version?

Hey there, I (we) would like to use your client but feel a bit uncertain about using your SNAPSHOT version because we would like to make our build artifact as reproducible as possible.
Therefore, I'd like to ask if it's possible to introduce proper release versions next to the snapshots.

Thanks in advance

Bump httpclient to 4.2 (or superior) to pre-configure a client using Java SE networking properties

HttpClient v. 4.2 introduces the possibility of pre-configuring a client using the standard Java SE networking properties. I suggest bumping the dependency to at least 4.2 and refactor the code to take advantage of this possibility. It should be as simple as creating HttpClient instances like this and configure them:

HttpClientBuilder.create().useSystemProperties().build();

Currently, the only workaround is passing the NexmoSmsClient instance a configured HttpClient instance:

NexmoSmsClient nsc = new NexmoSmsClient(key, secret);
nsc.setHttpClient(HttpClientBuilder.create().useSystemProperties().build());

However, it seems natural to me expecting that a library like this would take into account the aforementioned networking properties transparently.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.