Setting up AWS IOT Core JITR process on Android - java

I need to set up a JITR (Just in time registration) process to AWS IOT core for my Android Application using Android AWS IOT SDK. My implementation is done referring this . However, When trying to create a thing after creating a fresh X.509 certificate (On the first connection attempt), Even though the certificate is created on the server, the Server returns errors regarding "unmatched signatures and an empty template body".
This is my current sample implementation,
public class MainActivity extends AppCompatActivity {
private boolean thingExist;
private String certificateARN;
// IoT endpoint
// AWS Iot CLI describe-endpoint call returns: XXXXXXXXXX.iot.<region>.amazonaws.com
private static final String CUSTOMER_SPECIFIC_ENDPOINT = "";
// Cognito pool ID. For this app, pool needs to be unauthenticated pool with
// AWS IoT permissions.
private static final String COGNITO_POOL_ID = "";
// Name of the AWS IoT policy to attach to a newly created certificate
private static final String AWS_IOT_POLICY_NAME = "";
// Region of AWS IoT
private static final Regions MY_REGION = Regions.US_EAST_2;
// Filename of KeyStore file on the filesystem
private static final String KEYSTORE_NAME = "iot_keystore";
// Password for the private key in the KeyStore
private static final String KEYSTORE_PASSWORD = "password";
// Certificate and key aliases in the KeyStore
private static final String CERTIFICATE_ID = "default";
AWSIotClient mIotAndroidClient;
AWSIotMqttManager mqttManager;
String clientId;
String keystorePath;
String keystoreName;
String keystorePassword;
private boolean isAWSConnected;
private listThings mTask;
private boolean certificateExist;
private final String LOG_TAG = "AWS";
private final String serialId = "1110";
KeyStore clientKeyStore = null;
String certificateId;
CognitoCachingCredentialsProvider credentialsProvider;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
clientId = Settings.Global.getString(getApplicationContext().getContentResolver(), "device_name");
// Initialize the AWS Cognito credentials provider
credentialsProvider = new CognitoCachingCredentialsProvider(
getApplicationContext(), // context
COGNITO_POOL_ID, // Identity Pool ID
MY_REGION // Region
);
Region region = Region.getRegion(MY_REGION);
// MQTT Client
mqttManager = new AWSIotMqttManager(clientId, CUSTOMER_SPECIFIC_ENDPOINT);
// Set keepalive to 10 seconds. Will recognize disconnects more quickly but will also send
// MQTT pings every 10 seconds.
mqttManager.setKeepAlive(10);
// Set Last Will and Testament for MQTT. On an unclean disconnect (loss of connection)
// AWS IoT will publish this message to alert other clients.
AWSIotMqttLastWillAndTestament lwt = new AWSIotMqttLastWillAndTestament("Last will",
new Gson().toJson("Android client lost connection"), AWSIotMqttQos.QOS0);
mqttManager.setMqttLastWillAndTestament(lwt);
mIotAndroidClient = new AWSIotClient(credentialsProvider);
mIotAndroidClient.setRegion(region);
keystorePath = getFilesDir().getPath();
keystoreName = KEYSTORE_NAME;
keystorePassword = KEYSTORE_PASSWORD;
certificateId = CERTIFICATE_ID;
// To load cert/key from keystore on filesystem
try {
if (AWSIotKeystoreHelper.isKeystorePresent(keystorePath, keystoreName)) {
if (AWSIotKeystoreHelper.keystoreContainsAlias(certificateId, keystorePath,
keystoreName, keystorePassword)) {
Log.i(LOG_TAG, "Certificate " + certificateId
+ " found in keystore - using for MQTT.");
// load keystore from file into memory to pass on connection
clientKeyStore = AWSIotKeystoreHelper.getIotKeystore(certificateId,
keystorePath, keystoreName, keystorePassword);
certificateExist = true;
mTask = (listThings) new listThings().execute();
} else {
Log.i(LOG_TAG, "Key/cert " + certificateId + " not found in keystore.");
}
} else {
Log.i(LOG_TAG, "Keystore " + keystorePath + "/" + keystoreName + " not found.");
}
} catch (Exception e) {
Log.e(LOG_TAG, "An error occurred retrieving cert/key from keystore.", e);
}
if (clientKeyStore == null) {
certificateExist = false;
Log.i(LOG_TAG, "Cert/key was not found in keystore - creating new key and certificate.");
new Thread(new Runnable() {
#Override
public void run() {
try {
// Create a new private key and certificate. This call
// creates both on the server and returns them to the
// device.
CreateKeysAndCertificateRequest createKeysAndCertificateRequest =
new CreateKeysAndCertificateRequest();
createKeysAndCertificateRequest.setSetAsActive(true);
final CreateKeysAndCertificateResult createKeysAndCertificateResult;
createKeysAndCertificateResult =
mIotAndroidClient.createKeysAndCertificate(createKeysAndCertificateRequest);
Log.i(LOG_TAG,
"Cert ID: " +
createKeysAndCertificateResult.getCertificateId() +
" created.");
// store in keystore for use in MQTT client
// saved as alias "default" so a new certificate isn't
// generated each run of this application
AWSIotKeystoreHelper.saveCertificateAndPrivateKey(certificateId,
createKeysAndCertificateResult.getCertificatePem(),
createKeysAndCertificateResult.getKeyPair().getPrivateKey(),
keystorePath, keystoreName, keystorePassword);
certificateARN = createKeysAndCertificateResult.getCertificateArn();
// load keystore from file into memory to pass on
// connection
clientKeyStore = AWSIotKeystoreHelper.getIotKeystore(certificateId,
keystorePath, keystoreName, keystorePassword);
// Attach a policy to the newly created certificate.
// This flow assumes the policy was already created in
// AWS IoT and we are now just attaching it to the
// certificate.
AttachPrincipalPolicyRequest policyAttachRequest =
new AttachPrincipalPolicyRequest();
policyAttachRequest.setPolicyName(AWS_IOT_POLICY_NAME);
policyAttachRequest.setPrincipal(createKeysAndCertificateResult
.getCertificateArn());
mIotAndroidClient.attachPrincipalPolicy(policyAttachRequest);
mTask = (listThings) new listThings().execute();
} catch (Exception e) {
Log.e(LOG_TAG,
"Exception occurred when generating new private key and certificate.",
e);
}
}
}).start();
}
}
private class listThings extends AsyncTask<Void, Void, Boolean> {
// Listing registered things to verify whether a thing already exist under the same device ID.
#Override
protected Boolean doInBackground(Void... voids) {
Log.d(LOG_TAG, "Listing Things");
final ListThingsRequest request = new ListThingsRequest().withAttributeName("Device_ID")
.withAttributeValue(serialId).withMaxResults(1);
final ListThingsResult result = mIotAndroidClient.listThings(request);
if (!result.getThings().isEmpty()) {
thingExist = true;
return true;
} else {
thingExist = false;
return false;
}
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
Log.d(LOG_TAG, "onPostExecute: " + aBoolean.toString());
if (certificateExist) {
new createThing().execute();
} else {
new awsAsync().execute();
}
mTask.cancel(true);
}
}
private class awsAsync extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
if (thingExist) {
//Thing Exist, certificate doesn't exist
AttachThingPrincipalRequest thingPrincipalRequest = new AttachThingPrincipalRequest();
thingPrincipalRequest.setThingName(serialId);
thingPrincipalRequest.setPrincipal(certificateARN);
Log.d(LOG_TAG, "certificateARN " + certificateARN);
mIotAndroidClient.attachThingPrincipal(thingPrincipalRequest);
/*check if previous certificates are available and delete them*/
} else {
//Thing Doesn't Exist, certificate doesn't exist
try {
Log.d(LOG_TAG, "Thing does not Exist, certificate doesn't exist");
Map<String, String> attributes = new HashMap<String, String>() {{
put("Device_ID", serialId);
put("Android_version", Build.VERSION.RELEASE);
}};
CreateThingRequest createThingRequest = new CreateThingRequest();
createThingRequest.setThingName(serialId);
AttributePayload attributePayload = new AttributePayload();
attributePayload.setAttributes(attributes);
createThingRequest.setThingTypeName("Consenz_search");
createThingRequest.setAttributePayload(attributePayload);
mIotAndroidClient.createThing(createThingRequest);
AddThingToThingGroupRequest addThingToThingGroupRequest = new AddThingToThingGroupRequest();
addThingToThingGroupRequest.setThingName(serialId);
addThingToThingGroupRequest.setThingGroupName("Consenz_Group");
mIotAndroidClient.addThingToThingGroup(addThingToThingGroupRequest);
AttachThingPrincipalRequest thingPrincipalRequest = new AttachThingPrincipalRequest();
thingPrincipalRequest.setThingName(serialId);
thingPrincipalRequest.setPrincipal(certificateARN);
mIotAndroidClient.attachThingPrincipal(thingPrincipalRequest);
} catch (Exception e) {
Log.e(LOG_TAG,
"Excepetion occured when creating thing",
e);
}
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
connectToAWS();
}
}
private class createThing extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
if (!thingExist) {
try {
//Thing doesn't exist, Certificate exist
Log.d(LOG_TAG, "Thing does not Exist. Creating a thing");
Map<String, String> attributes = new HashMap<String, String>() {{
put("Device_ID", serialId);
put("Android_version", Build.VERSION.RELEASE);
}};
CreateThingRequest createThingRequest = new CreateThingRequest();
createThingRequest.setThingName(serialId);
AttributePayload attributePayload = new AttributePayload();
attributePayload.setAttributes(attributes);
createThingRequest.setThingTypeName("Consenz_search");
createThingRequest.setAttributePayload(attributePayload);
mIotAndroidClient.createThing(createThingRequest);
AddThingToThingGroupRequest addThingToThingGroupRequest = new AddThingToThingGroupRequest();
addThingToThingGroupRequest.setThingName(serialId);
addThingToThingGroupRequest.setThingGroupName("Consenz_Group");
mIotAndroidClient.addThingToThingGroup(addThingToThingGroupRequest);
AttachThingPrincipalRequest thingPrincipalRequest = new AttachThingPrincipalRequest();
thingPrincipalRequest.setThingName(serialId);
thingPrincipalRequest.setPrincipal(AWSIotKeystoreHelper.AWS_IOT_INTERNAL_KEYSTORE_PASSWORD);
mIotAndroidClient.attachThingPrincipal(thingPrincipalRequest);
//need to attach the current thing to existing certificate.
} catch (Exception e) {
Log.e(LOG_TAG,
"Excepetion occured when creating thing",
e);
}
} else {
//Thing exist, Certificate exist
//need to attach the current thing to existing certificate.
Log.d(LOG_TAG, "We here");
final ListThingPrincipalsRequest request = new ListThingPrincipalsRequest().withThingName(serialId);
final ListThingPrincipalsResult result = mIotAndroidClient.listThingPrincipals(request);
DescribeCertificateRequest request1 = new DescribeCertificateRequest().withCertificateId("default");
DescribeCertificateResult result1 = mIotAndroidClient.describeCertificate(request1);
String arn = result1.getCertificateDescription().getCertificateArn();
result.toString();
Log.d(LOG_TAG, "arn " + arn);
Log.d(LOG_TAG, "certificates " + result);
//Log.d(LOG_TAG, "Thing Exists. Attaching thing to certificate");
AttachThingPrincipalRequest thingPrincipalRequest = new AttachThingPrincipalRequest();
thingPrincipalRequest.setThingName(serialId);
//String arn = thingPrincipalRequest.getPrincipal(c);
//Log.d(LOG_TAG, "arn "+arn);
mIotAndroidClient.attachThingPrincipal(thingPrincipalRequest);
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
//Log.d(LOG_TAG, "Done creating thing");
connectToAWS();
}
}
private void connectToAWS() {
try {
Log.d(LOG_TAG, "Client ID: " + clientId);
mqttManager.connect(clientKeyStore, new AWSIotMqttClientStatusCallback() {
#Override
public void onStatusChanged(final AWSIotMqttClientStatus status,
final Throwable throwable) {
Log.d(LOG_TAG, "Status = " + String.valueOf(status));
runOnUiThread(new Runnable() {
#Override
public void run() {
if (status == AWSIotMqttClientStatus.Connecting) {
Log.d(LOG_TAG, "Connecting...");
isAWSConnected = false;
} else if (status == Connected) {
Log.d(LOG_TAG, "Connected");
isAWSConnected = true;
//creatething
publishToAWS();
} else if (status == AWSIotMqttClientStatus.Reconnecting) {
if (throwable != null) {
Log.e(LOG_TAG, "Connection error.", throwable);
isAWSConnected = false;
}
isAWSConnected = false;
Log.d(LOG_TAG, "Reconnecting");
} else if (status == AWSIotMqttClientStatus.ConnectionLost) {
if (throwable != null) {
Log.e(LOG_TAG, "Connection error.", throwable);
isAWSConnected = false;
}
isAWSConnected = false;
Log.d(LOG_TAG, "Disconnected");
} else {
isAWSConnected = false;
Log.d(LOG_TAG, "Disconnected");
}
}
});
}
});
} catch (final Exception e) {
Log.d(LOG_TAG, "Error! " + e.getMessage());
}
}
private void publishToAWS() {
//publishing MQQT messages to AWS
String version = "";
String versionRelease = Build.VERSION.RELEASE;
try {
version = this.getPackageManager().getPackageInfo(this.getPackageName(), 0).versionName;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
try {
mqttManager.publishString(new Gson().toJson(serialId), "Device_ID", AWSIotMqttQos.QOS0);
mqttManager.publishString(new Gson().toJson(version), "APK_Version", AWSIotMqttQos.QOS0);
mqttManager.publishString(new Gson().toJson(versionRelease), "Android_Version", AWSIotMqttQos.QOS0);
} catch (Exception e) {
Log.e(LOG_TAG, "Publish error.", e);
}
}
}
what am I doing wrong here? thanks in advance.

Related

Send pussh crossplatform, hub Azure

I have an application that is now being developed for IOS. I need them pushed between the platforms. As it is written today, in the backend, it works from Android for Android, but I changed the registration of the devices, so that they were registered with the respective templates (of each platform).
More, it stopped working obviously because it is written from Android to Android.
The record in the hub is correct. What should I change for push to be sent?
Backend code:
public static async void enviarPushNotification(ApiController controller, DataObjects.Notification notification)
{
// Get the settings for the server project.
HttpConfiguration config = controller.Configuration;
MobileAppSettingsDictionary settings =
controller.Configuration.GetMobileAppSettingsProvider().GetMobileAppSettings();
// Get the Notification Hubs credentials for the Mobile App.
string notificationHubName = settings.NotificationHubName;
string notificationHubConnection = settings
.Connections[MobileAppSettingsKeys.NotificationHubConnectionString].ConnectionString;
// Create a new Notification Hub client.
NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString(notificationHubConnection, notificationHubName);
// Android payload
JObject data = new JObject();
data.Add("Id", notification.Id);
data.Add("Descricao", notification.Descricao);
data.Add("Tipo", notification.Tipo);
data.Add("Id_usuario", notification.Id_usuario);
//data.Add("Informacao", notification.Informacao);
data.Add("Informacao", notification.Informacao);
data.Add("Status", notification.Status);
//alteração com a colocação da tag priority em caso de erro teste sem \"priority\": \"high\"
var androidNotificationPayload = "{ \"priority\": \"high\", \"data\" : {\"message\":" + JsonConvert.SerializeObject(data) + "}}";
// var androidNotificationPayload = "{ \"data\" : {\"message\":" + JsonConvert.SerializeObject(data) + "}}";
try
{
// Send the push notification and log the results.
String tag = "_UserId:" + notification.Id_usuario;
//var result = await hub.SendGcmNativeNotificationAsync(androidNotificationPayload);
var result = await hub.SendGcmNativeNotificationAsync(androidNotificationPayload, tag);
// Write the success result to the logs.
config.Services.GetTraceWriter().Info(result.State.ToString());
}
catch (System.Exception ex)
{
// Write the failure result to the logs.
config.Services.GetTraceWriter().Error(ex.Message, null, "Push.SendAsync Error");
}
}
Device code:
public class RegistrationIntentService extends IntentService {
private static final String TAG = "RegIntentService";
private NotificationHub hub;
public RegistrationIntentService() {
super(TAG);
}
public ApplicationUtils getApplicationUtils() {
return (ApplicationUtils) getApplication();
}
#Override
protected void onHandleIntent(Intent intent) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
try {
if (FirebaseInstanceId.getInstance() == null) {
FirebaseApp.initializeApp(this);
}
String FCM_token = FirebaseInstanceId.getInstance().getToken();
SaveSharedPreferences.setFCM(getApplicationContext(), FCM_token);
String registrationID = sharedPreferences.getString("registrationID", null);
if (registrationID == null) {
registerDevice(sharedPreferences, FCM_token);
} else {
String fcMtoken = sharedPreferences.getString("FCMtoken", "");
if (!fcMtoken.equals(FCM_token)) {
registerDevice(sharedPreferences, FCM_token);
}
}
} catch (Exception e) {
Log.e(TAG, "Failed to complete registration", e);
}
}
private void registerDevice(SharedPreferences sharedPreferences, String FCM_token) throws Exception {
String tag = "_UserId:" + getApplicationUtils().getUsuario().Id;
NotificationHub hub = new NotificationHub(NotificationSettings.HubName,
NotificationSettings.HubListenConnectionString, this);
String templateBodyGCM = "{\"data\":{\"message\":\"$(messageParam)\"}}";
TemplateRegistration registration = hub.registerTemplate(FCM_token, "simpleGCMTemplate", templateBodyGCM, tag);
String regID = registration.getRegistrationId();
sharedPreferences.edit().putString("registrationID", regID).apply();
sharedPreferences.edit().putString("FCMtoken", FCM_token).apply();
}
}

Certificate Pinning on Android with Robospice

I'm reading about certificate pinning on Android and I'm confused. I'm not using okhttp or retrofit so I have to do it manually.
There is a tutorial here: https://www.owasp.org/index.php/Certificate_and_Public_Key_Pinning#Android
where they are adding the certificate to list of trusted certificates. But there is also another tutorial when we're checking base64 of sha256 of the certificate installed on the server: https://medium.com/#appmattus/android-security-ssl-pinning-1db8acb6621e
Which approach is the correct one?
Why can't we just receive sha256 from the server in the header as browsers do and store it somewhere?
I would recommend this
https://www.paypal-engineering.com/2015/10/14/key-pinning-in-mobile-applications/
Android Method
The simplest approach is to use a JSEE-based method as shown below. This is the recommended approach for Android. The method’s input arguments are an HTTPS connection and a set of valid pins for the targeted URL.
private boolean validatePinning(HttpsURLConnection conn, Set<String> validPins) {
try {
Certificate[] certs = conn.getServerCertificates();
MessageDigest md = MessageDigest.getInstance("SHA-256");
for (Certificate cert : certs) {
X509Certificate x509Certificate = (X509Certificate) cert;
byte[] key = x509Certificate.getPublicKey().getEncoded();
md.update(key, 0, key.length);
byte[] hashBytes = md.digest();
StringBuffer hexHash = new StringBuffer();
for (int i = 0; i < hashBytes.length; i++) {
int k = 0xFF & hashBytes[i];
String tmp = (k<16)? "0" : "";
tmp += Integer.toHexString(0xFF & hashBytes[i]);
hexHash.append(tmp);
}
if (validPins.contains(hexHash.toString())) {
return true;
}
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
return false;
}
The pins are declared as strings. For instance:
Declaring Key Pins
private static final Set<String> PINS = new HashSet<String>(Arrays.asList(
new String[]{
"996b510ce2380da9c738...87cb13c9ec409941",
"ba47e83b1ccf0939bb40d2...edf856ba892c06481a"}));
Leveraging the above method, here is an example showing how this can be put to use. The only relevant portion is highlighted below.
Example Using Key Pinning
protected String doInBackground(String... urls) {
try {
/** Test pinning given the target URL **/
/** for now use pre-defined endpoint URL instead or urls[0] **/
Log.i(LOG_TAG, "==> PinningTestTask launched.");
String dest = defaultEndpoint;
URL targetURL = new URL(dest);
HttpsURLConnection targetConnection = (HttpsURLConnection) targetURL.openConnection();
targetConnection.connect();
if (validatePinning(targetConnection, PINS)) {
final String updateText = "Key pinning succeded for: " + dest;
runOnUiThread(new Runnable() {
#Override
public void run() {
textView.setText(updateText);
}
});
} else {
final String updateText = "Key pinning failed for: " + dest;
runOnUiThread(new Runnable() {
#Override
public void run() {
textView.setText(updateText);
}
});
}
} catch (Exception e) {
e.printStackTrace();
final String updateText = "Key pinning failed for: " + dest + "\n" + e.toString();
runOnUiThread(new Runnable() {
#Override
public void run() {
textView.setText(updateText);
}
});
}
return null;
}

ExceptionInInitializerError in jdk1.8 not in jdk1.6

5 with jdk1.8 when I run the project. I got an Exception ExceptionInInitializerError. But when I run the same project in jdk1.6. It is running successfully. That error message as
Exception in thread "main" java.lang.ExceptionInInitializerError
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at java.lang.Class.newInstance(Class.java:442)
at org.ofbiz.entity.GenericDelegator.initEntityEcaHandler(GenericDelegator.java:339)
at org.ofbiz.entity.DelegatorFactory.getDelegator(DelegatorFactory.java:42)
at org.ofbiz.catalina.container.CatalinaContainer.init(CatalinaContainer.java:175)
at org.ofbiz.base.container.ContainerLoader.loadContainer(ContainerLoader.java:189)
at org.ofbiz.base.container.ContainerLoader.load(ContainerLoader.java:66)
at org.ofbiz.base.start.Start.initStartLoaders(Start.java:260)
at org.ofbiz.base.start.Start.init(Start.java:97)
at org.ofbiz.base.start.Start.main(Start.java:411)
Caused by: java.lang.ArrayIndexOutOfBoundsException: 5747
at org.codehaus.aspectwerkz.org.objectweb.asm.ClassReader.readClass(Unknown Source)
at org.codehaus.aspectwerkz.org.objectweb.asm.ClassReader.accept(Unknown Source)
at org.codehaus.aspectwerkz.reflect.impl.asm.AsmClassInfo.getClassInfo(AsmClassInfo.java:308)
at org.codehaus.aspectwerkz.reflect.impl.asm.AsmClassInfo.getClassInfo(AsmClassInfo.java:331)
at org.codehaus.aspectwerkz.reflect.impl.asm.AsmClassInfo.createClassInfoFromStream(AsmClassInfo.java:790)
at org.codehaus.aspectwerkz.reflect.impl.asm.AsmClassInfo.getClassInfo(AsmClassInfo.java:273)
at org.codehaus.aspectwerkz.reflect.impl.asm.AsmClassInfo.getInterfaces(AsmClassInfo.java:619)
at org.codehaus.aspectwerkz.reflect.ClassInfoHelper.implementsInterface(ClassInfoHelper.java:56)
at org.codehaus.aspectwerkz.transform.inlining.compiler.AbstractJoinPointCompiler.collectCustomProceedMethods(AbstractJoinPointCompiler.java:237)
at org.codehaus.aspectwerkz.transform.inlining.compiler.AbstractJoinPointCompiler.collectCustomProceedMethods(AbstractJoinPointCompiler.java:208)
at org.codehaus.aspectwerkz.transform.inlining.compiler.AbstractJoinPointCompiler.initialize(AbstractJoinPointCompiler.java:149)
at org.codehaus.aspectwerkz.transform.inlining.compiler.AbstractJoinPointCompiler.(AbstractJoinPointCompiler.java:133)
at org.codehaus.aspectwerkz.transform.inlining.compiler.MethodExecutionJoinPointCompiler.(MethodExecutionJoinPointCompiler.java:33)
at org.codehaus.aspectwerkz.transform.inlining.compiler.JoinPointFactory.compileJoinPoint(JoinPointFactory.java:86)
at org.codehaus.aspectwerkz.joinpoint.management.JoinPointManager$CompiledJoinPoint.(JoinPointManager.java:262)
at org.codehaus.aspectwerkz.joinpoint.management.JoinPointManager.compileJoinPoint(JoinPointManager.java:251)
at org.codehaus.aspectwerkz.joinpoint.management.JoinPointManager.loadJoinPoint(JoinPointManager.java:118)
at org.ofbiz.entityext.eca.DelegatorEcaHandler.aw$initJoinPoints(DelegatorEcaHandler.java)
at org.ofbiz.entityext.eca.DelegatorEcaHandler.(DelegatorEcaHandler.java)
... 13 more"
I found two files are problem when I run the project in jdk1.8 that coding files are:
CatalinaContainer.java
/**
* CatalinaContainer - Tomcat 5
*
*/
public class CatalinaContainer implements Container {
public static final String CATALINA_HOSTS_HOME = System.getProperty("ofbiz.home") + "/framework/catalina/hosts";
public static final String J2EE_SERVER = "OFBiz Container 3.1";
public static final String J2EE_APP = "OFBiz";
public static final String module = CatalinaContainer.class.getName();
protected static Map<String, String> mimeTypes = new HashMap<String, String>();
// load the JSSE propertes (set the trust store)
static {
SSLUtil.loadJsseProperties();
}
protected Delegator delegator = null;
protected Embedded embedded = null;
protected Map<String, ContainerConfig.Container.Property> clusterConfig = new HashMap<String, ContainerConfig.Container.Property>();
protected Map<String, Engine> engines = new HashMap<String, Engine>();
protected Map<String, Host> hosts = new HashMap<String, Host>();
protected boolean contextReloadable = false;
protected boolean crossContext = false;
protected boolean distribute = false;
protected boolean enableDefaultMimeTypes = true;
protected String catalinaRuntimeHome;
/**
* #see org.ofbiz.base.container.Container#init(java.lang.String[], java.lang.String)
*/
public void init(String[] args, String configFile) throws ContainerException {
// get the container config
ContainerConfig.Container cc = ContainerConfig.getContainer("catalina-container", configFile);
if (cc == null) {
throw new ContainerException("No catalina-container configuration found in container config!");
}
// embedded properties
boolean useNaming = ContainerConfig.getPropertyValue(cc, "use-naming", false);
//int debug = ContainerConfig.getPropertyValue(cc, "debug", 0);
// grab some global context settings
this.delegator = DelegatorFactory.getDelegator(ContainerConfig.getPropertyValue(cc, "delegator-name", "default"));
this.contextReloadable = ContainerConfig.getPropertyValue(cc, "apps-context-reloadable", false);
this.crossContext = ContainerConfig.getPropertyValue(cc, "apps-cross-context", true);
this.distribute = ContainerConfig.getPropertyValue(cc, "apps-distributable", true);
this.catalinaRuntimeHome = ContainerConfig.getPropertyValue(cc, "catalina-runtime-home", "runtime/catalina");
// set catalina_home
System.setProperty("catalina.home", System.getProperty("ofbiz.home") + "/" + this.catalinaRuntimeHome);
// configure JNDI in the StandardServer
StandardServer server = (StandardServer) ServerFactory.getServer();
try {
server.setGlobalNamingContext(new InitialContext());
} catch (NamingException e) {
throw new ContainerException(e);
}
// create the instance of Embedded
embedded = new Embedded();
embedded.setUseNaming(useNaming);
// create the engines
List<ContainerConfig.Container.Property> engineProps = cc.getPropertiesWithValue("engine");
if (UtilValidate.isEmpty(engineProps)) {
throw new ContainerException("Cannot load CatalinaContainer; no engines defined!");
}
for (ContainerConfig.Container.Property engineProp: engineProps) {
createEngine(engineProp);
}
// load the web applications
loadComponents();
// create the connectors
List<ContainerConfig.Container.Property> connectorProps = cc.getPropertiesWithValue("connector");
if (UtilValidate.isEmpty(connectorProps)) {
throw new ContainerException("Cannot load CatalinaContainer; no connectors defined!");
}
for (ContainerConfig.Container.Property connectorProp: connectorProps) {
createConnector(connectorProp);
}
try {
embedded.initialize();
} catch (LifecycleException e) {
throw new ContainerException(e);
}
}
public boolean start() throws ContainerException {
// Start the embedded server
try {
embedded.start();
} catch (LifecycleException e) {
throw new ContainerException(e);
}
for (Connector con: embedded.findConnectors()) {
ProtocolHandler ph = con.getProtocolHandler();
if (ph instanceof Http11Protocol) {
Http11Protocol hph = (Http11Protocol) ph;
Debug.logInfo("Connector " + hph.getProtocols() + " # " + hph.getPort() + " - " +
(hph.getSecure() ? "secure" : "not-secure") + " [" + con.getProtocolHandlerClassName() + "] started.", module);
} else {
Debug.logInfo("Connector " + con.getProtocol() + " # " + con.getPort() + " - " +
(con.getSecure() ? "secure" : "not-secure") + " [" + con.getProtocolHandlerClassName() + "] started.", module);
}
}
Debug.logInfo("Started " + ServerInfo.getServerInfo(), module);
return true;
}
protected Engine createEngine(ContainerConfig.Container.Property engineConfig) throws ContainerException {
if (embedded == null) {
throw new ContainerException("Cannot create Engine without Embedded instance!");
}
ContainerConfig.Container.Property defaultHostProp = engineConfig.getProperty("default-host");
if (defaultHostProp == null) {
throw new ContainerException("default-host element of server property is required for catalina!");
}
String engineName = engineConfig.name;
String hostName = defaultHostProp.value;
StandardEngine engine = (StandardEngine) embedded.createEngine();
engine.setName(engineName);
engine.setDefaultHost(hostName);
// set the JVM Route property (JK/JK2)
String jvmRoute = ContainerConfig.getPropertyValue(engineConfig, "jvm-route", null);
if (jvmRoute != null) {
engine.setJvmRoute(jvmRoute);
}
// create the default realm -- TODO: make this configurable
String dbConfigPath = "catalina-users.xml";
MemoryRealm realm = new MemoryRealm();
realm.setPathname(dbConfigPath);
engine.setRealm(realm);
// cache the engine
engines.put(engine.getName(), engine);
// create a default virtual host; others will be created as needed
Host host = createHost(engine, hostName);
hosts.put(engineName + "._DEFAULT", host);
// configure clustering
List<ContainerConfig.Container.Property> clusterProps = engineConfig.getPropertiesWithValue("cluster");
if (clusterProps != null && clusterProps.size() > 1) {
throw new ContainerException("Only one cluster configuration allowed per engine");
}
if (UtilValidate.isNotEmpty(clusterProps)) {
ContainerConfig.Container.Property clusterProp = clusterProps.get(0);
createCluster(clusterProp, host);
clusterConfig.put(engineName, clusterProp);
}
// request dumper valve
boolean enableRequestDump = ContainerConfig.getPropertyValue(engineConfig, "enable-request-dump", false);
if (enableRequestDump) {
RequestDumperValve rdv = new RequestDumperValve();
engine.addValve(rdv);
}
// configure the CrossSubdomainSessionValve
boolean enableSessionValve = ContainerConfig.getPropertyValue(engineConfig, "enable-cross-subdomain-sessions", false);
if (enableSessionValve) {
CrossSubdomainSessionValve sessionValve = new CrossSubdomainSessionValve();
engine.addValve(sessionValve);
}
// configure the access log valve
String logDir = ContainerConfig.getPropertyValue(engineConfig, "access-log-dir", null);
AccessLogValve al = null;
if (logDir != null) {
al = new AccessLogValve();
if (!logDir.startsWith("/")) {
logDir = System.getProperty("ofbiz.home") + "/" + logDir;
}
File logFile = new File(logDir);
if (!logFile.isDirectory()) {
throw new ContainerException("Log directory [" + logDir + "] is not available; make sure the directory is created");
}
al.setDirectory(logFile.getAbsolutePath());
}
// configure the SslAcceleratorValve
String sslAcceleratorPortStr = ContainerConfig.getPropertyValue(engineConfig, "ssl-accelerator-port", null);
if (UtilValidate.isNotEmpty(sslAcceleratorPortStr)) {
Integer sslAcceleratorPort = Integer.valueOf(sslAcceleratorPortStr);
SslAcceleratorValve sslAcceleratorValve = new SslAcceleratorValve();
sslAcceleratorValve.setSslAcceleratorPort(sslAcceleratorPort);
engine.addValve(sslAcceleratorValve);
}
String alp2 = ContainerConfig.getPropertyValue(engineConfig, "access-log-pattern", null);
if (al != null && !UtilValidate.isEmpty(alp2)) {
al.setPattern(alp2);
}
String alp3 = ContainerConfig.getPropertyValue(engineConfig, "access-log-prefix", null);
if (al != null && !UtilValidate.isEmpty(alp3)) {
al.setPrefix(alp3);
}
boolean alp4 = ContainerConfig.getPropertyValue(engineConfig, "access-log-resolve", true);
if (al != null) {
al.setResolveHosts(alp4);
}
boolean alp5 = ContainerConfig.getPropertyValue(engineConfig, "access-log-rotate", false);
if (al != null) {
al.setRotatable(alp5);
}
if (al != null) {
engine.addValve(al);
}
embedded.addEngine(engine);
return engine;
}
protected Host createHost(Engine engine, String hostName) throws ContainerException {
if (embedded == null) {
throw new ContainerException("Cannot create Host without Embedded instance!");
}
Host host = embedded.createHost(hostName, CATALINA_HOSTS_HOME);
host.setDeployOnStartup(true);
host.setAutoDeploy(true);
host.setRealm(engine.getRealm());
engine.addChild(host);
hosts.put(engine.getName() + hostName, host);
return host;
}
protected Cluster createCluster(ContainerConfig.Container.Property clusterProps, Host host) throws ContainerException {
String defaultValveFilter = ".*.gif;.*.js;.*.jpg;.*.htm;.*.html;.*.txt;";
ReplicationValve clusterValve = new ReplicationValve();
clusterValve.setFilter(ContainerConfig.getPropertyValue(clusterProps, "rep-valve-filter", defaultValveFilter));
String mcb = ContainerConfig.getPropertyValue(clusterProps, "mcast-bind-addr", null);
String mca = ContainerConfig.getPropertyValue(clusterProps, "mcast-addr", null);
int mcp = ContainerConfig.getPropertyValue(clusterProps, "mcast-port", -1);
int mcf = ContainerConfig.getPropertyValue(clusterProps, "mcast-freq", 500);
int mcd = ContainerConfig.getPropertyValue(clusterProps, "mcast-drop-time", 3000);
if (mca == null || mcp == -1) {
throw new ContainerException("Cluster configuration requires mcast-addr and mcast-port properties");
}
McastService mcast = new McastService();
if (mcb != null) {
mcast.setMcastBindAddress(mcb);
}
mcast.setAddress(mca);
mcast.setPort(mcp);
mcast.setMcastDropTime(mcd);
mcast.setFrequency(mcf);
String tla = ContainerConfig.getPropertyValue(clusterProps, "tcp-listen-host", "auto");
int tlp = ContainerConfig.getPropertyValue(clusterProps, "tcp-listen-port", 4001);
int tlt = ContainerConfig.getPropertyValue(clusterProps, "tcp-sector-timeout", 100);
int tlc = ContainerConfig.getPropertyValue(clusterProps, "tcp-thread-count", 6);
//String tls = getPropertyValue(clusterProps, "", "");
if (tlp == -1) {
throw new ContainerException("Cluster configuration requires tcp-listen-port property");
}
NioReceiver listener = new NioReceiver();
listener.setAddress(tla);
listener.setPort(tlp);
listener.setSelectorTimeout(tlt);
listener.setMaxThreads(tlc);
listener.setMinThreads(tlc);
//listener.setIsSenderSynchronized(false);
ReplicationTransmitter trans = new ReplicationTransmitter();
try {
MultiPointSender mps = (MultiPointSender)Class.forName(ContainerConfig.getPropertyValue(clusterProps, "replication-mode", "org.apache.catalina.tribes.transport.bio.PooledMultiSender")).newInstance();
trans.setTransport(mps);
} catch (Exception exc) {
throw new ContainerException("Cluster configuration requires a valid replication-mode property: " + exc.getMessage());
}
String mgrClassName = ContainerConfig.getPropertyValue(clusterProps, "manager-class", "org.apache.catalina.ha.session.DeltaManager");
//int debug = ContainerConfig.getPropertyValue(clusterProps, "debug", 0);
// removed since 5.5.9? boolean expireSession = ContainerConfig.getPropertyValue(clusterProps, "expire-session", false);
// removed since 5.5.9? boolean useDirty = ContainerConfig.getPropertyValue(clusterProps, "use-dirty", true);
SimpleTcpCluster cluster = new SimpleTcpCluster();
cluster.setClusterName(clusterProps.name);
Manager manager = null;
try {
manager = (Manager)Class.forName(mgrClassName).newInstance();
} catch (Exception exc) {
throw new ContainerException("Cluster configuration requires a valid manager-class property: " + exc.getMessage());
}
//cluster.setManagerClassName(mgrClassName);
//host.setManager(manager);
//cluster.registerManager(manager);
cluster.setManagerTemplate((org.apache.catalina.ha.ClusterManager)manager);
//cluster.setDebug(debug);
// removed since 5.5.9? cluster.setExpireSessionsOnShutdown(expireSession);
// removed since 5.5.9? cluster.setUseDirtyFlag(useDirty);
GroupChannel channel = new GroupChannel();
channel.setChannelReceiver(listener);
channel.setChannelSender(trans);
channel.setMembershipService(mcast);
cluster.setChannel(channel);
cluster.addValve(clusterValve);
// removed since 5.5.9? cluster.setPrintToScreen(true);
// set the cluster to the host
host.setCluster(cluster);
Debug.logInfo("Catalina Cluster [" + cluster.getClusterName() + "] configured for host - " + host.getName(), module);
return cluster;
}
protected Connector createConnector(ContainerConfig.Container.Property connectorProp) throws ContainerException {
if (embedded == null) {
throw new ContainerException("Cannot create Connector without Embedded instance!");
}
// need some standard properties
String protocol = ContainerConfig.getPropertyValue(connectorProp, "protocol", "HTTP/1.1");
String address = ContainerConfig.getPropertyValue(connectorProp, "address", "0.0.0.0");
int port = ContainerConfig.getPropertyValue(connectorProp, "port", 0);
boolean secure = ContainerConfig.getPropertyValue(connectorProp, "secure", false);
if (protocol.toLowerCase().startsWith("ajp")) {
protocol = "ajp";
} else if ("memory".equals(protocol.toLowerCase())) {
protocol = "memory";
} else if (secure) {
protocol = "https";
} else {
protocol = "http";
}
Connector connector = null;
if (UtilValidate.isNotEmpty(connectorProp.properties)) {
connector = embedded.createConnector(address, port, protocol);
try {
for (ContainerConfig.Container.Property prop: connectorProp.properties.values()) {
connector.setProperty(prop.name, prop.value);
//connector.setAttribute(prop.name, prop.value);
}
embedded.addConnector(connector);
} catch (Exception e) {
throw new ContainerException(e);
}
}
return connector;
}
protected Context createContext(ComponentConfig.WebappInfo appInfo) throws ContainerException {
// webapp settings
Map<String, String> initParameters = appInfo.getInitParameters();
List<String> virtualHosts = appInfo.getVirtualHosts();
Engine engine = engines.get(appInfo.server);
if (engine == null) {
Debug.logWarning("Server with name [" + appInfo.server + "] not found; not mounting [" + appInfo.name + "]", module);
return null;
}
// set the root location (make sure we set the paths correctly)
String location = appInfo.componentConfig.getRootLocation() + appInfo.location;
location = location.replace('\\', '/');
if (location.endsWith("/")) {
location = location.substring(0, location.length() - 1);
}
// get the mount point
String mount = appInfo.mountPoint;
if (mount.endsWith("/*")) {
mount = mount.substring(0, mount.length() - 2);
}
// configure persistent sessions
Property clusterProp = clusterConfig.get(engine.getName());
Manager sessionMgr = null;
if (clusterProp != null) {
String mgrClassName = ContainerConfig.getPropertyValue(clusterProp, "manager-class", "org.apache.catalina.ha.session.DeltaManager");
try {
sessionMgr = (Manager)Class.forName(mgrClassName).newInstance();
} catch (Exception exc) {
throw new ContainerException("Cluster configuration requires a valid manager-class property: " + exc.getMessage());
}
} else {
sessionMgr = new StandardManager();
}
// create the web application context
StandardContext context = (StandardContext) embedded.createContext(mount, location);
context.setJ2EEApplication(J2EE_APP);
context.setJ2EEServer(J2EE_SERVER);
context.setLoader(embedded.createLoader(ClassLoaderContainer.getClassLoader()));
context.setCookies(appInfo.isSessionCookieAccepted());
context.addParameter("cookies", appInfo.isSessionCookieAccepted() ? "true" : "false");
context.setDisplayName(appInfo.name);
context.setDocBase(location);
context.setAllowLinking(true);
context.setReloadable(contextReloadable);
context.setDistributable(distribute);
context.setCrossContext(crossContext);
context.setPrivileged(appInfo.privileged);
context.setManager(sessionMgr);
context.getServletContext().setAttribute("_serverId", appInfo.server);
context.getServletContext().setAttribute("componentName", appInfo.componentConfig.getComponentName());
// create the Default Servlet instance to mount
StandardWrapper defaultServlet = new StandardWrapper();
defaultServlet.setServletClass("org.apache.catalina.servlets.DefaultServlet");
defaultServlet.setServletName("default");
defaultServlet.setLoadOnStartup(1);
defaultServlet.addInitParameter("debug", "0");
defaultServlet.addInitParameter("listing", "true");
defaultServlet.addMapping("/");
context.addChild(defaultServlet);
context.addServletMapping("/", "default");
// create the Jasper Servlet instance to mount
StandardWrapper jspServlet = new StandardWrapper();
jspServlet.setServletClass("org.apache.jasper.servlet.JspServlet");
jspServlet.setServletName("jsp");
jspServlet.setLoadOnStartup(1);
jspServlet.addInitParameter("fork", "false");
jspServlet.addInitParameter("xpoweredBy", "true");
jspServlet.addMapping("*.jsp");
jspServlet.addMapping("*.jspx");
context.addChild(jspServlet);
context.addServletMapping("*.jsp", "jsp");
// default mime-type mappings
configureMimeTypes(context);
// set the init parameters
for (Map.Entry<String, String> entry: initParameters.entrySet()) {
context.addParameter(entry.getKey(), entry.getValue());
}
if (UtilValidate.isEmpty(virtualHosts)) {
Host host = hosts.get(engine.getName() + "._DEFAULT");
context.setRealm(host.getRealm());
host.addChild(context);
context.getMapper().setDefaultHostName(host.getName());
} else {
// assume that the first virtual-host will be the default; additional virtual-hosts will be aliases
Iterator<String> vhi = virtualHosts.iterator();
String hostName = vhi.next();
boolean newHost = false;
Host host = hosts.get(engine.getName() + "." + hostName);
if (host == null) {
host = createHost(engine, hostName);
newHost = true;
}
while (vhi.hasNext()) {
host.addAlias(vhi.next());
}
context.setRealm(host.getRealm());
host.addChild(context);
context.getMapper().setDefaultHostName(host.getName());
if (newHost) {
hosts.put(engine.getName() + "." + hostName, host);
}
}
return context;
}
protected void loadComponents() throws ContainerException {
if (embedded == null) {
throw new ContainerException("Cannot load web applications without Embedded instance!");
}
// load the applications
List<ComponentConfig.WebappInfo> webResourceInfos = ComponentConfig.getAllWebappResourceInfos();
List<String> loadedMounts = FastList.newInstance();
if (webResourceInfos != null) {
for (int i = webResourceInfos.size(); i > 0; i--) {
ComponentConfig.WebappInfo appInfo = webResourceInfos.get(i - 1);
String mount = appInfo.getContextRoot();
if (!loadedMounts.contains(mount)) {
createContext(appInfo);
loadedMounts.add(mount);
} else {
appInfo.appBarDisplay = false; // disable app bar display on overrided apps
Debug.logInfo("Duplicate webapp mount; not loading : " + appInfo.getName() + " / " + appInfo.getLocation(), module);
}
}
}
}
public void stop() throws ContainerException {
try {
embedded.stop();
} catch (LifecycleException e) {
// don't throw this; or it will kill the rest of the shutdown process
Debug.logVerbose(e, module); // happens usually when running tests, disabled unless in verbose
}
}
protected void configureMimeTypes(Context context) throws ContainerException {
Map<String, String> mimeTypes = CatalinaContainer.getMimeTypes();
if (UtilValidate.isNotEmpty(mimeTypes)) {
for (Map.Entry<String, String> entry: mimeTypes.entrySet()) {
context.addMimeMapping(entry.getKey(), entry.getValue());
}
}
}
protected static synchronized Map<String, String> getMimeTypes() throws ContainerException {
if (UtilValidate.isNotEmpty(mimeTypes)) {
return mimeTypes;
}
if (mimeTypes == null) mimeTypes = new HashMap<String, String>();
URL xmlUrl = UtilURL.fromResource("mime-type.xml");
// read the document
Document mimeTypeDoc;
try {
mimeTypeDoc = UtilXml.readXmlDocument(xmlUrl, true);
} catch (SAXException e) {
throw new ContainerException("Error reading the mime-type.xml config file: " + xmlUrl, e);
} catch (ParserConfigurationException e) {
throw new ContainerException("Error reading the mime-type.xml config file: " + xmlUrl, e);
} catch (IOException e) {
throw new ContainerException("Error reading the mime-type.xml config file: " + xmlUrl, e);
}
if (mimeTypeDoc == null) {
Debug.logError("Null document returned for mime-type.xml", module);
return null;
}
// root element
Element root = mimeTypeDoc.getDocumentElement();
// mapppings
for (Element curElement: UtilXml.childElementList(root, "mime-mapping")) {
String extension = UtilXml.childElementValue(curElement, "extension");
String type = UtilXml.childElementValue(curElement, "mime-type");
mimeTypes.put(extension, type);
}
return mimeTypes;
}
}
Class.class file
try {
return tmpConstructor.newInstance((Object[])null);
} catch (InvocationTargetException e) {
Unsafe.getUnsafe().throwException(e.getTargetException());
// Not reached
return null;
}
I'm confused state. Please help me to recover this issue.
Thanks in advance.
In the stacktrace there is a
Caused by: java.lang.ArrayIndexOutOfBoundsException: 5747 at
org.codehaus.aspectwerkz.org.objectweb.asm.ClassReader.readClass(Unknown Source)
ASM is a tool to read and manipulate Java class files.
There have been changes to the class file format between JDK 6 and 8 and you (most probably) have an outdated version of ASM which runs into problems when reading Java 8 class files.
To solve the issue try to upgrade to the latest version of ASM (or Ofbiz).
EDIT: As commented by integratingweb Opentaps only supports JDK 6.

How to handle different method calls to web service in the same class using AsyncTask?

I'm developing an Android app, which is supposed to connect to a web service and save data into the app's local database. I'm using AsyncTask to connect to said web service from my "Login" class, which then returns the result to the processFinish method in "Login." The problem is that I need to separate the data I bring in several methods in the web service, and as far as I have seen, the result is always handled by processFinish. This is a problem because I'll need to handle the data differently depending on the method I call.
Is there a way to tell processFinish which method in my web service I called, so it can handle the result differently? I thought about sending the method's name from the web service itself as part of the result, but it feels forced, and I was hoping to do this in a cleaner way.
Here's the code I'm using:
LoginActivity.java (shortened):
public class LoginActivity extends ActionBarActivity implements AsyncResponse {
public static DBProvider oDB;
public JSONObject jsonObj;
public JSONObject jsonUser;
WebService webService;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
oDB = new DBProvider(this);
}
/*Function that validates user and password (on button press).*/
public void validateLogin(View view){
ConnectivityManager cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
if (!isConnected){
Toast.makeText(this, "No connection!", Toast.LENGTH_LONG).show();
}else{
/* params contains the method's name and parameters I send to the web service. */
String[][][] params = {
{
{"MyWebServiceMethod"}
},
{
{"user", "myUserName", "string"},
{"pass", "myPass", "string"}
}
};
try{
webService = new WebService();
webService.delegate = this;
webService.execute(params);
}catch(Exception ex){
Toast.makeText(this, "Error!: " + ex.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
public void processFinish(String result){
try{
// Here I handle the data in "result"
}
}catch(JSONException ex){
Toast.makeText(this, "JSONException: " + ex.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
WebService.java:
public class WebService extends AsyncTask<String[][][], Void, String> {
/**
* Variable Declaration................
*
*/
public AsyncResponse delegate = null;
String namespace = "http://example.net/";
private String url = "http://example.net/WS/MyWebService.asmx";
public String result;
String SOAP_ACTION;
SoapObject request = null, objMessages = null;
SoapSerializationEnvelope envelope;
HttpTransportSE HttpTransport;
/**
* Set Envelope
*/
protected void SetEnvelope() {
try {
// Creating SOAP envelope
envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
//You can comment that line if your web service is not .NET one.
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransport = new HttpTransportSE(url);
HttpTransport.debug = true;
} catch (Exception e) {
System.out.println("Soap Exception---->>>" + e.toString());
}
}
#Override
protected String doInBackground(String[][][]... params) {
// TODO Auto-generated method stub
try {
String[][][] data = params[0];
final String methodName = data[0][0][0];
final String[][] arguments = data[1];
SOAP_ACTION = namespace + methodName;
//Adding values to request object
request = new SoapObject(namespace, methodName);
PropertyInfo property;
for(int i=0; i<arguments.length; i++){
property = new PropertyInfo();
property.setName(arguments[i][0]);
property.setValue(arguments[i][1]);
if(arguments[i][2].equals("int")){
property.setType(int.class);
}
if(arguments[i][2].equals("string")){
property.setType(String.class);
}
request.addProperty(property);
}
SetEnvelope();
try {
//SOAP calling webservice
HttpTransport.call(SOAP_ACTION, envelope);
//Got Webservice response
result = envelope.getResponse().toString();
} catch (Exception e) {
// TODO: handle exception
result = "Catch1: " + e.toString() + ": " + e.getMessage();
}
} catch (Exception e) {
// TODO: handle exception
result = "Catch2: " + e.toString();
}
return result;
}
#Override
protected void onPostExecute(String result) {
delegate.processFinish(result);
}
/************************************/
}
AsyncResponse.java:
public interface AsyncResponse {
void processFinish(String output);
}
You can use different AsyncResponse classes. Anonymous classes make this more convenient:
// in one place
webService.delegate = new AsyncResponse() {
#Override
void processFinish(String response) {
// do something
}
};
// in another place
webService.delegate = new AsyncResponse() {
#Override
void processFinish(String response) {
// do something else
}
};

How to pass username and password at the time of handshaking to authenticate use in websocket?

i am devloping a group chat appication and i want to send username and password at the time of handshaking.
Here is my client side javascript code:
<script type="text/javascript">
var Chat = {};
Chat.socket = null;
Chat.connect = (function(host) {
if ('WebSocket' in window) {
Chat.socket = new WebSocket(host);
} else if ('MozWebSocket' in window) {
Chat.socket = new MozWebSocket(host);
} else {
alert("'Error: WebSocket is not supported by this browser.'")
Console.log('Error: WebSocket is not supported by this browser.');
return;
}
Chat.socket.onopen = function() {
Console.log('Info: WebSocket connection opened.');
document.getElementById('chat').onkeydown = function(event) {
if (event.keyCode == 13) {
Chat.sendMessage();
}
};
};
Chat.socket.onclose = function() {
document.getElementById('chat').onkeydown = null;
Console.log('Info: WebSocket closed.');
};
Chat.socket.onmessage = function(message) {
Console.log(message.data);
};
});
Chat.initialize = function() {
if (window.location.protocol == 'http:') {
Chat.connect('ws://' + window.location.host
+ '/WebSocketDemo/ChatWebSocketServlet');
} else {
Chat.connect('wss://' + window.location.host
+ '/WebSocketDemo/ChatWebSocketServlet');
}
};
Chat.sendMessage = (function() {
var message = document.getElementById('chat').value;
if (message != '') {
Chat.socket.send(message);
document.getElementById('chat').value = '';
}
});
var Console = {};
Console.log = (function(message) {
var console = document.getElementById('console');
var p = document.createElement('p');
p.style.wordWrap = 'break-word';
p.innerHTML = message;
console.appendChild(p);
while (console.childNodes.length > 25) {
console.removeChild(console.firstChild);
}
console.scrollTop = console.scrollHeight;
});
Chat.initialize();
</script>
and i have used tomcat 7 as a server.
Here is my server side code:
#Deprecated
public class ChatWebSocketServlet extends WebSocketServlet {
private static final long serialVersionUID = 1L;
private static final String GUEST_PREFIX = "Guest";
private final AtomicInteger connectionIds = new AtomicInteger(0);
private final Set<ChatMessageInbound> connections = new CopyOnWriteArraySet<ChatMessageInbound>();
#Override
protected StreamInbound createWebSocketInbound(String subProtocol,
HttpServletRequest request) {
return new ChatMessageInbound(connectionIds.incrementAndGet());
}
private final class ChatMessageInbound extends MessageInbound {
private final String nickname;
private ChatMessageInbound(int id) {
System.out.println("stage 1");
this.nickname = GUEST_PREFIX + id;
}
#Override
protected void onOpen(WsOutbound outbound) {
connections.add(this);
System.out.println("user:" + this);
String message = String.format("* %s %s", nickname, "has joined.");
broadcast(message);
}
#Override
protected void onClose(int status) {
connections.remove(this);
String message = String.format("* %s %s", nickname,
"has disconnected.");
broadcast(message);
}
#Override
protected void onBinaryMessage(ByteBuffer message) throws IOException {
throw new UnsupportedOperationException(
"Binary message not supported.");
}
#Override
protected void onTextMessage(CharBuffer message) throws IOException {
// Never trust the client
String filteredMessage = String.format("%s: %s", nickname,
HTMLFilter.filter(message.toString()));
broadcast(filteredMessage);
}
private void broadcast(String message) {
for (ChatMessageInbound connection : connections) {
try {
CharBuffer buffer = CharBuffer.wrap(message);
connection.getWsOutbound().writeTextMessage(buffer);
} catch (IOException ignore) {
// Ignore
}
}
}
}
}
Here i want to send User's credential before actual handshaking to authenticate user.
so how i can to in this?

Categories