From 934cc0ca4758158edd9ab146f3292069cc8c913f Mon Sep 17 00:00:00 2001 From: John Woodlock Date: Mon, 14 May 2012 16:43:52 +1000 Subject: [PATCH] WIP refactor api - export csv refactorings --- .../org/mifosng/ui/CommonRestOperations.java | 7 +- .../mifosng/ui/CommonRestOperationsImpl.java | 460 +++++++++--------- .../mifosng/ui/user/ExportCSVController.java | 159 ------ ...ing-0.96.js => stretchyreporting-0.965.js} | 11 +- .../views/common-head-stretchyreporting.jsp | 2 +- .../WEB-INF/views/reports/flexireport.jsp | 2 +- .../ReadExtraDataAndReportingService.java | 6 + .../ReadExtraDataAndReportingServiceImpl.java | 87 ++++ .../platform/api/ExportCSVController.java | 171 ------- .../platform/api/ReportingApiResource.java | 182 ++++--- 10 files changed, 433 insertions(+), 654 deletions(-) delete mode 100644 mifosng-individual-lending-app/src/main/java/org/mifosng/ui/user/ExportCSVController.java rename mifosng-individual-lending-app/src/main/webapp/WEB-INF/static/stretchyreporting/{stretchyreporting-0.96.js => stretchyreporting-0.965.js} (99%) delete mode 100644 mifosng-provider/src/main/java/org/mifosng/platform/api/ExportCSVController.java diff --git a/mifosng-individual-lending-app/src/main/java/org/mifosng/ui/CommonRestOperations.java b/mifosng-individual-lending-app/src/main/java/org/mifosng/ui/CommonRestOperations.java index c32e2755f..8373fe62f 100644 --- a/mifosng-individual-lending-app/src/main/java/org/mifosng/ui/CommonRestOperations.java +++ b/mifosng-individual-lending-app/src/main/java/org/mifosng/ui/CommonRestOperations.java @@ -1,7 +1,6 @@ package org.mifosng.ui; import java.util.Collection; -import java.util.Map; import org.mifosng.data.AppUserData; import org.mifosng.data.ClientData; @@ -28,7 +27,6 @@ import org.mifosng.data.command.SubmitLoanApplicationCommand; import org.mifosng.data.command.UndoLoanApprovalCommand; import org.mifosng.data.command.UndoLoanDisbursalCommand; import org.mifosng.data.command.UserCommand; -import org.mifosng.data.reports.GenericResultset; import org.springframework.security.oauth.consumer.ProtectedResourceDetails; public interface CommonRestOperations { @@ -125,7 +123,6 @@ public interface CommonRestOperations { LoanAccountData retrieveLoanAccount(Long loanId); - GenericResultset retrieveReportingData(String rptDB, String name, String type, Map extractedQueryParams); - - NewLoanWorkflowStepOneData retrieveNewLoanApplicationDetails(Long clientId, Long productId); + NewLoanWorkflowStepOneData retrieveNewLoanApplicationDetails(Long clientId, + Long productId); } \ No newline at end of file diff --git a/mifosng-individual-lending-app/src/main/java/org/mifosng/ui/CommonRestOperationsImpl.java b/mifosng-individual-lending-app/src/main/java/org/mifosng/ui/CommonRestOperationsImpl.java index 119c2444a..b90ada836 100644 --- a/mifosng-individual-lending-app/src/main/java/org/mifosng/ui/CommonRestOperationsImpl.java +++ b/mifosng-individual-lending-app/src/main/java/org/mifosng/ui/CommonRestOperationsImpl.java @@ -1,12 +1,9 @@ package org.mifosng.ui; -import java.io.UnsupportedEncodingException; import java.net.URI; -import java.net.URLEncoder; import java.util.ArrayList; import java.util.Collection; import java.util.List; -import java.util.Map; import org.mifosng.configuration.ApplicationConfigurationService; import org.mifosng.data.AppUserData; @@ -43,7 +40,6 @@ import org.mifosng.data.command.SubmitLoanApplicationCommand; import org.mifosng.data.command.UndoLoanApprovalCommand; import org.mifosng.data.command.UndoLoanDisbursalCommand; import org.mifosng.data.command.UserCommand; -import org.mifosng.data.reports.GenericResultset; import org.mifosng.ui.loanproduct.ClientValidationException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpEntity; @@ -59,28 +55,33 @@ import org.springframework.web.client.HttpStatusCodeException; import com.thoughtworks.xstream.XStream; -@Service(value="commonRestOperations") +@Service(value = "commonRestOperations") public class CommonRestOperationsImpl implements CommonRestOperations { - + private OAuthRestTemplate oauthRestServiceTemplate; private final ApplicationConfigurationService applicationConfigurationService; @Autowired public CommonRestOperationsImpl( - final OAuthRestTemplate oauthRestServiceTemplate, final ApplicationConfigurationService applicationConfigurationService) { + final OAuthRestTemplate oauthRestServiceTemplate, + final ApplicationConfigurationService applicationConfigurationService) { this.oauthRestServiceTemplate = oauthRestServiceTemplate; this.applicationConfigurationService = applicationConfigurationService; } - + private String getBaseServerUrl() { - return this.applicationConfigurationService.retrieveOAuthProviderDetails().getProviderBaseUrl(); + return this.applicationConfigurationService + .retrieveOAuthProviderDetails().getProviderBaseUrl(); } - + @Override public void logout(String accessToken) { - URI restUri = URI.create(getBaseServerUrl().concat("api/protected/user/").concat(accessToken).concat("/signout")); + URI restUri = URI.create(getBaseServerUrl() + .concat("api/protected/user/").concat(accessToken) + .concat("/signout")); - oauthRestServiceTemplate.exchange(restUri, HttpMethod.GET, emptyRequest(), null); + oauthRestServiceTemplate.exchange(restUri, HttpMethod.GET, + emptyRequest(), null); } @Override @@ -101,8 +102,8 @@ public class CommonRestOperationsImpl implements CommonRestOperations { @Override public Collection retrieveAllIndividualClients() { - URI restUri = URI - .create(getBaseServerUrl().concat("api/protected/client/all")); + URI restUri = URI.create(getBaseServerUrl().concat( + "api/protected/client/all")); ResponseEntity s = this.oauthRestServiceTemplate.exchange( restUri, HttpMethod.GET, emptyRequest(), ClientList.class); @@ -112,8 +113,8 @@ public class CommonRestOperationsImpl implements CommonRestOperations { @Override public Collection retrieveAllLoanProducts() { - URI restUri = URI - .create(getBaseServerUrl().concat("api/protected/product/loan/all")); + URI restUri = URI.create(getBaseServerUrl().concat( + "api/protected/product/loan/all")); ResponseEntity s = this.oauthRestServiceTemplate .exchange(restUri, HttpMethod.GET, emptyRequest(), @@ -122,22 +123,22 @@ public class CommonRestOperationsImpl implements CommonRestOperations { return s.getBody().getProducts(); } - - private ErrorResponseList parseErrors(HttpStatusCodeException e) { - + XStream xstream = new XStream(); xstream.alias("errorResponseList", ErrorResponseList.class); xstream.alias("errorResponse", ErrorResponse.class); - + ErrorResponseList errorList = new ErrorResponseList(); if (HttpStatus.BAD_REQUEST.equals(e.getStatusCode())) { - errorList = (ErrorResponseList)xstream.fromXML(e.getResponseBodyAsString()); - } else if (HttpStatus.NOT_FOUND.equals(e.getStatusCode())){ - + errorList = (ErrorResponseList) xstream.fromXML(e + .getResponseBodyAsString()); + } else if (HttpStatus.NOT_FOUND.equals(e.getStatusCode())) { + List errors = new ArrayList(); - errors.add(new ErrorResponse(e.getMessage(), "error", e.getMessage())); - + errors.add(new ErrorResponse(e.getMessage(), "error", e + .getMessage())); + errorList = new ErrorResponseList(errors); } else if (HttpStatus.UNAUTHORIZED.equals(e.getStatusCode())) { throw new AccessDeniedException(e.getMessage()); @@ -151,8 +152,8 @@ public class CommonRestOperationsImpl implements CommonRestOperations { public LoanSchedule calculateLoanSchedule( final CalculateLoanScheduleCommand command) { try { - URI restUri = URI - .create(getBaseServerUrl().concat("api/protected/loan/calculate")); + URI restUri = URI.create(getBaseServerUrl().concat( + "api/protected/loan/calculate")); ResponseEntity s = this.oauthRestServiceTemplate .exchange(restUri, HttpMethod.POST, @@ -165,34 +166,43 @@ public class CommonRestOperationsImpl implements CommonRestOperations { throw new ClientValidationException(errorList.getErrors()); } } - + @Override - public NewLoanWorkflowStepOneData retrieveNewLoanApplicationStepOneDetails(final Long clientId) { + public NewLoanWorkflowStepOneData retrieveNewLoanApplicationStepOneDetails( + final Long clientId) { try { - URI restUri = URI.create(getBaseServerUrl().concat("api/protected/loan/new/" + clientId.toString() + "/workflow/one")); + URI restUri = URI.create(getBaseServerUrl().concat( + "api/protected/loan/new/" + clientId.toString() + + "/workflow/one")); ResponseEntity s = this.oauthRestServiceTemplate - .exchange(restUri, HttpMethod.GET, emptyRequest(), NewLoanWorkflowStepOneData.class); - - // for now ensure user must select product on step one (even if there is only one product!) + .exchange(restUri, HttpMethod.GET, emptyRequest(), + NewLoanWorkflowStepOneData.class); + + // for now ensure user must select product on step one (even if + // there is only one product!) NewLoanWorkflowStepOneData data = s.getBody(); data.setProductId(null); - + return s.getBody(); } catch (HttpStatusCodeException e) { ErrorResponseList errorList = parseErrors(e); throw new ClientValidationException(errorList.getErrors()); } } - @Override - public NewLoanWorkflowStepOneData retrieveNewLoanApplicationDetails(Long clientId, Long productId) { + public NewLoanWorkflowStepOneData retrieveNewLoanApplicationDetails( + Long clientId, Long productId) { try { - URI restUri = URI.create(getBaseServerUrl().concat("api/protected/loan/new/" + clientId.toString() + "/product/" + productId.toString())); + URI restUri = URI.create(getBaseServerUrl().concat( + "api/protected/loan/new/" + clientId.toString() + + "/product/" + productId.toString())); + + ResponseEntity s = this.oauthRestServiceTemplate + .exchange(restUri, HttpMethod.GET, emptyRequest(), + NewLoanWorkflowStepOneData.class); - ResponseEntity s = this.oauthRestServiceTemplate.exchange(restUri, HttpMethod.GET, emptyRequest(), NewLoanWorkflowStepOneData.class); - return s.getBody(); } catch (HttpStatusCodeException e) { ErrorResponseList errorList = parseErrors(e); @@ -203,8 +213,8 @@ public class CommonRestOperationsImpl implements CommonRestOperations { @Override public Long submitLoanApplication(final SubmitLoanApplicationCommand command) { try { - URI restUri = URI - .create(getBaseServerUrl().concat("api/protected/loan/new")); + URI restUri = URI.create(getBaseServerUrl().concat( + "api/protected/loan/new")); ResponseEntity s = this.oauthRestServiceTemplate .postForEntity(restUri, @@ -217,14 +227,17 @@ public class CommonRestOperationsImpl implements CommonRestOperations { throw new ClientValidationException(errorList.getErrors()); } } - + @Override public EntityIdentifier deleteLoan(Long loanId) { try { - URI restUri = URI.create(getBaseServerUrl().concat("api/protected/loan/").concat(loanId.toString())); + URI restUri = URI.create(getBaseServerUrl().concat( + "api/protected/loan/").concat(loanId.toString())); + + ResponseEntity s = this.oauthRestServiceTemplate + .exchange(restUri, HttpMethod.DELETE, null, + EntityIdentifier.class); - ResponseEntity s = this.oauthRestServiceTemplate.exchange(restUri, HttpMethod.DELETE, null, EntityIdentifier.class); - return s.getBody(); } catch (HttpStatusCodeException e) { ErrorResponseList errorList = parseErrors(e); @@ -235,8 +248,8 @@ public class CommonRestOperationsImpl implements CommonRestOperations { @Override public EntityIdentifier approveLoan(final LoanStateTransitionCommand command) { try { - URI restUri = URI - .create(getBaseServerUrl().concat("api/protected/loan/approve")); + URI restUri = URI.create(getBaseServerUrl().concat( + "api/protected/loan/approve")); ResponseEntity s = this.oauthRestServiceTemplate .postForEntity(restUri, @@ -254,8 +267,8 @@ public class CommonRestOperationsImpl implements CommonRestOperations { public EntityIdentifier undoLoanApproval( final UndoLoanApprovalCommand command) { try { - URI restUri = URI - .create(getBaseServerUrl().concat("api/protected/loan/undoapproval")); + URI restUri = URI.create(getBaseServerUrl().concat( + "api/protected/loan/undoapproval")); ResponseEntity s = this.oauthRestServiceTemplate .postForEntity(restUri, undoLoanApprovalRequest(command), @@ -271,8 +284,8 @@ public class CommonRestOperationsImpl implements CommonRestOperations { @Override public EntityIdentifier rejectLoan(final LoanStateTransitionCommand command) { try { - URI restUri = URI - .create(getBaseServerUrl().concat("api/protected/loan/reject")); + URI restUri = URI.create(getBaseServerUrl().concat( + "api/protected/loan/reject")); ResponseEntity s = this.oauthRestServiceTemplate .postForEntity(restUri, @@ -287,10 +300,11 @@ public class CommonRestOperationsImpl implements CommonRestOperations { } @Override - public EntityIdentifier withdrawLoan(final LoanStateTransitionCommand command) { + public EntityIdentifier withdrawLoan( + final LoanStateTransitionCommand command) { try { - URI restUri = URI - .create(getBaseServerUrl().concat("api/protected/loan/withdraw")); + URI restUri = URI.create(getBaseServerUrl().concat( + "api/protected/loan/withdraw")); ResponseEntity s = this.oauthRestServiceTemplate .postForEntity(restUri, @@ -305,10 +319,11 @@ public class CommonRestOperationsImpl implements CommonRestOperations { } @Override - public EntityIdentifier disburseLoan(final LoanStateTransitionCommand command) { + public EntityIdentifier disburseLoan( + final LoanStateTransitionCommand command) { try { - URI restUri = URI - .create(getBaseServerUrl().concat("api/protected/loan/disburse")); + URI restUri = URI.create(getBaseServerUrl().concat( + "api/protected/loan/disburse")); ResponseEntity s = this.oauthRestServiceTemplate .postForEntity(restUri, @@ -326,8 +341,8 @@ public class CommonRestOperationsImpl implements CommonRestOperations { public EntityIdentifier undloLoanDisbursal( final UndoLoanDisbursalCommand command) { try { - URI restUri = URI - .create(getBaseServerUrl().concat("api/protected/loan/undodisbursal")); + URI restUri = URI.create(getBaseServerUrl().concat( + "api/protected/loan/undodisbursal")); ResponseEntity s = this.oauthRestServiceTemplate .postForEntity(restUri, undoLoanDisbursalRequest(command), @@ -339,11 +354,13 @@ public class CommonRestOperationsImpl implements CommonRestOperations { throw new ClientValidationException(errorList.getErrors()); } } - + @Override public LoanRepaymentData retrieveNewLoanRepaymentDetails(Long loanId) { try { - URI restUri = URI.create(getBaseServerUrl().concat("api/protected/loan/").concat(loanId.toString()).concat("/repayment/")); + URI restUri = URI.create(getBaseServerUrl() + .concat("api/protected/loan/").concat(loanId.toString()) + .concat("/repayment/")); ResponseEntity s = this.oauthRestServiceTemplate .exchange(restUri, HttpMethod.GET, emptyRequest(), @@ -357,9 +374,12 @@ public class CommonRestOperationsImpl implements CommonRestOperations { } @Override - public LoanRepaymentData retrieveLoanRepaymentDetails(Long loanId, Long repaymentId) { + public LoanRepaymentData retrieveLoanRepaymentDetails(Long loanId, + Long repaymentId) { try { - URI restUri = URI.create(getBaseServerUrl().concat("api/protected/loan/").concat(loanId.toString()).concat("/repayment/").concat(repaymentId.toString())); + URI restUri = URI.create(getBaseServerUrl() + .concat("api/protected/loan/").concat(loanId.toString()) + .concat("/repayment/").concat(repaymentId.toString())); ResponseEntity s = this.oauthRestServiceTemplate .exchange(restUri, HttpMethod.GET, emptyRequest(), @@ -373,10 +393,11 @@ public class CommonRestOperationsImpl implements CommonRestOperations { } @Override - public EntityIdentifier makeLoanRepayment(final LoanTransactionCommand command) { + public EntityIdentifier makeLoanRepayment( + final LoanTransactionCommand command) { try { - URI restUri = URI - .create(getBaseServerUrl().concat("api/protected/loan/repayment")); + URI restUri = URI.create(getBaseServerUrl().concat( + "api/protected/loan/repayment")); ResponseEntity s = this.oauthRestServiceTemplate .postForEntity(restUri, loanTransactionRequest(command), @@ -388,15 +409,17 @@ public class CommonRestOperationsImpl implements CommonRestOperations { throw new ClientValidationException(errorList.getErrors()); } } - + @Override - public EntityIdentifier adjustLoanRepayment(AdjustLoanTransactionCommand command) { + public EntityIdentifier adjustLoanRepayment( + AdjustLoanTransactionCommand command) { try { - URI restUri = URI - .create(getBaseServerUrl().concat("api/protected/loan/repayment/adjust")); + URI restUri = URI.create(getBaseServerUrl().concat( + "api/protected/loan/repayment/adjust")); ResponseEntity s = this.oauthRestServiceTemplate - .postForEntity(restUri, adjustLoanRepaymentRequest(command), + .postForEntity(restUri, + adjustLoanRepaymentRequest(command), EntityIdentifier.class); return s.getBody(); @@ -405,11 +428,13 @@ public class CommonRestOperationsImpl implements CommonRestOperations { throw new ClientValidationException(errorList.getErrors()); } } - + @Override public LoanRepaymentData retrieveNewLoanWaiverDetails(Long loanId) { try { - URI restUri = URI.create(getBaseServerUrl().concat("api/protected/loan/").concat(loanId.toString()).concat("/waive/")); + URI restUri = URI.create(getBaseServerUrl() + .concat("api/protected/loan/").concat(loanId.toString()) + .concat("/waive/")); ResponseEntity s = this.oauthRestServiceTemplate .exchange(restUri, HttpMethod.GET, emptyRequest(), @@ -425,8 +450,8 @@ public class CommonRestOperationsImpl implements CommonRestOperations { @Override public EntityIdentifier waiveLoanAmount(LoanTransactionCommand command) { try { - URI restUri = URI - .create(getBaseServerUrl().concat("api/protected/loan/waive")); + URI restUri = URI.create(getBaseServerUrl().concat( + "api/protected/loan/waive")); ResponseEntity s = this.oauthRestServiceTemplate .postForEntity(restUri, loanTransactionRequest(command), @@ -438,22 +463,24 @@ public class CommonRestOperationsImpl implements CommonRestOperations { throw new ClientValidationException(errorList.getErrors()); } } - - private HttpEntity loanTransactionRequest(final LoanTransactionCommand command) { + + private HttpEntity loanTransactionRequest( + final LoanTransactionCommand command) { HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.set("Accept", "application/xml"); requestHeaders.set("Content-Type", "application/xml"); return new HttpEntity(command, requestHeaders); } - + private HttpEntity adjustLoanRepaymentRequest( final AdjustLoanTransactionCommand command) { HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.set("Accept", "application/xml"); requestHeaders.set("Content-Type", "application/xml"); - return new HttpEntity(command, requestHeaders); + return new HttpEntity(command, + requestHeaders); } private HttpEntity undoLoanDisbursalRequest( @@ -480,7 +507,8 @@ public class CommonRestOperationsImpl implements CommonRestOperations { requestHeaders.set("Accept", "application/xml"); requestHeaders.set("Content-Type", "application/xml"); - return new HttpEntity(command, requestHeaders); + return new HttpEntity(command, + requestHeaders); } private HttpEntity submitLoanApplicationRequest( @@ -502,12 +530,12 @@ public class CommonRestOperationsImpl implements CommonRestOperations { return new HttpEntity(command, requestHeaders); } - + @Override public EntityIdentifier createUser(final UserCommand command) { try { - URI restUri = URI - .create(getBaseServerUrl().concat("api/protected/admin/user/new")); + URI restUri = URI.create(getBaseServerUrl().concat( + "api/protected/admin/user/new")); ResponseEntity s = this.oauthRestServiceTemplate .postForEntity(restUri, createUserRequest(command), @@ -519,12 +547,13 @@ public class CommonRestOperationsImpl implements CommonRestOperations { throw new ClientValidationException(errorList.getErrors()); } } - + @Override public EntityIdentifier updateUser(UserCommand command) { try { - URI restUri = URI - .create(getBaseServerUrl().concat("api/protected/admin/user/").concat(command.getId().toString())); + URI restUri = URI.create(getBaseServerUrl().concat( + "api/protected/admin/user/").concat( + command.getId().toString())); ResponseEntity s = this.oauthRestServiceTemplate .postForEntity(restUri, createUserRequest(command), @@ -536,12 +565,12 @@ public class CommonRestOperationsImpl implements CommonRestOperations { throw new ClientValidationException(errorList.getErrors()); } } - + @Override public EntityIdentifier updateCurrentUserDetails(UserCommand command) { try { - URI restUri = URI - .create(getBaseServerUrl().concat("api/protected/admin/user/current")); + URI restUri = URI.create(getBaseServerUrl().concat( + "api/protected/admin/user/current")); ResponseEntity s = this.oauthRestServiceTemplate .postForEntity(restUri, createUserRequest(command), @@ -553,15 +582,17 @@ public class CommonRestOperationsImpl implements CommonRestOperations { throw new ClientValidationException(errorList.getErrors()); } } - + @Override - public EntityIdentifier updateCurrentUserPassword(ChangePasswordCommand command) { + public EntityIdentifier updateCurrentUserPassword( + ChangePasswordCommand command) { try { - URI restUri = URI - .create(getBaseServerUrl().concat("api/protected/admin/user/current/password")); + URI restUri = URI.create(getBaseServerUrl().concat( + "api/protected/admin/user/current/password")); ResponseEntity s = this.oauthRestServiceTemplate - .postForEntity(restUri, createUpdateCurrentUserPasswordRequest(command), + .postForEntity(restUri, + createUpdateCurrentUserPasswordRequest(command), EntityIdentifier.class); return s.getBody(); @@ -570,16 +601,16 @@ public class CommonRestOperationsImpl implements CommonRestOperations { throw new ClientValidationException(errorList.getErrors()); } } - + @Override public void deleteUser(Long userId) { - URI restUri = URI.create(getBaseServerUrl().concat("api/protected/admin/user/").concat(userId.toString())); + URI restUri = URI.create(getBaseServerUrl().concat( + "api/protected/admin/user/").concat(userId.toString())); this.oauthRestServiceTemplate.delete(restUri); } - private HttpEntity createUserRequest( - final UserCommand command) { + private HttpEntity createUserRequest(final UserCommand command) { HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.set("Accept", "application/xml"); @@ -589,19 +620,20 @@ public class CommonRestOperationsImpl implements CommonRestOperations { command, requestHeaders); return requestEntity; } - - private HttpEntity createUpdateCurrentUserPasswordRequest(final ChangePasswordCommand command) { + + private HttpEntity createUpdateCurrentUserPasswordRequest( + final ChangePasswordCommand command) { HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.set("Accept", "application/xml"); requestHeaders.set("Content-Type", "application/xml"); - HttpEntity requestEntity = new HttpEntity(command, requestHeaders); + HttpEntity requestEntity = new HttpEntity( + command, requestHeaders); return requestEntity; } - private HttpEntity roleRequest( - final RoleCommand command) { + private HttpEntity roleRequest(final RoleCommand command) { HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.set("Accept", "application/xml"); @@ -615,8 +647,8 @@ public class CommonRestOperationsImpl implements CommonRestOperations { @Override public Collection retrieveAllUsers() { try { - URI restUri = URI - .create(getBaseServerUrl().concat("api/protected/admin/user/all")); + URI restUri = URI.create(getBaseServerUrl().concat( + "api/protected/admin/user/all")); ResponseEntity s = this.oauthRestServiceTemplate .exchange(restUri, HttpMethod.GET, emptyRequest(), @@ -628,31 +660,37 @@ public class CommonRestOperationsImpl implements CommonRestOperations { throw new ClientValidationException(errorList.getErrors()); } } - + @Override public AppUserData retrieveNewUserDetails() { - - URI restUri = URI.create(getBaseServerUrl().concat("api/protected/admin/user/new")); - ResponseEntity s = this.oauthRestServiceTemplate.exchange(restUri, HttpMethod.GET, emptyRequest(), AppUserData.class); + URI restUri = URI.create(getBaseServerUrl().concat( + "api/protected/admin/user/new")); + + ResponseEntity s = this.oauthRestServiceTemplate.exchange( + restUri, HttpMethod.GET, emptyRequest(), AppUserData.class); return s.getBody(); } - + @Override public AppUserData retrieveUser(Long userId) { - URI restUri = URI.create(getBaseServerUrl().concat("api/protected/admin/user/").concat(userId.toString())); + URI restUri = URI.create(getBaseServerUrl().concat( + "api/protected/admin/user/").concat(userId.toString())); - ResponseEntity s = this.oauthRestServiceTemplate.exchange(restUri, HttpMethod.GET, emptyRequest(), AppUserData.class); + ResponseEntity s = this.oauthRestServiceTemplate.exchange( + restUri, HttpMethod.GET, emptyRequest(), AppUserData.class); return s.getBody(); } - + @Override public AppUserData retrieveCurrentUser() { - URI restUri = URI.create(getBaseServerUrl().concat("api/protected/admin/user/current")); + URI restUri = URI.create(getBaseServerUrl().concat( + "api/protected/admin/user/current")); - ResponseEntity s = this.oauthRestServiceTemplate.exchange(restUri, HttpMethod.GET, emptyRequest(), AppUserData.class); + ResponseEntity s = this.oauthRestServiceTemplate.exchange( + restUri, HttpMethod.GET, emptyRequest(), AppUserData.class); return s.getBody(); } @@ -660,8 +698,8 @@ public class CommonRestOperationsImpl implements CommonRestOperations { @Override public Collection retrieveAllRoles() { try { - URI restUri = URI - .create(getBaseServerUrl().concat("api/protected/admin/role/all")); + URI restUri = URI.create(getBaseServerUrl().concat( + "api/protected/admin/role/all")); ResponseEntity s = this.oauthRestServiceTemplate .exchange(restUri, HttpMethod.GET, emptyRequest(), @@ -676,28 +714,32 @@ public class CommonRestOperationsImpl implements CommonRestOperations { @Override public RoleData retrieveRole(final Long roleId) { - - URI restUri = URI.create(getBaseServerUrl().concat("api/protected/admin/role/").concat(roleId.toString())); - ResponseEntity s = this.oauthRestServiceTemplate.exchange(restUri, HttpMethod.GET, emptyRequest(), RoleData.class); - + URI restUri = URI.create(getBaseServerUrl().concat( + "api/protected/admin/role/").concat(roleId.toString())); + + ResponseEntity s = this.oauthRestServiceTemplate.exchange( + restUri, HttpMethod.GET, emptyRequest(), RoleData.class); + return s.getBody(); } - + @Override public RoleData retrieveNewRoleDetails() { - URI restUri = URI.create(getBaseServerUrl().concat("api/protected/admin/role/new")); + URI restUri = URI.create(getBaseServerUrl().concat( + "api/protected/admin/role/new")); + + ResponseEntity s = this.oauthRestServiceTemplate.exchange( + restUri, HttpMethod.GET, emptyRequest(), RoleData.class); - ResponseEntity s = this.oauthRestServiceTemplate.exchange(restUri, HttpMethod.GET, emptyRequest(), RoleData.class); - return s.getBody(); } @Override public EntityIdentifier createRole(final RoleCommand command) { try { - URI restUri = URI - .create(getBaseServerUrl().concat("api/protected/admin/role/new")); + URI restUri = URI.create(getBaseServerUrl().concat( + "api/protected/admin/role/new")); ResponseEntity s = this.oauthRestServiceTemplate .postForEntity(restUri, roleRequest(command), @@ -709,12 +751,13 @@ public class CommonRestOperationsImpl implements CommonRestOperations { throw new ClientValidationException(errorList.getErrors()); } } - + @Override public EntityIdentifier updateRole(RoleCommand command) { try { - URI restUri = URI - .create(getBaseServerUrl().concat("api/protected/admin/role/").concat(command.getId().toString())); + URI restUri = URI.create(getBaseServerUrl().concat( + "api/protected/admin/role/").concat( + command.getId().toString())); ResponseEntity s = this.oauthRestServiceTemplate .postForEntity(restUri, roleRequest(command), @@ -729,21 +772,22 @@ public class CommonRestOperationsImpl implements CommonRestOperations { @Override public Collection retrieveAllPermissions() { - - URI restUri = URI.create(getBaseServerUrl().concat("api/protected/admin/permissions/all")); - ResponseEntity s = this.oauthRestServiceTemplate - .exchange(restUri, HttpMethod.GET, emptyRequest(), - PermissionList.class); + URI restUri = URI.create(getBaseServerUrl().concat( + "api/protected/admin/permissions/all")); - return s.getBody().getPermissions(); + ResponseEntity s = this.oauthRestServiceTemplate + .exchange(restUri, HttpMethod.GET, emptyRequest(), + PermissionList.class); + + return s.getBody().getPermissions(); } @Override public Collection retrieveAllPermissionGroups() { try { - URI restUri = URI - .create(getBaseServerUrl().concat("api/protected/admin/permissiongroup/all")); + URI restUri = URI.create(getBaseServerUrl().concat( + "api/protected/admin/permissiongroup/all")); ResponseEntity s = this.oauthRestServiceTemplate .exchange(restUri, HttpMethod.GET, emptyRequest(), @@ -758,13 +802,14 @@ public class CommonRestOperationsImpl implements CommonRestOperations { @Override public ClientData retrieveNewIndividualClient() { - URI restUri = URI.create(getBaseServerUrl().concat("api/protected/client/new")); + URI restUri = URI.create(getBaseServerUrl().concat( + "api/protected/client/new")); + + ResponseEntity s = this.oauthRestServiceTemplate.exchange( + restUri, HttpMethod.GET, emptyRequest(), ClientData.class); - ResponseEntity s = this.oauthRestServiceTemplate.exchange(restUri, HttpMethod.GET, emptyRequest(), ClientData.class); - return s.getBody(); } - @Override public ClientData retrieveClientDetails(Long clientId) { @@ -786,10 +831,13 @@ public class CommonRestOperationsImpl implements CommonRestOperations { @Override public EntityIdentifier enrollClient(EnrollClientCommand command) { try { - - URI restUri = URI.create(getBaseServerUrl().concat("api/protected/client/new")); - ResponseEntity s = this.oauthRestServiceTemplate.postForEntity(restUri, enrollClientRequest(command), EntityIdentifier.class); + URI restUri = URI.create(getBaseServerUrl().concat( + "api/protected/client/new")); + + ResponseEntity s = this.oauthRestServiceTemplate + .postForEntity(restUri, enrollClientRequest(command), + EntityIdentifier.class); return s.getBody(); } catch (HttpStatusCodeException e) { @@ -797,7 +845,7 @@ public class CommonRestOperationsImpl implements CommonRestOperations { throw new ClientValidationException(errorList.getErrors()); } } - + private HttpEntity enrollClientRequest( final EnrollClientCommand command) { HttpHeaders requestHeaders = new HttpHeaders(); @@ -806,13 +854,18 @@ public class CommonRestOperationsImpl implements CommonRestOperations { return new HttpEntity(command, requestHeaders); } - + @Override public EntityIdentifier addNote(NoteCommand command) { try { - URI restUri = URI.create(getBaseServerUrl().concat("api/protected/client/").concat(command.getClientId().toString()).concat("/note/new")); + URI restUri = URI.create(getBaseServerUrl() + .concat("api/protected/client/") + .concat(command.getClientId().toString()) + .concat("/note/new")); - ResponseEntity s = this.oauthRestServiceTemplate.postForEntity(restUri, noteRequest(command), EntityIdentifier.class); + ResponseEntity s = this.oauthRestServiceTemplate + .postForEntity(restUri, noteRequest(command), + EntityIdentifier.class); return s.getBody(); } catch (HttpStatusCodeException e) { @@ -820,14 +873,16 @@ public class CommonRestOperationsImpl implements CommonRestOperations { throw new ClientValidationException(errorList.getErrors()); } } - @Override public EntityIdentifier updateNote(NoteCommand command) { try { - URI restUri = URI.create(getBaseServerUrl().concat("api/protected/note/").concat(command.getId().toString())); + URI restUri = URI.create(getBaseServerUrl().concat( + "api/protected/note/").concat(command.getId().toString())); - ResponseEntity s = this.oauthRestServiceTemplate.postForEntity(restUri, noteRequest(command), EntityIdentifier.class); + ResponseEntity s = this.oauthRestServiceTemplate + .postForEntity(restUri, noteRequest(command), + EntityIdentifier.class); return s.getBody(); } catch (HttpStatusCodeException e) { @@ -839,10 +894,14 @@ public class CommonRestOperationsImpl implements CommonRestOperations { @Override public NoteData retrieveClientNote(Long clientId, Long noteId) { try { - URI restUri = URI.create(getBaseServerUrl().concat("api/protected/client/").concat(clientId.toString()).concat("/note/").concat(noteId.toString())); + URI restUri = URI.create(getBaseServerUrl() + .concat("api/protected/client/") + .concat(clientId.toString()).concat("/note/") + .concat(noteId.toString())); - ResponseEntity s = this.oauthRestServiceTemplate.exchange( - restUri, HttpMethod.GET, emptyRequest(), NoteData.class); + ResponseEntity s = this.oauthRestServiceTemplate + .exchange(restUri, HttpMethod.GET, emptyRequest(), + NoteData.class); return s.getBody(); } catch (HttpStatusCodeException e) { @@ -850,14 +909,17 @@ public class CommonRestOperationsImpl implements CommonRestOperations { throw new ClientValidationException(errorList.getErrors()); } } - + @Override public Collection retrieveClientNotes(Long clientId) { try { - URI restUri = URI.create(getBaseServerUrl().concat("api/protected/client/").concat(clientId.toString()).concat("/note/all")); + URI restUri = URI.create(getBaseServerUrl() + .concat("api/protected/client/") + .concat(clientId.toString()).concat("/note/all")); - ResponseEntity s = this.oauthRestServiceTemplate.exchange( - restUri, HttpMethod.GET, emptyRequest(), NoteDataList.class); + ResponseEntity s = this.oauthRestServiceTemplate + .exchange(restUri, HttpMethod.GET, emptyRequest(), + NoteDataList.class); return s.getBody().getNotes(); } catch (HttpStatusCodeException e) { @@ -865,7 +927,7 @@ public class CommonRestOperationsImpl implements CommonRestOperations { throw new ClientValidationException(errorList.getErrors()); } } - + private HttpEntity noteRequest(final NoteCommand command) { HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.set("Accept", "application/xml"); @@ -877,13 +939,14 @@ public class CommonRestOperationsImpl implements CommonRestOperations { @Override public ClientDataWithAccountsData retrieveClientAccount(Long clientId) { try { - URI restUri = URI - .create(getBaseServerUrl().concat("api/protected/client/").concat(clientId.toString()).concat("/withaccounts")); + URI restUri = URI.create(getBaseServerUrl() + .concat("api/protected/client/") + .concat(clientId.toString()).concat("/withaccounts")); ResponseEntity s = this.oauthRestServiceTemplate .exchange(restUri, HttpMethod.GET, emptyRequest(), ClientDataWithAccountsData.class); - + return s.getBody(); } catch (HttpStatusCodeException e) { ErrorResponseList errorList = parseErrors(e); @@ -894,58 +957,13 @@ public class CommonRestOperationsImpl implements CommonRestOperations { @Override public LoanAccountData retrieveLoanAccount(Long loanId) { try { - URI restUri = URI - .create(getBaseServerUrl().concat("api/protected/loan/" - + loanId)); + URI restUri = URI.create(getBaseServerUrl().concat( + "api/protected/loan/" + loanId)); ResponseEntity s = this.oauthRestServiceTemplate .exchange(restUri, HttpMethod.GET, emptyRequest(), LoanAccountData.class); - - return s.getBody(); - } catch (HttpStatusCodeException e) { - ErrorResponseList errorList = parseErrors(e); - throw new ClientValidationException(errorList.getErrors()); - } - } - - @Override - public GenericResultset retrieveReportingData(String rptDB, String name, String type, Map extractedQueryParams) { - try { - - StringBuilder uriAsString = new StringBuilder(getBaseServerUrl()) - .append("api/v1/flexiblereporting/exportcsv/") - .append(encodeURIComponent(rptDB)) - .append('/') - .append(encodeURIComponent(name)) - .append('/') - .append(encodeURIComponent(type)) - .append('/'); - - String officeIdValue = "0"; - String currencyIdValue = "-1"; // represents all currencies - - if (extractedQueryParams.size() > 3) { - for (String key : extractedQueryParams.keySet()) { - if (key.equalsIgnoreCase("${officeId}")) { - officeIdValue = extractedQueryParams.get(key); - } - - if (key.equalsIgnoreCase("${currencyId}")) { - currencyIdValue = extractedQueryParams.get(key); - } - } - } - - uriAsString.append("office/").append(encodeURIComponent(officeIdValue)).append('/'); - uriAsString.append("currency/").append(encodeURIComponent(currencyIdValue)).append('/'); - - URI restUri = URI.create(uriAsString.toString()); - - ResponseEntity s = this.oauthRestServiceTemplate - .exchange(restUri, HttpMethod.GET, emptyRequest(), GenericResultset.class); - return s.getBody(); } catch (HttpStatusCodeException e) { ErrorResponseList errorList = parseErrors(e); @@ -953,26 +971,4 @@ public class CommonRestOperationsImpl implements CommonRestOperations { } } - - - - - //jpw prob remove after - private static String encodeURIComponent(String component) { - String result = null; - - try { - result = URLEncoder.encode(component, "UTF-8") - .replaceAll("\\%28", "(") - .replaceAll("\\%29", ")") - .replaceAll("\\+", "%20") - .replaceAll("\\%27", "'") - .replaceAll("\\%21", "!") - .replaceAll("\\%7E", "~"); - } catch (UnsupportedEncodingException e) { - result = component; - } - - return result; - } } \ No newline at end of file diff --git a/mifosng-individual-lending-app/src/main/java/org/mifosng/ui/user/ExportCSVController.java b/mifosng-individual-lending-app/src/main/java/org/mifosng/ui/user/ExportCSVController.java deleted file mode 100644 index 94046000e..000000000 --- a/mifosng-individual-lending-app/src/main/java/org/mifosng/ui/user/ExportCSVController.java +++ /dev/null @@ -1,159 +0,0 @@ -package org.mifosng.ui.user; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.servlet.ServletOutputStream; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.mifosng.data.ErrorResponse; -import org.mifosng.data.reports.GenericResultset; -import org.mifosng.data.reports.ResultsetColumnHeader; -import org.mifosng.data.reports.ResultsetDataRow; -import org.mifosng.ui.CommonRestOperations; -import org.mifosng.ui.loanproduct.ClientValidationException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.access.AccessDeniedException; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.ExceptionHandler; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.ResponseBody; - -@Controller -public class ExportCSVController { - - private final static Logger logger = LoggerFactory.getLogger(ExportCSVController.class); - - private final CommonRestOperations commonRestOperations; - - @Autowired - public ExportCSVController(final CommonRestOperations commonRestOperations) { - this.commonRestOperations = commonRestOperations; - } - - @ExceptionHandler(AccessDeniedException.class) - public String accessDeniedException() { - return "unAuthorizedAction"; - } - - @ExceptionHandler(ClientValidationException.class) - public @ResponseBody Collection validationException(ClientValidationException ex, HttpServletResponse response) { - - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.setContentType("application/json"); - - return ex.getValidationErrors(); - } - - @RequestMapping(value = "/exportcsv*", method = RequestMethod.GET) - public void handleExportCSV(final HttpServletRequest request, HttpServletResponse response) throws IOException { - - @SuppressWarnings("unchecked") - Map queryParams = request.getParameterMap(); - - String rptDB = queryParams.get("MRP_rptDB")[0]; - String name = queryParams.get("MRP_Name")[0]; - String type = queryParams.get("MRP_Type")[0]; - - Set keys = queryParams.keySet(); - Map extractedQueryParams = new HashMap(); - String pKey; - String pValue; - for (String k : keys) { - - if (k.startsWith("MRP_")) { - pKey = "${" + k.substring(4) + "}"; - pValue = queryParams.get(k)[0]; - // logger.info(name + ": " + pKey + ": " + pValue); - extractedQueryParams.put(pKey, pValue); - } - } - -// if (extractedQueryParams.size() > 3) { -// throw new UnsupportedOperationException("Not able to support this report for export to CSV right now."); -// } - - GenericResultset result = this.commonRestOperations.retrieveReportingData(rptDB, name, type, extractedQueryParams); - - // response.setContentType("application/octet-stream"); - response.setContentType("application/x-msdownload"); - - response.setHeader("Content-Disposition", - "attachment;filename=" + name.replaceAll(" ", "") + ".csv"); - - ServletOutputStream out = response.getOutputStream(); - StringBuffer sb = generateCsvFileBuffer(result); - - InputStream in = new ByteArrayInputStream(sb.toString().getBytes( - "UTF-8")); - - byte[] outputByte = new byte[4096]; - Integer readLen = in.read(outputByte, 0, 4096); - - while (readLen != -1) { - out.write(outputByte, 0, readLen); - readLen = in.read(outputByte, 0, 4096); - } - in.close(); - out.flush(); - out.close(); - - } - - private static StringBuffer generateCsvFileBuffer(GenericResultset result) { - StringBuffer writer = new StringBuffer(); - - List columnHeaders = result.getColumnHeaders(); - logger.info("NO. of Columns: " + columnHeaders.size()); - Integer chSize = columnHeaders.size(); - for (int i = 0; i < chSize; i++) { - writer.append('"' + columnHeaders.get(i).getColumnName() + '"'); - if (i < (chSize - 1)) - writer.append(","); - } - writer.append('\n'); - - List data = result.getData(); - List row; - Integer rSize; -// String currCol; - String currColType; - String currVal; - logger.info("NO. of Rows: " + data.size()); - for (int i = 0; i < data.size(); i++) { - row = data.get(i).getRow(); - rSize = row.size(); - for (int j = 0; j < rSize; j++) { -// currCol = columnHeaders.get(j).getColumnName(); - currColType = columnHeaders.get(j).getColumnType(); - currVal = row.get(j); - if (currVal != null) { - if (currColType.equals("DECIMAL") - || currColType.equals("DOUBLE") - || currColType.equals("BIGINT") - || currColType.equals("SMALLINT") - || currColType.equals("INT")) - writer.append(currVal); - else - writer.append('"' + currVal + '"'); - } - if (j < (rSize - 1)) - writer.append(","); - } - writer.append('\n'); - } - - return writer; - } - -} \ No newline at end of file diff --git a/mifosng-individual-lending-app/src/main/webapp/WEB-INF/static/stretchyreporting/stretchyreporting-0.96.js b/mifosng-individual-lending-app/src/main/webapp/WEB-INF/static/stretchyreporting/stretchyreporting-0.965.js similarity index 99% rename from mifosng-individual-lending-app/src/main/webapp/WEB-INF/static/stretchyreporting/stretchyreporting-0.96.js rename to mifosng-individual-lending-app/src/main/webapp/WEB-INF/static/stretchyreporting/stretchyreporting-0.965.js index 1d8833f2b..1c708b844 100644 --- a/mifosng-individual-lending-app/src/main/webapp/WEB-INF/static/stretchyreporting/stretchyreporting-0.96.js +++ b/mifosng-individual-lending-app/src/main/webapp/WEB-INF/static/stretchyreporting/stretchyreporting-0.965.js @@ -82,11 +82,6 @@ function initialiseReporting(params) { if (params.pentahoUrl) pentahoUrl = params.pentahoUrl else pentahoUrl = ""; - if (params.exportUrl) exportUrl = params.exportUrl - else exportUrl = ""; - - // alert("export url: " + exportUrl); - loadingImg = "dots64.gif"; if (params.loadingImg) loadingImg = params.loadingImg; @@ -1109,8 +1104,8 @@ function getExportCSV(inParams) { //paramCount = paramCount + 1; } - var fullExportUrl = exportUrl + inQueryParameters; - //alert('Export url: ' + fullExportUrl); + //var fullExportUrl = RESTUrl + inQueryParameters + "&exportCSV=true"; + var fullExportUrl = RESTUrl + "/exportjpw" + inQueryParameters; showMsg("full export url: " + fullExportUrl); var loadHTML = ''; @@ -1133,7 +1128,7 @@ function getPentahoReport(inParams) { } var fullReportUrl = pentahoUrl + inQueryParameters; - showMsg("full pentaho url: " + fullExportUrl); + showMsg("full pentaho url: " + fullReportUrl); var loadHTML = ''; diff --git a/mifosng-individual-lending-app/src/main/webapp/WEB-INF/views/common-head-stretchyreporting.jsp b/mifosng-individual-lending-app/src/main/webapp/WEB-INF/views/common-head-stretchyreporting.jsp index 46cf2f03f..c6ab9283e 100644 --- a/mifosng-individual-lending-app/src/main/webapp/WEB-INF/views/common-head-stretchyreporting.jsp +++ b/mifosng-individual-lending-app/src/main/webapp/WEB-INF/views/common-head-stretchyreporting.jsp @@ -16,6 +16,6 @@ - + diff --git a/mifosng-individual-lending-app/src/main/webapp/WEB-INF/views/reports/flexireport.jsp b/mifosng-individual-lending-app/src/main/webapp/WEB-INF/views/reports/flexireport.jsp index 66fcfd7e1..3d6358cb6 100644 --- a/mifosng-individual-lending-app/src/main/webapp/WEB-INF/views/reports/flexireport.jsp +++ b/mifosng-individual-lending-app/src/main/webapp/WEB-INF/views/reports/flexireport.jsp @@ -94,7 +94,7 @@ var reportingParams = { RESTUrl: "${baseUrl}api/v1/reports", pentahoUrl: "${baseUrl}pentahoreport", //old link exportUrl: "${rootContext}exportcsv", - exportUrl: "${baseUrl}exportcsv", + //not needed now exportUrl: "${baseUrl}exportcsv", bundleDir: "${resValue}/stretchyreporting/mifosngbundle/", reportsListDiv: "myListOfReports", runReportDiv: "myRunReportButton", diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/ReadExtraDataAndReportingService.java b/mifosng-provider/src/main/java/org/mifosng/platform/ReadExtraDataAndReportingService.java index 43ba96b01..33f953d8a 100644 --- a/mifosng-provider/src/main/java/org/mifosng/platform/ReadExtraDataAndReportingService.java +++ b/mifosng-provider/src/main/java/org/mifosng/platform/ReadExtraDataAndReportingService.java @@ -1,12 +1,18 @@ package org.mifosng.platform; +import java.io.OutputStream; import java.util.Map; +import javax.ws.rs.core.StreamingOutput; + import org.mifosng.data.ExtraDatasets; import org.mifosng.data.reports.GenericResultset; public interface ReadExtraDataAndReportingService { + StreamingOutput retrieveReportCSV(String rptDB, String name, + String type, Map extractedQueryParams); + //@PreAuthorize(value = "hasAnyRole('REPORTING_SUPER_USER_ROLE')") GenericResultset retrieveGenericResultset(String rptDB, String name, String type, Map extractedQueryParams); diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/ReadExtraDataAndReportingServiceImpl.java b/mifosng-provider/src/main/java/org/mifosng/platform/ReadExtraDataAndReportingServiceImpl.java index de3d5e641..b67d643f8 100644 --- a/mifosng-provider/src/main/java/org/mifosng/platform/ReadExtraDataAndReportingServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosng/platform/ReadExtraDataAndReportingServiceImpl.java @@ -1,5 +1,9 @@ package org.mifosng.platform; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; import java.sql.Connection; import java.sql.ResultSet; import java.sql.ResultSetMetaData; @@ -14,6 +18,7 @@ import javax.sql.DataSource; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; +import javax.ws.rs.core.StreamingOutput; import org.mifosng.data.ExtraDatasetRow; import org.mifosng.data.ExtraDatasets; @@ -39,6 +44,88 @@ public class ReadExtraDataAndReportingServiceImpl implements this.dataSource = dataSource; } + + @Override + public StreamingOutput retrieveReportCSV(final String rptDB, + final String name, final String type, + final Map queryParams) { + + return new StreamingOutput() { + public void write(OutputStream out) throws IOException, WebApplicationException { + try { + + GenericResultset result = retrieveGenericResultset(rptDB, name, type, queryParams); + StringBuffer sb = generateCsvFileBuffer(result); + + InputStream in = new ByteArrayInputStream(sb.toString().getBytes( + "UTF-8")); + + byte[] outputByte = new byte[4096]; + Integer readLen = in.read(outputByte, 0, 4096); + + while (readLen != -1) { + out.write(outputByte, 0, readLen); + readLen = in.read(outputByte, 0, 4096); + } + //in.close(); + //out.flush(); + //out.close(); + } catch (Exception e) { + throw new WebApplicationException(e); + } + } + }; + + } + + + private static StringBuffer generateCsvFileBuffer(GenericResultset result) { + StringBuffer writer = new StringBuffer(); + + List columnHeaders = result.getColumnHeaders(); + logger.info("NO. of Columns: " + columnHeaders.size()); + Integer chSize = columnHeaders.size(); + for (int i = 0; i < chSize; i++) { + writer.append('"' + columnHeaders.get(i).getColumnName() + '"'); + if (i < (chSize - 1)) + writer.append(","); + } + writer.append('\n'); + + List data = result.getData(); + List row; + Integer rSize; + // String currCol; + String currColType; + String currVal; + logger.info("NO. of Rows: " + data.size()); + for (int i = 0; i < data.size(); i++) { + row = data.get(i).getRow(); + rSize = row.size(); + for (int j = 0; j < rSize; j++) { + // currCol = columnHeaders.get(j).getColumnName(); + currColType = columnHeaders.get(j).getColumnType(); + currVal = row.get(j); + if (currVal != null) { + if (currColType.equals("DECIMAL") + || currColType.equals("DOUBLE") + || currColType.equals("BIGINT") + || currColType.equals("SMALLINT") + || currColType.equals("INT")) + writer.append(currVal); + else + writer.append('"' + currVal + '"'); + } + if (j < (rSize - 1)) + writer.append(","); + } + writer.append('\n'); + } + + return writer; + } + + @Override public GenericResultset retrieveGenericResultset(final String rptDB, final String name, final String type, diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/api/ExportCSVController.java b/mifosng-provider/src/main/java/org/mifosng/platform/api/ExportCSVController.java deleted file mode 100644 index 33448988c..000000000 --- a/mifosng-provider/src/main/java/org/mifosng/platform/api/ExportCSVController.java +++ /dev/null @@ -1,171 +0,0 @@ -package org.mifosng.platform.api; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.servlet.ServletContext; -import javax.servlet.ServletOutputStream; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.mifosng.data.reports.GenericResultset; -import org.mifosng.data.reports.ResultsetColumnHeader; -import org.mifosng.data.reports.ResultsetDataRow; -import org.mifosng.platform.ReadExtraDataAndReportingService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.access.AccessDeniedException; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.ExceptionHandler; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.context.ServletContextAware; - -@Controller -public class ExportCSVController implements ServletContextAware { - - private final static Logger logger = LoggerFactory - .getLogger(ExportCSVController.class); - - private final ReadExtraDataAndReportingService readExtraDataAndReportingService; - - @Autowired - public ExportCSVController( - final ReadExtraDataAndReportingService readExtraDataAndReportingService) { - logger.info("ExportCSVController started"); - this.readExtraDataAndReportingService = readExtraDataAndReportingService; - } - - @ExceptionHandler(AccessDeniedException.class) - public String accessDeniedException() { - return "unAuthorizedAction"; - } - - /* - * @ExceptionHandler(ClientValidationException.class) public @ResponseBody - * Collection validationException(ClientValidationException - * ex, HttpServletResponse response) { - * - * response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - * response.setContentType("application/json"); - * - * return ex.getValidationErrors(); } - */ - @RequestMapping(value = "/exportcsv", method = RequestMethod.GET) - public void handleExportCSV(final HttpServletRequest request, - HttpServletResponse response) throws IOException { - logger.info("handleExportCSV started"); - @SuppressWarnings("unchecked") - Map queryParams = request.getParameterMap(); - - String rptDB = queryParams.get("MRP_rptDB")[0]; - String name = queryParams.get("MRP_Name")[0]; - String type = queryParams.get("MRP_Type")[0]; - - Set keys = queryParams.keySet(); - Map extractedQueryParams = new HashMap(); - String pKey; - String pValue; - for (String k : keys) { - - if (k.startsWith("MRP_")) { - pKey = "${" + k.substring(4) + "}"; - pValue = queryParams.get(k)[0]; - // logger.info(name + ": " + pKey + ": " + pValue); - extractedQueryParams.put(pKey, pValue); - } - } - - // if (extractedQueryParams.size() > 3) { - // throw new - // UnsupportedOperationException("Not able to support this report for export to CSV right now."); - // } - - GenericResultset result = this.readExtraDataAndReportingService - .retrieveGenericResultset(rptDB, name, type, - extractedQueryParams); - - // response.setContentType("application/octet-stream"); - response.setContentType("application/x-msdownload"); - - response.setHeader("Content-Disposition", - "attachment;filename=" + name.replaceAll(" ", "") + ".csv"); - - ServletOutputStream out = response.getOutputStream(); - StringBuffer sb = generateCsvFileBuffer(result); - - InputStream in = new ByteArrayInputStream(sb.toString().getBytes( - "UTF-8")); - - byte[] outputByte = new byte[4096]; - Integer readLen = in.read(outputByte, 0, 4096); - - while (readLen != -1) { - out.write(outputByte, 0, readLen); - readLen = in.read(outputByte, 0, 4096); - } - in.close(); - out.flush(); - out.close(); - - } - - private static StringBuffer generateCsvFileBuffer(GenericResultset result) { - StringBuffer writer = new StringBuffer(); - - List columnHeaders = result.getColumnHeaders(); - logger.info("NO. of Columns: " + columnHeaders.size()); - Integer chSize = columnHeaders.size(); - for (int i = 0; i < chSize; i++) { - writer.append('"' + columnHeaders.get(i).getColumnName() + '"'); - if (i < (chSize - 1)) - writer.append(","); - } - writer.append('\n'); - - List data = result.getData(); - List row; - Integer rSize; - // String currCol; - String currColType; - String currVal; - logger.info("NO. of Rows: " + data.size()); - for (int i = 0; i < data.size(); i++) { - row = data.get(i).getRow(); - rSize = row.size(); - for (int j = 0; j < rSize; j++) { - // currCol = columnHeaders.get(j).getColumnName(); - currColType = columnHeaders.get(j).getColumnType(); - currVal = row.get(j); - if (currVal != null) { - if (currColType.equals("DECIMAL") - || currColType.equals("DOUBLE") - || currColType.equals("BIGINT") - || currColType.equals("SMALLINT") - || currColType.equals("INT")) - writer.append(currVal); - else - writer.append('"' + currVal + '"'); - } - if (j < (rSize - 1)) - writer.append(","); - } - writer.append('\n'); - } - - return writer; - } - - @Override - public void setServletContext(ServletContext servletContext) { - // TODO Auto-generated method stub - - } - -} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/api/ReportingApiResource.java b/mifosng-provider/src/main/java/org/mifosng/platform/api/ReportingApiResource.java index 609b88945..5626ed643 100644 --- a/mifosng-provider/src/main/java/org/mifosng/platform/api/ReportingApiResource.java +++ b/mifosng-provider/src/main/java/org/mifosng/platform/api/ReportingApiResource.java @@ -1,11 +1,16 @@ package org.mifosng.platform.api; +import java.io.ByteArrayInputStream; import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; import java.util.Arrays; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.Set; +import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.Consumes; import javax.ws.rs.GET; @@ -21,11 +26,14 @@ import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; import javax.ws.rs.core.Response.Status; +import javax.ws.rs.core.StreamingOutput; import javax.ws.rs.core.UriInfo; import org.mifosng.data.ErrorResponse; import org.mifosng.data.ErrorResponseList; import org.mifosng.data.reports.GenericResultset; +import org.mifosng.data.reports.ResultsetColumnHeader; +import org.mifosng.data.reports.ResultsetDataRow; import org.mifosng.platform.ReadExtraDataAndReportingService; import org.mifosng.platform.exceptions.ApplicationDomainRuleException; import org.mifosng.platform.exceptions.NewDataValidationException; @@ -42,109 +50,129 @@ import org.springframework.stereotype.Component; @Scope("singleton") public class ReportingApiResource { - private final static Logger logger = LoggerFactory.getLogger(ReportingApiResource.class); - + private final static Logger logger = LoggerFactory + .getLogger(ReportingApiResource.class); + @Autowired private ReadExtraDataAndReportingService ReadExtraDataAndReportingService; - + private String _corsHeaders; - + private Response makeCORS(ResponseBuilder req, String returnMethod) { - ResponseBuilder rb = req - .header("Access-Control-Allow-Origin", "*") - .header("Access-Control-Allow-Methods", "GET, POST, OPTIONS"); - - if (!"".equals(returnMethod)) { - rb.header("Access-Control-Allow-Headers", returnMethod); - } - - return rb.build(); + ResponseBuilder rb = req.header("Access-Control-Allow-Origin", "*") + .header("Access-Control-Allow-Methods", "GET, POST, OPTIONS"); + + if (!"".equals(returnMethod)) { + rb.header("Access-Control-Allow-Headers", returnMethod); + } + + return rb.build(); } - + private Response makeCORS(ResponseBuilder req) { - return makeCORS(req, _corsHeaders); + return makeCORS(req, _corsHeaders); + } + + private Response makeCORSExport(ResponseBuilder req, String exportFilename, + String returnMethod) { + ResponseBuilder rb = req + .header("Access-Control-Allow-Origin", "*") + .header("Access-Control-Allow-Methods", "GET, POST, OPTIONS") + .header("Content-Disposition", + "attachment;filename=" + exportFilename); + + if (!"".equals(returnMethod)) { + rb.header("Access-Control-Allow-Headers", returnMethod); + } + + return rb.build(); + } + + private Response makeCORSExport(ResponseBuilder req, String exportFilename) { + return makeCORSExport(req, exportFilename, _corsHeaders); } // This OPTIONS request/response is necessary // if you consumes other format than text/plain or // if you use other HTTP verbs than GET and POST @OPTIONS - public Response corsMyResource(@HeaderParam("Access-Control-Request-Headers") String requestH) { - _corsHeaders = requestH; - return makeCORS(Response.ok(), requestH); + public Response corsMyResource( + @HeaderParam("Access-Control-Request-Headers") String requestH) { + _corsHeaders = requestH; + return makeCORS(Response.ok(), requestH); } - + @GET - @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) - @Produces({ MediaType.APPLICATION_JSON}) - public Response retrieveReport(@Context UriInfo uriInfo, @Context HttpServletResponse httpServletResponse) { - - MultivaluedMap queryParams = uriInfo.getQueryParameters(); + @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) + @Produces({ MediaType.APPLICATION_JSON }) + public Response retrieveReport(@Context UriInfo uriInfo, + @Context HttpServletResponse httpServletResponse) { + + MultivaluedMap queryParams = uriInfo + .getQueryParameters(); String rptDB = queryParams.getFirst("MRP_rptDB"); String name = queryParams.getFirst("MRP_Name"); String type = queryParams.getFirst("MRP_Type"); - + Map extractedQueryParams = new HashMap(); - - Set keys = queryParams.keySet(); + + Set keys = queryParams.keySet(); String pKey; String pValue; - for (String k : keys) { - - if (k.startsWith("MRP_")) - { + for (String k : keys) { + + if (k.startsWith("MRP_")) { pKey = "${" + k.substring(4) + "}"; pValue = queryParams.get(k).get(0); - + extractedQueryParams.put(pKey, pValue); } - } - logger.info("BEGINNING REQUEST FOR: " + name); - GenericResultset result = this.ReadExtraDataAndReportingService.retrieveGenericResultset(rptDB, name, type, extractedQueryParams); - -// JSONWithPadding paddedResult = new JSONWithPadding(result, -// callbackName); - - return makeCORS(Response.ok().entity(result)); - } - - @GET - @Path("/exportcsv/{reportDb}/{reportName}/{reportType}/office/{officeId}/currency/{currencyId}") - @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) - @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) - public Response exportCsvReport( - @PathParam("reportDb") String rptDB, - @PathParam("reportName") String name, - @PathParam("reportType") String type, - @PathParam("officeId") Long officeId, @PathParam("currencyId") Long currencyId) throws IOException { - - try { - Map extractedQueryParams = new HashMap(); - - if (officeId != null && officeId > 0) { - extractedQueryParams.put("${officeId}", officeId.toString()); - } - - if (currencyId != null) { - extractedQueryParams.put("${currencyId}", currencyId.toString()); - } - - GenericResultset result = this.ReadExtraDataAndReportingService.retrieveGenericResultset(rptDB, name, type, extractedQueryParams); - - return Response.ok().entity(result).build(); - } catch (UnAuthenticatedUserException e) { - throw new WebApplicationException(Response.status(Status.UNAUTHORIZED).build()); - } catch (AccessDeniedException e) { - ErrorResponse errorResponse = new ErrorResponse("error.msg.no.permission", "id"); - ErrorResponseList list = new ErrorResponseList(Arrays.asList(errorResponse)); - throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(list).build()); - } catch (ApplicationDomainRuleException e) { - throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getErrors())).build()); - } catch (NewDataValidationException e) { - throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(new ErrorResponseList(e.getValidationErrors())).build()); } + logger.info("BEGINNING REQUEST FOR: " + name); + GenericResultset result = this.ReadExtraDataAndReportingService + .retrieveGenericResultset(rptDB, name, type, + extractedQueryParams); + return makeCORS(Response.ok().entity(result)); + } - + + @GET + @Path("/exportjpw") + @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) + @Produces({ "application/x-msdownload" }) + public Response retrieveReportExport(@Context UriInfo uriInfo, + @Context HttpServletResponse httpServletResponse) { + + MultivaluedMap queryParams = uriInfo + .getQueryParameters(); + String rptDB = queryParams.getFirst("MRP_rptDB"); + String name = queryParams.getFirst("MRP_Name"); + String type = queryParams.getFirst("MRP_Type"); + + Map extractedQueryParams = new HashMap(); + + Set keys = queryParams.keySet(); + String pKey; + String pValue; + for (String k : keys) { + + if (k.startsWith("MRP_")) { + pKey = "${" + k.substring(4) + "}"; + pValue = queryParams.get(k).get(0); + + extractedQueryParams.put(pKey, pValue); + } + } + logger.info("BEGINNING Export REQUEST FOR: " + name); + + StreamingOutput result = this.ReadExtraDataAndReportingService + .retrieveReportCSV(rptDB, name, type, extractedQueryParams); + + return makeCORSExport(Response.ok().entity(result), + name.replaceAll(" ", "") + ".csv"); + + } + @GET @Path("forceauth") public Response hackToForceAuthentication() {