In WSO2 apim 1.10.0, I created a tenant with domain ofer.com, with admin username ofer, password admin
I'm able to login to carbon management console UI for this tenant using credentials ofer#ofer.com, password: admin.
Now I'm trying to use RemoteRegistry in order to export the tiers.xml of that tenant.
Here is the code:
import java.io.File;
import java.net.URL;
import org.wso2.carbon.registry.app.RemoteRegistry;
import org.wso2.carbon.registry.core.utils.RegistryClientUtils;
public class test {
private static String serverHostname = "...";
public static void main(String[] args) throws Exception {
System.setProperty("javax.net.ssl.trustStore", "p:/main/test/wso2carbon.jks");
System.setProperty("javax.net.ssl.trustStorePassword", "wso2carbon");
System.setProperty("javax.net.ssl.trustStoreType","JKS");
System.setProperty("carbon.repo.write.mode", "true");
RemoteRegistry remote_registry = new RemoteRegistry(new URL("https://" + serverHostname + ":9443/registry"), "ofer#ofer.com", "admin");
File toFile = new File("e:/tiers.xml");
RegistryClientUtils.exportFromRegistry( toFile, "/_system/governance/apimgt/applicationdata/tiers.xml" ,remote_registry);
}
}
When I run this code with credentials admin/admin:
RemoteRegistry remote_registry = new RemoteRegistry(new URL("https://" + serverHostname + ":9443/registry"), "admin", "admin");
It runs successfully, but with
RemoteRegistry remote_registry = new RemoteRegistry(new URL("https://" + serverHostname + ":9443/registry"), "ofer#ofer.com", "admin");
I get a "unatuthorized" exception:
Exception in thread "main" org.wso2.carbon.registry.core.exceptions.RegistryException: Failed to export from registry
at org.wso2.carbon.registry.core.utils.RegistryClientUtils.exportFromRegistry(RegistryClientUtils.java:89)
at test.main(test.java:26)
Caused by: org.wso2.carbon.registry.core.exceptions.RegistryException: Unauthorized
at org.wso2.carbon.registry.app.RemoteRegistry.get(RemoteRegistry.java:174)
at org.wso2.carbon.registry.core.utils.RegistryClientUtils.processExport(RegistryClientUtils.java:123)
at org.wso2.carbon.registry.core.utils.RegistryClientUtils.exportFromRegistry(RegistryClientUtils.java:86)
... 1 more
Any idea what I have missed? Is there anywhere I should grant access to ofer#ofer.com to do the export?
/// EDITED ///
I see now that there is another class, RemoteRegistryService for getting a user registry. I'm trying:
RemoteRegistryService registryService = new RemoteRegistryService("http://" + serverHostname + ":9763/registry", "admin", "admin");
UserRegistry ur = registryService.getSystemRegistry(...)
For this to work I see that it requires a realm service. How do I get hold of that?
Found it out.
The URL should include the tenant domain, i.e. instead of
http://localhost:9443/registry
http://localhost:9443/t//registry
Updated code:
import java.io.File;
import java.net.URL;
import org.wso2.carbon.registry.app.RemoteRegistry;
import org.wso2.carbon.registry.core.utils.RegistryClientUtils;
public class test {
private static String serverHostname = "...";
public static void main(String[] args) throws Exception {
System.setProperty("javax.net.ssl.trustStore", "p:/main/test/wso2carbon.jks");
System.setProperty("javax.net.ssl.trustStorePassword", "wso2carbon");
System.setProperty("javax.net.ssl.trustStoreType","JKS");
System.setProperty("carbon.repo.write.mode", "true");
RemoteRegistry remote_registry = new RemoteRegistry(new URL("https://" + serverHostname + ":9443/t/ofer.com/registry"), "ofer#ofer.com", "admin");
File toFile = new File("e:/tiers.xml");
RegistryClientUtils.exportFromRegistry( toFile, "/_system/governance/apimgt/applicationdata/tiers.xml" ,remote_registry);
}
}
Related
Hi I'm realizing the authentication with aws cognito I created the link between aws and android through this class:
import android.content.Context;
import java.util.HashMap;
import java.util.Map;
import com.amazonaws.auth.CognitoCachingCredentialsProvider;
import com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUserPool;
import com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUserSession;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
public class Cognito {
public final static String USER_POOL_ID = "USER_POOL_ID";
public final static String IDENTITY_POOL_ID = "IDENTITY_POOL_ID";
public final static String CLIENT_ID = "CLIENT_ID";
public final static String CLIENT_SECRET = null;
public final static Regions REGION = Regions.US_EAST_1;
private static Cognito cognito;
private final CognitoUserPool cognitoUserPool;
private final CognitoCachingCredentialsProvider cognitoCachingCredentialsProvider;
private Cognito(Context context) {
cognitoUserPool = new CognitoUserPool(
context,
USER_POOL_ID,
CLIENT_ID,
CLIENT_SECRET,
REGION
);
cognitoCachingCredentialsProvider = new CognitoCachingCredentialsProvider(
context,
IDENTITY_POOL_ID,
REGION
);
}
public CognitoUserPool getCognitoUserPool() {
return cognitoUserPool;
}
public static Cognito getInstance(Context context) {
if(cognito != null)
return cognito;
return (cognito = new Cognito(context));
}
public void setLogin(CognitoUserSession session) {
cognitoCachingCredentialsProvider.clear();
Map<String,String> login = new HashMap<>();
login.put(
"cognito-idp." + Region.getRegion(REGION) + ".amazonaws.com/" + USER_POOL_ID,
session.getIdToken().getJWTToken()
);
cognitoCachingCredentialsProvider.setLogins(login);
}
}
but I have the following errors when I upload the data and click the button for user registration:
E/AWSKeyValueStore: com.amazonaws.internal.keyvaluestore.KeyNotFoundException: Error occurred while accessing AndroidKeyStore to retrieve the key for keyAlias: com.amazonaws.android.auth.aesKeyStoreAlias
I/AWSKeyValueStore: Deleting the encryption key identified by the keyAlias: com.amazonaws.android.auth.aesKeyStoreAlias
E/AWSKeyValueStore: Error in retrieving the decryption key used to decrypt the data from the persistent store. Returning null for the requested dataKey = IDENTITY_POOL_ID.identityId
E/AWSKeyValueStore: com.amazonaws.internal.keyvaluestore.KeyNotFoundException: Error occurred while accessing AndroidKeyStore to retrieve the key for keyAlias: com.amazonaws.android.auth.aesKeyStoreAlias
I/AWSKeyValueStore: Deleting the encryption key identified by the keyAlias: com.amazonaws.android.auth.aesKeyStoreAlias
E/AWSKeyValueStore: Error in retrieving the decryption key used to decrypt the data from the persistent store. Returning null for the requested dataKey = IDENTITY_POOL_ID.expirationDate
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
how can i solve?
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Collections;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.services.drive.DriveScopes;
public class pred {
public static String getGoogleAccessToken(String jsonKeyFilePath)
throws FileNotFoundException, IOException, GeneralSecurityException {
GoogleCredential credential = GoogleCredential.fromStream(
new FileInputStream(jsonKeyFilePath)).createScoped(
Collections.singleton(DriveScopes.DRIVE));
credential.refreshToken();
return credential.getAccessToken();
}
public static void main(String[] args) throws IOException, GeneralSecurityException {
String a=getGoogleAccessToken("D:ml-latest-small\\untitled\\src\\woven*************.json");
System.out.println(a);
}
}
I want to get access token to get prediction from a version deployed in the google cloud. Above code
gives an access token to google drive. Is there a way to change this part (DriveScopes.DRIVE) to get
an access token to google cloud. Or is there a another way to get access token from java.
I am trying to use Amazon SES to send email to my corporate account. I have copied by aws access keys to ~/.aws/credentials file. Seems i am consistently getting the error:
Error message: The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.
The Canonical String for this request should have been
'POST
/
amz-sdk-invocation-id:638ed10a-22cd-12f5-c9a5-25a672a6c38d
amz-sdk-retry:3/136/485
host:email.us-east-1.amazonaws.com
user-agent:aws-sdk-java/1.11.172 Mac_OS_X/10.11.5 Java_HotSpot(TM)_64-Bit_Server_VM/25.60-b23/1.8.0_60
x-amz-date:20170808T040309Z
amz-sdk-invocation-id;amz-sdk-retry;host;user-agent;x-amz-date
1c21e3af09924eec311e370c8e6710c0bc3fa2027fe213db11f02b22d79b6c91'
The String-to-Sign should have been
'AWS4-HMAC-SHA256
20170808T040309Z
20170808/us-east-1/ses/aws4_request
82a2179c0dda36b0a4f80c111a8119cc8a65d768a0ff65de4c9b7ccf69a6b68a' (Service: AmazonSimpleEmailService; Status Code: 403; Error Code: SignatureDoesNotMatch; Request ID: 7dbfbcaa-7bee-11e7-a445-27be327c79a0)
com.amazonaws.services.simpleemail.model.AmazonSimpleEmailServiceException: The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.
The Canonical String for this request should have been
'POST
/
amz-sdk-invocation-id:638ed10a-22cd-12f5-c9a5-25a672a6c38d
amz-sdk-retry:3/136/485
host:email.us-east-1.amazonaws.com
user-agent:aws-sdk-java/1.11.172 Mac_OS_X/10.11.5 Java_HotSpot(TM)_64-Bit_Server_VM/25.60-b23/1.8.0_60
x-amz-date:20170808T040309Z
amz-sdk-invocation-id;amz-sdk-retry;host;user-agent;x-amz-date
1c21e3af09924eec311e370c8e6710c0bc3fa2027fe213db11f02b22d79b6c91'
The String-to-Sign should have been
'AWS4-HMAC-SHA256
20170808T040309Z
20170808/us-east-1/ses/aws4_request
82a2179c0dda36b0a4f80c111a8119cc8a65d768a0ff65de4c9b7ccf69a6b68a' (Service: AmazonSimpleEmailService; Status Code: 403; Error Code: SignatureDoesNotMatch; Request ID: 7dbfbcaa-7bee-11e7-a445-27be327c79a0)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.handleErrorResponse(AmazonHttpClient.java:1587)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeOneRequest(AmazonHttpClient.java:1257)
Code base:
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.ByteBuffer;
import java.util.Properties;
import java.util.UUID;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import com.amazonaws.AmazonClientException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.simpleemail.AmazonSimpleEmailServiceClient;
import com.amazonaws.services.simpleemail.model.RawMessage;
import com.amazonaws.services.simpleemail.model.SendRawEmailRequest;
public class SESClient {
private static String EMAIL_FROM = "##########";
private static String EMAIL_REPLY_TO = "##########";
private static String EMAIL_RECIPIENT = "##########";
// Remember to use two slashes in place of each slash.
private static Regions AWS_REGION = Regions.US_EAST_1;
private static String EMAIL_SUBJECT = "Amazon SES email test";
private static String EMAIL_BODY_TEXT = "This MIME email was sent through Amazon SES using SendRawEmail.";
public static void main(String[] args) throws AddressException, MessagingException, IOException {
Session session = Session.getDefaultInstance(new Properties());
MimeMessage message = new MimeMessage(session);
message.setSubject(EMAIL_SUBJECT, "UTF-8");
message.setFrom(new InternetAddress(EMAIL_FROM));
message.setReplyTo(new Address[]{new InternetAddress(EMAIL_REPLY_TO)});
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(EMAIL_RECIPIENT));
// Cover wrap
MimeBodyPart wrap = new MimeBodyPart();
// Alternative TEXT/HTML content
MimeMultipart cover = new MimeMultipart("alternative");
MimeBodyPart html = new MimeBodyPart();
cover.addBodyPart(html);
wrap.setContent(cover);
MimeMultipart content = new MimeMultipart("related");
message.setContent(content);
content.addBodyPart(wrap);
String[] attachmentsFiles = new String[]{
//EMAIL_ATTACHMENTS
};
StringBuilder sb = new StringBuilder();
for (String attachmentFileName : attachmentsFiles) {
String id = UUID.randomUUID().toString();
sb.append("<img src=\"cid:");
sb.append(id);
sb.append("\" alt=\"ATTACHMENT\"/>\n");
MimeBodyPart attachment = new MimeBodyPart();
DataSource fds = new FileDataSource(attachmentFileName);
attachment.setDataHandler(new DataHandler(fds));
attachment.setHeader("Content-ID", "<" + id + ">");
attachment.setFileName(fds.getName());
content.addBodyPart(attachment);
}
html.setContent("<html><body><h1>HTML</h1>\n" + EMAIL_BODY_TEXT + "</body></html>", "text/html");
try {
System.out.println("Attempting to send an email through Amazon SES by using the AWS SDK for Java...");
/*
* The ProfileCredentialsProvider will return your [default]
* credential profile by reading from the credentials file
* located at
* (~/.aws/credentials).
*
* TransferManager manages a pool of threads, so we create a
* single instance and share it throughout our application.
*/
AWSCredentials credentials = null;
try {
credentials = new ProfileCredentialsProvider().getCredentials();
} catch (Exception e) {
throw new AmazonClientException(
"Cannot load the credentials from the credential profiles file. " +
"Please make sure that your credentials file is at the correct " +
"location (~/.aws/credentials), and is in valid format.",
e);
}
AmazonSimpleEmailServiceClient client = new AmazonSimpleEmailServiceClient(credentials);
Region REGION = Region.getRegion(AWS_REGION);
client.setRegion(REGION);
// Print the raw email content on the console
PrintStream out = System.out;
message.writeTo(out);
// Send the email.
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
message.writeTo(outputStream);
RawMessage rawMessage = new RawMessage(ByteBuffer.wrap(outputStream.toByteArray()));
SendRawEmailRequest rawEmailRequest = new SendRawEmailRequest(rawMessage);
client.sendRawEmail(rawEmailRequest);
System.out.println("Email sent!");
} catch (Exception ex) {
System.out.println("Email Failed");
System.err.println("Error message: " + ex.getMessage());
ex.printStackTrace();
}
}
}
I am trying to upload a file to Amazon S3 bucket using Groovy script. I tried the following code
#Grab( 'net.java.dev.jets3t:jets3t:0.9.0' )
import org.jets3t.service.impl.rest.httpclient.RestS3Service
import org.jets3t.service.security.AWSCredentials
import org.jets3t.service.model.*
import java.io.*;
bucketName='bucketname'
accessKey='accesskey'
secretKey='secretkey'
folder='D:/'
public putS3() {}
def login = new AWSCredentials( accessKey, secretKey )
def expiry = new GregorianCalendar( 2011,0,1 ).time
def s3 = new RestS3Service( login )
def bucket = new S3Bucket( bucketName )
args.each{fileName->
def key="$folder/$fileName"
def s3obj=new S3Object(bucket,newFile('D:/sample.txt'))
s3obj.key = key
println "\nUploading $fileName to $bucketName/$key"
s3obj = s3.putObject( bucket, s3obj )
def link = s3.createSignedGetUrl( bucketName, key, login, expiry, false )
println "$fileName : $link"
}
code in the args block is not getting executed. When I execute this in Groovy Console it displays the result as []. Kindly help me where am I going wrong?
I don't have an S3 account to test with but here's a simplied example based upon the documenation:
import org.jets3t.service.impl.rest.httpclient.RestS3Service
import org.jets3t.service.model.S3Bucket
import org.jets3t.service.model.S3Object
import org.jets3t.service.security.AWSCredentials
#Grab('net.java.dev.jets3t:jets3t:0.9.0')
accessKey = 'accesskey'
secretKey = 'secretkey'
bucketName = 'bucketname'
fileName = 'D:\\sample.txt'
credentials = new AWSCredentials(accessKey, secretKey)
service = new RestS3Service(credentials)
bucket = new S3Bucket(bucketName)
file = new File(fileName)
fileObject = new S3Object(file)
fileObject.key = fileName
service.putObject(bucket, fileObject)
expiryTime = new Date() + 1 // 24 hours from current date
link = service.createSignedGetUrl(bucket.name, fileObject.key, expiryTime)
println "$fileName : $link"
I came accross that example recently as I attempt to code a quick groovy to upload to a S3 Bucket, however, all my attempts have ended up with 301
org.jets3t.service.S3ServiceException: Service Error Message. -- ResponseCode: 301, ResponseStatus: Moved Permanently, XML Error Message: <?xml version="1.0" encoding="UTF-8"?><Error><Code>PermanentRedirect</Code><Message>The bucket you are attempting to access must be addressed using the specified endpoint. Please send all future requests to this endpoint.</Message><Endpoint>bucketname.s3.amazonaws.com</Endpoint><Bucket>bucketname</Bucket><RequestId>4CF5EDE9EF604DBB</RequestId><HostId>89KoQLvd93pXhnxJGcEaziSrSOPFRNXqbfPfY7LTe03z5rvVLAVx7UnFkts/Qe1fQ7eOWsaAL7A=</HostId></Error>
at org.jets3t.service.S3Service.putObject(S3Service.java:2358)
at org.jets3t.service.S3Service$putObject.call(Unknown Source)
at awsBucketDrop.run(awsBucketDrop.groovy:21)
At first I though this was a bucket location issue, as I found reference around 301 for that, however I've modified the code to swap to the bucket location, to no avail.
import org.jets3t.service.model.S3Bucket
import org.jets3t.service.model.S3Object
import org.jets3t.service.security.AWSCredentials
#Grab('net.java.dev.jets3t:jets3t:0.9.4')
accessKey = '<key>'
secretKey = '<secret>'
bucketName = '<bucketname>'
fileName = '<fileLocation>'
credentials = new AWSCredentials(accessKey, secretKey)
service = new RestS3Service(credentials)
bucket = new S3Bucket(bucketName,"eu-west-1")
println bucket.getLocation()
file = new File(fileName)
fileObject = new S3Object(file)
fileObject.key = fileName
service.putObject(bucket, fileObject)
expiryTime = new Date() + 1 // 24 hours from current date
link = service.createSignedGetUrl(bucket.name, fileObject.key, expiryTime)
println "$fileName : $link"
Now, this sdk has not been updated since 2015, so it's a fairly old SDK so I get the feeling it's no longer compatible (and might have some url hard coded into it) but if you had similar experience that you managed to solve out, let me know.
Thanks
If you come accross this and need a working groovy, I've loosely modified this code to work as a simple groovy
import com.amazonaws.AmazonServiceException;
import com.amazonaws.SdkClientException;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;
import java.io.File;
import java.io.IOException;
Regions clientRegion = Regions.EU_WEST_1;
String bucketName = "bucketname";
String stringObjKeyName = "stringObjKeyName";
String fileObjKeyName = "fileObjKeyName";
String fileName = "fileLocation";
try {
//This code expects that you have AWS credentials set up per:
// https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/setup-credentials.html
AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
.withRegion(clientRegion)
.build();
// Upload a text string as a new object.
s3Client.putObject(bucketName, stringObjKeyName, "Uploaded String Object");
// Upload a file as a new object with ContentType and title specified.
PutObjectRequest request = new PutObjectRequest(bucketName, fileObjKeyName, new File(fileName));
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentType("plain/text");
metadata.addUserMetadata("x-amz-meta-title", "someTitle");
request.setMetadata(metadata);
s3Client.putObject(request);
} catch (AmazonServiceException e) {
// The call was transmitted successfully, but Amazon S3 couldn't process
// it, so it returned an error response.
e.printStackTrace();
} catch (SdkClientException e) {
// Amazon S3 couldn't be contacted for a response, or the client
// couldn't parse the response from Amazon S3.
e.printStackTrace();
}
I need to create web service client in Java using Eclipse the consumes the onvif wsdl.
I spent several hours without finding a how to do that, this the first time I am using soap, my experience was in REST.
I tried many tutorials like this to create web service client, but when I am trying to choose the wsdl file from my local disk, eclipse shows the an error Could not retrieve the WSDL file ..., the link structure I used for the file was file:/C:/ONVIF/media.wsdl.
I need to use any Java framework that support WS-Notification to implement my client.
Can you please tell me how to implement client web service that consumes the WSDL files.
Do I need web server to implement soap web service client?
If yes, why?
Here is a complete code and guide on how to consume one of ONVIF's wsdl files (devicemgmt.wsdl) and how to use it to connect to a device:
package test;
import java.io.IOException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import javax.xml.namespace.QName;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPHeader;
import javax.xml.ws.Binding;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.Holder;
import javax.xml.ws.Service;
import javax.xml.ws.handler.Handler;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;
import org.onvif.ver10.device.wsdl.Device;
import org.onvif.ver10.schema.DateTime;
import org.onvif.ver10.schema.SystemDateTime;
import org.onvif.ver10.schema.Time;
import com.sun.org.apache.xml.internal.security.utils.Base64;
public class OnvifTest {
private static TimeZone utc = TimeZone.getTimeZone("UTC");
private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
static {
sdf.setTimeZone(utc);
}
private static long serverTime = 0;
private static long clientTime = 0;
private static final String ip = "...";
private static final String user = "...";
private static final String pass = "...";
// Some cameras (e.g. Axis) require that you set the user/pass on the ONVIF section in it's web interface
// If the camera is reset to factory defaults and was never accessed from the web, then
// either no user/pass is needed or the default user/pass can be used
#SuppressWarnings("rawtypes")
public static void main(String[] args) throws IOException {
// The altered wsdl file
URL url = new URL("file://"+System.getProperty("user.home")+"/onvif/devicemgmt.wsdl");
// This file was downloaded from the onvif website and added a mock service in order to make it complete:
// <wsdl:service name="DeviceService">
// <wsdl:port name="DevicePort" binding="tds:DeviceBinding">
// <soap:address location="http://localhost/onvif/device_service"/>
// </wsdl:port>
// </wsdl:service>
// The altered file was then used to generate java classes using $JAVA_HOME/bin/wsimport -Xnocompile -extension devicemgmt.wsdl
QName qname = new QName("http://www.onvif.org/ver10/device/wsdl", "DeviceService");
Service service = Service.create(url, qname);
Device device = service.getPort(Device.class);
BindingProvider bindingProvider = (BindingProvider)device;
// Add a security handler for the credentials
final Binding binding = bindingProvider.getBinding();
List<Handler> handlerList = binding.getHandlerChain();
if (handlerList == null)
handlerList = new ArrayList<Handler>();
handlerList.add(new SecurityHandler());
binding.setHandlerChain(handlerList);
// Set the actual web services address instead of the mock service
Map<String, Object> requestContext = bindingProvider.getRequestContext();
requestContext.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, "http://"+ip+"/onvif/device_service");
// Read the time from the server
SystemDateTime systemDateAndTime = device.getSystemDateAndTime();
// Mark the local time (no need for an actual clock, the monotone counter will do just fine)
clientTime = System.nanoTime()/1000000;
// Generate the server time in msec since epoch
DateTime utcDateTime = systemDateAndTime.getUTCDateTime();
org.onvif.ver10.schema.Date date = utcDateTime.getDate();
Time time = utcDateTime.getTime();
Calendar c = new GregorianCalendar(utc);
c.set(date.getYear(), date.getMonth()-1, date.getDay(), time.getHour(), time.getMinute(), time.getSecond());
System.out.println(sdf.format(c.getTime()));
serverTime = c.getTimeInMillis();
// Now try and read something interesting
Holder<String> manufacturer = new Holder<String>();
Holder<String> model = new Holder<String>();
Holder<String> firmwareVersion = new Holder<String>();
Holder<String> serialNumber = new Holder<String>();
Holder<String> hardwareId = new Holder<String>();
device.getDeviceInformation(manufacturer, model, firmwareVersion, serialNumber, hardwareId);
System.out.println(manufacturer.value);
System.out.println(model.value);
System.out.println(firmwareVersion.value);
System.out.println(serialNumber.value);
System.out.println(hardwareId.value);
}
// Calcualte the password digest from a concatenation of the nonce, the creation time and the password itself
private static String calculatePasswordDigest(byte[] nonceBytes, String created, String password) {
String encoded = null;
try {
MessageDigest md = MessageDigest.getInstance( "SHA1" );
md.reset();
md.update( nonceBytes );
md.update( created.getBytes() );
md.update( password.getBytes() );
byte[] encodedPassword = md.digest();
encoded = Base64.encode(encodedPassword);
} catch (NoSuchAlgorithmException ex) {
}
return encoded;
}
// Calculate what time is it right now on the server
private static String localToGmtTimestamp() {
return sdf.format(new Date(System.nanoTime()/1000000 - clientTime + serverTime));
}
// This handler will add the authentication parameters
private static final class SecurityHandler implements SOAPHandler<SOAPMessageContext> {
#Override
public boolean handleMessage(final SOAPMessageContext msgCtx) {
// Indicator telling us which direction this message is going in
final Boolean outInd = (Boolean) msgCtx.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
// Handler must only add security headers to outbound messages
if (outInd.booleanValue() && clientTime!=0 && user!=null && pass!=null) {
try {
// Create the timestamp
String timestamp = localToGmtTimestamp();
// Generate a random nonce
byte[] nonceBytes = new byte[16];
for (int i=0 ; i<16 ; ++i)
nonceBytes[i] = (byte)(Math.random()*256-128);
// Digest
String dig=calculatePasswordDigest(nonceBytes, timestamp, pass);
// Create the xml
SOAPEnvelope envelope = msgCtx.getMessage().getSOAPPart().getEnvelope();
SOAPHeader header = envelope.getHeader();
if (header == null)
header = envelope.addHeader();
SOAPElement security =
header.addChildElement("Security", "wsse", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
SOAPElement usernameToken =
security.addChildElement("UsernameToken", "wsse");
SOAPElement username =
usernameToken.addChildElement("Username", "wsse");
username.addTextNode(user);
SOAPElement password =
usernameToken.addChildElement("Password", "wsse");
password.setAttribute("Type", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest");
password.addTextNode(dig);
SOAPElement nonce =
usernameToken.addChildElement("Nonce", "wsse");
nonce.setAttribute("EncodingType", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary");
nonce.addTextNode(Base64.encode(nonceBytes));
SOAPElement created = usernameToken.addChildElement("Created", "wsu", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
created.addTextNode(timestamp);
} catch (final Exception e) {
e.printStackTrace();
return false;
}
}
return true;
}
// Other required methods on interface need no guts
#Override
public boolean handleFault(SOAPMessageContext context) {
// TODO Auto-generated method stub
return false;
}
#Override
public void close(MessageContext context) {
// TODO Auto-generated method stub
}
#Override
public Set<QName> getHeaders() {
// TODO Auto-generated method stub
return null;
}
}
}
I would recommend using wsimport command to generate the web service client to consume the web services.
The command can be executed from cmd prompt,
wsimport -d D:\WS-Client -extension -keep -XadditionalHeaders http://path-to-your-webserbice-wsdl-file/sampleWSDL?wsdl
After execution of the above command all the generated .class files and .java (source) files will be placed inside D:\WS-Client folder with proper package structure as mentioned in the wsdl file.
just ignore the .class files and copy entire package folder and include it in your consumer project to use it.
It will be like, you have the deployed web services in your source code. Just call the methods from the service classes and ohhla :)
The WSDL you were provided is invalid. Most likely due to the extensive documentation tags that were used in it. You can verify this by trying to load it in SoapUI. Your best bet is to contact the vendor to find out if they have a cleaner version of the WSDL they can provide you.
first you want to deploy your web service project on any server means tomcat or other.
after that use the running server WSDL file URL for create the client.