Commit 1a71e89d authored by Andrijana Predojevic's avatar Andrijana Predojevic
Browse files

Making REST service for exporting results of query in qbe designer in csv file

parent a328995f
......@@ -8,6 +8,7 @@ import java.util.Set;
import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
......@@ -15,6 +16,8 @@ import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import javax.ws.rs.core.StreamingOutput;
import org.apache.log4j.Logger;
import org.hibernate.Session;
......@@ -57,10 +60,13 @@ import it.eng.spagobi.engines.qbe.QbeEngineConfig;
import it.eng.spagobi.services.common.SsoServiceInterface;
import it.eng.spagobi.services.proxy.DataSetServiceProxy;
import it.eng.spagobi.services.rest.annotations.ManageAuthorization;
import it.eng.spagobi.services.rest.annotations.UserConstraint;
import it.eng.spagobi.tools.dataset.bo.DataSetParametersList;
import it.eng.spagobi.tools.dataset.bo.IDataSet;
import it.eng.spagobi.tools.dataset.common.datastore.IDataStore;
import it.eng.spagobi.tools.dataset.common.datawriter.JSONDataWriter;
import it.eng.spagobi.tools.dataset.common.iterator.CsvStreamingOutput;
import it.eng.spagobi.tools.dataset.common.iterator.DataIterator;
import it.eng.spagobi.tools.dataset.common.metadata.IFieldMetaData;
import it.eng.spagobi.tools.dataset.common.metadata.IMetaData;
import it.eng.spagobi.tools.dataset.constants.DataSetConstants;
......@@ -424,7 +430,7 @@ public class QbeQueryResource extends AbstractQbeEngineResource {
EntityManager entityManager = ((IJpaDataSource) statement.getDataSource()).getEntityManager();
Session session = (Session) entityManager.getDelegate();
Map<String, String> envs = getEnv();
Map<String, Object> envs = getEnv();
String driverName = null;
Set<String> filterNames = session.getSessionFactory().getDefinedFilterNames();
Iterator<String> it = filterNames.iterator();
......@@ -884,4 +890,80 @@ public class QbeQueryResource extends AbstractQbeEngineResource {
}
@POST
@Path("/export")
@Produces(MediaType.TEXT_PLAIN)
@UserConstraint(functionalities = { SpagoBIConstants.SELF_SERVICE_DATASET_MANAGEMENT })
public Response export(@javax.ws.rs.core.Context HttpServletRequest req, @QueryParam("outputType") @DefaultValue("csv") String outputType,
@QueryParam("currentQueryId") String id) {
JSONObject jsonEncodedReq = null;
JSONArray catalogue;
Query query = null;
JSONArray queries = null;
JSONObject queryJSON = null;
JSONArray subqueriesJSON = null;
JSONObject subqueryJSON = null;
try {
jsonEncodedReq = RestUtilities.readBodyAsJSONObject(req);
JSONArray pars = jsonEncodedReq.optJSONArray(DataSetConstants.PARS);
catalogue = jsonEncodedReq.getJSONArray("catalogue");
if (catalogue == null) {
catalogue = jsonEncodedReq.getJSONArray("qbeJSONQuery");
JSONObject jo = new JSONObject(catalogue);
jo = jo.getJSONObject("catalogue");
queries = jo.getJSONArray("queries");
} else {
queries = new JSONArray(catalogue.toString());
}
try {
for (int i = 0; i < queries.length(); i++) {
queryJSON = queries.getJSONObject(i);
if (queryJSON.get("id").equals(id)) {
query = deserializeQuery(queryJSON);
} else {
subqueriesJSON = queryJSON.getJSONArray("subqueries");
for (int j = 0; j < subqueriesJSON.length(); j++) {
subqueryJSON = subqueriesJSON.getJSONObject(j);
if (subqueryJSON.get("id").equals(id)) {
query = deserializeQuery(subqueryJSON);
}
}
}
}
} catch (SerializationException e) {
String message = "Impossible to deserialize query";
throw new SpagoBIEngineServiceException("DESERIALIZATING QUERY", message, e);
}
} catch (Exception e) {
e.printStackTrace();
}
UserProfile userProfile = (UserProfile) getEnv().get(EngineConstants.ENV_USER_PROFILE);
IModelAccessModality accessModality = getEngineInstance().getDataSource().getModelAccessModality();
Query filteredQuery = accessModality.getFilteredStatement(query, this.getEngineInstance().getDataSource(), userProfile.getUserAttributes());
IDataSet dataSet = getActiveQueryAsDataSet(filteredQuery);
dataSet.setUserProfileAttributes(getUserProfile().getUserAttributes());
Assert.assertTrue(dataSet.isIterable(), "Impossible to export a non-iterable data set");
DataIterator iterator = null;
try {
logger.debug("Starting iteration to transfer data");
iterator = dataSet.iterator();
StreamingOutput stream = new CsvStreamingOutput(iterator);
ResponseBuilder response = Response.ok(stream);
response.header("Content-Disposition", "attachment;filename=" + "report" + "." + outputType + "\";");
return response.build();
} catch (Exception e) {
if (iterator != null) {
iterator.close();
}
throw e;
}
}
}
......@@ -8,7 +8,7 @@
</md-button>
<md-menu-content>
<md-menu-item ng-repeat="exporter in exportService.getExporters()">
<md-button class="md-button" ng-click="exportService.exportQueryResults(query,exporter.mimeType)" >
<md-button class="md-button" ng-click="exportService.exportQueryResults(query, exporter.mimeType, bodySend)" >
{{exporter.name | uppercase}}
</md-button>
</md-menu-item>
......
......@@ -17,11 +17,11 @@
*/
(function(){
var scripts = document.getElementsByTagName("script");
var currentScriptPath = scripts[scripts.length - 1].src;
currentScriptPath = currentScriptPath.substring(0, currentScriptPath.lastIndexOf('/') + 1);
angular.module('exportModule')
.directive('exportMenu', function($mdDialog, $mdMenu) {
return {
......@@ -30,28 +30,34 @@
scope: {},
templateUrl: currentScriptPath + 'export.menu.tmpl.html',
link: function link(scope, element, attrs) {
scope.$on('editQueryObj', function (event, data) {
console.log("editQueryObj");
console.log(data);
scope.query = data;
});
scope.$on('bodySend', function (event, data) {
console.log("bodySend");
console.log(data);
scope.bodySend = data;
});
}
};
})
function exportMenuController($scope,exportService,sbiModule_translate){
$scope.exportService = exportService;
$scope.translate = sbiModule_translate;
$scope.openMenu = function(menu, e){
e.stopPropagation();
menu(e);
}
}
})();
\ No newline at end of file
......@@ -17,47 +17,64 @@
*/
(function(){
angular.module('exportModule').factory('exportService', function(sbiModule_action_builder,sbiModuleDownloadService,sbiModule_messaging){
angular.module('exportModule').factory('exportService', function(sbiModule_action_builder,sbiModuleDownloadService,sbiModule_messaging, sbiModule_restServices, sbiModule_config){
var exporters = [];
exporters.push(new Exporter('csv','text/csv'));
exporters.push(new Exporter('xls','application/vnd.ms-excel'));
exporters.push(new Exporter('xlsx','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'));
return {
exportQueryResults:function(query,mimeType){
var exportResultAction = sbiModule_action_builder.getActionBuilder("POST");
exportResultAction.actionName = "EXPORT_RESULT_ACTION";
exportResultAction.queryParams.MIME_TYPE = mimeType;
exportResultAction.formParams.query = query;
exportResultAction.conf.responseType = 'arraybuffer';
exportResultAction.executeAction().then(function(response){
sbiModuleDownloadService.getBlob(response);
},function(response){
var decodedString = String.fromCharCode.apply(null, new Uint8Array(response.data));
var obj = JSON.parse(decodedString);
sbiModule_messaging.showErrorMessage(obj.errors[0].message, 'Error');
});
exportQueryResults:function(query, mimeType, bodySend){
if(mimeType=='text/csv') {
var config = {"responseType": "arraybuffer"};
var q="?SBI_EXECUTION_ID="+sbiModule_config.sbiExecutionID+"&currentQueryId="+query.id;
var promise = sbiModule_restServices.promisePost('qbequery/export', q, bodySend, config);
var fileName = "report.csv";
var fileExtension = 'csv';
promise.then(function(response){
sbiModuleDownloadService.getBlob(response, fileName, fileExtension);
},function(response){
var decodedString = String.fromCharCode.apply(null, new Uint8Array(response.data));
var obj = JSON.parse(decodedString);
sbiModule_messaging.showErrorMessage(obj.errors[0].message, 'Error');
});
} else {
var exportResultAction = sbiModule_action_builder.getActionBuilder("POST");
exportResultAction.actionName = "EXPORT_RESULT_ACTION";
exportResultAction.queryParams.MIME_TYPE = mimeType;
exportResultAction.formParams.query = query;
exportResultAction.conf.responseType = 'arraybuffer';
exportResultAction.executeAction().then(function(response){
sbiModuleDownloadService.getBlob(response);
},function(response){
var decodedString = String.fromCharCode.apply(null, new Uint8Array(response.data));
var obj = JSON.parse(decodedString);
sbiModule_messaging.showErrorMessage(obj.errors[0].message, 'Error');
});
}
},
getExporters:function(){
return exporters;
}
}
})
function Exporter(name,mymeType){
this.name = name;
this.mimeType = mymeType;
}
})();
\ No newline at end of file
......@@ -94,6 +94,7 @@ function qbeFunction($scope,$rootScope,entity_service,query_service,filters_serv
} else {
$scope.addToQueryModelWithoutExecutingQuery($scope.editQueryObj, $scope.queryModel);
}
$rootScope.$broadcast('bodySend', $scope.bodySend);
window.parent.queryCatalogue = {catalogue: {queries: [$scope.editQueryObj]}};
},true)
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment