0% found this document useful (0 votes)
86 views9 pages

Report Generation via Web Service

This document contains code for a Java class called RunReport that generates reports by calling a RWWebservice. It takes in an HTTP request and response, generates a report request parameter string, calls the web service to run the report job, parses the XML response, and returns an AjaxReportResponse object with status and other report details. It checks for authorization, gets the user ID and app name from the request, and has logic to handle success, waiting, and error status codes from the response.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
86 views9 pages

Report Generation via Web Service

This document contains code for a Java class called RunReport that generates reports by calling a RWWebservice. It takes in an HTTP request and response, generates a report request parameter string, calls the web service to run the report job, parses the XML response, and returns an AjaxReportResponse object with status and other report details. It checks for authorization, gets the user ID and app name from the request, and has logic to handle success, waiting, and error status codes from the response.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 9

package id.co.ahm.report.generator.

action;

import id.co.ahm.report.authorization.dao.AuthorizationDao;
import id.co.ahm.report.authorization.dao.UserSessionDao;
import id.co.ahm.report.generator.model.*;
import id.co.ahm.report.generator.util.*;
import org.apache.commons.lang.RandomStringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.springframework.http.HttpEntity;
import org.springframework.http.MediaType;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

/**
* Created with IntelliJ IDEA. User: andri.khrisharyadi Date: 10/23/13 Time:
* 1:19 PM
* <p/>
* Running Report Generator to call rwwebservice
*/
public class RunReport extends BaseActionServlet {

private UserSessionDao userSessionDao = new UserSessionDao();

/**
* call Rwwebservice to generate report
*
* @param request
* @param response
* @return
*/
private AjaxReportResponse generateReport(HttpServletRequest request,
HttpServletResponse response) {
AjaxReportResponse ajaxReportResponse = new AjaxReportResponse();

// // parameter type prop connection


// String propConn =
StringUtils.stringNvl(request.getParameter(Constants.ParamaterName.PROP),
Constants.REPORT_CONNECTION_DEFAULT);
//
// //check server yg aktif
// ServerHostname serverHostname = ServerUtils.checkActiveServer(
// propConn);
//
// if (serverHostname == null) {
// ajaxReportResponse.setStatusCode(Constants.StatusCode.ERROR_STATUS);
//
ajaxReportResponse.setErrorMessage(prop.getProperty("report.message.error.noserver"
));
// return ajaxReportResponse;
// }
//
// ReportRequest reportRequest = createReportParam(request, serverHostname);
//
// String param0 = reportRequest.generateReportRequestParam();
//
// //TODO : USE LOGGER
// //System.out.println("[WS PARAM0] " + param0);
// Boolean sync =
Boolean.parseBoolean(request.getParameter(Constants.ParamaterName.SYNC));
//
// String xmlResult = "";
// String filenameResult = "";
// String jobId = "";
//
// String vUserId = getSessionUserId(request);
//
// if (vUserId == null || vUserId.isEmpty()) {
// ajaxReportResponse.setStatusCode(Constants.StatusCode.ERROR_STATUS);
//
ajaxReportResponse.setErrorMessage(prop.getProperty("report.message.error.nouser"))
;
// return ajaxReportResponse;
// }
//
// //check authorization
// String reportName =
request.getParameter(Constants.ParamaterName.SOURCE_FILE);
// String jsessionid =
request.getParameter(Constants.ParamaterName.J_SESSION_ID);
// String appName = getAppName(reportName);
//
// System.out.println("APP NAME ===== : " + appName);
//
// if (!checkAuthorization(request, vUserId, appName)) {
// ajaxReportResponse.setStatusCode(Constants.StatusCode.ERROR_STATUS);
//
ajaxReportResponse.setErrorMessage(prop.getProperty("report.message.error.unauthori
zed")
// + "[" + appName + "]");
// return ajaxReportResponse;
// }
//
// String nameLdap = getNameLdap(request);
//
// ajaxReportResponse.setUsername(StringUtils.stringNvl(nameLdap, ""));
//
// //call rwwebservice report
// try {
// xmlResult =
ReportProxyUtil.getRWWebService(reportRequest.getHostname()).runJob(param0, true);
// // get statusCode
// String statusCode = ReportXmlParser.getStatusCode(xmlResult);
//
// jobId = ReportXmlParser.getJobId(xmlResult);
//
// //TODO : USE LOGGER
// //System.out.println("[XML RESULT] " + xmlResult);
// // jika tidak terjadi error saat create report
// if (statusCode != null && !statusCode.isEmpty()) {
//
// ajaxReportResponse.setStatusCode(statusCode);
//
// if (reportRequest.getDestType().equals(Constants.DestType.CACHE))
{
// filenameResult = ReportXmlParser.getDestFilename(xmlResult);
// } else //filenameResult = reportRequest.getDestFile();
// {
// filenameResult = reportRequest.getFilename();
// }
//
// //System.out.println("Filename : " + filenameResult);
// ajaxReportResponse.setJobId(jobId);
// ajaxReportResponse.setReportFileName(filenameResult);
// ajaxReportResponse.setProp(propConn);
//
ajaxReportResponse.setEmail(request.getParameter(Constants.ParamaterName.EMAIL));
//
ajaxReportResponse.setUrlRedirect(serverHostname.getUrlRedirect());
//
// if (statusCode.equals(Constants.StatusCode.SUCCESS_STATUS)) {
//
//
ajaxReportResponse.setErrorMessage(prop.getProperty("report.message.status.succces"
));
//
ajaxReportResponse.setFileType(request.getParameter(Constants.ParamaterName.DEST_FO
RMAT));
//
// String userEmail =
request.getParameter(Constants.ParamaterName.EMAIL);
//
// // kirim email report ke email user jika parameter emailnya
tidak kosong
// if (userEmail != null && !userEmail.isEmpty()) {
// //TODO : USE LOGGER
// //System.out.println("[MUST SEND MAIL] !");
//
//
sendMailtoUser(request.getParameter(Constants.ParamaterName.EMAIL),
// serverHostname.getUrlRedirect() +
filenameResult);
//
// } else {
// //TODO : USE LOGGER
// System.out.println("[SORRY, NO EMAIL PROVIDED] !");
// }
//
//////
//// // request url
//// final String url = "http://localhost:8080/execute";
//// // create an instance of RestTemplate
//// RestTemplate restTemplate = new RestTemplate();
//// // create headers
//// HttpHeaders headers = new HttpHeaders();
//// // set `Content-Type`
//// headers.setContentType(MediaType.APPLICATION_JSON);
//// //setting up the request body
//// Filepath filepath = new Filepath();
////// filepath.setFullpath(ajaxReportResponse.getUrlRedirect()
+ ajaxReportResponse.getReportFileName());
////
filepath.setFullpath("http://localhost:8086/ahmitsys064/test1.honda1");
//// //request entity is created with request body and headers
//// HttpEntity<Filepath> requestEntity = new
HttpEntity<>(filepath, headers);
//// ResponseEntity<String> responseEntity =
restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
//// responseEntity.getBody();
// } else if
(statusCode.equals(Constants.StatusCode.WAITING_IN_QUEUE_STATUS)) {
//
//
ajaxReportResponse.setErrorMessage(prop.getProperty("report.message.status.waiting"
));
//
// }
// } else { // jika terjadi error saat create report
// ReportErrorResponse errorResponse = new ReportErrorResponse();
// errorResponse = ReportXmlParser.getErrorResponse(xmlResult);
//
ajaxReportResponse.setStatusCode(Constants.StatusCode.ERROR_STATUS);
// ajaxReportResponse.setErrorMessage(errorResponse.getMessage());
// }
//
// } catch (Exception ex) { // jika terjadi kegagalan saat call rwWebservice
// //TODO : USE LOGGER
// System.out.println("[RWWebservice] Error " + ex.getMessage());
//
// ajaxReportResponse.setStatusCode(Constants.StatusCode.ERROR_STATUS);
// ajaxReportResponse.setErrorMessage(ex.getMessage());
// }
// delete session
//deleteSession(jsessionid);
ajaxReportResponse.setErrorMessage("Report Finished successfully");
ajaxReportResponse.setStatusCode(Constants.StatusCode.SUCCESS_STATUS);
ajaxReportResponse.setUrlRedirect("172.16.2.11:8081/ahmitsys064/");
ajaxReportResponse.setReportFileName("test1.honda1");
ajaxReportResponse.setFileType("honda1");

return ajaxReportResponse;
}

/**
* Get AppName
*
* @param request
* @return
*/
private String getAppName(String reportName) {
String appName = null;
//int titik = reportName.indexOf(".");
if (!reportName.isEmpty() || !reportName.equals("")) {
appName = substring(reportName, 8, 9); // Standard check
if (appName.equalsIgnoreCase("r")) { // Old standard
appName = substring(reportName, 0, 8) // Module name
+ substring(reportName, 9, 12); // Application number
} else { // New standard
if (reportName.lastIndexOf("\\") > -1) {
appName = substring(reportName, // D:\\data\\ahmXXYYYNNNrNN ==>
ahmXXYYYNNN
reportName.lastIndexOf("\\") + 1,
reportName.lastIndexOf("\\") + 12);
} else if (reportName.lastIndexOf("/") > -1) {
appName = substring(reportName, // /data/ahmXXYYYNNNrNN ==>
ahmXXYYYNNN
reportName.lastIndexOf("/") + 1,
reportName.lastIndexOf("/") + 12);
} else {
appName = substring(reportName, 0, 11); // Module name +
Application number
}
}
}

return appName;
}

/**
* create report parameter
*
* @param request
* @param serverHostname
* @return
*/
private ReportRequest createReportParam(HttpServletRequest request,
ServerHostname serverHostname) {

String destType =
StringUtils.stringNvl(request.getParameter(Constants.ParamaterName.DEST_TYPE),
Constants.DEFAULT_DEST_TYPE);

ReportRequest reportRequest = new ReportRequest();

//reportRequest.setHostname(prop.getProperty("report.server.host")
+":"+prop.getProperty("report.server.port"));
reportRequest.setHostname(serverHostname.getHostName() + ":" +
prop.getProperty("report.server.port"));

reportRequest.setReportServer(serverHostname.getServerName());

String sourceRdf =
request.getParameter(Constants.ParamaterName.SOURCE_FILE);
int titik = sourceRdf.indexOf(".");
if (titik > 0) {
try {
sourceRdf = sourceRdf.substring(0, titik);
} catch (Exception e) {
sourceRdf =
request.getParameter(Constants.ParamaterName.SOURCE_FILE);
}
}

// mengambil path source folder dari konfigurasi server

reportRequest.setSourceFile(propConnection.getProperty("report.source.folder")
+ sourceRdf + "." + Constants.DEFAULT_REPORT_EXT);
reportRequest.setDestType(destType);

String ext = request.getParameter(Constants.ParamaterName.DEST_FORMAT);

if (ext != null) {
//jika destFormatnya honda1 / honda2 maka akan langsung diarakan ke
dflt
if
(request.getParameter(Constants.ParamaterName.DEST_FORMAT).equalsIgnoreCase(Constan
ts.DestFormatType.HONDA_1)
||
request.getParameter(Constants.ParamaterName.DEST_FORMAT).equalsIgnoreCase(Constant
s.DestFormatType.HONDA_2)) {
reportRequest.setDestFormat(Constants.DestFormatType.DFLT);
} else {

reportRequest.setDestFormat(request.getParameter(Constants.ParamaterName.DEST_FORMA
T));
}
} else {
reportRequest.setDestFormat(Constants.DEFAULT_DEST_FORMAT);
}

//get connection report


ReportConnection connection =
ReportUtils.getReportConnection(request.getParameter(Constants.ParamaterName.PROP))
;
reportRequest.setConnectionStr(connection.getDbStringConnection());

//tambahkan userparameter jika ada di query String


reportRequest.setOtherParam(ReportUtils.getUserParams(request));

String filename = getDestinationFilename(request);

reportRequest.setDestFile(propConnection.getProperty("report.destination.folder") +
filename); // request.getParameter("destName"));
reportRequest.setFilename(filename);

return reportRequest;
}

/**
* Get File name
*
* @param request
* @return
*/
private String getDestinationFilename(HttpServletRequest request) {
if (request.getParameter(Constants.ParamaterName.DEST_NAME) != null && !
request.getParameter(Constants.ParamaterName.DEST_NAME).isEmpty()) {
return request.getParameter(Constants.ParamaterName.DEST_NAME);
} else {
String ext =
StringUtils.stringNvl(request.getParameter(Constants.ParamaterName.DEST_FORMAT),
Constants.DEFAULT_DEST_FORMAT);

if (ext.equals(Constants.DestFormatType.DFLT)) {
ext = Constants.FileExtension.HONDA1;
}

if (ext.equals(Constants.DestFormatType.SPREADSHEET)) {
ext = Constants.FileExtension.XLS;
}

String reportName =
ReportUtils.getFilenameWitoutExt(request.getParameter(Constants.ParamaterName.SOURC
E_FILE));

return (reportName != null ? reportName :


request.getParameter(Constants.ParamaterName.SOURCE_FILE))
+ "_" + UUID.randomUUID() + "."
+ ext;
}
}

/**
* Check Authorization
*
* @param request
* @param userId
* @return
*/
private Boolean checkAuthorization(HttpServletRequest request, String userId,
String appName) {
AuthorizationDao authorizationDao = new AuthorizationDao();
Boolean authorized = authorizationDao.getAuthorizationJPA(
request.getParameter(Constants.ParamaterName.V_MODULE_NAME),
appName, userId
);
return authorized;
}

/**
* Get User id by
*
* @param request by session id
* @return
*/
private String getSessionUserId(HttpServletRequest request) {

String userId =
userSessionDao.getVUserId(request.getParameter(Constants.ParamaterName.J_SESSION_ID
));

return userId;
}

/**
* Get nama ldap form JSessionId
*
* @param request
* @return
*/
private String getNameLdap(HttpServletRequest request) {
return userSessionDao.getUsernameLdapFromSession(request.getParameter(
Constants.ParamaterName.J_SESSION_ID));
}
/**
*
* @param request
*/
private void deleteSession(String jsessionid) {
userSessionDao.deleteSession(jsessionid);
}

/**
* Send a email
*
* @param mailTo
* @param urlReport
*/
private void sendMailtoUser(final String mailTo, final String urlReport) {

ExecutorService executor = Executors.newFixedThreadPool(1);

Runnable worker = new SendMailReportWorker(mailTo, urlReport);


executor.execute(worker);

// This will make the executor accept no new threads


// and finish all existing threads in the queue
executor.shutdown();
// Wait until all threads are finish

//TODO : USE LOGGER


//System.out.println("Finished all threads ; send email on RunReport()");
}

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

instantiateProperties();
instantiateProperties(request);
AjaxReportResponse result = generateReport(request, response);

writeResultToJson(request, response, result);


}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

instantiateProperties();
instantiateProperties(request);
AjaxReportResponse result = generateReport(request, response);

writeResultToJson(request, response, result);


}

/**
* Substring string
*
* @param sourceData
* @param beginIndex
* @param endIndex
* @return
*/
public static String substring(String sourceData, int beginIndex, int endIndex)
{
int length = 0;
try {
if (sourceData == null) {
return "";
} else {
length = sourceData.length();
return sourceData.substring(beginIndex, endIndex);
}
} catch (StringIndexOutOfBoundsException sex) {
if ((beginIndex >= length) || (endIndex <= 0)) {
return "";
} else if ((beginIndex < 0) && (endIndex > length)) {
return sourceData;
} else if ((beginIndex < 0) && (endIndex <= length)) {
return substring(sourceData, 0, endIndex);
} else if (endIndex > length) {
return substring(sourceData, beginIndex, length);
} else {
throw sex;
}
}
}

You might also like