Birt Report not opening in PDF - ajax

Hello guys
I am sending my form values to controller and controller to rptdesign file my it is generating the report in temp folder with proper value but my requirement is that it should user to save or open dialog so that user can save the report or open
i think ajax request will not allow to download any file so if some one know to better solution plz reply
my controller is below
#RequestMapping("/leave/generateEmpLeaveReport.json")
public void generateEmployeeLeaveReport(HttpServletRequest request,
HttpServletResponse response) throws Exception {
String reportName = "D:/git-repositories/cougar_leave/src/java/com//report/myLeaveSummary.rptdesign";
File designTemplateFile = new File(reportName);
if (!designTemplateFile.exists()) {
throw new FileNotFoundException(reportName);
}
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("empId", NumberUtils.toInt(request.getParameter("id")));
parameters.put("reportTitle", "EMPLOYEE LEAVE");
parameters.put("fromDate", request.getParameter("fromDate"));
parameters.put("toDate", request.getParameter("toDate"));
parameters.put("leaveType",
NumberUtils.toInt(request.getParameter("leaveType")));
parameters.put("transactionType",
NumberUtils.toInt(request.getParameter("transactionType")));
reportManager.addSystemParams(parameters, null,
RequestUtils.getUser(request));
File file = null;
try {
ReportType reportType = ReportType.PDF;
OfflineReportContext reportContext = new OfflineReportContext(
reportName, reportType, parameters, null,
"EMPLOYEE LEAVE SUMMARY");
StringBuffer buffer = new StringBuffer();
file = offlineReportGenerator.generateReportFile(reportContext,
buffer);
ControllerUtils
.openFile(file.getParent(), response, file.getName());
} catch (Exception e) {
log.error(e, e);
} finally {
if (file != null && file.exists()) {
file.canExecute();
}
}
}
my ajax request is below
generateReport : function() {
if (this.form.valid()) {
fromDate = new Date($("input[name='fromDate']").val())
toDate = new Date($("input[name='toDate']").val())
if (fromDate > toDate) {
GtsJQuery
.showError("To date should be greater or equals than From date !")
} else {
var request = GtsJQuery.ajax3(GtsJQuery.getContextPath()
+ '/leave/generateEmpLeaveReport.json', {
data : {
id : $("input[name='employeeId']").val(),
fromDate : $("input[name='fromDate']")
.val(),
toDate : $("input[name='toDate']").val(),
leaveType : $("select[name='leaveType']")
.val(),
transactionType : $("select[name='transactionType']")
.val(),
orderBy : $("select[name='orderBy']").val()
}
});
request.success(this.callback("onSubscribeSuccess"))
}
}
},

The controller response should be the temp file itself, just adjust the content-type.

Related

Migrating Apache Struts Action to Spring Rest Controller

I have a webpage whose backend is in Java and the framework is very old (Apache Struts Framework)
The webpage contains buttons textboxes and tables which we can fill and press Add , delete and edit button
All this code is currently written in Action file in java
We need to convert this code and put it in a new Controller file (Rest Controller)
Action files will still be present we just need them till loading JSP onto the page
Once JSP is loaded every button click,event handler (i.e. Add, delete, edit) should be handled by controller
Earlier button clicks were going to Action like formSubmit
We will still need to keep the Action file because we are using Struts framework so we will require action file
Giving an example of two files of how they look after migration -
Apache Struts Action Code-
public final ActionForward updateUserDetails(final ActionMapping mapping,
final ActionForm form, final HttpServletRequest request,
final HttpServletResponse response) throws IOException {
UserAdminForm uForm = (UserAdminForm) form;
UserAdminVO vo = userManager.getUserByUserPk(Integer.parseInt(uForm.getUserPK()));
String olddiscoverId = vo.getDiscoverId();
String oldDiscoverAccess = vo.getDiscoverAccess();
try {
if(!ISC.SUPER_USER_ROLE.equals(workContext.getRole()) && !workContext.getUser().equalsIgnoreCase(uForm.getUserID())) {
manager.logError("** Possible breach: Logged in user[" + workContext.getUser() + "] is attempting to update details for " + uForm.getUserID() + ". **");
processErrorMessages(CConstant.USER_MISSMATCH_FOR_UPDATE_OPERATION,
request);
return mapping.findForward(CConstant.ACTION_FORWARD_SUCCESS);
}
setLandingPageAndOtherDetailsForUserUpdate(uForm, vo);
if (manager.isDebugEnabled()) {
manager.logDebug("User admin VO from user form =" + vo);
manager.logDebug("Old user id : " + uForm.getOldUserID()
+ " New User id : " + uForm.getUserID());
}
DiscoverResponse discoverResponse = null;
if("true".equalsIgnoreCase(globalSysParamManager.getParamValue(ENABLE_DISCOVER_SYSTEM_FEATURE))){
discoverResponse = updateDiscoverAccess(oldDiscoverAccess, olddiscoverId, vo);
if(discoverResponse!=null && CConstant.ERROR_STR.equalsIgnoreCase(discoverResponse.getResult())){
vo.setDiscoverAccess(oldDiscoverAccess);
}
}
userManager.updateUser(vo);
syncOtherUsersWithDiscover(vo);
refreshWorkContext(vo);
processSuccessMessage(CConstant.USER_UPDATE_SUCCESS, discoverResponse, request);
} catch (BusinessServiceException e) {
manager.logError("Error in User Update Action", e);
ActionMessages messages = new ActionMessages();
messages.add(
ActionMessages.GLOBAL_MESSAGE,
new ActionMessage(e.getErrorCode(), new Object[] { e
.getMessage() }));
saveErrors(request, messages);
} catch (BusinessServiceCommonsException e) {
manager.logError("Error in User Update Action", e);
ActionMessages messages = new ActionMessages();
messages.add(
ActionMessages.GLOBAL_MESSAGE,
new ActionMessage(e.getErrorCode(), new Object[] { e
.getMessage() }));
saveErrors(request, messages);
}
try {
loadCarparks(uForm, vo);
request.getSession(false).setAttribute(PARK_FOR_LOCATION,
uForm.getCarparkList());
} catch (BusinessServiceException e) {
manager.logError("Error in User Display Action ", e);
processBusinessServiceException(e, request);
}
if ("true".equals(uForm.getPasswordExpired())) {
response.sendRedirect(request.getContextPath()
+ "/logout.cprms?doLogout=true");
return null;
}
return mapping.findForward(CConstant.ACTION_FORWARD_SUCCESS);
}
Rest Controller Code -
#PutMapping
public ResponseEntity<Object> updateUser(#RequestBody UserAdminForm userAdminForm, HttpServletRequest request){
List<String> errorMessages = validateUserDetails(userAdminForm);
if(!errorMessages.isEmpty()){
return new ResponseEntity<>(errorMessages, HttpStatus.BAD_REQUEST);
}
ICWorkContext workContext = ControllerUtility.initializeWorkContext(userAdminForm.getLocationId(),request);
var userAdminVO = userManager.getUser(userAdminForm.getUserID());
String oldDiscoverId = userAdminVO.getDiscoverId();
String oldDiscoverAccess = userAdminVO.getDiscoverAccess();
DiscoverResponse discoverResponse = null;
try {
if(!ISC.SUPER_USER_ROLE.equals(workContext.getRole()) && !workContext.getUser().equalsIgnoreCase(userAdminForm.getUserID())) {
LOGGER.logError("** Possible breach: Logged in user[" + workContext.getUser() + "] is attempting to update details for " + userAdminForm.getUserID() + ". **");
String errorMessage = messages.getMessage(CConstant.USER_MISSMATCH_FOR_UPDATE_OPERATION);
return new ResponseEntity<>(errorMessage,HttpStatus.NOT_ACCEPTABLE);
}
setLandingPageAndOtherDetailsForUserUpdate(userAdminForm, userAdminVO,workContext);
if("true".equalsIgnoreCase(globalSysParamManager.getParamValue(ENABLE_DISCOVER_SYSTEM_FEATURE))){
discoverResponse = updateDiscoverAccess(oldDiscoverAccess, oldDiscoverId, userAdminVO);
if(discoverResponse!=null && CConstant.ERROR_STR.equalsIgnoreCase(discoverResponse.getResult())){
userAdminVO.setDiscoverAccess(oldDiscoverAccess);
}
}
userManager.updateUser(userAdminVO);
syncOtherUsersWithDiscover(userAdminVO);
refreshWorkContext(userAdminVO,workContext);
} catch (Exception exception) {
LOGGER.logError("Error in Update User API", exception);
return new ResponseEntity<>(HttpStatus.NOT_ACCEPTABLE);
}
Map<String, Object> response = new HashMap<>(2);
List<String> successMessages = new ArrayList<>(2);
successMessages.add(messages.getMessage(CConstant.USER_UPDATE_SUCCESS));
getDiscoverResponseMessage(discoverResponse, response, successMessages);
response.put(SUCCESS_MESSAGE,successMessages);
return new ResponseEntity<>(response,HttpStatus.OK);
}
I want to migrate this Action Code to Rest Controller -
public final ActionForward displayAllLeaves(final ActionMapping mapping,
final ActionForm form, final HttpServletRequest request,
final HttpServletResponse response) throws IOException,
ServletException {
boolean checkFlag = true;
LumpConfigFB lumpConfigFB = (LumpConfigFB) form;
storeProductWithoutDNAToRequest(request);
try {
LumpConfigVO lumpConfigVO = new LumpConfigVO();
if ((null == workContext.getCarparkPK())
|| "".equals(workContext.getCarparkPK())) {
BusinessServiceException businessServiceException = new BusinessServiceException(
CPRMSConstant.NO_C_ERROR);
businessServiceException
.setErrorCode(CConstant.NO_C_ERROR);
processBusinessServiceException(businessServiceException,
request);
return mapping
.findForward(CConstant.ACTION_FORWARD_SUCCESS);
}
// populateVO
populateLumpConfigVO(lumpConfigFB, lumpConfigVO);
lumpConfigManager.displayAllLeaves(lumpConfigVO);
if (((null != lumpConfigVO.getMappedLumpDefList()) && (lumpConfigVO
.getMappedLumpDefList().size() > 0))
|| ((null != lumpConfigVO.getUnmappedLumpDefList()) && (lumpConfigVO
.getUnmappedLumpDefList().size() > 0))) {
List<LumpConfigVO> mappedLumpDefList = lumpConfigVO
.getMappedLumpDefList();
HashMap<String, LumpConfigVO> lumpNameMap = new HashMap<String, LumpConfigVO>();
List<String> lumpNameList = new ArrayList<String>();
if (null != mappedLumpDefList && mappedLumpDefList.size() > 0) {
for (LumpConfigVO configVO : mappedLumpDefList) {
lumpNameList.add(configVO.getLumpName());
lumpNameMap.put(configVO.getLumpName(), configVO);
}
mappedLumpDefList.clear();
Collections.sort(lumpNameList,
String.CASE_INSENSITIVE_ORDER);
for (String lumpName : lumpNameList) {
mappedLumpDefList.add(lumpNameMap.get(lumpName));
}
lumpConfigFB.setMappedLumpDefList(mappedLumpDefList);
}
List<LumpConfigVO> unMappedLumpDefList = lumpConfigVO
.getUnmappedLumpDefList();
if (null != unMappedLumpDefList
&& unMappedLumpDefList.size() > 0) {
Collections.sort(unMappedLumpDefList, new LumpComparator());
lumpConfigFB.setUnmappedLumpDefList(unMappedLumpDefList);
}
} else {
lumpConfigFB.setMappedLumpDefList(null);
lumpConfigFB.setUnmappedLumpDefList(null);
BusinessServiceException businessServiceException = new BusinessServiceException(
CConstant.LEAF_NOT_FOUND_ERROR);
businessServiceException
.setErrorCode(CConstant.LEAF_NOT_FOUND_ERROR);
processBusinessServiceException(businessServiceException,
request);
checkFlag = false;
}
if (null != request.getAttribute("jobid")
&& !"".equals(request.getAttribute("jobid"))) {
String jobId = (String) request.getAttribute("jobid");
ActionErrors actionErrors = new ActionErrors();
ActionMessages messages = new ActionMessages();
if ("failure".equals(request.getAttribute("jobid").toString())) {
String errorCode = (String) request
.getAttribute("errorcode");
actionErrors.add(ActionMessages.GLOBAL_MESSAGE,
new ActionMessage(errorCode));
saveErrors(request, (ActionMessages) actionErrors);
} else {
actionErrors.add(ActionMessages.GLOBAL_MESSAGE,
new ActionMessage(CConstant.AGGR_QUEUE_SUCCESS,
jobId));
messages.add(actionErrors);
saveMessages(request, messages);
}
}
} catch (BusinessServiceException businessServiceException) {
processBusinessServiceException(businessServiceException, request);
checkFlag = false;
}
return mapping.findForward(CConstant.ACTION_FORWARD_SUCCESS);
}
I have also written a Rest Controller Code for this Action file but I am not sure If I am going right -
public class LeavesController {
#Autowired
private LumpConfigManager lumpConfigManager;
#GetMapping
public ResponseEntity<List<LumpConfigVO>> getAllLeaves(HttpServletRequest request) {
try {
LumpConfigVO lumpConfigVO = new LumpConfigVO();
if ((null == workContext.getCarparkPK())
|| "".equals(workContext.getCarparkPK())) {
throw new BusinessServiceException(CPRMSConstant.NO_CARPARK_ERROR);
}
populateLumpConfigVO(lumpConfigFB, lumpConfigVO);
lumpConfigManager.displayAllLeaves(lumpConfigVO);
if (((null != lumpConfigVO.getMappedLumpDefList()) && (lumpConfigVO
.getMappedLumpDefList().size() > 0))
|| ((null != lumpConfigVO.getUnmappedLumpDefList()) && (lumpConfigVO
.getUnmappedLumpDefList().size() > 0))) {
List<LumpConfigVO> mappedLumpDefList = lumpConfigVO
.getMappedLumpDefList();
HashMap<String, LumpConfigVO> lumpNameMap = new HashMap<String, LumpConfigVO>();
List<String> lumpNameList = new ArrayList<String>();
if (null != mappedLumpDefList && mappedLumpDefList.size() > 0) {
for (LumpConfigVO configVO : mappedLumpDefList) {
lumpNameList.add(configVO.getLumpName());
lumpNameMap.put(configVO.getLumpName(), configVO);
}
mappedLumpDefList.clear();
Collections.sort(lumpNameList,
String.CASE_INSENSITIVE_ORDER);
for (String lumpName : lumpNameList) {
mappedLumpDefList.add(lumpNameMap.get(lumpName));
}
}
List<LumpConfigVO> unMappedLumpDefList = lumpConfigVO
.getUnmappedLumpDefList();
if (null != unMappedLumpDefList
&& unMappedLumpDefList.size() > 0) {
Collections.sort(unMappedLumpDefList, new LumpComparator());
}
return ResponseEntity.ok(lumpConfigVO);
} else {
throw new BusinessServiceException(CPRMSConstant.LEAF_NOT_FOUND_ERROR);
}
} catch (BusinessServiceException businessServiceException) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, businessServiceException.getMessage(), businessServiceException);
}
}
// helper method for populating LumpConfigVO from LumpConfigFB
private void populateLumpConfigVO(LumpConfigFB lumpConfigFB, LumpConfigVO lumpConfigVO) {
// implementation here
}
// helper method for storing product without DNA to request
private void storeProductWithoutDNAToRequest(HttpServletRequest request) {
// implementation here
}
// other helper methods and properties omitted
}

TaskContinuation.cs not found exception while accessing WebAPI Task

I'm trying to fetch records from a db cursor from the Client app.
Debugging Web API shows that the Cursor returns records but when returning to the Client it throws mscorlib.pdb not loaded window and clicking on Load option it throws TaskContinuation.cs not found exception
Code snippets as below ( removed irrelevant codes for readability )
WebAPI
[HttpPost("{values}")]
public async Task<ActionResult> Post([FromBody] JToken values)
{
// code removed for readility
string[] cursors = { };
cursors = await cursor.GetRpts();
CursorClass firstCursor = JsonConvert.DeserializeObject<CursorClass>(cursors[0]);
return new OkObjectResult(cursors);
}
public async Task<string[]> GetRpts()
{
try
{
DataTable[] dataTables;
CursorClass[] cursorClasses = new CursorClass[5];
//stripped some code
using (DataAccess dataAccess = new DataAccess()
{
ParamData = PrepareDoc(),
ProcedureName = Constants.Rpt,
RecordSets = this.CursorNumbers,
})
{
Int32 errorNumber = await dataAccess.RunComAsync();
dataTables = dataAccess.TableData;
};
//fetching code stripped off
string[] _cursors = Array.ConvertAll(cursorClasses, JsonConvert.SerializeObject);
return _cursors;
}
catch (Exception ex)
{
string tt = ex.Message;
}
}
public async Task<Int32> RunComAsync()
{
Int32 returnValue = 0;
try
{
//open db connection
//---------- Running the Command in asysnc mode ----------
Task<int> task = new Task<int>(oracleCommand.ExecuteNonQuery);
task.Start();
returnValue = await task;
//--------------------------------------------------------
OracleRefCursor[] refCursor = { null, null, null, null, null };
for (int _sub = 0; _sub < RecordSets; _sub++)
{
//DT declaration / connection code removed
dataAdapter.Fill(dataTable, refCursor[_sub]);
TableData[_sub] = dataTable;
}
}
catch (Exception ex)
{
return LogMsg(ex);
}
finally
{
this.Dispose(true);
}
CloseConnection();
return LogMsg(null,"Successful Operation");
}
Client
private async Task<HttpStatusCode> CallService()
{
HttpResponseMessage _response = null;
try
{
using (HttpRequestMessage requestMessage = new HttpRequestMessage()
{
Content = new System.Net.Http.StringContent(JsonRepo, System.Text.Encoding.UTF8, HeaderJson),
RequestUri = new Uri(UriString),
Method = HttpMethod.Post,
})
{
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", Utils.TOKEN) ;
_response = await httpClient.SendAsync(requestMessage);
if (_response.IsSuccessStatusCode)
{
string httpResponse = await _response.Content.ReadAsStringAsync();
httpString = JsonConvert.DeserializeObject<string[]>(httpResponse);
}
}
}
return ErrorCode;
}
Is that something related to async operation? while debugging the API it confirms the Datatable with records . Any inputs are deeply appreciated.
error image
TIA

.NET MVC Web API Upload file to local storage and data model to database

I want to upload a file and pass the model with it. But when I try it from postman, it Always bring error.
Here is my code
public async Task<IHttpActionResult> PostArPumPd([FromBody] tx_arPumPd pum)
{
try
{
if (pum == null)
{
return Content(HttpStatusCode.BadRequest, "Enter the data correctly");
}
else
{
tx_arPumPd arpumpds = new tx_arPumPd()
{
doc_no = doc,
doc_date = DateTime.Now,
descs = pum.descs,
currency_code = pum.currency_code,
amount = pum.amount,
employee_code = pum.employee_code,
head_code = pum.head_code,
company_code = pum.company_code,
created_by = pum.emp_code,
created_date = DateTime.Now
};
db.tx_arPumPd.Add(arpumpds);
var multiFormDataStreamProvider = new MultiFileUploadProvider(Constants.MEDIA_PATH);
var mod = "PP";
var newFileName = mod + "_" + doc;
await Request.Content.ReadAsMultipartAsync(multiFormDataStreamProvider);
try
{
await FileHelper.Upload(multiFormDataStreamProvider, mod, newFileName);
db.SaveChanges();
return Content(HttpStatusCode.Created, "Data was save");
}
catch (Exception ex)
{
return Content(HttpStatusCode.BadRequest, ex);
}
}
}
catch (Exception ex)
{
return Content(HttpStatusCode.BadRequest, ex);
}
}
I get an Error while i get to this part
await Request.Content.ReadAsMultipartAsync(multiFormDataStreamProvider);
This is the error
ioexception: unexpected end of mime multipart stream. mime multipart
message is not complete test with postman
Is there anyone who know why? And Help me to upload file and the data model?
Thank you very much for your help
Okay I found the answer. To save a file and the Form data, i'm not parse the model. I'm just send the data from postmant using form data and the value is Json data. So I read the request from ReadAsMultipartAsync and get the Json data, and then deserilize the json. After that we can save the data.
This how I send the data from postmant
Postmant
and this is the code
public async Task<IHttpActionResult> PostArPumPd()
{
try
{
var multiFormDataStreamProvider = new MultiFileUploadProvider(Constants.MEDIA_PATH);
var readToProvider = await Request.Content.ReadAsMultipartAsync(multiFormDataStreamProvider);
// Get Json Data and Deserialize it
var json = await readToProvider.Contents[0].ReadAsStringAsync();
tx_arPumPd a = JsonConvert.DeserializeObject<tx_arPumPd>(json);
// Set mod and file name for FileHelper classl
var mod = "PP";
var newFileName = mod + "_" + doc ;
tx_arPumPd arpumpds = new tx_arPumPd()
{
doc_no = doc,
doc_date = DateTime.Now,
descs = a.descs,
currency_code = a.currency_code,
amount = a.amount,
employee_code = a.employee_code,
head_code = a.head_code,
company_code = a.company_code,
created_by = a.emp_code,
created_date = DateTime.Now
};
db.tx_arPumPd.Add(arpumpds);
var dtl = a.tx_arPumPdDtl;
foreach (var item in dtl)
{
item.doc_no = doc;
item.bg_is_ok = true;
item.bg_approved = true;
item.bg_app_date = DateTime.Now;
item.created_by = a.emp_Code;
item.created_date = DateTime.Now;
db.tx_arPumPdDtl.Add(item);
}
try
{
await FileHelper.Upload(multiFormDataStreamProvider, mod, newFileName);
db.SaveChanges();
return Content(HttpStatusCode.Created, "Data was save");
}
catch (Exception ex)
{
return Content(HttpStatusCode.BadRequest, ex);
}
}
catch (Exception ex)
{
return Content(HttpStatusCode.BadRequest, ex);
}
}
if anyone has a better way to do this, i'm still very happy getting to know about it.
Thank you.

calling my apex method in apex trigger getting the error

public static void insertInboundJive(Map<Id, String> mapCases){
try{
system.debug('Aditya');
Map<Id, String> mapCases1 = new Map<Id, String>();
Map<Id, Integer> mapIncrements = new Map<Id, Integer>();
//List<ICS_Case_Interaction__c> lstCaseInteraction;
if(mapCases != null && mapCases.size() > 0) {
List<ICS_Case_Interaction__c> lstCaseInteraction = [ SELECT Id,case__r.origin FROM ICS_Case_Interaction__c Where case__r.Id =:mapCases.keySet()];
for(ICS_Case_Interaction__c caseInteracts :lstCaseInteraction ){
if(caseInteracts.case__r.Id != null && caseInteracts.case__r.Status == 'New Customer Message'){
system.debug('**AdityaDebug**' +caseInteracts.case__r.Id);
system.debug('**AdityaDebug**' +caseInteracts.case__r.Status);
mapcases1.put(caseInteracts.case__r.Id , TYPE_JIVE_INBOUND);
Integer intIncrement = mapIncrements.get(caseInteracts.case__r.Id);
system.debug('Increment' +intIncrement);
if(intIncrement != null){
intIncrement++;
system.debug('Increment++' +intIncrement);
}
else {
intIncrement = 1;
}
mapIncrements.put(caseInteracts.case__r.Id, intIncrement);
}
}
if(mapCases.size() > 0) {
insertByCaseAsync(mapCases, mapIncrements);
}
}
}
catch(Exception ex){
Core_Log_Entry.logEntryWithException('Case Interaction Metrics', 'CaseInteraction','insertInboundEmail', 'Error', null, null, ex);
}
}
This is my Method in the class.I am trying to call the apex method in the trigger.but its throwing the error.Could you please help me and try to reach out the best.
The error which I am getting was
line 188, col 106. Method does not exist or incorrect signature: void insertInboundJive(List) from the type ICS_Case_Interactions_Trigger_Handler
if(trigger.isUpdate) {
if(Label.ICS_Case_Interaction_Metrics.equals('1')) {ICS_Case_Interactions_Trigger_Handler.insertInboundJive(trigger.new);}
}
You are trying to pass the wrong parameters. In the method you have defined that when called you need to pass a Map where the values are String however you are passing Trigger.new which is a list of Objects. My approach is to handle the mapping in the trigger and then manipulate data in the controller:
In this case you can do the below to pass the records and get the string of data you want in the controller.. or do it in the trigger so you don't change the controller.
Map<Id,Contact> map = new Map<Id,ICS_Case_Interaction__c>(); // new map
for(ICS_Case_Interaction__c con :trigger.new){
map.put(con.Id, con); // enter the records you need for the method
}
if(trigger.isUpdate) {
if(Label.ICS_Case_Interaction_Metrics.equals('1')) {
ICS_Case_Interactions_Trigger_Handler.insertInboundJive(map);
}
}
and in the controller you should have
public static void insertInboundJive(Map<Id, ICS_Case_Interaction__c> mapCases){
}

Spring mvc When using enctype="multipart/form-data" modelAttribute values equal null in the controller

I use spring mvc I want to uplaod image to jsp form so I add enctype="multipart/form-data" to the form tag but when i add this, modelAttribute values equals null in the controller
This is my form in jsp page:
<form:form action="saveContact" method="post" modelAttribute="Contacting" id="container" enctype="multipart/form-data">
This is the header of the function in controller:
#RequestMapping(value = "/saveContact", method = RequestMethod.POST)
public ModelAndView saveContact(#ModelAttribute ("Contacting") Contacting Contacting,ModelAndView modelndView,HttpServletRequest request ,HttpServletResponse response
) throws Exception {............}
#ModelAttribute ("Contacting") Contacting Contacting all values are null. and When I erease the enctype="multipart/form-data" from form tag its work well but I cant upload the image
this is the uplaud function:
public void uplaodImages(String url,HttpServletRequest request) {
// configures upload settings
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(THRESHOLD_SIZE);
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(MAX_FILE_SIZE);
upload.setSizeMax(MAX_REQUEST_SIZE);
String uuidValue = "";
FileItem itemFile = null;
try {
// parses the request's content to extract file data
List formItems = upload.parseRequest(request);
Iterator iter = formItems.iterator();
// iterates over form's fields to get UUID Value
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
if (item.getFieldName().equalsIgnoreCase(UUID_STRING)) {
uuidValue = item.getString();
}
}
// processes only fields that are not form fields
if (!item.isFormField()) {
itemFile = item;
}
}
if (itemFile != null) {
// get item inputstream to upload file into s3 aws
BasicAWSCredentials awsCredentials = new BasicAWSCredentials(AMAZON_ACCESS_KEY, AMAZON_SECRET_KEY);
AmazonS3 s3client = new AmazonS3Client(awsCredentials);
try {
ObjectMetadata om = new ObjectMetadata();
om.setContentLength(itemFile.getSize());
om.setContentType("image/png");
String ext = FilenameUtils.getExtension(itemFile.getName());
String keyName = uuidValue + '.' + ext;
// s3client.putObject(new PutObjectRequest(S3_BUCKET_NAME,"99/after/img", itemFile,st om));
// s3client.setObjectAcl(S3_BUCKET_NAME, "99/after/img", CannedAccessControlList.PublicRead);
TransferManager tm = new TransferManager(new ProfileCredentialsProvider());
System.out.println("Hello");
// TransferManager processes all transfers asynchronously,
// so this call will return immediately.
Upload upload1 = tm.upload(
S3_BUCKET_NAME, url, itemFile.getInputStream(),om);
System.out.println("Hello2");
try {
// Or you can block and wait for the upload to finish
upload1.waitForCompletion();
System.out.println("Upload complete.");
} catch (AmazonClientException amazonClientException) {
System.out.println("Unable to upload file, upload was aborted.");
amazonClientException.printStackTrace();
}
} catch (AmazonServiceException ase) {
// LOGGER.error(uuidValue + ":error:" + ase.getMessage());
} catch (AmazonClientException ace) {
//LOGGER.error(uuidValue + ":error:" + ace.getMessage());
}
} else {
//LOGGER.error(uuidValue + ":error:" + "No Upload file");
System.out.println("No Upload file");
}
} catch (Exception ex) {
//LOGGER.error(uuidValue + ":" + ":error: " + ex.getMessage());
System.out.println(ex.getMessage());
}
//LOGGER.info(uuidValue + ":Upload done");
System.out.println("Upload done");
}
#RequestMapping(value = "/form.html", method = RequestMethod.POST)
public String handleFormUpload(#RequestParam("name") String name,
#RequestParam("file") MultipartFile file) throws Exception {
}

Resources