WIP refactor api - export csv refactorings

This commit is contained in:
John Woodlock
2012-05-14 16:43:52 +10:00
parent ad14229e99
commit 934cc0ca47
10 changed files with 433 additions and 654 deletions
@@ -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<String, String> extractedQueryParams);
NewLoanWorkflowStepOneData retrieveNewLoanApplicationDetails(Long clientId, Long productId);
NewLoanWorkflowStepOneData retrieveNewLoanApplicationDetails(Long clientId,
Long productId);
}
@@ -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<ClientData> retrieveAllIndividualClients() {
URI restUri = URI
.create(getBaseServerUrl().concat("api/protected/client/all"));
URI restUri = URI.create(getBaseServerUrl().concat(
"api/protected/client/all"));
ResponseEntity<ClientList> s = this.oauthRestServiceTemplate.exchange(
restUri, HttpMethod.GET, emptyRequest(), ClientList.class);
@@ -112,8 +113,8 @@ public class CommonRestOperationsImpl implements CommonRestOperations {
@Override
public Collection<LoanProductData> retrieveAllLoanProducts() {
URI restUri = URI
.create(getBaseServerUrl().concat("api/protected/product/loan/all"));
URI restUri = URI.create(getBaseServerUrl().concat(
"api/protected/product/loan/all"));
ResponseEntity<LoanProductList> 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<ErrorResponse> errors = new ArrayList<ErrorResponse>();
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<LoanSchedule> 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<NewLoanWorkflowStepOneData> 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<NewLoanWorkflowStepOneData> s = this.oauthRestServiceTemplate
.exchange(restUri, HttpMethod.GET, emptyRequest(),
NewLoanWorkflowStepOneData.class);
ResponseEntity<NewLoanWorkflowStepOneData> 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<EntityIdentifier> 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<EntityIdentifier> s = this.oauthRestServiceTemplate
.exchange(restUri, HttpMethod.DELETE, null,
EntityIdentifier.class);
ResponseEntity<EntityIdentifier> 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<EntityIdentifier> 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<EntityIdentifier> 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<EntityIdentifier> 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<EntityIdentifier> 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<EntityIdentifier> 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<EntityIdentifier> 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<LoanRepaymentData> 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<LoanRepaymentData> 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<EntityIdentifier> 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<EntityIdentifier> 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<LoanRepaymentData> 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<EntityIdentifier> s = this.oauthRestServiceTemplate
.postForEntity(restUri, loanTransactionRequest(command),
@@ -438,22 +463,24 @@ public class CommonRestOperationsImpl implements CommonRestOperations {
throw new ClientValidationException(errorList.getErrors());
}
}
private HttpEntity<LoanTransactionCommand> loanTransactionRequest(final LoanTransactionCommand command) {
private HttpEntity<LoanTransactionCommand> loanTransactionRequest(
final LoanTransactionCommand command) {
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.set("Accept", "application/xml");
requestHeaders.set("Content-Type", "application/xml");
return new HttpEntity<LoanTransactionCommand>(command, requestHeaders);
}
private HttpEntity<AdjustLoanTransactionCommand> adjustLoanRepaymentRequest(
final AdjustLoanTransactionCommand command) {
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.set("Accept", "application/xml");
requestHeaders.set("Content-Type", "application/xml");
return new HttpEntity<AdjustLoanTransactionCommand>(command, requestHeaders);
return new HttpEntity<AdjustLoanTransactionCommand>(command,
requestHeaders);
}
private HttpEntity<UndoLoanDisbursalCommand> undoLoanDisbursalRequest(
@@ -480,7 +507,8 @@ public class CommonRestOperationsImpl implements CommonRestOperations {
requestHeaders.set("Accept", "application/xml");
requestHeaders.set("Content-Type", "application/xml");
return new HttpEntity<LoanStateTransitionCommand>(command, requestHeaders);
return new HttpEntity<LoanStateTransitionCommand>(command,
requestHeaders);
}
private HttpEntity<SubmitLoanApplicationCommand> submitLoanApplicationRequest(
@@ -502,12 +530,12 @@ public class CommonRestOperationsImpl implements CommonRestOperations {
return new HttpEntity<CalculateLoanScheduleCommand>(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<EntityIdentifier> 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<EntityIdentifier> 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<EntityIdentifier> 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<EntityIdentifier> 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<UserCommand> createUserRequest(
final UserCommand command) {
private HttpEntity<UserCommand> 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<ChangePasswordCommand> createUpdateCurrentUserPasswordRequest(final ChangePasswordCommand command) {
private HttpEntity<ChangePasswordCommand> createUpdateCurrentUserPasswordRequest(
final ChangePasswordCommand command) {
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.set("Accept", "application/xml");
requestHeaders.set("Content-Type", "application/xml");
HttpEntity<ChangePasswordCommand> requestEntity = new HttpEntity<ChangePasswordCommand>(command, requestHeaders);
HttpEntity<ChangePasswordCommand> requestEntity = new HttpEntity<ChangePasswordCommand>(
command, requestHeaders);
return requestEntity;
}
private HttpEntity<RoleCommand> roleRequest(
final RoleCommand command) {
private HttpEntity<RoleCommand> 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<AppUserData> 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<UserList> 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<AppUserData> s = this.oauthRestServiceTemplate.exchange(restUri, HttpMethod.GET, emptyRequest(), AppUserData.class);
URI restUri = URI.create(getBaseServerUrl().concat(
"api/protected/admin/user/new"));
ResponseEntity<AppUserData> 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<AppUserData> s = this.oauthRestServiceTemplate.exchange(restUri, HttpMethod.GET, emptyRequest(), AppUserData.class);
ResponseEntity<AppUserData> 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<AppUserData> s = this.oauthRestServiceTemplate.exchange(restUri, HttpMethod.GET, emptyRequest(), AppUserData.class);
ResponseEntity<AppUserData> 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<RoleData> 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<RoleList> 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<RoleData> s = this.oauthRestServiceTemplate.exchange(restUri, HttpMethod.GET, emptyRequest(), RoleData.class);
URI restUri = URI.create(getBaseServerUrl().concat(
"api/protected/admin/role/").concat(roleId.toString()));
ResponseEntity<RoleData> 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<RoleData> s = this.oauthRestServiceTemplate.exchange(
restUri, HttpMethod.GET, emptyRequest(), RoleData.class);
ResponseEntity<RoleData> 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<EntityIdentifier> 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<EntityIdentifier> s = this.oauthRestServiceTemplate
.postForEntity(restUri, roleRequest(command),
@@ -729,21 +772,22 @@ public class CommonRestOperationsImpl implements CommonRestOperations {
@Override
public Collection<PermissionData> retrieveAllPermissions() {
URI restUri = URI.create(getBaseServerUrl().concat("api/protected/admin/permissions/all"));
ResponseEntity<PermissionList> 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<PermissionList> s = this.oauthRestServiceTemplate
.exchange(restUri, HttpMethod.GET, emptyRequest(),
PermissionList.class);
return s.getBody().getPermissions();
}
@Override
public Collection<EnumOptionReadModel> 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<EnumOptionList> 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<ClientData> s = this.oauthRestServiceTemplate.exchange(
restUri, HttpMethod.GET, emptyRequest(), ClientData.class);
ResponseEntity<ClientData> 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<EntityIdentifier> s = this.oauthRestServiceTemplate.postForEntity(restUri, enrollClientRequest(command), EntityIdentifier.class);
URI restUri = URI.create(getBaseServerUrl().concat(
"api/protected/client/new"));
ResponseEntity<EntityIdentifier> 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<EnrollClientCommand> enrollClientRequest(
final EnrollClientCommand command) {
HttpHeaders requestHeaders = new HttpHeaders();
@@ -806,13 +854,18 @@ public class CommonRestOperationsImpl implements CommonRestOperations {
return new HttpEntity<EnrollClientCommand>(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<EntityIdentifier> s = this.oauthRestServiceTemplate.postForEntity(restUri, noteRequest(command), EntityIdentifier.class);
ResponseEntity<EntityIdentifier> 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<EntityIdentifier> s = this.oauthRestServiceTemplate.postForEntity(restUri, noteRequest(command), EntityIdentifier.class);
ResponseEntity<EntityIdentifier> 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<NoteData> s = this.oauthRestServiceTemplate.exchange(
restUri, HttpMethod.GET, emptyRequest(), NoteData.class);
ResponseEntity<NoteData> 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<NoteData> 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<NoteDataList> s = this.oauthRestServiceTemplate.exchange(
restUri, HttpMethod.GET, emptyRequest(), NoteDataList.class);
ResponseEntity<NoteDataList> 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<NoteCommand> 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<ClientDataWithAccountsData> 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<LoanAccountData> 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<String, String> 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<GenericResultset> 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;
}
}
@@ -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<ErrorResponse> 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<String, String[]> 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<String> keys = queryParams.keySet();
Map<String, String> extractedQueryParams = new HashMap<String, String>();
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<ResultsetColumnHeader> 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<ResultsetDataRow> data = result.getData();
List<String> 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;
}
}
@@ -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 = '<iframe id=rptLoadingFrame src="' + fullExportUrl + '" frameborder="0" onload="jQuery.stretchyReporting.clearLoadingImg();" width="100%" height="600px" style="background:url(';
loadHTML += "'" + loadingImg + "'" + ') no-repeat scroll 50% 100px;"><p>Your browser does not support iframes.</p></iframe>';
@@ -1133,7 +1128,7 @@ function getPentahoReport(inParams) {
}
var fullReportUrl = pentahoUrl + inQueryParameters;
showMsg("full pentaho url: " + fullExportUrl);
showMsg("full pentaho url: " + fullReportUrl);
var loadHTML = '<iframe src="' + fullReportUrl + '" frameborder="1" width="100%" height="600px" style="background:url(';
loadHTML += "'" + loadingImg + "'" + ') no-repeat scroll 50% 100px;"><p>Your browser does not support iframes.</p></iframe>';
@@ -16,6 +16,6 @@
<script type="text/javascript" src="${resValue}/libs/DataTables-1.8.2/extras/TableTools/media/js/TableTools.min.js"></script>
<script type="text/javascript" src="${resValue}/libs/jquery.i18n.properties-min-1.0.9.js"></script>
<script type="text/javascript" src="${resValue}/libs/OAuthSimple.js"></script>
<script type="text/javascript" src="${resValue}/stretchyreporting/stretchyreporting-0.96.js"></script>
<script type="text/javascript" src="${resValue}/stretchyreporting/stretchyreporting-0.965.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
@@ -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",
@@ -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<String, String> extractedQueryParams);
//@PreAuthorize(value = "hasAnyRole('REPORTING_SUPER_USER_ROLE')")
GenericResultset retrieveGenericResultset(String rptDB, String name,
String type, Map<String, String> extractedQueryParams);
@@ -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<String, String> 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<ResultsetColumnHeader> 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<ResultsetDataRow> data = result.getData();
List<String> 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,
@@ -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<ErrorResponse> 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<String, String[]> 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<String> keys = queryParams.keySet();
Map<String, String> extractedQueryParams = new HashMap<String, String>();
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<ResultsetColumnHeader> 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<ResultsetDataRow> data = result.getData();
List<String> 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
}
}
@@ -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<String, String> queryParams = uriInfo.getQueryParameters();
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Produces({ MediaType.APPLICATION_JSON })
public Response retrieveReport(@Context UriInfo uriInfo,
@Context HttpServletResponse httpServletResponse) {
MultivaluedMap<String, String> queryParams = uriInfo
.getQueryParameters();
String rptDB = queryParams.getFirst("MRP_rptDB");
String name = queryParams.getFirst("MRP_Name");
String type = queryParams.getFirst("MRP_Type");
Map<String, String> extractedQueryParams = new HashMap<String, String>();
Set<String> keys = queryParams.keySet();
Set<String> 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<String, String> extractedQueryParams = new HashMap<String, String>();
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<String, String> queryParams = uriInfo
.getQueryParameters();
String rptDB = queryParams.getFirst("MRP_rptDB");
String name = queryParams.getFirst("MRP_Name");
String type = queryParams.getFirst("MRP_Type");
Map<String, String> extractedQueryParams = new HashMap<String, String>();
Set<String> 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() {