Java-Spring Reflection brings method which are not present in the class - java

I try to investigate classes available in a given package. for time being i have hard coded the class name, I get so many methods which are not available in the class when i try to print all the methods and parameter type the method takes
the following is my main class where i investigate the class and its method :
package com.hexgen.reflection;
`// removed imports to post question`
import com.hexgen.tools.HexgenClassUtils;
public class HexgenWebAPITest {
#SuppressWarnings({ "rawtypes", "unchecked", "unused" })
public static void main(String[] args) {
HexgenWebAPITest test = new HexgenWebAPITest();
HexgenClassUtils hexgenClassUtils = new HexgenClassUtils();
String uri="";
String[] mappingValues=null;
HttpClientRequests httpRequest = new HttpClientRequests();
Class parames = CreateRequisitionRO[].class;
Class booleanVal;
booleanVal = Boolean.TYPE;
Class cls;
try {
List classNames = hexgenClassUtils.findMyTypes("com.hexgen.*");
Iterator<Class> it = classNames.iterator();
while(it.hasNext())
{
Class obj = it.next();
System.out.println("Methods available in : "+obj.getName());
System.out.println("===================================");
if(obj.getName().equals("com.hexgen.api.facade.HexgenWebAPI")){
cls = Class.forName(obj.getName());
cls.getClass();
Method[] method = cls.getDeclaredMethods();
int i=1;
for (Method method2 : method) {
System.out.println(+i+":"+method2.getName());
Class[] parameterTypes = method2.getParameterTypes();
for (Class class1 : parameterTypes) {
System.out.println("Parameter Type : "+class1.getName());
}
i++;
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
this is the Utility Class
package com.hexgen.tools;
// removed imports to post the question here
public class HexgenClassUtils {
#SuppressWarnings({ "rawtypes"})
public List<Class> findMyTypes(String basePackage) throws IOException, ClassNotFoundException
{
ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resourcePatternResolver);
List<Class> candidates = new ArrayList<Class>();
String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
resolveBasePackage(basePackage) + "/" + "**/*.class";
Resource[] resources = resourcePatternResolver.getResources(packageSearchPath);
for (Resource resource : resources) {
if (resource.isReadable()) {
MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
if (isCandidate(metadataReader)) {
candidates.add(Class.forName(metadataReader.getClassMetadata().getClassName()));
}
}
}
return candidates;
}
public String resolveBasePackage(String basePackage) {
return ClassUtils.convertClassNameToResourcePath(SystemPropertyUtils.resolvePlaceholders(basePackage));
}
#SuppressWarnings({ "rawtypes", "unchecked" })
public boolean isCandidate(MetadataReader metadataReader) throws ClassNotFoundException
{
try {
Class c = Class.forName(metadataReader.getClassMetadata().getClassName());
if (!c.isInterface() && c.getAnnotation(Controller.class) != null) {
return true;
}
}
catch(Throwable e){
}
return false;
}
}
and this is the actual class which i am investigating:
package com.hexgen.api.facade;
`// removed imports to post question here`
import com.hexgen.datauploader.ETLServiceProvider;
import com.hexgen.ro.response.UserDetailsResponse;
/**
* Hexagon Global IT Services (ALL RIGHTS RESERVED) Created with IntelliJ IDEA.
* User: mayankk Date: 23/11/12 Time: 10:27 AM To change this template use File
* | Settings | File Templates.
*/
#Controller
#Transactional
public class HexgenWebAPI {
#Resource(name = "facadeDbFuncs")
private DbFuncs dbFuncs;
#Resource(name = "gatekeeper")
private IGateKeeper gateKeeper;
#Resource(name = "userContext")
private UserContext userContext;
#Resource(name = "costCalc")
private FinancialCalculator financialCalculator;
#Resource(name = "ytmCalc")
private YTMCalculator ytmCalc;
#Resource(name = "etlService")
private ETLServiceProvider etlService;
#Resource(name = "biManager")
private IBIManager biManager;
private String tmpFileName;
Logger logger = LoggerFactory.getLogger(HexgenWebAPI.class);
private Pattern c4Pattern;
public HexgenWebAPI() {
String cmdPattern = "([bsBS])[ ]+(\\w+)[ ]+(\\d+)[ ]*#[ ]*(\\d+\\.?\\d*)";
c4Pattern = Pattern.compile(cmdPattern);
}
#RequestMapping(method = RequestMethod.GET, value = "/user/details")
public #ResponseBody
UserDetailsResponse getLoggedinUserDetails() {
HexGenUser details = (HexGenUser) SecurityContextHolder.getContext()
.getAuthentication().getPrincipal();
populateImplementationDetails(response);
return response;
}
private void populateImplementationDetails(UserDetailsResponse response) {
logger.debug("Finding revision details");
try {
CodeSource codeSource = this.getClass().getProtectionDomain()
.getCodeSource();
if (codeSource != null) {
JarInputStream jarStream = new JarInputStream(codeSource
.getLocation().openStream());
Manifest manifest = jarStream.getManifest();
logger.debug("Manifest not found!");
if (manifest != null) {
}
}
} catch (Throwable e) {
logger.debug(e.getMessage());
}
logger.debug("Could not find revision details, seems like development environment.");
}
#PreAuthorize("isAuthenticated() and hasPermission(#request, 'CREATE_REQUISITION')")
#RequestMapping(method = RequestMethod.POST, value = "/trade/createrequisition")
public #ResponseBody
void createRequisition(#RequestBody CreateRequisitionRO[] request,
#RequestHeader("validateOnly") boolean validateOnly) {
logger.debug("Starting createRequisition()...");
for (int i = 0; i < request.length; i++) {
CreateRequisitionRO requisitionRequest = request[i];
{
logger.debug("Record is for update ? {}", mr.isUpdate());
logger.debug("attrs are {}", mr.getChangedRecord());
}
gateKeeper.route(request);
}
#PreAuthorize("isAuthenticated() and hasPermission(#request, 'CREATE_ORDER')")
#RequestMapping(method = RequestMethod.POST, value = "/trade/createorder")
public #ResponseBody
void createOrder(#RequestBody CreateOrderRO request,
#RequestHeader("validateOnly") boolean validateOnly) {
TradeDtl orderRow = dbFuncs.references.tradeDtl.findByTransId(request
.getTransRef());
d
logger.debug("Starting createOrder()...");
gateKeeper.route(request);
}
#RequestMapping(method = RequestMethod.POST, value = "/trade/confirmorder")
public #ResponseBody
void confirmOrder(#RequestBody ConfirmOrderRO request,
#RequestHeader("validateOnly") boolean validateOnly) {
logger.debug("Starting confirmOrder()...");
gateKeeper.route(request);
}
#RequestMapping(method = RequestMethod.PUT, value = "/trade/review/approve")
public #ResponseBody
void approveReview(#RequestBody ApproveReviewRO request,
#RequestHeader("validateOnly") boolean validateOnly) {
logger.trace("approveReview({},{})", request, validateOnly);
gateKeeper.route(request);
}
#RequestMapping(method = RequestMethod.PUT, value = "/trade/review/reject")
public #ResponseBody
void rejectReview(#RequestBody RejectReviewRO request,
#RequestHeader("validateOnly") boolean validateOnly) {
logger.trace("HexgenWebAPI.rejectReview({},{})", request, validateOnly);
gateKeeper.route(request);
}
#RequestMapping(method = RequestMethod.PUT, value = "/upload/overwrite/approve")
public #ResponseBody
void approveUpload(#RequestBody ApproveReviewRO request,
#RequestHeader("validateOnly") boolean validateOnly) {
logger.trace("approveUpload({},{})", request, validateOnly);
UploadJobMaster uploadJobMaster = dbFuncs.references.uploadJobMaster.findOne(request.getId());
AbstractUploadOverwriteRO uploadAcceptRO = null;
Class<?> loaderRO = null;
try {
String className = etlService.getOverwriteAcceptEventName(uploadJobMaster.getUploadGenericType());
loaderRO = Class.forName(className);
uploadAcceptRO = (AbstractUploadOverwriteRO) loaderRO.newInstance();
uploadAcceptRO.setUploadID(uploadJobMaster.getUploadId());
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
gateKeeper.route((IRO) uploadAcceptRO);
}
#RequestMapping(method = RequestMethod.PUT, value = "/upload/overwrite/reject")
public #ResponseBody
void rejectUpload(#RequestBody RejectReviewRO request,
#RequestHeader("validateOnly") boolean validateOnly) {
try {
String className = etlService.getOverwriteRejectEventName(uploadJobMaster.getUploadGenericType());
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
gateKeeper.route((IRO) uploadRejectRO);
}
#RequestMapping(method = RequestMethod.POST, value = "/upload/file")
public #ResponseBody
FileUploadResponse upload(#RequestParam("file") MultipartFile file) {
FileUploadResponse fileUploadResponse = new FileUploadResponse();
try {
file.transferTo(tmpFile);
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
fileUploadResponse.setStatusMessage("passed");
return fileUploadResponse;
}
#RequestMapping(method = RequestMethod.POST, value = "/upload/form/{uploadType}/{uploadName}")
public #ResponseBody
void uploadForm(#PathVariable String uploadType,
#PathVariable String uploadName) {
FileReceivedForUploadRO requisitionRequest = new FileReceivedForUploadRO(
gateKeeper.route(requisitionRequest);
}
//Reports
#PostFilter("isAuthenticated() and hasPermission(null, 'REPG' + filterObject.groupId)")
#RequestMapping(method = RequestMethod.GET, value = "/reports/groups")
public #ResponseBody
List<ReportsGroups> RetrieveReportGroups() {
UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
return biManager.getReportGroups();
}
#PostFilter("isAuthenticated() and hasPermission(null, 'REPN' + filterObject.reportId)")
#RequestMapping(method = RequestMethod.GET, value = "/reports/list")
public #ResponseBody
List<ReportNames> RetrieveReports(#RequestParam("groupId") BigDecimal groupId) {
return biManager.getReportNames(groupId);
}
#PreAuthorize("isAuthenticated() and hasPermission(null, 'REPN' + #reportId)")
#RequestMapping(method = RequestMethod.GET, value = "/reports/fields")
public #ResponseBody
List<FilterParameters> RetrieveReportFields(#RequestParam("reportId") BigDecimal reportId) {
ReportGroupMapping report = dbFuncs.references.reportGroupMapping.findOne(reportId);
return biManager.getFilterParameters(report.getReportName());
}
#PreAuthorize("isAuthenticated() and hasPermission(null, 'REPN' + #request.reportId)")
#RequestMapping(method = RequestMethod.POST, value = "/reports/generateurl")
public #ResponseBody
GenerateURLResponse generateURL(#RequestBody GenerateURLRO request) {
ReportGroupMapping report = dbFuncs.references.reportGroupMapping.findOne(request.getReportId());
try {
return new GenerateURLResponse(biManager.generateURL(report.getReportName(), request.getReportParameters()));
} catch(BOValidationException e) {
throw new ValidationException(e.getViolations());
}
}
// TODO throw away code
#RequestMapping(method = RequestMethod.POST, value = "/upload/eodprocess")
public #ResponseBody
void dayChange() {
DayChangeRO dayChangeRO = new DayChangeRO();
gateKeeper.route(dayChangeRO);
}
#RequestMapping(method = RequestMethod.GET, value = "/overview/holdings")
public #ResponseBody
List<HoldingsRO> generateHoldingsReport() {
List<HoldingsQO> holdingsQO = dbFuncs.references.reportsMgrFinders
.getAllHoldings();
holdingsRO.add(new HoldingsRO(holding.getAssetClass(), holding
.getUnRealTcy(), holding.getUnRealPcy()));
}
return holdingsRO;
}
#RequestMapping(method = RequestMethod.GET, value = "/overview/funds")
public #ResponseBody
List<FundOverviewRO> generatePortfolioTrend() {
List<FundOverviewQO> fundOverviewQO = dbFuncs.references.reportsMgrFinders
.getPortfolioMovement();
List<FundOverviewRO> fundOverviewRO = new ArrayList<FundOverviewRO>();
.getLast30Day()));
}
return fundOverviewRO;
}
#RequestMapping(method = RequestMethod.GET, value = "/fund/holdings/{portfolio}")
public #ResponseBody
List<HoldingsRO> generateHoldingsReport(#PathVariable String portfolio) {
List<HoldingsQO> holdingsQO = dbFuncs.references.reportsMgrFinders
.getFundHoldings(portfolio);
List<HoldingsRO> holdingsRO = new ArrayList<HoldingsRO>();
for (HoldingsQO holding : holdingsQO) {
String securityDescription = holding.getSecurityDescription()
.substring(
0,
Math.min(holding.getSecurityDescription().length(),
20));
holdingsRO.add(new HoldingsRO(holding.getAssetClass(), holding
.getAccrIntTcy(), holding.getAodTcy(), holding
.getUnRealTcy(), holding.getUnRealPcy()));
}
return holdingsRO;
}
#RequestMapping(method = RequestMethod.GET, value = "/fund/concentration/{portfolio}")
public #ResponseBody
ConcentrationRO[] getConcentrationForFund(#PathVariable String portfolio) {
List<ConcentrationRO> concentrations = new ArrayList<ConcentrationRO>();
concentrations
.add(generateConcentrationRO(dbFuncs.references.concentrationFinders
.getAssetGroupExposureFor(userContext.getCompany(),
portfolio)));
concentrations
.add(generateConcentrationRO(dbFuncs.references.concentrationFinders
.getAssetClassExposureFor(userContext.getCompany(),
portfolio)));
concentrations
.add(generateConcentrationRO(dbFuncs.references.concentrationFinders
.getIndustryExposureFor(userContext.getCompany(),
portfolio, "IND")));
return concentrations
.toArray(new ConcentrationRO[concentrations.size()]);
}
#RequestMapping(method = RequestMethod.GET, value = "/overview/concentration")
public #ResponseBody
ConcentrationRO[] getConcentrationForFund() {
List<ConcentrationRO> concentrations = new ArrayList<ConcentrationRO>();
concentrations
.add(generateConcentrationRO(dbFuncs.references.concentrationFinders
.getAssetGroupExposureFor(userContext.getCompany())));
concentrations
.add(generateConcentrationRO(dbFuncs.references.concentrationFinders
.getAssetClassExposureFor(userContext.getCompany())));
concentrations
.add(generateConcentrationRO(dbFuncs.references.concentrationFinders
.getIndustryExposureFor(userContext.getCompany(), "IND")));
return concentrations
.toArray(new ConcentrationRO[concentrations.size()]);
}
public ConcentrationRO generateConcentrationRO(
ConcentrationFinders concentrationFinder) {
ConcentrationRO concentrationRO = new ConcentrationRO();
for (ValueQO valueQO : concentrationFinder.getValues()) {
concentrationRO.addValue(valueQO.getName(), valueQO.getActual(),
valueQO.getGuidance());
}
return concentrationRO;
}
#RequestMapping(method = RequestMethod.POST, value = "/c4/execute")
public #ResponseBody
void executeC4Command(#RequestBody C4CommandRO request) {
logger.debug("Received command for execution : " + request.getCmd());
try {
Matcher matcher = c4Pattern.matcher(request.getCmd());
if (matcher.matches()) {
String parsedTransCode = matcher.group(1);
} else {
logger.debug("Invalid C4 command");
throw new RuntimeException();
}
} catch (Throwable e) {
logger.debug("Ooops !! C4 command execution failed - "
+ e.getMessage());
throw new RuntimeException(e);
}
}
// FIXME C4 throw away code
private void createRequisitionThroughC4(String security, String transCode,
BigDecimal price, BigDecimal quantity) {
logger.debug("Starting createRequisition() through C4...");
try {
Security securityRow = dbFuncs.references.security
.findBySecurity(security);
if (securityRow.getIsIntApplic() || securityRow.getIsDiscounted()) {
createRequisition.setYtm(ytmCalc.computeXIRR(security, price,
userContext.getBusinessDate()));
} else {
createRequisition.setYtm(BigDecimal.ZERO);
}
SystemDefault defaults = dbFuncs.references.systemDefault
.findByParamLevelAndCompanyAndDivisionAndPortfolio(
ParamLevel.PF, userContext.getCompany(),
userContext.getDivision(), portfolio);
OutputValuesFromInvestmentsDO response = financialCalculator
.costSettlementCalculator(input);
createRequisition.setTransSrlNo(BigDecimal.ONE);
if (transCode.equals("BUY")) {
createRequisition.setInflowOutflow(InflowOutflow.I);
} else {
createRequisition.setInflowOutflow(InflowOutflow.O);
}
createRequisition.setFundManager(createRequisition.getUserId());
createRequisition.setCustodianN(defaults.getCustodianN());
gateKeeper.route(createRequisition);
} catch (Throwable e) {
logger.debug("Ooops !! C4 command execution failed - "
+ e.getMessage());
throw new RuntimeException(e);
}
}
}
but the folloing is the out put i get where i see many methods are not present in the class :
1:ajc$get$validator
Parameter Type : com.hexgen.api.facade.HexgenWebAPI
2:ajc$set$validator
Parameter Type : com.hexgen.api.facade.HexgenWebAPI
Parameter Type : javax.validation.Validator
3:ajc$get$requestToEventTranslator
Parameter Type : com.hexgen.api.facade.HexgenWebAPI
4:ajc$set$requestToEventTranslator
Parameter Type : com.hexgen.api.facade.HexgenWebAPI
Parameter Type : com.hexgen.p0.translator.RequestToEventTranslator
5:ajc$interMethodDispatch2$com_hexgen_api_facade_HexgenWebAPIValidation$validate
Parameter Type : com.hexgen.ro.IRO
6:handleValidationException
Parameter Type : com.hexgen.api.facade.ValidationException
7:createRequisition
Parameter Type : [Lcom.hexgen.ro.request.CreateRequisitionRO;
Parameter Type : boolean
8:getLoggedinUserDetails
9:populateImplementationDetails
Parameter Type : com.hexgen.ro.response.UserDetailsResponse
10:excelMDM
Parameter Type : com.hexgen.ro.request.MdmFromExcelRO
11:createOrder
Parameter Type : com.hexgen.ro.request.CreateOrderRO
Parameter Type : boolean
12:confirmOrder
Parameter Type : com.hexgen.ro.request.ConfirmOrderRO
Parameter Type : boolean
13:approveReview
Parameter Type : com.hexgen.ro.request.ApproveReviewRO
Parameter Type : boolean
14:rejectReview
Parameter Type : com.hexgen.ro.request.RejectReviewRO
Parameter Type : boolean
15:approveUpload
Parameter Type : com.hexgen.ro.request.ApproveReviewRO
Parameter Type : boolean
16:rejectUpload
Parameter Type : com.hexgen.ro.request.RejectReviewRO
Parameter Type : boolean
17:upload
Parameter Type : org.springframework.web.multipart.MultipartFile
18:uploadForm
Parameter Type : java.lang.String
Parameter Type : java.lang.String
19:RetrieveReportGroups
20:RetrieveReports
Parameter Type : java.math.BigDecimal
21:RetrieveReportFields
Parameter Type : java.math.BigDecimal
22:generateURL
Parameter Type : com.hexgen.ro.request.GenerateURLRO
23:dayChange
24:generateHoldingsReport
25:generateHoldingsReport
Parameter Type : java.lang.String
26:generatePortfolioTrend
27:getConcentrationForFund
Parameter Type : java.lang.String
28:getConcentrationForFund
29:generateConcentrationRO
Parameter Type : com.hexgen.core.orm.finders.repositories.ConcentrationFinders
30:executeC4Command
Parameter Type : com.hexgen.ro.request.C4CommandRO
31:createRequisitionThroughC4
Parameter Type : java.lang.String
Parameter Type : java.lang.String
Parameter Type : java.math.BigDecimal
Parameter Type : java.math.BigDecimal
32:createRequisition_aroundBody0
Parameter Type : com.hexgen.api.facade.HexgenWebAPI
Parameter Type : [Lcom.hexgen.ro.request.CreateRequisitionRO;
Parameter Type : boolean
33:createRequisition_aroundBody1$advice
Parameter Type : com.hexgen.api.facade.HexgenWebAPI
Parameter Type : [Lcom.hexgen.ro.request.CreateRequisitionRO;
Parameter Type : boolean
Parameter Type : com.hexgen.api.facade.HexgenWebAPIValidation
Parameter Type : [Lcom.hexgen.ro.IRO;
Parameter Type : boolean
Parameter Type : com.hexgen.api.facade.HexgenWebAPI
Parameter Type : org.aspectj.runtime.internal.AroundClosure
34:createOrder_aroundBody2
Parameter Type : com.hexgen.api.facade.HexgenWebAPI
Parameter Type : com.hexgen.ro.request.CreateOrderRO
Parameter Type : boolean
35:createOrder_aroundBody3$advice
Parameter Type : com.hexgen.api.facade.HexgenWebAPI
Parameter Type : com.hexgen.ro.request.CreateOrderRO
Parameter Type : boolean
Parameter Type : com.hexgen.api.facade.HexgenWebAPIValidation
Parameter Type : com.hexgen.ro.IRO
Parameter Type : boolean
Parameter Type : com.hexgen.api.facade.HexgenWebAPI
Parameter Type : org.aspectj.runtime.internal.AroundClosure
36:confirmOrder_aroundBody4
Parameter Type : com.hexgen.api.facade.HexgenWebAPI
Parameter Type : com.hexgen.ro.request.ConfirmOrderRO
Parameter Type : boolean
37:confirmOrder_aroundBody5$advice
Parameter Type : com.hexgen.api.facade.HexgenWebAPI
Parameter Type : com.hexgen.ro.request.ConfirmOrderRO
Parameter Type : boolean
Parameter Type : com.hexgen.api.facade.HexgenWebAPIValidation
Parameter Type : com.hexgen.ro.IRO
Parameter Type : boolean
Parameter Type : com.hexgen.api.facade.HexgenWebAPI
Parameter Type : org.aspectj.runtime.internal.AroundClosure
38:approveReview_aroundBody6
Parameter Type : com.hexgen.api.facade.HexgenWebAPI
Parameter Type : com.hexgen.ro.request.ApproveReviewRO
Parameter Type : boolean
39:approveReview_aroundBody7$advice
Parameter Type : com.hexgen.api.facade.HexgenWebAPI
Parameter Type : com.hexgen.ro.request.ApproveReviewRO
Parameter Type : boolean
Parameter Type : com.hexgen.api.facade.HexgenWebAPIValidation
Parameter Type : com.hexgen.ro.IRO
Parameter Type : boolean
Parameter Type : com.hexgen.api.facade.HexgenWebAPI
Parameter Type : org.aspectj.runtime.internal.AroundClosure
40:rejectReview_aroundBody8
Parameter Type : com.hexgen.api.facade.HexgenWebAPI
Parameter Type : com.hexgen.ro.request.RejectReviewRO
Parameter Type : boolean
41:rejectReview_aroundBody9$advice
Parameter Type : com.hexgen.api.facade.HexgenWebAPI
Parameter Type : com.hexgen.ro.request.RejectReviewRO
Parameter Type : boolean
Parameter Type : com.hexgen.api.facade.HexgenWebAPIValidation
Parameter Type : com.hexgen.ro.IRO
Parameter Type : boolean
Parameter Type : com.hexgen.api.facade.HexgenWebAPI
Parameter Type : org.aspectj.runtime.internal.AroundClosure
42:approveUpload_aroundBody10
Parameter Type : com.hexgen.api.facade.HexgenWebAPI
Parameter Type : com.hexgen.ro.request.ApproveReviewRO
Parameter Type : boolean
43:approveUpload_aroundBody11$advice
Parameter Type : com.hexgen.api.facade.HexgenWebAPI
Parameter Type : com.hexgen.ro.request.ApproveReviewRO
Parameter Type : boolean
Parameter Type : com.hexgen.api.facade.HexgenWebAPIValidation
Parameter Type : com.hexgen.ro.IRO
Parameter Type : boolean
Parameter Type : com.hexgen.api.facade.HexgenWebAPI
Parameter Type : org.aspectj.runtime.internal.AroundClosure
44:rejectUpload_aroundBody12
Parameter Type : com.hexgen.api.facade.HexgenWebAPI
Parameter Type : com.hexgen.ro.request.RejectReviewRO
Parameter Type : boolean
45:rejectUpload_aroundBody13$advice
Parameter Type : com.hexgen.api.facade.HexgenWebAPI
Parameter Type : com.hexgen.ro.request.RejectReviewRO
Parameter Type : boolean
Parameter Type : com.hexgen.api.facade.HexgenWebAPIValidation
Parameter Type : com.hexgen.ro.IRO
Parameter Type : boolean
Parameter Type : com.hexgen.api.facade.HexgenWebAPI
Parameter Type : org.aspectj.runtime.internal.AroundClosure
46:ajc$preClinit

Different parts of the Spring frame-work perform instrumentation at run-time to, to augment classes and provide additional functionality. Spring uses three different kinds of instrumentation:
DynamicProxies - this is a feature of J2SE, and allows generating an interface "on-the-fly" by specifying "method handlers" - a method that gets called to handle method invocations. The handler will look at the method signature and arguments to decide what to do. Typically this will involve adding dome functionality before or after calling a the corresponding method on a concrete target class that implements the same interface. (Hence the name 'proxy'). Dynamic Proxies are the default when a class is backed by an interface.
Byte-code-engineering (BCEL). This involves overriding the class-loader method that loads a class the first time it is required. The overridden method returns a sub-class that is generated at runtime, and includes extra functionality. The library that Spring uses this is 'cglib' which is built on top of 'asm'. . . These libraries prioritize performance over ease-of-use. . . (ease of use not being a concern, since the Spring user doesn't do any byte-code engineering for themselves - just uses the instrumented classes).
AspectJ weaving. This involves using either compile-time weaving or runtime weaving. In the case of the latter a special Java Agent is used (cmd-line argument to the JVM) instead of intercepting the classloader.
Examples of instrumentation are annotation-based transactions, security annotations, validation, etc.
You are observing the second type of instrumentation (a runtime generated sub-class), which is the default for concrete classes. . . (AspectJ can be used in more complex situations, such as providing dependency injection on classes outside of the Spring container).

Related

Failed to convert value of type StandardMultipartHttpServletRequest$StandardMultipartFile' to required type 'java.lang.String

I have simple form which can upload files and it's controoler, for safety i decided to implement PRG pattern, but now my cod doesn't work.
#PostMapping("/books")
public String add(#Valid #ModelAttribute("book") Book book, HttpServletResponse response,RedirectAttributes redirectAttributes, BindingResult result, #RequestParam(value = "photo", required = false) MultipartFile photo, Model forExc, #RequestParam(value = "valute") String valute) {
if (result.hasErrors()) return "addBook";
if (!photo.isEmpty()) {
try {
validateImg(photo);
} catch (IOException ex) {
result.reject("uk_UA", "Поганий тип");
return "addBook";
}
}
redirectAttributes.addFlashAttribute("book",book);
redirectAttributes.addAttribute("photo", photo);
redirectAttributes.addAttribute("valute", valute);
redirectAttributes.addFlashAttribute( "success",true);
return "redirect:/valid";
}
#GetMapping("/valid")
public String validations(HttpServletRequest request,Model model, #ModelAttribute("success") boolean success, #ModelAttribute("book") Book book, #RequestParam("valute") String valute, #RequestParam(value = "photo",required = false) MultipartFile photo) {
if (success) {
StringBuilder builder = new StringBuilder();
builder.append(service.download(photo));
Logger.getAnonymousLogger().info("SOMETHING HAS BROKEN IN LOGGING FILE");
System.out.println("INSIDE ADD METHOD ");
book.setFileId(builder.toString());
service.add(book);
return "redirect:/books";
} else {
return "redirect:/index.jsp";
}
}
When i add a book i get this exception:
org.springframework.beans.ConversionNotSupportedException: Failed to convert value of type 'org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile' to required type 'java.lang.String'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile' to required type 'java.lang.String': no matching editors or conversion strategy found

Is it possible to get the values dynamically in #WebInitParam?

I have a JSP page wherein user has to enter some custom URL. I want to pass that custom url in #WebInitParam in my servlet
#WebServlet(name = "oauthCustomURL", initParams = {
#WebInitParam(name = "clientId", value = "123"),
#WebInitParam(name = "key", value = "***"),
#WebInitParam(name = "environment", value = "customUrl"),
}) //in value I want to pass the value entered by user
#WebInitParam's are used for the configuration of servlets implemented by third-party libraries. Usually, these libraries use methods getInitParameterNames() and getInitParameter() of abstract class GenericServlet (but you should check in library code for it).
For the dynamic setting of the #WebInitParam you can override those methods in your servlet implementation. Below is an example of how to do it.
#WebServlet(urlPatterns = "/abc/*")
public class DynamicInitParamServlet extends SomeCustomLibraryHttpServlet {
private static final String WEB_INIT_PARAM_NAME = "some.param.name";
private Integer webInitParamValue = null;
#Override
public void init(ServletConfig config) throws ServletException {
// calculate init param value dynamically,
// TODO: implement your own code
webInitParamValue = 2 * 3;
// call custom library servlet init after init parameter value is set
super.init(config);
}
#Override
public Enumeration<String> getInitParameterNames() {
if (webInitParamValue != null) {
final Set<String> initParameterNames = new HashSet<>(Collections.list(super.getInitParameterNames()));
initParameterNames.add(WEB_INIT_PARAM_NAME);
return Collections.enumeration(initParameterNames);
} else {
return super.getInitParameterNames();
}
}
#Override
public String getInitParameter(String name) {
if (WEB_INIT_PARAM_NAME.compareTo(name) == 0 && webInitParamValue != null) {
return "" + webInitParamValue;
} else {
return super.getInitParameter(name);
}
}
}

Mulesoft Java Transformer

I have no clue how to use a Java Transformer in Mulesoft. I want to basically take a String and convert it to a URL, but I cannot figure out how to use the Java method or anything.
What am I doing wrong? How can I take I call my method, or make it so that my method is used with the value I want it to be?
ERRORS:
org.mule.module.launcher.DeploymentInitException:
IllegalStateException: Cannot convert value of type
[transformers.StringTransformer] to required type
[org.mule.api.processor.MessageProcessor] for property
'messageProcessors[4]': no matching editors or conversion strategy
found
Caused by: org.mule.api.config.ConfigurationException: Error creating
bean with name 'streamMigrateAccountToCustomer': Initialization of
bean failed; nested exception is
org.springframework.beans.ConversionNotSupportedException: Failed to
convert property value of type [java.util.ArrayList] to required type
[java.util.List] for property 'messageProcessors'; nested exception is
java.lang.IllegalStateException: Cannot convert value of type
[transformers.StringTransformer] to required type
[org.mule.api.processor.MessageProcessor] for property
'messageProcessors[4]': no matching editors or conversion strategy
found (org.mule.api.lifecycle.InitialisationException)
(org.mule.api.config.ConfigurationException)
StringTransformer
#ContainsTransformerMethods
public class StringTransformer
{
public String website;
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
#Transformer
public String stringToURL(String string) throws MalformedURLException
{
return new java.net.URL(string).toString();
}
}
XML
<custom-transformer class="transformers.StringTransformer" doc:name="Java">
<spring:property name="website" value="#[payload.Website]"/>
</custom-transformer>
INPUT TO JAVA TRANSFORMER
%dw 1.0
%output application/java
---
{
Id: payload.Id,
Name: payload.Name,
Active_CMRR__c: payload.Active_CMRR__c,
BillingStreet: payload.BillingStreet,
BillingCity: payload.BillingCity,
BillingState: payload.BillingState,
BillingPostalCode: payload.BillingPostalCode,
BillingCountry: payload.BillingCountry,
OwnerId: payload.OwnerId,
Website: payload.Website,
Contract_End_Date__c: payload.Contract_End_Date__c,
NS_Account_Number__c: payload.NS_Account_Number__c,
Phone: payload.Phone,
Subscription_Start_Date__c: payload.Subscription_Start_Date__c,
NS_Account_Name__c: payload.NS_Account_Name__c,
type: payload.type,
Owner: {
NS_Account_Manager_Id__c: payload.Owner.NS_Account_Manager_Id__c,
Id: payload.Owner.Id,
type: payload.Owner.type,
Name: payload.Owner.Name
}
}
For a simple string manipulation I prefer to use a simple MEL expression, heres an example of creating a new variable.
<set-variable variableName="website" value="#[new java.net.URL(payload.Website).toString()]" doc:name="Variable"/>
To do a java transformations on the MuleMessage, I prefer to extend the AbstractMessageTransformer class.
public class ExampleAbstractMessageTransformer extends AbstractMessageTransformer {
#Override
public Object transformMessage(MuleMessage message, String outputEncoding) throws TransformerException {
// TODO Auto-generated method stub
HashMap<String, String> payload = new HashMap<String, String>();
String websiteUrl = new String();
//Grab Payload
payload = (HashMap<String, String>) message.getPayload();
try {
websiteUrl = stringToURL(payload.get("Website").toString());
} catch (MalformedURLException e) {
e.printStackTrace();
}
message.setInvocationProperty("websiteUrl", websiteUrl);
return message;
}
public String stringToURL(String string) throws MalformedURLException {
return new java.net.URL(string).toString();
}
}
Implementing within the Mulesoft flow. Assuming the java code is packaged as com.stackoverflow.transformers utilize the "custom-transformer" component.
<custom-transformer class="com.stackoverflow.transformers.ExampleAbstractMessageTransformer" doc:name="Java" />
you can use invoke component to call java method. check https://docs.mulesoft.com/mule-user-guide/v/3.7/invoke-component-reference
#ContainsTransformerMethods // since Mule 3.0.1
public class MyTransformers {  
  #Transformer  
  public URL stringToURL(String string) {  
return new java.net.URL(string);
}
#Transformer
public List<URL> stringsToURLs(String string) {    
List<URL urls = new ArrayList<URL>();   
for (StringTokenizer tokenizer = new StringTokenizer(string); tokenizer.hasMoreTokens();) {       
urls.add(new URL(tokenizer.nextToken()));
}   
return urls;
}
}

How to validate file type, size while uploading in Rest in Spring?

I am trying to implement file uploading using spring and Rest. Here what I have done this far
#RestController
#RequestMapping("/rest/upload")
public class ProfileImageUploadController {
#Autowired
ImageValidator imageValidator;
#RequestMapping(value="/{userId}/image", method=RequestMethod.POST)
public #ResponseBody String handleFileUpload(
#PathVariable("userId") Integer userId,
#ModelAttribute("image") SingleImageFile image,
BindingResult result){
MultipartFile file = image.getFile();
imageValidator.validate(file, result);
if(!result.hasErrors()){
String name = file.getOriginalFilename();
try{
file.transferTo(new File("/home/maclein/Desktop/"+name));
return "You have successfully uploaded " + name + "!";
}catch(Exception e){
return "You have failed to upload " + name + " => " + e.getMessage();
}
} else {
return result.getFieldErrors().toString();
}
}
}
Here is my ImageValidator
#Component
public class ImageValidator implements Validator {
#Override
public boolean supports(Class<?> arg0) {
// TODO Auto-generated method stub
return false;
}
#Override
public void validate(Object uploadedFile, Errors error) {
MultipartFile file = (MultipartFile) uploadedFile;
if(file.isEmpty() || file.getSize()==0)
error.rejectValue("file", "Please select a file");
if(!(file.getContentType().toLowerCase().equals("image/jpg")
|| file.getContentType().toLowerCase().equals("image/jpeg")
|| file.getContentType().toLowerCase().equals("image/png"))){
error.rejectValue("file", "jpg/png file types are only supported");
}
}
}
But while testing through postman its showing the error if file is pdf but in a weird way. Here is the string representation of the error
"[Field error in object 'image' on field 'file': rejected value [org.springframework.web.multipart.commons.CommonsMultipartFile#3fc04a65]; codes [jpg/png file types are only supported.image.file,jpg/png file types are only supported.file,jpg/png file types are only supported.org.springframework.web.multipart.MultipartFile,jpg/png file types are only supported]; arguments []; default message [null]]"
I cannot understand why the error list length is 4. My motive is to show error in json if it is not validated.
If there is any standard way to do this kind of validation ? I am new to spring and Rest. So someone please show me the way to achieve the goal.
protected List<String> extractErrorMessages(BindingResult result) {
List<String> errorMessages = new ArrayList<>();
for (Object object : result.getAllErrors()) {
if (object instanceof FieldError) {
FieldError fieldError = (FieldError) object;
errorMessages.add(fieldError.getCode());
}
}
return errorMessages;
}
Take a look at fieldError methods, probably in your case you should use getField

how to get annotations in java through reflection

this is my annotations:
#RequestMapping(method = RequestMethod.POST, value = "/trade/createrequisition")
now i would like to get request method it is POST in this case and the value it is /trade/createrequisition in this case.
How to do this using reflection in java.
Please help me to resolve this.
EDIT:
this is what is my actual method :
#PreAuthorize("isAuthenticated() and hasPermission(#request, 'CREATE_REQUISITION')")
#RequestMapping(method = RequestMethod.POST, value = "/trade/createrequisition")
public #ResponseBody
void createRequisition(#RequestBody CreateRequisitionRO[] request,
#RequestHeader("validateOnly") boolean validateOnly) {
....
}
this is how i tried to get the #RequestiMapping:
package com.hexgen.reflection;
import java.lang.reflect.Method;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.hexgen.api.facade.HexgenWebAPI;
public class WebAPITest {
public static void main(String[] args) {
try {
Class<HexgenWebAPI> clazz = HexgenWebAPI.class;
Method methodAnnotaion = clazz.getMethod("createRequisition");
RequestMapping methodRequestMappingAnnotation = methodAnnotaion.getAnnotation(RequestMapping.class);
RequestMethod[] methods = methodRequestMappingAnnotation.method();
String[] mappingValues = methodRequestMappingAnnotation.value();
for(RequestMethod req : methods){
System.out.println("RequestMethod : " + req);
}
for (String string : mappingValues) {
System.out.println("mappingValues : " + string);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
but i get this exception :
java.lang.NoSuchMethodException: com.hexgen.api.facade.HexgenWebAPI.createRequisition()
at java.lang.Class.getMethod(Class.java:1605)
at com.hexgen.reflection.WebAPITest.main(WebAPITest.java:12)
As you are trying to get the RequestMapping annotation, and it can be placed at a class or a method, see both uses below:
For a class YourClass:
Class<YourClass> clazz = YourClass.class;
RequestMapping clazzRequestMappingAnnotation = clazz.getAnnotation(RequestMapping.class);
RequestMethod[] methods = clazzRequestMappingAnnotation.method();
String[] mappingValues = clazzRequestMappingAnnotation.value();
For a method methodName at a class YourClass:
Class<YourClass> clazz = YourClass.class;
Method method = clazz.getMethod("methodName");
RequestMapping methodRequestMappingAnnotation = method.getAnnotation(RequestMapping.class);
RequestMethod[] methods = methodRequestMappingAnnotation.method();
String[] mappingValues = methodRequestMappingAnnotation.value();
If this annotation is on a class (eg: Test) then
RequestMapping a = Test.class.getAnnotation(RequestMapping.class);
RequestMethod m = a.getMethod();

Categories