Spring Aspects not executing but aspect was scanned while starting web sphere server - spring-aop

why my Aspect not executing eventhough aspect class was scanned while loading by spring container.
My Aspect class as below:
package com.qmp.aspect;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.qmp.data.addressstd.request.AddressStdRequest;
import com.qmp.data.autorate.request.AutoRateRequest;
import com.qmp.data.brightline.request.BrightLineRequest;
import com.qmp.data.email.request.SendEmailRequest;
import com.qmp.data.retrievequote.request.RetrieveQuoteRequest;
import com.qmp.data.savequote.request.SaveQuoteRequest;
import com.qmp.data.vin.request.VINRequest;
#Component
#Aspect
#EnableAspectJAutoProxy
public class QMPLoggingAspect {
private static final Log log = LogFactory.getLog(QMPLoggingAspect.class
.getName());
private static long vinrequestCount = 0;
private static long addresStdrequestCount = 0;
private static long saveQuoterequestCount = 0;
private static long retQuoterequestCount = 0;
private static long autoRaterequestCount = 0;
private static long brightLinerequestCount = 0;
private static long emailServicerequestCount = 0;
#Around("execution(* com.qmp.service.QMPService.sendEmail(..)) && args(emailRequest)")
public void logAroundEmailService(ProceedingJoinPoint joinPoint,
SendEmailRequest emailRequest) {
System.out.println("venkat======================>");
ServletRequestAttributes t = (ServletRequestAttributes) RequestContextHolder
.currentRequestAttributes();
HttpServletRequest req = t.getRequest();
HttpSession session = req.getSession();
long lStartTime = new Date().getTime();
log.debug("Email Service Execution Starts:: SessionId:: - " + session != null ? session
.getId() : ""
+ " - "
+ "TimeStamp:::"
+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")
.format(new Date()));
try {
joinPoint.proceed();
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long lEndTime = new Date().getTime();
log.debug("Email Service Execution Ends:: SessionId:: - " + session != null ? session
.getId() : ""
+ " - "
+ "TimeStamp:::"
+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")
.format(new Date()));
log.debug("Email Service Elapsed milliseconds==>"
+ (lEndTime - lStartTime) + " :: SessionId:: - " + session != null ? session
.getId() : "" + " Request Number==>" + emailServicerequestCount);
emailServicerequestCount++;
}
#Around("execution(* com.qmp.service.QMPService.doVinLookUp(..)) && args(vinRequest)")
public void logAroundVinLookup(ProceedingJoinPoint joinPoint,
VINRequest vinRequest) {
ServletRequestAttributes t = (ServletRequestAttributes) RequestContextHolder
.currentRequestAttributes();
HttpServletRequest req = t.getRequest();
HttpSession session = req.getSession();
long lStartTime = new Date().getTime();
log.debug("VIN Look up Execution Starts:: SessionId:: - " + session != null ? session
.getId() : ""
+ " - "
+ "TimeStamp:::"
+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")
.format(new Date()));
try {
joinPoint.proceed();
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long lEndTime = new Date().getTime();
log.debug("VIN Look up Execution Ends:: SessionId:: - " + session != null ? session
.getId() : ""
+ " - "
+ "TimeStamp:::"
+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")
.format(new Date()));
log.debug("VIN Look up Elapsed milliseconds==>"
+ (lEndTime - lStartTime) + " :: SessionId:: - " + session != null ? session
.getId() : "" + " Request Number==>" + vinrequestCount);
vinrequestCount++;
}
#Around("execution(* com.qmp.service.QMPService.doBrightLine(..)) && args(brightLineRequest)")
public void logAroundBrightline(ProceedingJoinPoint joinPoint,
BrightLineRequest brightLineRequest) {
ServletRequestAttributes t = (ServletRequestAttributes) RequestContextHolder
.currentRequestAttributes();
HttpServletRequest req = t.getRequest();
HttpSession session = req.getSession();
long lStartTime = new Date().getTime();
log.debug("Brightline Execution Starts:: SessionId:: - " + session != null ? session
.getId() : ""
+ " - "
+ "TimeStamp:::"
+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")
.format(new Date()));
try {
joinPoint.proceed();
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long lEndTime = new Date().getTime();
log.debug("Brightline Execution Ends:: SessionId:: - " + session != null ? session
.getId() : ""
+ " - "
+ "TimeStamp:::"
+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")
.format(new Date()));
log.debug("Brightline Elapsed milliseconds==>"
+ (lEndTime - lStartTime) + " :: SessionId:: - " + session != null ? session
.getId() : "" + " Request Number==>" + brightLinerequestCount);
brightLinerequestCount++;
}
#Around("execution(* com.qmp.service.QMPService.performAutoRate(..)) && args(autoRateRequest)")
public void logAroundAutoRate(ProceedingJoinPoint joinPoint,
AutoRateRequest autoRateRequest) {
ServletRequestAttributes t = (ServletRequestAttributes) RequestContextHolder
.currentRequestAttributes();
HttpServletRequest req = t.getRequest();
HttpSession session = req.getSession();
long lStartTime = new Date().getTime();
log.debug("Auto rate Execution Starts:: SessionId:: - " + session != null ? session
.getId() : ""
+ " - "
+ "TimeStamp:::"
+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")
.format(new Date()));
try {
joinPoint.proceed();
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long lEndTime = new Date().getTime();
log.debug("Auto rate Execution Ends:: SessionId:: - " + session != null ? session
.getId() : ""
+ " - "
+ "TimeStamp:::"
+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")
.format(new Date()));
log.debug("Auto rate Elapsed milliseconds==>" + (lEndTime - lStartTime)
+ " :: SessionId:: - " + session != null ? session.getId()
: "" + " Request Number==>" + autoRaterequestCount);
autoRaterequestCount++;
}
#Around("execution(* com.qmp.service.QMPService.performAddressStandardization(..)) && args(addressStdRequest)")
public void logAroundAddressStd(ProceedingJoinPoint joinPoint,
AddressStdRequest addressStdRequest) {
ServletRequestAttributes t = (ServletRequestAttributes) RequestContextHolder
.currentRequestAttributes();
HttpServletRequest req = t.getRequest();
HttpSession session = req.getSession();
long lStartTime = new Date().getTime();
log.debug("Address Std Execution Starts:: SessionId:: - " + session != null ? session
.getId() : ""
+ " - "
+ "TimeStamp:::"
+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")
.format(new Date()));
try {
joinPoint.proceed();
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long lEndTime = new Date().getTime();
log.debug("Address Std Execution Ends:: SessionId:: - " + session != null ? session
.getId() : ""
+ " - "
+ "TimeStamp:::"
+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")
.format(new Date()));
log.debug("Address Std Elapsed milliseconds==>"
+ (lEndTime - lStartTime) + " :: SessionId:: - " + session != null ? session
.getId() : "" + " Request Number==>" + addresStdrequestCount);
addresStdrequestCount++;
}
#Around("execution(* com.qmp.service.QMPService.retrieveQuote(..)) && args(retrieveQuoteRequest)")
public void logAroundRetrieveQuote(ProceedingJoinPoint joinPoint,
RetrieveQuoteRequest retrieveQuoteRequest) {
ServletRequestAttributes t = (ServletRequestAttributes) RequestContextHolder
.currentRequestAttributes();
HttpServletRequest req = t.getRequest();
HttpSession session = req.getSession();
long lStartTime = new Date().getTime();
log.debug("Retrieve Quote Execution Starts:: SessionId:: - " + session != null ? session
.getId() : ""
+ " - "
+ "TimeStamp:::"
+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")
.format(new Date()));
try {
joinPoint.proceed();
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long lEndTime = new Date().getTime();
log.debug("Retrieve Quote Execution Ends:: SessionId:: - " + session != null ? session
.getId() : ""
+ " - "
+ "TimeStamp:::"
+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")
.format(new Date()));
log.debug("Retrieve Quote Elapsed milliseconds==>"
+ (lEndTime - lStartTime) + " :: SessionId:: - " + session != null ? session
.getId() : "" + " Request Number==>" + retQuoterequestCount);
retQuoterequestCount++;
}
#Around("execution(* com.qmp.service.QMPService.saveQuote(..)) && args(saveQuoteRequest)")
public void logAroundSaveQuote(ProceedingJoinPoint joinPoint,
SaveQuoteRequest saveQuoteRequest) {
ServletRequestAttributes t = (ServletRequestAttributes) RequestContextHolder
.currentRequestAttributes();
HttpServletRequest req = t.getRequest();
HttpSession session = req.getSession();
long lStartTime = new Date().getTime();
log.debug("Save Quote Execution Starts:: SessionId:: - " + session != null ? session
.getId() : ""
+ " - "
+ "TimeStamp:::"
+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")
.format(new Date()));
try {
joinPoint.proceed();
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long lEndTime = new Date().getTime();
log.debug("Save Quote Execution Ends:: SessionId:: - " + session != null ? session
.getId() : ""
+ " - "
+ "TimeStamp:::"
+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")
.format(new Date()));
log.debug("Save Quote Elapsed milliseconds==>"
+ (lEndTime - lStartTime) + " :: SessionId:: - " + session != null ? session
.getId() : "" + " Request Number==>" + saveQuoterequestCount);
saveQuoterequestCount++;
}
}
applicationContext.xml :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<context:component-scan base-package="com.qmp.service" />
<context:component-scan base-package="com.qmp.service.email" />
<context:component-scan base-package="com.qmp.util" />
<context:component-scan base-package="com.qmp.service.brightline" />
<context:component-scan base-package="com.qmp.dao" />
<context:component-scan base-package="com.qmp.aspect" />
<aop:aspectj-autoproxy />
</beans>
Interface : QMPService.java
package com.qmp.service;
import com.farmers.ffq.exceptions.BaseFFQ3Exception;
import com.farmers.pla.service.PlaServiceException;
import com.qmp.data.addressstd.request.AddressStdRequest;
import com.qmp.data.addressstd.response.AddressStdResponse;
import com.qmp.data.autorate.request.AutoRateRequest;
import com.qmp.data.autorate.response.AutoRateResponse;
import com.qmp.data.brightline.request.BrightLineRequest;
import com.qmp.data.brightline.response.BrightLineResponse;
import com.qmp.data.email.request.SendEmailRequest;
import com.qmp.data.email.response.SendEmailResp;
import com.qmp.data.retrievequote.request.RetrieveQuoteRequest;
import com.qmp.data.retrievequote.response.RetrieveQuoteResponse;
import com.qmp.data.savequote.request.SaveQuoteRequest;
import com.qmp.data.savequote.response.SaveQuoteResponse;
import com.qmp.data.vin.request.VINRequest;
import com.qmp.data.vin.response.VINResponse;
public interface QMPService {
public VINResponse doVinLookUp(VINRequest vinRequest);
public BrightLineResponse doBrightLine(BrightLineRequest brightLineRequest);
public AutoRateResponse performAutoRate(AutoRateRequest autoRateRequest);
public AddressStdResponse performAddressStandardization(
AddressStdRequest addressStdRequest) throws BaseFFQ3Exception,
PlaServiceException;
public RetrieveQuoteResponse retrieveQuote(
RetrieveQuoteRequest retrieveQuoteRequest)
throws BaseFFQ3Exception, PlaServiceException;
public SaveQuoteResponse saveQuote(SaveQuoteRequest saveQuoteRequest)
throws BaseFFQ3Exception, PlaServiceException;
public SendEmailResp sendEmail(SendEmailRequest emailRequest);
}
Implimentation class :
QMPServiceMgr.java
//I have implimented all methods in this class.
Controller class :
package com.qmp.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.farmers.ffq.exceptions.BaseFFQ3Exception;
import com.farmers.pla.service.PlaServiceException;
import com.qmp.data.addressstd.request.AddressStdRequest;
import com.qmp.data.addressstd.response.AddressStdResponse;
import com.qmp.data.autorate.request.AutoRateRequest;
import com.qmp.data.autorate.response.AutoRateResponse;
import com.qmp.data.brightline.request.BrightLineRequest;
import com.qmp.data.brightline.response.BrightLineResponse;
import com.qmp.data.email.request.SendEmailRequest;
import com.qmp.data.email.response.SendEmailResp;
import com.qmp.data.retrievequote.request.RetrieveQuoteRequest;
import com.qmp.data.retrievequote.response.RetrieveQuoteResponse;
import com.qmp.data.savequote.request.SaveQuoteRequest;
import com.qmp.data.savequote.response.SaveQuoteResponse;
import com.qmp.data.vin.request.VINRequest;
import com.qmp.data.vin.response.VINResponse;
import com.qmp.service.QMPService;
#RestController
public class QMPController {
#Autowired
private QMPService qmpService;
#RequestMapping(value = "/vin", method = RequestMethod.POST)
public VINResponse doVinLookUp(#RequestBody VINRequest vinRequest) {
return qmpService.doVinLookUp(vinRequest);
}
#RequestMapping(value = "/brightline", method = RequestMethod.POST)
public BrightLineResponse performBrightLine(
#RequestBody BrightLineRequest brightLineRequest) {
return qmpService.doBrightLine(brightLineRequest);
}
#RequestMapping(value = "/autoRate", method = RequestMethod.POST)
public AutoRateResponse performAutoRate(
#RequestBody AutoRateRequest autoRateRequest) {
return qmpService.performAutoRate(autoRateRequest);
}
#RequestMapping(value = "/address", method = RequestMethod.POST)
public AddressStdResponse performAddrStandardization(
#RequestBody AddressStdRequest addressStdRequest)
throws PlaServiceException, BaseFFQ3Exception {
AddressStdResponse addressStdResponse = null;
return addressStdResponse = qmpService
.performAddressStandardization(addressStdRequest);
}
#RequestMapping(value = "/retQuote", method = RequestMethod.POST)
public RetrieveQuoteResponse retrieveQuote(
#RequestBody RetrieveQuoteRequest retrieveQuoteRequest)
throws PlaServiceException, BaseFFQ3Exception {
return qmpService.retrieveQuote(retrieveQuoteRequest);
}
#RequestMapping(value = "/saveQuote", method = RequestMethod.POST)
public SaveQuoteResponse saveQuote(
#RequestBody SaveQuoteRequest saveQuoteRequest)
throws PlaServiceException, BaseFFQ3Exception {
return qmpService.saveQuote(saveQuoteRequest);
}
#RequestMapping(value = "/comnms/v1/emailNotifications", method = RequestMethod.POST)
public SendEmailResp sendEmail(
#RequestBody SendEmailRequest sendEmailRequest) {
return qmpService.sendEmail(sendEmailRequest);
}
}
While loading it is verifying all syntax's and going good but not sure why logging Aspect not injecting while executing Rest Service.
Any assistance appreciated.
Note : i tried sample program using same configuration in Tomcat working good. But not sure why it is not executing in my Project which is running on Websphere.
Thanks,
Venkat.

Related

HttpClient post body param is not sent correctly when using 'application/x-www-form-urlencoded' content type request header

I am posting request using httpClient like:
I have imported HttpClientModule in app.module.js for http get and post request.
const httpOptionsWithCookie = {
headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded'}),
withCredentials: true
};
this.baseUrl ("link of API")
postArguments is an object like " {name:"xyz",company:"abc"}"
this.http.post(this.baseUrl, postArguments, httpOptionsWithCookie);
I am using angular5 in front end and spring mvc at back end
I am new in angular5.
API side code :
**spring mvc imports
#RestController
#RequestMapping(value = "/api/leavePeriod")
public class LeavePeriodControllerApi {
private static LogHelper logHelper = LogHelper
.getInstance(LeaveApplicationControllerApi.class);
#Autowired
HttpSession session;
#Autowired
Environment env;
#Autowired
ILeavePeriodService service;
#Autowired
ISecurityCommonService securityCommonService;
#Autowired
ILeaveCategoryService leaveCategoryService;
#Autowired
ICompanyService companyService;
#Autowired
LeavePeriodValidator leavePeriodValidator;
private User user = new User();
private String LOGINUSER = "";
#RequestMapping(value = "/viewLeavePeriod", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public Map<String, Object> viewLeavePeriod( #ModelAttribute LeavePeriodForm form,HttpServletRequest request,#RequestParam(value ="companyId" ,required = false)
String companyId, #RequestParam(value ="leaveCategoryId", required = false)
String leaveCategoryId )throws HRAlignBaseException {
user = (User) session.getAttribute("user");
LOGINUSER = "LoginUser " + user.getEmpName() + " loginuser empCode "
+ user.getEmpCode();
Map<String, Object> returnMap = new HashMap<String, Object>();
try{
if(companyId!= null && companyId!="")
{
form.setCompanyId(Integer.parseInt(companyId));
}
if(leaveCategoryId!= null && leaveCategoryId!="")
{
form.setLeaveCategoryId(Integer.parseInt(leaveCategoryId));
}
returnMap = service.view(form);
returnMap.put("periodList", form.getLeavePeriodVoList());
returnMap.put("comId", form.getCompanyId());
returnMap.put("leaveCatId", form.getLeaveCategoryId());
} catch (Exception e) {
e.printStackTrace();
}
logHelper
.info("################"
+ LOGINUSER
+ "############# END Enter LeavePeriodController viewLeavePeriod");
return returnMap;
}
}
the same http post request work in angularjs but it's not working in angular5.
Also when doing the same http post from ARC, it's working fine but not working for angular5
for 'Content-Type': 'application/x-www-form-urlencoded' form data should be sent like "menuId=5&buttonRights=adfasdfad&abc=aasdfasdfd" and not in json format so this feature available in angularjs(ngResource)but not in angular 5(HttpClient).
this is a standard way to post data.
Below code is for simple object.
import { URLSearchParams } from "#angular/http"
testRequest() {
let data = new URLSearchParams();
data.append('username', username);
data.append('password', password);
this.http
.post('/api', data)
.subscribe(data => {
alert('ok');
}, error => {
console.log(error.json());
});
}
if you want to post object or nested object ,you have to manually convert the object to query string using below code.
jsonTransformRequest (data) {
var param = function (obj) {
var query = '';
var name, value, fullSubName, subValue, innerObj, i;
for (name in obj) {
value = obj[name];
if (value instanceof Array) {
for (i = 0; i < value.length; ++i) {
subValue = value[i];
fullSubName = name + '[' + i + ']';
innerObj = {};
innerObj[fullSubName] = subValue;
query += param(innerObj) + '&';
}
} else if (value instanceof Object) {
for (let subName in value) {
subValue = value[subName];
fullSubName = name + '.' + subName;
innerObj = {};
innerObj[fullSubName] = subValue;
query += param(innerObj) + '&';
}
} else if (value !== undefined && value !== null) {
query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
}
}
return query.length ? query.substr(0, query.length - 1) : query;
};
var ret = (data != null && typeof data === 'object') ? param(data) :
data;
return ret;
};

Salesforce writing Test class of Future Method - Coverage 28%

I have a class where in I am trying to call a HTTP request. I have created a Mock Test and a Test class.
My Test class is successful with 28% code coverage but it fails in recognizing the call out methods I have used in my class Below is code
My Class -
public class PD_WelcomeMaroPost {
#future(callout=true)
public static void sendEmailThroughMaro(string myInpEmail) {
string successContacts = '';
string failureContacts = '';
List<Stripe_Subscripton__c> subsToUpdate = new List<Stripe_Subscripton__c>();
//List<Case> newCase = new List<Case>();
// SQL to fetch FBO who Joined Today
list<Account> conts = new list<Account> ([SELECT Id, name, Email_FLP_com__c,
(SELECT Id FROM Stripe_Subscriptons__r WHERE Start_Date__c= TODAY
AND Status__c='active'
AND Welcome_Email__C = false LIMIT 1)from account
where ID IN (select Distributor__c from Stripe_Subscripton__c
where Start_Date__c= TODAY AND Status__c='active'
AND Welcome_Email__C = false)
AND Email_FLP_com__c != NULL LIMIT 100]);
system.debug('>>>>>>>>>>' + conts);
overallEmail myEmail = new overallEmail();
for(Account c : conts){
string resultBodyGet = '';
myEmail.email.campaign_id = 172;
myEmail.email.contact.Email = c.Email_FLP_com__c;
myEmail.email.contact.first_name = c.name;
/**MAp<String, String> tags = new Map<String, String>();
tags.put('firstName', c.name);
myEmail.email.tags = tags;**/
system.debug('#### Input JSON: ' + JSON.serialize(myEmail));
try{
String endpoint = 'http://api.maropost.com/accounts/1173/emails/deliver.json?auth_token=j-V4sx8ueUT7eKM8us_Cz5JqXBzoRrNS3p1lEZyPUPGcwWNoVNZpKQ';
HttpRequest req = new HttpRequest();
req.setEndpoint(endpoint);
req.setMethod('POST');
req.setHeader('Content-type', 'application/json');
req.setbody(JSON.serialize(myEmail));
Http http = new Http();
system.debug('Sending email');
HTTPResponse response = http.send(req);
system.debug('sent email');
resultBodyGet = response.getBody();
system.debug('Output response:' + resultBodyGet);
maroResponse myMaroResponse = new maroResponse();
myMaroResponse = (maroResponse) JSON.deserialize(resultBodyGet, maroResponse.class);
system.debug('#### myMaroResponse: ' + myMaroResponse);
if(myMaroResponse.message == 'Email was sent successfully')
successContacts = successContacts + ';' + c.Email_FLP_com__c;
else
failureContacts = failureContacts + ';' + c.Email_FLP_com__c;
}
catch (exception e) {
failureContacts = failureContacts + ';' + c.Email_FLP_com__c;
system.debug('#### Exception caught: ' + e.getMessage());
}
c.Stripe_Subscriptons__r[0].Welcome_Email__c = true;
c.Stripe_Subscriptons__r[0].Welcome_Email_Sent_Date__c = system.today();
subsToUpdate.add(c.Stripe_Subscriptons__r[0]);
}
Update subsToUpdate;
}
public class maroResponse {
public string message {get;set;}
}
public class overallEmail {
public emailJson email = new emailJson();
}
public class emailJson {
public Integer campaign_id;
public contactJson contact = new contactJson();
//Public Map<String, String> tags;
}
public class contactJson {
public string email;
public string first_name;
}
}
My MockTest Class- I have used this Mockclass to generate Mock response. The documentation does not have a test method thus used the same format
#isTest
Global class PD_WelcomeMaroPostMock implements HttpCalloutMock {
Global HttpResponse respond(HttpRequest req) {
// Create a fake response
//
//System.assertEquals(JSON.serialize(myEmail),req.getbody());
HttpResponse res = new HttpResponse();
res.setHeader('Content-Type', 'application/json');
res.setBody('{"status":"success"}');
res.setStatusCode(200);
return res;
}
}
This is my Test class - This is the class I have used for the response. I have a successful insert job but my HTTP responses are failing.
#IsTest
private class PD_WelcomeMaroPost_test {
public class overallEmail {
public emailJson email = new emailJson();
}
public class emailJson {
public Integer campaign_id;
public contactJson contact = new contactJson();
}
public class contactJson {
public string email;
public string first_name;
}
#IsTest
private static void testemail() {
overallEmail myEmail = new overallEmail();
Account a = new Account();
a.Name ='Test' ;
a.Email_FLP_com__c = 'test#nextsphere.com';
insert a ;
Stripe_Subscripton__c s = new Stripe_Subscripton__c();
// insert subscription --
s.Distributor__c = a.Id;
S.Welcome_Email__c = TRUE;
S.Welcome_Email_Sent_Date__c = system.today();
s.Subscription_Id__c = 'sub_9H0LLYFZkekdMA' ;
INSERT S;
Test.setMock(HttpCalloutMock.class, new PD_WelcomeMaroPostMock());
String endpoint = 'http://api.maropost.com/accounts/1173/emails/deliver.json?auth_token=j-V4sx8ueUT7eKM8us_Cz5JqXBzoRrNS3p1lEZyPUPGcwWNoVNZpKQ';
HttpRequest req = new HttpRequest();
req.setEndpoint(endpoint);
req.setMethod('POST');
req.setHeader('Content-type', 'application/json');
req.setbody(JSON.serialize(myEmail));
Test.startTest();
PD_WelcomeMaroPost.sendEmailThroughMaro('test#nextsphere.com');
Test.stopTest();
}
}
When declaring a Mock myself, I declare it inside the test start transaction:
Test.startTest();
Test.setMock(WebServiceMock.class, new WebServiceMockImpl());
// Rest of test code here
Test.stopTest();
Also inside your test class you seem to only build the HTTP request and not send it try adding the below:
HttpResponse res = http.send(req);
if (res.getStatusCode() == 200) { } else { }

How to get path of isolated storage in silverlight?

I read a similar post here... I tried implementing it but getting an exception saying
Attempt by method 'get_path_isolated.Page.button1_Click(System.Object, System.Windows.RoutedEventArgs)' to access field 'System.IO.IsolatedStorage.IsolatedStorageFileStream.m_FullPath' failed.
I have this code
public void button1_Click(object sender, RoutedEventArgs e)
{
isoStore = IsolatedStorageFile.GetUserStoreForApplication();
isoStore.CreateDirectory("root_dir");
IsolatedStorageFileStream iostream = new IsolatedStorageFileStream("sampleFile.txt", FileMode.Create, isoStore);
StreamWriter writer = new StreamWriter(iostream);
writer.Write("jaimokar");
try
{
FieldInfo pi = iostream.GetType().GetField("m_FullPath", BindingFlags.Instance | BindingFlags.NonPublic);
string path = pi.GetValue(iostream).ToString();
}
catch (Exception ex)
{
textBox1.Text += ex.Message;
}
where I'm going wrong? Please help me..
For those that have Elevated Permissions (especially in browser) I have come up with a semi-functional solution to determine the path. Unfortunately, if you switch from dev to live you will see a different folder path, so you have to include it here, also you should add a check for which version you are running (dev or live) via a passed in page parameter or the host url or so
private string GetProfilePath() {
var fullname = string.Empty;
try
{
// ReSharper disable IdentifierTypo
// ReSharper disable CommentTypo
var profilePath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
profilePath = Path.GetDirectoryName(profilePath);
profilePath = Path.Combine(profilePath, #"LocalLow\Microsoft\Silverlight\is");
//profilePath = Path.Combine(profilePath, IsoPathStaging + "\\");
var directoryInfo = new DirectoryInfo(profilePath); // C:\Users\<username>\AppData\LocalLow\Microsoft\Silverlight\is --constant
var dirs = directoryInfo.EnumerateDirectories();
// ReSharper disable PossibleMultipleEnumeration
fullname = "1: " + dirs.First().FullName;
dirs = dirs.First().EnumerateDirectories(); // \ir5ffeej.4of --random
fullname = "2: " + dirs.First().FullName;
dirs = dirs.First().EnumerateDirectories(); // \lfab1wva.xmb --random
fullname = "3: " + dirs.First().FullName;
dirs = dirs.First().EnumerateDirectories(); // \1 --constant
fullname = "4: " + dirs.First().FullName;
dirs = dirs.Where(d => d.Name == "s"); // \s --constant
fullname = "5: " + dirs.First().FullName;
var dirs2 = dirs.First().EnumerateDirectories()
.Where(d => d.Name == "sbudlbc2oqx0eo0odi5nzpo2qppp3zmxxxxxxxxxxxxxxxxxxxxxxxxx").ToList(); // \<dev dir> --constant-ish
if (!dirs2.Any())
{
dirs2 = dirs.First().EnumerateDirectories()
.Where(d => d.Name == "2gbsxl5no1wzqebnzbj2wglhi33za1rxxxxxxxxxxxxxxxxxxxxxxxxx").ToList(); // \<live dir> --constant-ish
}
if (!dirs2.Any())
{
throw new Exception("Unable to locate silverlight storage");
}
fullname = "6: " + dirs2.First().FullName;
dirs = dirs2.First().EnumerateDirectories().Where(d => d.Name == "f"); // \f --constant
fullname = "7: " + dirs.First().FullName;
var dir = dirs.First(); // final
fullname = dir.FullName;
// ReSharper restore CommentTypo
// ReSharper restore PossibleMultipleEnumeration
return fullname;
// ReSharper restore IdentifierTypo
}
catch (NotSupportedException ex)
{
Debug.WriteLine(ex);
MessageBox.Show(
"Failed to run (Not Supported):"
+ Environment.NewLine + fullname
+ Environment.NewLine + ex.Message,
messageBoxTitle,
MessageBoxButton.OK);
CheckElevatedPermissions();
return string.Empty;
}
catch (Exception ex)
{
Debug.WriteLine(ex);
MessageBox.Show(
"Failed to run:"
+ Environment.NewLine + fullname
+ Environment.NewLine + ex.Message,
messageBoxTitle,
MessageBoxButton.OK);
return string.Empty;
}
}
Again, you must have elevated rights for this to work, later I would use this path to locate a file for some other use:
var fullPath = Path.Combine(GetProfilePath(), FileName);
Run(fullPath.Replace("\\\\", "\\"));
private static void Run(string fullPath)
{
try
{
CheckElevatedPermissions();
var shell = AutomationFactory.CreateObject("WScript.Shell");
shell.Run("\"" + fullPath + "\"");
}
catch (NotSupportedException ex)
{
Debug.WriteLine(ex);
MessageBox.Show(
"Failed to run (Not Supported):"
+ Environment.NewLine + fullPath
+ Environment.NewLine + ex.Message,
messageBoxTitle,
MessageBoxButton.OK);
CheckElevatedPermissions();
}
catch (Exception ex)
{
Debug.WriteLine(ex);
MessageBox.Show(
"Failed to run:"
+ Environment.NewLine + fullPath
+ Environment.NewLine + ex.Message,
messageBoxTitle,
MessageBoxButton.OK);
}
}

android database sqlite rawquery, no content

I have an Activity called Wartung. In this Activity are textfields which should be auto filled by database content. Writing to the DB table works but reading from it doesn't.
I didn't get any errors or warnings in LogCat.
In the method Wartung.getWartungsDaten(String serienNr) I call the method of the helper class DBController.getLetzterWartungsDaten(String serienNr). The last one does a rawquery to the DB.
To test which parts of the code are executed, ich make a toast("1") which is showed, also toast("2") , but toast("3") isn't. The problem must be in the line "Cursor wartungsCursor = this.dbHelper.getLetzteWartungsDaten(serienNr);" or in the helper class respectively in the method getLetzteWartungsDaten().
Here is my class Wartung:
public class Wartung extends Activity {
private DBController dbHelper;
private SQLiteDatabase db;
private EditText serienNr;
private EditText datum;
private EditText zeit;
private EditText benutzer;
private EditText beschreibung;
private EditText statusAktuell;
private Spinner statusNeu;
private Button buttonAendern;
private LinearLayout layoutStatusAktuell;
private LinearLayout layoutStatusNeu;
private String sSerienNr;
private String sArtikelId;
private String sDatum;
private String sZeit;
private String sBenutzer;
private String sStatus;
private String sBeschreibung;
private List<String> statusListe;
private List<String> listeWartungSerienNr;
private List<String> listeWartungDatum;
private List<String> listeWartungZeit;
private List<String> listeWartungBenutzer;
private List<String> listeWartungStatus;
private List<String> listeWartungBeschreibung;
private boolean editModus = false;
private boolean gespeichert = false;
private int statusPosition = -1;
/**
* Initialisierung aller Objekte
*
*/
private void initObjekte() {
this.serienNr = (EditText) this.findViewById(R.id.editText_wartung_content_serienNr);
this.datum = (EditText) this.findViewById(R.id.editText_wartung_content_datum);
this.zeit = (EditText) this.findViewById(R.id.editText_wartung_content_zeit);
this.benutzer = (EditText) this.findViewById(R.id.editText_wartung_content_benutzer);
this.statusAktuell = (EditText) this.findViewById(R.id.editText_wartung_content_aktueller_status);
this.statusNeu = (Spinner) this.findViewById(R.id.spinner_wartung_content_neuer_status);
this.layoutStatusAktuell = (LinearLayout) this.findViewById(R.id.linearLayoutStatusAktuell);
this.layoutStatusNeu = (LinearLayout) this.findViewById(R.id.linearLayoutStatusNeu);
this.listeWartungSerienNr = new ArrayList<String>();
this.listeWartungDatum = new ArrayList<String>();
this.listeWartungZeit = new ArrayList<String>();
this.listeWartungBenutzer = new ArrayList<String>();
this.listeWartungStatus = new ArrayList<String>();
this.listeWartungBeschreibung = new ArrayList<String>();
this.sArtikelId = new String();
this.sDatum = new String();
this.sZeit = new String();
this.sBenutzer = new String();
this.sStatus = new String();
this.sBeschreibung = new String();
this.statusListe = new ArrayList<String>();
setStatusInSpinner();
this.beschreibung = (EditText) this.findViewById(R.id.editTextMultiLine_wartung_content_aenderung);
}
public void toast(String text) {
Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
}
/**
*
* #param serienNr
*/
private void getWartungsDaten(String serienNr) {
this.dbHelper = new DBController(this);
this.db = this.dbHelper.getReadableDatabase();
toast("1");
// Cursor auswerten
try {
toast("2");
Cursor wartungsCursor = dbHelper.getLetzteWartungsDaten(serienNr);
toast("3");
// Daten zerlegen
if (wartungsCursor != null) {
if (wartungsCursor.moveToFirst()) {
do {
this.listeWartungDatum.add(wartungsCursor.getString(wartungsCursor.getColumnIndexOrThrow(DBController.KEY_DATUM)));
this.listeWartungZeit.add(wartungsCursor.getString(wartungsCursor.getColumnIndexOrThrow(DBController.KEY_ZEIT)));
} while (wartungsCursor.moveToNext());
}
}
// String result = "result: " + this.sSerienNr + " " + this.sDatum + " " + this.sZeit + " " + this.sBenutzer + " " + this.sStatus + " " + this.sBeschreibung;
String result = "result: " + this.listeWartungDatum.get(0).toString() + " " + this.listeWartungZeit.get(0).toString();
toast("Erhaltene Daten: " + result);
} catch (Exception e) {
;
} finally {
this.db.close();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_wartung);
this.setupActionBar();
initObjekte();
setObjekteReadable();
// Zu Testzwecken wird immer der erste Artikel aus der Datenbank ausgewählt
getWartungsDaten("SerienNr 0000");
}
}
And here is my Helper class DBController:
public Cursor getLetzteWartungsDaten(String serienNr) {
this.db = this.getReadableDatabase();
// Filter-String um die anhängenden Daten über die SerienNr zu bekommen
String serienNrFilter = "SELECT " +
DBController.TABLE_WARTUNG + "." + DBController.KEY_DATUM + ", " +
DBController.TABLE_WARTUNG + "." + DBController.KEY_ZEIT + ", " +
"FROM " + DBController.TABLE_WARTUNG
"ORDER BY " + DBController.KEY_DATUM + " DESC," + DBController.KEY_ZEIT + " DESC" + ")";
return db.rawQuery(serienNrFilter, /*new String[] { serienNr }*/null);
}
I have some other methods with reading methods but only this one doesn't work and I don't know why.
I hope you can help me.
Thanks!
You have an unnecessary comma:
DBController.KEY_ZEIT + ", " +
"FROM "
i.e. syntax error.

GAE/J, PayPal request - NoClassDefFoundError for AuthorizationRequiredException

I am new to Google App Engine (Java) and PayPal process. I am using tutorial provided http://googleappengine.blogspot.com/2010/06/paypal-introduces-paypal-x-platform.html and NOT sure why I am getting following exception:
Uncaught exception from servlet
java.lang.NoClassDefFoundError: com/paypal/adaptive/exceptions/AuthorizationRequiredException
Here is my Servlet Class file which suppose to do preapproval and provide preapproval key and authorization url ..
import java.io.IOException;
import java.util.logging.Logger;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.paypal.adaptive.api.requests.fnapi.ParallelPay;
import com.paypal.adaptive.api.responses.PayResponse;
import com.paypal.adaptive.core.APICredential;
import com.paypal.adaptive.core.AckCode;
import com.paypal.adaptive.core.CurrencyCodes;
import com.paypal.adaptive.core.PaymentType;
import com.paypal.adaptive.core.Receiver;
import com.paypal.adaptive.core.ServiceEnvironment;
import com.paypal.adaptive.exceptions.AuthorizationRequiredException;
import com.paypal.adaptive.exceptions.InvalidAPICredentialsException;
import com.paypal.adaptive.exceptions.InvalidResponseDataException;
import com.paypal.adaptive.exceptions.MissingAPICredentialsException;
import com.paypal.adaptive.exceptions.MissingParameterException;
import com.paypal.adaptive.exceptions.NotEnoughReceivers;
import com.paypal.adaptive.exceptions.PayPalErrorException;
import com.paypal.adaptive.exceptions.PaymentExecException;
import com.paypal.adaptive.exceptions.PaymentInCompleteException;
import com.paypal.adaptive.exceptions.ReceiversCountMismatchException;
import com.paypal.adaptive.exceptions.RequestAlreadyMadeException;
import com.paypal.adaptive.exceptions.RequestFailureException;
#SuppressWarnings("serial")
public class CWEMartServlet extends HttpServlet {
private static final Logger log = Logger.getLogger(CWEMartServlet.class.getName());
private static APICredential credentialObj;
#Override
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
super.init(config);
// Get the value of APIUsername
String APIUsername = getServletConfig().getInitParameter("PPAPIUsername");
String APIPassword = getServletConfig().getInitParameter("PPAPIPassword");
String APISignature = getServletConfig().getInitParameter("PPAPISignature");
String AppID = getServletConfig().getInitParameter("PPAppID");
String AccountEmail = getServletConfig().getInitParameter("PPAccountEmail");
if(APIUsername == null || APIUsername.length() <= 0
|| APIPassword == null || APIPassword.length() <=0
|| APISignature == null || APISignature.length() <= 0
|| AppID == null || AppID.length() <=0 ) {
// requires API Credentials not set - throw exception
throw new ServletException("APICredential(s) missing");
}
credentialObj = new APICredential();
credentialObj.setAPIUsername(APIUsername);
credentialObj.setAPIPassword(APIPassword);
credentialObj.setSignature(APISignature);
credentialObj.setAppId(AppID);
credentialObj.setAccountEmail(AccountEmail);
log.info("Servlet initialized successfully");
}
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
try {
String id = req.getParameter("id");
String title = req.getParameter("title");
String order = req.getParameter("order");
String returnParam = req.getParameter("return");
String cancel = req.getParameter("cancel");
if(cancel != null && cancel.equals("1")) {
// user canceled the payment
getServletConfig().getServletContext().getRequestDispatcher("/paymentcancel.jsp").forward(req, resp);
} else if(returnParam != null && returnParam.equals("1")){
getServletConfig().getServletContext().getRequestDispatcher("/paymentsuccess.jsp").forward(req, resp);
} else if(order != null && order.length() > 0){
// process order
try {
StringBuilder url = new StringBuilder();
url.append(req.getRequestURL());
String returnURL = url.toString() + "?return=1&payKey=${payKey}&id="+ id + "&title=" + title;
String cancelURL = url.toString() + "?cancel=1&id="+ id + "&title=" + title;
//String ipnURL = url.toString() + "?action=ipn";
ParallelPay parallelPay = new ParallelPay(2);
parallelPay.setCancelUrl(cancelURL);
parallelPay.setReturnUrl(returnURL);
parallelPay.setCredentialObj(credentialObj);
parallelPay.setUserIp(req.getRemoteAddr());
parallelPay.setApplicationName("Sample app on GAE");
parallelPay.setCurrencyCode(CurrencyCodes.USD);
parallelPay.setEnv(ServiceEnvironment.SANDBOX);
//parallelPay.setIpnURL(ipnURL);
parallelPay.setLanguage("en_US");
parallelPay.setMemo(title);
// set the receivers
Receiver primaryReceiver = new Receiver();
primaryReceiver.setAmount(5.0);
primaryReceiver.setEmail("jagdis_1325390370_biz#yahoo.com");
primaryReceiver.setPaymentType(PaymentType.GOODS);
parallelPay.addToReceivers(primaryReceiver);
// set the second receivers
Receiver rec1 = new Receiver();
rec1.setAmount(3.0);
rec1.setEmail("jagdis_1331173124_biz#yahoo.com");
rec1.setPaymentType(PaymentType.GOODS);
parallelPay.addToReceivers(rec1);
PayResponse payResponse = parallelPay.makeRequest();
log.info("Payment success - payKey:" + payResponse.getPayKey());
} catch (IOException e) {
resp.getWriter().println("Payment Failed w/ IOException");
} catch (MissingAPICredentialsException e) {
// No API Credential Object provided - log error
e.printStackTrace();
resp.getWriter().println("No APICredential object provided");
} catch (InvalidAPICredentialsException e) {
// invalid API Credentials provided - application error - log error
e.printStackTrace();
resp.getWriter().println("Invalid API Credentials " + e.getMissingCredentials());
} catch (MissingParameterException e) {
// missing parameter - log error
e.printStackTrace();
resp.getWriter().println("Missing Parameter error: " + e.getParameterName());
} catch(ReceiversCountMismatchException e){
// missing receiver - log error
e.printStackTrace();
resp.getWriter().println("Receiver count did not match - expected: "
+ e.getExpectedNumberOfReceivers()
+ " - actual:" + e.getActualNumberOfReceivers());
} catch (RequestFailureException e) {
// HTTP Error - some connection issues ?
e.printStackTrace();
resp.getWriter().println("Request HTTP Error: " + e.getHTTP_RESPONSE_CODE());
} catch (InvalidResponseDataException e) {
// PayPal service error
// log error
e.printStackTrace();
resp.getWriter().println("Invalid Response Data from PayPal: \"" + e.getResponseData() + "\"");
} catch (PayPalErrorException e) {
// Request failed due to a Service/Application error
e.printStackTrace();
if(e.getResponseEnvelope().getAck() == AckCode.Failure){
// log the error
resp.getWriter().println("Received Failure from PayPal (ack)");
resp.getWriter().println("ErrorData provided:");
resp.getWriter().println(e.getPayErrorList().toString());
if(e.getPaymentExecStatus() != null){
resp.getWriter().println("PaymentExecStatus: " + e.getPaymentExecStatus());
}
} else if(e.getResponseEnvelope().getAck() == AckCode.FailureWithWarning){
// there is a warning - log it!
resp.getWriter().println("Received Failure with Warning from PayPal (ack)");
resp.getWriter().println("ErrorData provided:");
resp.getWriter().println(e.getPayErrorList().toString());
}
} catch (RequestAlreadyMadeException e) {
// shouldn't occur - log the error
e.printStackTrace();
resp.getWriter().println("Request to send a request that has already been sent!");
} catch (PaymentExecException e) {
resp.getWriter().println("Failed Payment Request w/ PaymentExecStatus: " + e.getPaymentExecStatus().toString());
resp.getWriter().println("ErrorData provided:");
resp.getWriter().println(e.getPayErrorList().toString());
}catch (PaymentInCompleteException e){
resp.getWriter().println("Incomplete Payment w/ PaymentExecStatus: " + e.getPaymentExecStatus().toString());
resp.getWriter().println("ErrorData provided:");
resp.getWriter().println(e.getPayErrorList().toString());
} catch (NumberFormatException e) {
// invalid number passed
e.printStackTrace();
resp.getWriter().println("Invalid number of receivers sent");
} catch (NotEnoughReceivers e) {
// not enough receivers - min requirements for Parallel pay not met
e.printStackTrace();
resp.getWriter().println("Min number of receivers not met - Min Required:"
+ e.getMinimumRequired() + " - actual set:" + e.getActualNumber());
} catch (AuthorizationRequiredException e) {
// redirect the user to PayPal for Authorization
resp.getWriter().println("\"PPAuthzUrl\": \"" + e.getAuthorizationUrl(ServiceEnvironment.SANDBOX) + "\", \"Status\": \"CREATED\"");
// resp.sendRedirect(e.getAuthorizationUrl(ServiceEnvironment.SANDBOX));
// resp.getWriter().println("\"PPAuthzUrl\": \"" + e.getEmbeddedPaymentsAuthorizationUrl(ServiceEnvironment.SANDBOX, ExpType.LIGHTBOX) + "\", \"Status\": \"CREATED\"");
}
} else if(id == null || id.length() <= 0) {
getServletConfig().getServletContext().getRequestDispatcher("/index.jsp").forward(req, resp);
} else {
getServletConfig().getServletContext().getRequestDispatcher("/order.jsp").forward(req, resp);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Check if you have the paypal.jar in lib directory. If you are not sure, unjar the paypal related lib files and check if you have AuthorizationRequiredException.class in at least one of them.

Resources