diff --git a/addons/cadastrapp/js/searchParcelleByRef.js b/addons/cadastrapp/js/searchParcelleByRef.js index 82f7ee5d..668bd11e 100644 --- a/addons/cadastrapp/js/searchParcelleByRef.js +++ b/addons/cadastrapp/js/searchParcelleByRef.js @@ -542,21 +542,61 @@ GEOR.Addons.Cadastre.initRechercheParcelle = function() { } else if (currentForm.id == 'parcForthForm') { // Recherche parcelle par fichier if (currentForm.getForm().findField('filePath').value != undefined && currentForm.getForm().findField('filePath').value.length > 2) { - + + // Message de chargement + var box = Ext.MessageBox.wait("Lecture du document...",OpenLayers.i18n('Chargement')); + + // Titre de l'onglet resultat var resultTitle = OpenLayers.i18n('cadastrapp.result.title.fichier'); + + // LECTURE CSV + var files = document.getElementById("parcForthForm").querySelectorAll("input[type=file]")[0].files; + + function readFile (blob, callback){ + var reader = new FileReader(); + reader.onload = callback; + reader.readAsText(blob); + } - // sousmet le form (pour envoyer le fichier) - currentForm.getForm().submit({ - url : GEOR.Addons.Cadastre.cadastrappWebappUrl + 'fromParcellesFile', - params : {}, - success : function(form, action) { - GEOR.Addons.Cadastre.addNewResultParcelle(resultTitle, GEOR.Addons.Cadastre.getResultParcelleStore(action.response.responseText, true)); - }, - failure : function(form, action) { - alert('ERROR'); - } + // read content + readFile(files[0], function(e){ + + if (typeof(e.target.result) == "string"){ + + var content = JSON.stringify(e.target.result); + content = JSON.parse(content); + // Separateurs: virgule, point virgule, pipe, espace et retour à la ligne + content = content.split(/\r\n|\n|,|;|\|/); + + // Filtre pour ne garder que ce qui ressemble a un identifiant de parcelle + // et ne garder qu'une occurence de chaque identifiant + var parcellesFromFile = content.filter(function (value, index, self) { + return (self.indexOf(value) === index && value.length >= 8 && value.match("^[0-9]{5,}.*")); + }); + + // Envoie la liste de compte communal extraite du fichier + Ext.Ajax.request({ + method : 'POST', + url : GEOR.Addons.Cadastre.url.serviceParcelle, + params : { parcelle : parcellesFromFile}, + success : function(result) { + box.hide(); + GEOR.Addons.Cadastre.addNewResultParcelle(resultTitle, GEOR.Addons.Cadastre.getResultParcelleStore(result.responseText, false)); + }, + failure : function(form, action) { + box.hide(); + alert('ERROR'); + } + }); + }else{ + box.hide(); + alert('Mauvais type de fichier'); + } }); - } else { + + } + + else { //TITRE de l'onglet resultat var resultTitle = "Recherche par lot"; diff --git a/cadastrapp/README.md b/cadastrapp/README.md index 1c713157..777a30df 100644 --- a/cadastrapp/README.md +++ b/cadastrapp/README.md @@ -16,18 +16,18 @@ This application is made to be installed behind GeOrchestra security proxy. To i -- As for gerochestra tomcat instance, you will have to create a new instance (choose a port not already use here we choose 8480 for http endpoint and 8405 to stop ``` - sudo tomcat6-instance-create -p 8480 -c 8405 /var/lib/tomcat-cadastrapp + sudo tomcat9-instance-create -p 8480 -c 8405 /var/lib/tomcat-cadastrapp ``` ### Init policy and service sudo mkdir /var/lib/tomcat-cadastrapp/conf/policy.d sudo touch /var/lib/tomcat-cadastrapp/conf/policy.d/empty.policy - sudo chown -R tomcat6:tomcat6 /var/lib/tomcat-cadastrapp - sudo cp /etc/init.d/tomcat6 /etc/init.d/tomcat-cadastrapp - sudo cp /etc/default/tomcat6 /etc/default/tomcat-cadastrapp + sudo chown -R tomcat:tomcat /var/lib/tomcat-cadastrapp + sudo cp /etc/init.d/tomcat9 /etc/init.d/tomcat-cadastrapp + sudo cp /etc/default/tomcat9 /etc/default/tomcat-cadastrapp Finally, edit the ```/etc/init.d/tomcat-cadastrapp``` script, find the following line: ``` -# Provides: tomcat6 +# Provides: tomcat9 ``` ... and replace it with: ``` @@ -44,12 +44,12 @@ JAVA_OPTS="-Djava.awt.headless=true -XX:+UseConcMarkSweepGC" And later add these lines (change the ```STOREPASSWORD``` string): ``` JAVA_OPTS="$JAVA_OPTS \ - -Xms1024m \ + -Xms256m \ -Xmx1024m \ -XX:MaxPermSize=256m" JAVA_OPTS="$JAVA_OPTS \ - -Djavax.net.ssl.trustStore=/etc/tomcat6/keystore \ + -Djavax.net.ssl.trustStore=/etc/georchestra/keystore \ -Djavax.net.ssl.trustStorePassword=STOREPASSWORD" ``` ### Configure connectors @@ -86,7 +86,7 @@ In ```/var/lib/tomcat-cadastrapp/conf/context.xml```, add a new ResourceLink at #### Add jar require for this datasource To be able to connect to postgresql database, tomcat will have to get postgresql client librairie in his classloader. -In tomcat6 instance, you will have to add ```postgresql-9.1-901-1.jdbc4.jar``` to ```/var/lib/tomcat-cadastrapp/lib``` folder (with a symlink) +In tomcat9 instance, you will have to add ```postgresql-42.2.22.jar``` to ```/var/lib/tomcat-cadastrapp/lib``` folder (with a symlink) ### Start the instance diff --git a/cadastrapp/pom.xml b/cadastrapp/pom.xml index 93698b91..5e137da2 100644 --- a/cadastrapp/pom.xml +++ b/cadastrapp/pom.xml @@ -12,18 +12,18 @@ Web application for cadastre management over Georchestra UTF-8 - 1.8.6 - 1.7.25 - 1.2.3 + 2.12.3 + 1.7.30 + 1.2.7 1.7.25 - 9.4-1205-jdbc4 - 3.0.4 - 4.3.24.RELEASE - 4.1.7.Final - 4.0.1.Final - 9.2 - 2.0.17 - 2.3.0 + 42.3.1 + 5.3.9 + 6.0.0.Alpha7 + 5.1.2.Final + 25.2 + 3.0.0-RC1 + 2.3.2 + 2.10.5 @@ -52,28 +52,8 @@ - org.apache.cxf - cxf-rt-frontend-jaxrs - ${cxf.version} - - - org.apache.cxf - cxf-rt-rs-client - ${cxf.version} - - - org.codehaus.jackson - jackson-core-asl - ${jackson.version} - - - org.codehaus.jackson - jackson-mapper-asl - ${jackson.version} - - - org.codehaus.jackson - jackson-jaxrs + com.fasterxml.jackson.core + jackson-databind ${jackson.version} @@ -92,6 +72,11 @@ spring-web ${spring.version} + + org.springframework + spring-webmvc + ${spring.version} + org.springframework @@ -106,7 +91,7 @@ org.springframework.data spring-data-jpa - 1.11.22.RELEASE + 2.5.4 @@ -116,7 +101,7 @@ - org.hibernate + org.hibernate.orm hibernate-core ${hibernate-version} compile @@ -144,7 +129,7 @@ - org.hibernate + org.hibernate.orm hibernate-entitymanager ${hibernate-version} compile @@ -180,7 +165,7 @@ - org.hibernate + org.hibernate.orm hibernate-ehcache ${hibernate-version} compile @@ -228,28 +213,23 @@ org.apache.commons commons-lang3 - 3.6 + 3.11 org.apache.xmlgraphics fop - 2.3 - - - net.sf.supercsv - super-csv - 2.4.0 - - - net.sf.supercsv - super-csv-dozer - 2.4.0 - + 2.6 + - org.geotools - gt-render - ${geotools.version} + net.sf.supercsv + super-csv + 2.4.0 + + + net.sf.supercsv + super-csv-dozer + 2.4.0 org.geotools @@ -261,6 +241,11 @@ gt-wms ${geotools.version} + + org.geotools + gt-http + ${geotools.version} + org.geotools gt-wfs-ng @@ -281,7 +266,7 @@ junit junit - 4.12 + 4.13.1 test @@ -300,13 +285,29 @@ provided javax.servlet javax.servlet-api - 3.0.1 + 3.1.0 org.apache.pdfbox pdfbox ${pdfbox.version} + + + io.springfox + springfox-swagger2 + ${springfox.version} + + + io.springfox + springfox-swagger-ui + ${springfox.version} + + + io.springfox + springfox-spring-webmvc + ${springfox.version} + @@ -339,7 +340,7 @@ org.eclipse.jetty jetty-maven-plugin - 9.2.11.v20150529 + 9.4.41.v20210516 /cadastrapp/ @@ -360,56 +361,23 @@ org.apache.maven.plugins maven-javadoc-plugin 2.10.3 - - - - org.apache.cxf - cxf-java2wadl-plugin - 3.0.0 - - - org.apache.maven.plugins maven-compiler-plugin - 1.7 - 1.7 + 1.8 + 1.8 - org.apache.maven.plugins - maven-war-plugin - 3.2.3 - - - - target/site - - - target/generated - apidocs - - - - + maven-dependency-plugin + 3.1.2 + - - maven-javadoc-plugin - - - build-javadocs - generate-sources - - javadoc - - - - - + org.codehaus.mojo exec-maven-plugin 1.6.0 @@ -452,7 +420,7 @@ maven-assembly-plugin - 3.2.0 + 3.3.0 addon-assembly.xml @@ -468,52 +436,10 @@ - - org.apache.cxf - cxf-java2wadl-plugin - ${cxf.version} - - - - parsejavadoc - generate-sources - - parsejavadoc - - - - process-classes - process-classes - - java2wadl - - - - org.georchestra.cadastrapp.service.BatimentController - org.georchestra.cadastrapp.service.CommuneController - org.georchestra.cadastrapp.service.ParcelleController - org.georchestra.cadastrapp.service.ProprietaireController - org.georchestra.cadastrapp.service.CoProprietaireController - org.georchestra.cadastrapp.service.SectionController - org.georchestra.cadastrapp.service.InfoBulleController - org.georchestra.cadastrapp.service.UniteCadastraleController - org.georchestra.cadastrapp.service.VoieController - org.georchestra.cadastrapp.service.pdf.BordereauParcellaireController - org.georchestra.cadastrapp.service.pdf.ReleveProprieteController - org.georchestra.cadastrapp.service.pdf.DemandeController - org.georchestra.cadastrapp.service.DatadirController - - org.apache.cxf.maven_plugin.javatowadl.ResourceMapJavaDocProvider - true - - - - pl.project13.maven git-commit-id-plugin - 3.0.1 + 4.0.3 @@ -597,7 +523,7 @@ org.apache.maven.plugins maven-antrun-plugin - 1.7 + 3.0.0 set-project-packageversion @@ -656,57 +582,6 @@ - - rpmPackage - - - - org.apache.maven.plugins - maven-war-plugin - - - org.codehaus.mojo - rpm-maven-plugin - 2.1.3 - - - generate-rpm - - rpm - - - - - georchestra-${project.artifactId} - UTF-8 - Applications/Internet - ${rpm.gpg.key} - - - /usr/share/lib/georchestra-${project.artifactId} - - - ${project.build.directory} - - cadastrapp.war - - - - - - / - - - ${basedir}/src/deb/resources - - - - - - - - - docker @@ -719,7 +594,7 @@ com.spotify docker-maven-plugin - 0.3.8 + 1.2.2 ${dockerImageName} ${project.basedir}/src/docker @@ -739,7 +614,7 @@ com.google.guava guava - 19.0 + 30.1.1-jre diff --git a/cadastrapp/src/main/java/org/georchestra/cadastrapp/configuration/CadastrappPlaceHolder.java b/cadastrapp/src/main/java/org/georchestra/cadastrapp/configuration/CadastrappPlaceHolder.java index 7389e625..b67a78ee 100644 --- a/cadastrapp/src/main/java/org/georchestra/cadastrapp/configuration/CadastrappPlaceHolder.java +++ b/cadastrapp/src/main/java/org/georchestra/cadastrapp/configuration/CadastrappPlaceHolder.java @@ -10,7 +10,13 @@ import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer; - +/** + * + * CadastrappPlaceHolder + * + * @author Pierre Jégo / pierre.jego@jdev.fr + * + */ public class CadastrappPlaceHolder extends PropertyPlaceholderConfigurer { private static Map propertiesMap; diff --git a/cadastrapp/src/main/java/org/georchestra/cadastrapp/configuration/SwaggerConfig.java b/cadastrapp/src/main/java/org/georchestra/cadastrapp/configuration/SwaggerConfig.java new file mode 100644 index 00000000..1947ef15 --- /dev/null +++ b/cadastrapp/src/main/java/org/georchestra/cadastrapp/configuration/SwaggerConfig.java @@ -0,0 +1,52 @@ +package org.georchestra.cadastrapp.configuration; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import springfox.documentation.builders.ApiInfoBuilder; +import springfox.documentation.PathProvider; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.service.ApiInfo; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; +import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc; + + +@Configuration +@EnableSwagger2WebMvc +public class SwaggerConfig { + + + @Bean + public Docket api() { + + + return new Docket(DocumentationType.SWAGGER_2) + .pathProvider(new PathProvider() { + + // remvove duplicate cadastrapp entry in operation path + @Override + public String getOperationPath(String operationPath) { + return operationPath.replace("cadastrapp/", ""); + } + + @Override + public String getResourceListingPath(String groupName, String apiDeclaration) { + return null; + } + }) + .select() + .apis(RequestHandlerSelectors.any()) + .build() + .apiInfo(apiInfo()); + } + + private ApiInfo apiInfo() { + return new ApiInfoBuilder().title("geOrchestra Cadastrapp API").description("API to access to Majic and EDIGEO information").version("1.10") + .termsOfServiceUrl("https://docs.georchestra.org/cadastrapp/latest/") + .license("GNU General Public License v3.0") + .licenseUrl("https://github.com/georchestra/georchestra/blob/master/LICENSE.txt") + .build(); + } + +} diff --git a/cadastrapp/src/main/java/org/georchestra/cadastrapp/helper/BatimentHelper.java b/cadastrapp/src/main/java/org/georchestra/cadastrapp/helper/BatimentHelper.java index 36d6b0b1..8eeeba3b 100644 --- a/cadastrapp/src/main/java/org/georchestra/cadastrapp/helper/BatimentHelper.java +++ b/cadastrapp/src/main/java/org/georchestra/cadastrapp/helper/BatimentHelper.java @@ -3,8 +3,6 @@ import java.util.List; import java.util.Map; -import javax.ws.rs.core.HttpHeaders; - import org.georchestra.cadastrapp.service.CadController; import org.slf4j.Logger; @@ -26,7 +24,7 @@ public final class BatimentHelper extends CadController { * * @return buildings information on this plot */ - public List> getBuildings(String parcelle, HttpHeaders headers ){ + public List> getBuildings(String parcelle){ logger.debug("infoOngletBatiment - parcelle : " + parcelle); @@ -36,7 +34,7 @@ public List> getBuildings(String parcelle, HttpHeaders heade queryBuilder.append(databaseSchema); queryBuilder.append(".proprietebatie pb "); queryBuilder.append(" where pb.parcelle = ? "); - queryBuilder.append(addAuthorizationFiltering(headers, "pb.")); + queryBuilder.append(addAuthorizationFiltering("pb.")); queryBuilder.append(" ORDER BY pb.dnubat"); JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); diff --git a/cadastrapp/src/main/java/org/georchestra/cadastrapp/helper/ProprietaireHelper.java b/cadastrapp/src/main/java/org/georchestra/cadastrapp/helper/ProprietaireHelper.java index e2424539..c1411f69 100644 --- a/cadastrapp/src/main/java/org/georchestra/cadastrapp/helper/ProprietaireHelper.java +++ b/cadastrapp/src/main/java/org/georchestra/cadastrapp/helper/ProprietaireHelper.java @@ -4,8 +4,6 @@ import java.util.List; import java.util.Map; -import javax.ws.rs.core.HttpHeaders; - import org.georchestra.cadastrapp.service.CadController; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -21,16 +19,15 @@ public final class ProprietaireHelper extends CadController { * * @param parcelleList plots list * @param isAddressConcat true to display address in only on field address, false to display each dlign - * @param headers A leaste level CNIL1 form http headers * @return information list of owner whith address field concat in one field (if isAddressConcat is true) */ - public List> getProprietairesByParcelles(HttpHeaders headers, List parcelleList, boolean isAddressConcat) { + public List> getProprietairesByParcelles(List parcelleList, boolean isAddressConcat) { // Init list to return response even if nothing in it. List> proprietaires = new ArrayList>(); // User need to be at least CNIL1 level - if (getUserCNILLevel(headers)>0){ + if (getUserCNILLevel()>0){ if(parcelleList != null && !parcelleList.isEmpty()){ @@ -49,7 +46,7 @@ public List> getProprietairesByParcelles(HttpHeaders headers queryBuilder.append(".proprietaire_parcelle proparc "); queryBuilder.append(createWhereInQuery(parcelleList.size(), "proparc.parcelle")); queryBuilder.append(" and prop.comptecommunal = proparc.comptecommunal"); - queryBuilder.append(addAuthorizationFiltering(headers, "prop.")); + queryBuilder.append(addAuthorizationFiltering("prop.")); queryBuilder.append(" ORDER BY prop.dnulp, prop.app_nom_usage "); JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); diff --git a/cadastrapp/src/main/java/org/georchestra/cadastrapp/model/request/InformationRequest.java b/cadastrapp/src/main/java/org/georchestra/cadastrapp/model/request/InformationRequest.java index d3cb905f..b973df81 100644 --- a/cadastrapp/src/main/java/org/georchestra/cadastrapp/model/request/InformationRequest.java +++ b/cadastrapp/src/main/java/org/georchestra/cadastrapp/model/request/InformationRequest.java @@ -9,10 +9,13 @@ import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; +import javax.persistence.JoinTable; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; +import javax.persistence.SequenceGenerator; import javax.persistence.Table; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; @@ -32,7 +35,8 @@ public class InformationRequest implements Serializable{ private static final long serialVersionUID = 5439786730972374577L; @Id - @GeneratedValue + @SequenceGenerator(name = "HibernateSequence", sequenceName = "hibernate_sequence", initialValue = 0, allocationSize = 1) + @GeneratedValue(generator = "HibernateSequence") private long requestId; @ManyToOne(optional=false, fetch = FetchType.EAGER) @@ -43,6 +47,10 @@ public class InformationRequest implements Serializable{ private Date requestDate; @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER) + @JoinTable(name = "request_information_object_request", + joinColumns = {@JoinColumn(name = "request_information_requestid")}, + inverseJoinColumns = {@JoinColumn(name = "objectsrequest_objectid")} + ) private Set objectsRequest; @Column(name="askby") diff --git a/cadastrapp/src/main/java/org/georchestra/cadastrapp/model/request/ObjectRequest.java b/cadastrapp/src/main/java/org/georchestra/cadastrapp/model/request/ObjectRequest.java index 01ae444c..6f4aee3e 100644 --- a/cadastrapp/src/main/java/org/georchestra/cadastrapp/model/request/ObjectRequest.java +++ b/cadastrapp/src/main/java/org/georchestra/cadastrapp/model/request/ObjectRequest.java @@ -6,6 +6,7 @@ import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; +import javax.persistence.SequenceGenerator; import javax.persistence.Table; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; @@ -21,7 +22,8 @@ public class ObjectRequest implements Serializable { private static final long serialVersionUID = 5439786730972374577L; @Id - @GeneratedValue + @SequenceGenerator(name = "HibernateSequence", sequenceName = "hibernate_sequence", initialValue = 0, allocationSize = 1) + @GeneratedValue(generator = "HibernateSequence") private long objectId; @Column(name = "type") diff --git a/cadastrapp/src/main/java/org/georchestra/cadastrapp/model/request/UserRequest.java b/cadastrapp/src/main/java/org/georchestra/cadastrapp/model/request/UserRequest.java index 5a85397f..b99803ce 100644 --- a/cadastrapp/src/main/java/org/georchestra/cadastrapp/model/request/UserRequest.java +++ b/cadastrapp/src/main/java/org/georchestra/cadastrapp/model/request/UserRequest.java @@ -6,6 +6,7 @@ import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; +import javax.persistence.SequenceGenerator; import javax.persistence.Table; import javax.xml.bind.annotation.XmlAttribute; @@ -19,7 +20,8 @@ public class UserRequest implements Serializable { private static final long serialVersionUID = -9140660737315556020L; @Id - @GeneratedValue + @SequenceGenerator(name = "HibernateSequence", sequenceName = "hibernate_sequence", initialValue = 0, allocationSize = 1) + @GeneratedValue(generator = "HibernateSequence") @Column(name="userid") private long userId; diff --git a/cadastrapp/src/main/java/org/georchestra/cadastrapp/providers/CadastrappInterceptor.java b/cadastrapp/src/main/java/org/georchestra/cadastrapp/providers/CadastrappInterceptor.java new file mode 100644 index 00000000..687a39bd --- /dev/null +++ b/cadastrapp/src/main/java/org/georchestra/cadastrapp/providers/CadastrappInterceptor.java @@ -0,0 +1,95 @@ +package org.georchestra.cadastrapp.providers; + +import org.georchestra.cadastrapp.service.constants.CadastrappConstants; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; + +import java.util.Arrays; +import java.util.Map.Entry; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.stereotype.Component; +import org.springframework.web.servlet.HandlerInterceptor; +import org.springframework.web.servlet.ModelAndView; + +/** + * Log all request + * @author Pierre Jégo + * + */ +@Component +public class CadastrappInterceptor implements HandlerInterceptor { + + final Logger logger = LoggerFactory.getLogger(CadastrappInterceptor.class); + + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) + throws Exception { + + final String rolesList = request.getHeader(CadastrappConstants.HTTP_HEADER_ROLES); + final String userName = request.getHeader(CadastrappConstants.HTTP_HEADER_USERNAME); + final String org = request.getHeader(CadastrappConstants.HTTP_HEADER_ORGANISME); + + // Add contexte information, used in logs and to limit access to data + MDC.put(CadastrappConstants.HTTP_HEADER_USERNAME, userName); + MDC.put(CadastrappConstants.HTTP_HEADER_ROLES, rolesList); + MDC.put(CadastrappConstants.HTTP_HEADER_ORGANISME, org); + MDC.put("uri", request.getRequestURI()); + + logger.info("Incoming request"); + + // Add debug information (duration and parameters list) + if(logger.isDebugEnabled()){ + + // used for duration + long startTime = System.currentTimeMillis(); + request.setAttribute("startTime", startTime); + + // list of params + StringBuilder paramsSBuilder = new StringBuilder("Parameter list : { "); + for (Entry entry : request.getParameterMap().entrySet()){ + paramsSBuilder.append(entry.getKey()).append(":"); + paramsSBuilder.append(Arrays.toString(entry.getValue())).append("--"); + } + paramsSBuilder.append(" }"); + logger.debug(paramsSBuilder.toString()); + } + return true; + } + + @Override + public void postHandle( HttpServletRequest request, HttpServletResponse response, + Object handler, ModelAndView modelAndView) throws Exception { + + // Add duration + if(logger.isDebugEnabled()){ + long executeTime = System.currentTimeMillis() - (Long)request.getAttribute("startTime"); + logger.debug("Request handle in " + executeTime + "ms"); + } + + logger.info("Send response"); + + MDC.remove(CadastrappConstants.HTTP_HEADER_USERNAME); + MDC.remove(CadastrappConstants.HTTP_HEADER_ROLES); + MDC.remove(CadastrappConstants.HTTP_HEADER_ORGANISME); + MDC.remove("uri"); + } + + @Override + public void afterCompletion(HttpServletRequest request, HttpServletResponse response, + Object handler, Exception ex) throws Exception { + + // Add duration + if(logger.isDebugEnabled()){ + long executeTime = System.currentTimeMillis() - (Long)request.getAttribute("startTime"); + logger.debug("Request finished in " + executeTime + "ms"); + + logger.debug("Make sure to clear MDC information"); + } + MDC.clear(); + } + +} diff --git a/cadastrapp/src/main/java/org/georchestra/cadastrapp/providers/PreReponseFilter.java b/cadastrapp/src/main/java/org/georchestra/cadastrapp/providers/PreReponseFilter.java deleted file mode 100644 index ea3b7c07..00000000 --- a/cadastrapp/src/main/java/org/georchestra/cadastrapp/providers/PreReponseFilter.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.georchestra.cadastrapp.providers; - -import java.io.IOException; - -import javax.ws.rs.container.ContainerRequestContext; -import javax.ws.rs.container.ContainerResponseContext; -import javax.ws.rs.container.ContainerResponseFilter; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.slf4j.MDC; - -/** - * Log all request - * @author gfi - * - */ -public class PreReponseFilter implements ContainerResponseFilter { - - final Logger logger = LoggerFactory.getLogger(PreReponseFilter.class); - - @Override - public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { - - logger.info("Sending response"); - - MDC.remove("user"); - MDC.remove("roles"); - MDC.remove("uri"); - - } - -} \ No newline at end of file diff --git a/cadastrapp/src/main/java/org/georchestra/cadastrapp/providers/PreRequestFilter.java b/cadastrapp/src/main/java/org/georchestra/cadastrapp/providers/PreRequestFilter.java deleted file mode 100644 index b98d3dec..00000000 --- a/cadastrapp/src/main/java/org/georchestra/cadastrapp/providers/PreRequestFilter.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.georchestra.cadastrapp.providers; - -import java.io.IOException; - -import javax.ws.rs.container.ContainerRequestContext; -import javax.ws.rs.container.ContainerRequestFilter; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.slf4j.MDC; - -/** - * Log all request - * @author gfi - * - */ -public class PreRequestFilter implements ContainerRequestFilter { - - final Logger logger = LoggerFactory.getLogger(PreRequestFilter.class); - - @Override - public void filter(ContainerRequestContext requestContext) throws IOException { - - String rolesList = requestContext.getHeaderString("sec-roles"); - String org = requestContext.getHeaderString("sec-org"); - String userName = requestContext.getHeaderString("sec-username"); - MDC.put("user", userName); - MDC.put("org", org); - MDC.put("roles", rolesList); - MDC.put("uri", requestContext.getUriInfo().getPath()); - - logger.info("Incoming request"); - - if(logger.isDebugEnabled()){ - logger.debug("Parameter list : " + requestContext.getUriInfo().getQueryParameters()); - } - - } -} diff --git a/cadastrapp/src/main/java/org/georchestra/cadastrapp/repository/ObjectRequestRepository.java b/cadastrapp/src/main/java/org/georchestra/cadastrapp/repository/ObjectRequestRepository.java index e53bae7d..e2ef81b8 100644 --- a/cadastrapp/src/main/java/org/georchestra/cadastrapp/repository/ObjectRequestRepository.java +++ b/cadastrapp/src/main/java/org/georchestra/cadastrapp/repository/ObjectRequestRepository.java @@ -7,7 +7,7 @@ /** * - * @author gfi + * @author Pierre Jégo * * Repository to get InformationRequest for database * diff --git a/cadastrapp/src/main/java/org/georchestra/cadastrapp/repository/RequestRepository.java b/cadastrapp/src/main/java/org/georchestra/cadastrapp/repository/RequestRepository.java index 65e73265..22f45b1b 100644 --- a/cadastrapp/src/main/java/org/georchestra/cadastrapp/repository/RequestRepository.java +++ b/cadastrapp/src/main/java/org/georchestra/cadastrapp/repository/RequestRepository.java @@ -10,7 +10,7 @@ /** * - * @author gfi + * @author Pierre jego * * Repository to get InformationRequest for database * diff --git a/cadastrapp/src/main/java/org/georchestra/cadastrapp/repository/UserRequestRepository.java b/cadastrapp/src/main/java/org/georchestra/cadastrapp/repository/UserRequestRepository.java index ef964ef1..fb8cf13a 100644 --- a/cadastrapp/src/main/java/org/georchestra/cadastrapp/repository/UserRequestRepository.java +++ b/cadastrapp/src/main/java/org/georchestra/cadastrapp/repository/UserRequestRepository.java @@ -6,7 +6,7 @@ /** * - * @author gfi + * @author Pierre Jégo * * Repository to get UserRequest for database */ diff --git a/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/BatimentController.java b/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/BatimentController.java index 507a8a74..7d334e74 100644 --- a/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/BatimentController.java +++ b/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/BatimentController.java @@ -4,47 +4,42 @@ import java.util.List; import java.util.Map; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.MediaType; - import org.georchestra.cadastrapp.helper.BatimentHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; - +@Controller public class BatimentController extends CadController { final static Logger logger = LoggerFactory.getLogger(BatimentController.class); @Autowired BatimentHelper batimentHelper; - - @GET - @Path("/getBatiments") - @Produces(MediaType.APPLICATION_JSON) + + @RequestMapping(path ="/getBatiments", produces = {MediaType.APPLICATION_JSON_VALUE}, method= {RequestMethod.GET}) /** * getBuildingsDetails - * Returns information about batiment dnubat on given parcell + * Returns information about batiment dnubat on given plot * - * @param headers http headers used * @param parcelle parcelle id * @param dnubat batiment number * * @return JSON list */ - public List> getBuildingsDetails(@Context HttpHeaders headers, - @QueryParam("parcelle") String parcelle, - @QueryParam("dnubat") String dnubat){ + public @ResponseBody List> getBuildingsDetails( + @RequestParam("parcelle") String parcelle, + @RequestParam("dnubat") String dnubat){ List> batiments = new ArrayList>(); - if (getUserCNILLevel(headers) == 0) { + if (getUserCNILLevel() == 0) { logger.info("User does not have enough rights to see information about batiment"); } else if(parcelle != null && !parcelle.isEmpty() @@ -81,28 +76,24 @@ else if(parcelle != null && !parcelle.isEmpty() return batiments; } - - @GET - @Path("/getBatimentsByParcelle") - @Produces(MediaType.APPLICATION_JSON) + @RequestMapping(path = "/getBatimentsByParcelle" , produces = {MediaType.APPLICATION_JSON_VALUE}, method= {RequestMethod.GET}) /** * Returns all building from given plot - * - * @param headers http headers used only available for CNIL 2 + * * @param parcelle on unique plot id * * @return JSON list compose with all dnubat from this plot, list is empy if no data, or if user doesn't have rights */ - public List> getBuildingsByParcelle(@Context HttpHeaders headers, - @QueryParam("parcelle") String parcelle){ + public @ResponseBody List> getBuildingsByParcelle( + @RequestParam String parcelle){ List> batiments = new ArrayList>(); - if (getUserCNILLevel(headers) == 0) { + if (getUserCNILLevel() == 0) { logger.info("User does not have enough rights to see information about buildings"); } else if(parcelle != null && !parcelle.isEmpty()) { - batiments = batimentHelper.getBuildings(parcelle, headers); + batiments = batimentHelper.getBuildings(parcelle); } else{ logger.info(" Missing input parameter "); diff --git a/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/CadController.java b/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/CadController.java index c16aa8d7..5f64014a 100644 --- a/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/CadController.java +++ b/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/CadController.java @@ -7,16 +7,17 @@ import javax.annotation.Resource; import javax.sql.DataSource; -import javax.ws.rs.core.HttpHeaders; import org.georchestra.cadastrapp.configuration.CadastrappPlaceHolder; +import org.georchestra.cadastrapp.service.constants.CadastrappConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.slf4j.MDC; import org.springframework.jdbc.core.JdbcTemplate; /** * - * @author gfi + * @author pierre jego * */ public class CadController { @@ -43,8 +44,7 @@ public class CadController { protected final String ACCES_ERROR_LOG = "User does not have rights to see thoses informations"; protected final String EMPTY_REQUEST_LOG = "Parcelle Id List is empty nothing to search"; - - + /** * */ @@ -106,14 +106,12 @@ protected boolean checkAreMandatoryParametersValid(List mandatoryList) { * @param headers httpheader information, here we need sec-roles information * @return 0 if user doesnot have any specific right, 1 for CNILLEVEL 1 et 2 for CNILLEVEL 2 */ - protected int getUserCNILLevel(HttpHeaders headers) { + protected int getUserCNILLevel() { int cnilLevel = 0; - + String rolesList = MDC.get(CadastrappConstants.HTTP_HEADER_ROLES); + logger.debug(" Check user CNIL Level "); - - // Get CNIL Group information - String rolesList = headers.getHeaderString("sec-roles"); logger.debug(" Get user roles informations : " + rolesList); if (rolesList!=null && rolesList.contains(cnil2RoleName)) { cnilLevel = 2; @@ -125,27 +123,20 @@ protected int getUserCNILLevel(HttpHeaders headers) { return cnilLevel; } - /** - * Filter information depending on groups information - * - * - * @param headers to search groups filtering - * @return an SQL condition to add to initial query - */ - protected String addAuthorizationFiltering(HttpHeaders headers) { - return addAuthorizationFiltering(headers, ""); + protected String addAuthorizationFiltering() { + return addAuthorizationFiltering(""); } - + /** * Filter information depending on groups information * - * - * @param headers to search groups filtering * @param tableAlias table alias for original request to add to the condition * * @return query to complete user right */ - protected String addAuthorizationFiltering(HttpHeaders headers, String tableAlias) { + protected String addAuthorizationFiltering(String tableAlias) { + + logger.debug("Check user geographical limitation "); List> limitations; List communes = new ArrayList(); @@ -153,15 +144,15 @@ protected String addAuthorizationFiltering(HttpHeaders headers, String tableAlia StringBuilder queryFilter = new StringBuilder(); - String usernameString = headers.getHeaderString("sec-username"); + String usernameString = MDC.get(CadastrappConstants.HTTP_HEADER_USERNAME); if (usernameString == null){ logger.debug("Not checking geographical limitation, anonymous user"); return queryFilter.toString(); } // get org in header - String orgString = headers.getHeaderString("sec-org"); + String orgString = MDC.get(CadastrappConstants.HTTP_HEADER_ORGANISME); // get roles in heade - String roleListString = headers.getHeaderString("sec-roles"); + String roleListString = MDC.get(CadastrappConstants.HTTP_HEADER_ROLES); // merge org+roles to get groups list List groupsList = new ArrayList(); diff --git a/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/CoProprietaireController.java b/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/CoProprietaireController.java index 69dcef7b..13ed6062 100644 --- a/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/CoProprietaireController.java +++ b/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/CoProprietaireController.java @@ -15,18 +15,6 @@ import java.util.List; import java.util.Map; -import javax.ws.rs.DefaultValue; -import javax.ws.rs.FormParam; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.ResponseBuilder; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; @@ -40,6 +28,7 @@ import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; +import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import org.apache.fop.apps.FOPException; import org.apache.fop.apps.Fop; @@ -53,6 +42,17 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Controller; +import org.springframework.http.ContentDisposition; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; + /** * Service to get co owners information @@ -60,6 +60,7 @@ * @author pierre jego * */ +@Controller public class CoProprietaireController extends CadController { static final Logger logger = LoggerFactory.getLogger(CoProprietaireController.class); @@ -70,9 +71,7 @@ public class CoProprietaireController extends CadController { @Autowired ProprieteHelper proprieteHelper; - @Path("/getCoProprietaireList") - @GET - @Produces(MediaType.APPLICATION_JSON) + @RequestMapping(path ="/getCoProprietaireList", produces = {MediaType.APPLICATION_JSON_VALUE}, method= {RequestMethod.GET}) /** * * /getCoProprietaireList @@ -85,18 +84,18 @@ public class CoProprietaireController extends CadController { * * @throws SQLException */ - public List> getCoProprietairesList(@Context HttpHeaders headers, - @QueryParam("parcelle") String parcelle, - @QueryParam("comptecommunal") String comptecommunal, - @QueryParam("cgocommune") String cgocommune, - @QueryParam("ddenom") String ddenom, - @DefaultValue("0") @QueryParam("details") int details) throws SQLException { + public @ResponseBody List> getCoProprietairesList( + @RequestParam(required= false) String parcelle, + @RequestParam(required= false) String comptecommunal, + @RequestParam(required= false) String cgocommune, + @RequestParam(required= false) String ddenom, + @RequestParam(defaultValue= "0", required= false) int details) throws SQLException { List> coProprietaires = new ArrayList>(); List queryParams = new ArrayList(); // only for CNIL1 and CNIL2 - if (getUserCNILLevel(headers) > 0 && cgocommune != null && cgocommune.length() >0) { + if (getUserCNILLevel() > 0 && cgocommune != null && cgocommune.length() >0) { boolean isParamValid = false; @@ -135,7 +134,7 @@ public List> getCoProprietairesList(@Context HttpHeaders hea if(isParamValid){ queryCoProprietaireBuilder.append("and prop.comptecommunal = proparc.comptecommunal "); - queryCoProprietaireBuilder.append(addAuthorizationFiltering(headers, "prop.")); + queryCoProprietaireBuilder.append(addAuthorizationFiltering("prop.")); JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); coProprietaires = jdbcTemplate.queryForList(queryCoProprietaireBuilder.toString(), queryParams.toArray()); } @@ -144,25 +143,23 @@ public List> getCoProprietairesList(@Context HttpHeaders hea return coProprietaires; } - @Path("/getCoProprietaire") - @GET - @Produces(MediaType.APPLICATION_JSON) + @RequestMapping(path = "/getCoProprietaire", produces = {MediaType.APPLICATION_JSON_VALUE}, method= {RequestMethod.GET}) /** * getCoProprietaire * * @param parcelle * @return */ - public Map getCoProprietaire(@QueryParam("parcelle") String parcelle, - @DefaultValue("0") @QueryParam("start") int start, - @DefaultValue("25") @QueryParam("limit") int limit, @Context HttpHeaders headers) { + public @ResponseBody Map getCoProprietaire(@RequestParam String parcelle, + @RequestParam(defaultValue= "0", required= false) int start, + @RequestParam(defaultValue= "25", required= false) int limit) { logger.debug("get Co Proprietaire - parcelle : " + parcelle); Map finalResult = new HashMap(); List> result = new ArrayList>(); - if (getUserCNILLevel(headers) > 0) { + if (getUserCNILLevel() > 0) { JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); @@ -173,7 +170,7 @@ public Map getCoProprietaire(@QueryParam("parcelle") String parc queryCount.append(".co_propriete_parcelle propar, "); queryCount.append(databaseSchema); queryCount.append(".proprietaire p where propar.parcelle = ? and p.comptecommunal = propar.comptecommunal "); - queryCount.append(addAuthorizationFiltering(headers, "p.")); + queryCount.append(addAuthorizationFiltering("p.")); queryCount.append(" ) as temp;"); int resultCount = jdbcTemplate.queryForObject(queryCount.toString(), new Object[] {parcelle}, Integer.class); @@ -193,7 +190,7 @@ public Map getCoProprietaire(@QueryParam("parcelle") String parc queryBuilder.append(databaseSchema); queryBuilder.append(".proprietaire p where propar.parcelle = ? "); queryBuilder.append(" and p.comptecommunal = propar.comptecommunal "); - queryBuilder.append(addAuthorizationFiltering(headers, "p.")); + queryBuilder.append(addAuthorizationFiltering("p.")); queryBuilder.append(" ORDER BY p.app_nom_usage "); queryBuilder.append(" LIMIT ?"); queryBuilder.append(" OFFSET ?"); @@ -210,10 +207,7 @@ public Map getCoProprietaire(@QueryParam("parcelle") String parc } - - @POST - @Path("/exportCoProprietaireByParcelles") - @Produces("text/csv") + @RequestMapping(path = "/exportCoProprietaireByParcelles", produces = {"text/csv;charset=utf-8"}, method= {RequestMethod.POST}) /** * Create a csv file from given parcelles id * @@ -224,18 +218,17 @@ public Map getCoProprietaire(@QueryParam("parcelle") String parc * * @throws SQLException */ - public Response exportProprietaireByParcelles( - @Context HttpHeaders headers, - @FormParam("parcelles") String parcelles) throws SQLException { + public ResponseEntity exportProprietaireByParcelles( + @RequestParam String parcelles) throws SQLException { // Create empty content - ResponseBuilder response = Response.noContent(); + ResponseEntity response = new ResponseEntity(HttpStatus.NO_CONTENT); // User need to be at least CNIL1 level - if (getUserCNILLevel(headers)>0){ + if (getUserCNILLevel()>0){ String entete = "proprio_id;droit_reel_libelle;denomination_usage;parcelles;civilite;nom_usage;prenom_usage;denomination_naissance;nom_naissance;prenom_naissance;adresse_ligne3;adresse_ligne4;adresse_ligne5;adresse_ligne6;forme_juridique"; - if(getUserCNILLevel(headers)>1){ + if(getUserCNILLevel()>1){ entete = entete + ";lieu_naissance; date_naissance"; } @@ -252,7 +245,7 @@ public Response exportProprietaireByParcelles( queryBuilder.append("select prop.comptecommunal, ccodro_lib, app_nom_usage, string_agg(parcelle, ','), ccoqua_lib, dnomus, dprnus, ddenom, dnomlp, dprnlp, dlign3, dlign4, dlign5, dlign6, dformjur "); // If user is CNIL2 add birth information - if(getUserCNILLevel(headers)>1){ + if(getUserCNILLevel()>1){ queryBuilder.append(", dldnss, jdatnss "); } queryBuilder.append("from "); @@ -262,10 +255,10 @@ public Response exportProprietaireByParcelles( queryBuilder.append(".co_propriete_parcelle proparc "); queryBuilder.append(createWhereInQuery(parcelleList.length, "proparc.parcelle")); queryBuilder.append(" and prop.comptecommunal = proparc.comptecommunal "); - queryBuilder.append(addAuthorizationFiltering(headers)); + queryBuilder.append(addAuthorizationFiltering()); queryBuilder.append("GROUP BY prop.comptecommunal, ccodro_lib, app_nom_usage, ccoqua_lib, dnomus, dprnus, ddenom, dnomlp, dprnlp, dlign3, dlign4, dlign5, dlign6, dformjur"); // If user is CNIL2 add birth information - if(getUserCNILLevel(headers)>1){ + if(getUserCNILLevel()>1){ queryBuilder.append(", dldnss, jdatnss "); } queryBuilder.append(" ORDER BY prop.comptecommunal"); @@ -280,8 +273,9 @@ public Response exportProprietaireByParcelles( file = exportHelper.createCSV(coproprietaires, entete); // build csv response - response = Response.ok((Object) file); - response.header("Content-Disposition", "attachment; filename=" + file.getName()); + HttpHeaders headers = new HttpHeaders(); + headers.setContentDispositionFormData("filename", file.getName()); + response = new ResponseEntity(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK); }catch (IOException e) { logger.error("Error while creating CSV files ", e); } finally { @@ -298,12 +292,10 @@ public Response exportProprietaireByParcelles( logger.info("User does not have rights to see thoses informations"); } - return response.build(); + return response; } - @POST - @Path("/exportLotsAsCSV") - @Produces("text/csv") + @RequestMapping(path = "/exportLotsAsCSV", produces = {"text/csv;charset=utf-8"}, method= {RequestMethod.POST}) /** * Create a csv file from given plot and building id * @@ -315,14 +307,14 @@ public Response exportProprietaireByParcelles( * * @throws SQLException */ - public Response exportLotsAsSCV( - @Context HttpHeaders headers, - @FormParam("parcelle") String parcelle, @FormParam("dnubat") String dnubat) throws SQLException { + public ResponseEntity exportLotsAsSCV( + @RequestParam String parcelle, + @RequestParam String dnubat) throws SQLException { // Create empty content - ResponseBuilder response = Response.noContent(); + ResponseEntity response = new ResponseEntity(HttpStatus.NO_CONTENT); - if(getUserCNILLevel(headers)>0){ + if(getUserCNILLevel()>0){ logger.debug("Input parameters are : " + parcelle + " - " + dnubat); String entete = "parcelle_num;numero_local;batiment;numero_lot;part_lot;total_lot;logement;dependance;local_commercial;type_proprietaire;compte_communal;nom_proprietaire;adresse"; @@ -335,8 +327,9 @@ public Response exportLotsAsSCV( file = exportHelper.createCSV(bundleResults, entete); // build csv response - response = Response.ok((Object) file); - response.header("Content-Disposition", "attachment; filename=" + file.getName()); + HttpHeaders headers = new HttpHeaders(); + headers.setContentDispositionFormData("filename", file.getName()); + response = new ResponseEntity(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK); }catch (IOException e) { logger.error("Error while creating CSV files ", e); } finally { @@ -348,16 +341,13 @@ public Response exportLotsAsSCV( logger.info("User does not have rights to see thoses informations"); } - return response.build(); + return response; } - @POST - @Path("/exportLotsAsPDF") - @Produces("application/pdf") + @RequestMapping(path = "/exportLotsAsPDF" , produces = {MediaType.APPLICATION_PDF_VALUE}, method= {RequestMethod.POST}) /** * Create a pdf file from given plot and building id * - * @param headers Used to filter displayed information * @param parcelle String * @param dnubat String * @@ -365,14 +355,14 @@ public Response exportLotsAsSCV( * * @throws SQLException */ - public Response exportLotsAsPDF( - @Context HttpHeaders headers, - @FormParam("parcelle") String parcelle, @FormParam("dnubat") String dnubat) throws SQLException { + public ResponseEntity exportLotsAsPDF( + @RequestParam String parcelle, + @RequestParam String dnubat) throws SQLException { // Create empty content - ResponseBuilder response = Response.noContent(); + ResponseEntity response = new ResponseEntity(HttpStatus.NO_CONTENT); - if(getUserCNILLevel(headers)>0){ + if(getUserCNILLevel()>0){ logger.debug("Input parameters are : " + parcelle + " - " + dnubat); final String xslTemplate = "xsl/lots.xsl"; @@ -457,11 +447,17 @@ public Response exportLotsAsPDF( transformerPDF.transform(src, res); out.close(); - + // Create response - response = Response.ok((Object) pdfResult); - response.header("Content-Disposition", "attachment; filename=" + pdfResult.getName()); + ContentDisposition contentDisposition = ContentDisposition.builder("attachment") + .filename(pdfResult.getName()) + .build(); + + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_PDF); + headers.setContentDisposition(contentDisposition); + response = new ResponseEntity(FileUtils.readFileToByteArray(pdfResult), headers, HttpStatus.OK); } catch (JAXBException jaxbException) { logger.warn("Error during converting object to xml : " + jaxbException); } catch (TransformerException transformerException) { @@ -503,6 +499,6 @@ public Response exportLotsAsPDF( logger.info("User does not have rights to see thoses informations"); } - return response.build(); + return response; } } diff --git a/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/CommuneController.java b/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/CommuneController.java index fdf73e90..9ef1fb49 100644 --- a/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/CommuneController.java +++ b/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/CommuneController.java @@ -4,27 +4,24 @@ import java.util.List; import java.util.Map; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.HttpHeaders; - -import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Controller; +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; +@Controller public class CommuneController extends CadController{ final static Logger logger = LoggerFactory.getLogger(CommuneController.class); - @Path("/getCommune/") - @GET - @Produces("application/json") + @RequestMapping(path = "/getCommune", produces = {MediaType.APPLICATION_JSON_VALUE}, method= {RequestMethod.GET}) /** * /getCommune * @@ -41,10 +38,9 @@ public class CommuneController extends CadController{ * * @throws SQLException */ - public List> getCommunesList( - @Context HttpHeaders headers, - @QueryParam("libcom") String libCom, - @QueryParam("cgocommune") String cgoCommune){ + public @ResponseBody List> getCommunesList( + @RequestParam(name= "libcom", required= false) String libCom, + @RequestParam(name= "cgocommune", required= false) String cgoCommune){ List> communes = new ArrayList>(); List queryParams = new ArrayList(); @@ -86,7 +82,7 @@ public List> getCommunesList( } if(isSearchFiltered){ - queryBuilder.append(addAuthorizationFiltering(headers)); + queryBuilder.append(addAuthorizationFiltering()); } queryBuilder.append(" order by libcom "); diff --git a/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/ConfigurationController.java b/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/ConfigurationController.java index c0c36796..7a749a3b 100644 --- a/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/ConfigurationController.java +++ b/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/ConfigurationController.java @@ -3,30 +3,28 @@ import java.util.HashMap; import java.util.Map; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; - import org.georchestra.cadastrapp.configuration.CadastrappPlaceHolder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; -public class ConfigurationController { +@Controller +public class ConfigurationController extends CadController{ final static Logger logger = LoggerFactory.getLogger(ConfigurationController.class); - - @GET - @Path("/getConfiguration") - @Produces(MediaType.APPLICATION_JSON) + @RequestMapping(path = "/getConfiguration", produces = {MediaType.APPLICATION_JSON_VALUE}, method= {RequestMethod.GET}) /** * Returns server configuration witch is common to client side * * @return JSON list */ - public Map getConfiguration(){ + public @ResponseBody Map getConfiguration(){ Map configuration = new HashMap(); diff --git a/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/DatadirController.java b/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/DatadirController.java index 6d502487..8f5152f3 100644 --- a/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/DatadirController.java +++ b/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/DatadirController.java @@ -5,17 +5,19 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; import java.io.File; import java.io.FileInputStream; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - - +@Controller public class DatadirController extends CadController { static final Logger logger = LoggerFactory.getLogger(DatadirController.class); @@ -102,31 +104,34 @@ private String imageToString(String nameImage){ * * @return Response that contain File */ - @POST - @Path("/getImageFromDataDir") - public Response getBaseMapPreview(@RequestParam("imageName") String imageName) { + @RequestMapping(path = "/getImageFromDataDir", produces = {MediaType.TEXT_PLAIN_VALUE}, method= {RequestMethod.POST}) + public ResponseEntity getBaseMapPreview(@RequestParam("imageName") String imageName) { + String encodedImage; String encodedErrorImage; - // use to find mime type try{ // return image as data base64 encodedImage = imageToString(imageName); + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.TEXT_PLAIN); + if(encodedImage != null){ - return Response.ok(encodedImage,MediaType.TEXT_PLAIN).build(); + return new ResponseEntity(encodedImage, headers, HttpStatus.OK); } else { // return image error as data base64 encodedErrorImage = imageToString("error.png"); if(encodedErrorImage != null){ logger.error("File not exist or fail to encode file : display error image"); - return Response.ok(encodedErrorImage,MediaType.TEXT_PLAIN).build(); + return new ResponseEntity(encodedErrorImage, headers, HttpStatus.OK); } else { - return Response.status(Response.Status.NOT_FOUND).entity("Image not found for : " + imageName).build(); + return ResponseEntity.status(HttpStatus.NOT_FOUND).body(("Image not found for : " + imageName)); } } } catch (Exception e){ - // response with bad request error - return Response.status(Response.Status.BAD_REQUEST).entity(e).build(); + // response with bad request error + logger.error("Error while getting image from datadir", e); + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage()); } } diff --git a/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/HabitationController.java b/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/HabitationController.java index 2c5d5b91..3d58647a 100644 --- a/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/HabitationController.java +++ b/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/HabitationController.java @@ -5,17 +5,15 @@ import java.util.List; import java.util.Map; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.MediaType; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.http.MediaType; import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; /** * HabitationController @@ -25,35 +23,31 @@ * @author pierre * */ +@Controller public class HabitationController extends CadController { static final Logger logger = LoggerFactory.getLogger(HabitationController.class); - - @GET - @Path("/getHabitationDetails") - @Produces(MediaType.APPLICATION_JSON) + @RequestMapping(path = "/getHabitationDetails", produces = {MediaType.APPLICATION_JSON_VALUE}, method= {RequestMethod.GET}) /** * Returns information about habitation * - * @param headers HttpHeaders http headers used - * information will only be return if user is CNIL2 * @param annee String corresponding to year of wanted information (normally only current year available) * @param invar String id habitation * * @return Map containing informations from article 40 50 and 60, * empty list if missing input parameter or if user doesn't have privilege */ - public Map getHabitationDetails(@Context HttpHeaders headers, - @QueryParam("annee") String annee, - @QueryParam("invar") String invar){ + public @ResponseBody Map getHabitationDetails( + @RequestParam String annee, + @RequestParam String invar){ Map habitationDesc = new HashMap(); List queryParams = new ArrayList(); queryParams.add(annee); queryParams.add(invar); - if (getUserCNILLevel(headers) == 0) { + if (getUserCNILLevel() == 0) { logger.info("User needs does not have enough rights to see habitation details"); } else if(annee != null && invar != null) @@ -74,7 +68,7 @@ else if(annee != null && invar != null) * @param queryParams List composed with year and invar information * @return List> */ - private List> getArticle40Details(List queryParams){ + private @ResponseBody List> getArticle40Details(List queryParams){ logger.debug("getArticle40Details"); StringBuilder queryBuilder = new StringBuilder(); diff --git a/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/ImageParcelleController.java b/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/ImageParcelleController.java index 1ff94b18..db412491 100644 --- a/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/ImageParcelleController.java +++ b/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/ImageParcelleController.java @@ -8,9 +8,9 @@ import java.awt.RenderingHints; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; -import java.io.File; import java.io.IOException; import java.io.Serializable; +import java.io.ByteArrayOutputStream; import java.net.URL; import java.net.URLEncoder; import java.nio.charset.Charset; @@ -18,41 +18,39 @@ import java.util.Map; import javax.imageio.ImageIO; -import javax.ws.rs.DefaultValue; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.ResponseBuilder; import javax.xml.transform.TransformerException; import org.georchestra.cadastrapp.configuration.CadastrappPlaceHolder; -import org.geotools.data.ows.HTTPClient; -import org.geotools.data.ows.Layer; -import org.geotools.data.ows.SimpleHttpClient; +import org.geotools.data.DataStore; +import org.geotools.data.DataStoreFinder; +import org.geotools.http.HTTPClient; +import org.geotools.http.SimpleHttpClient; import org.geotools.data.simple.SimpleFeatureCollection; import org.geotools.data.simple.SimpleFeatureIterator; import org.geotools.data.simple.SimpleFeatureSource; -import org.geotools.data.wfs.impl.WFSContentDataStore; -import org.geotools.data.wfs.impl.WFSDataStoreFactory; -import org.geotools.data.wms.WebMapServer; -import org.geotools.data.wms.request.GetMapRequest; -import org.geotools.data.wms.response.GetMapResponse; +import org.geotools.data.wfs.WFSDataStoreFactory; import org.geotools.factory.CommonFactoryFinder; import org.geotools.filter.text.cql2.CQL; import org.geotools.filter.text.cql2.CQLException; import org.geotools.geometry.jts.JTS; import org.geotools.ows.ServiceException; +import org.geotools.ows.wms.Layer; +import org.geotools.ows.wms.WebMapServer; +import org.geotools.ows.wms.request.GetMapRequest; +import org.geotools.ows.wms.response.GetMapResponse; import org.geotools.styling.FeatureTypeStyle; import org.geotools.styling.Fill; import org.geotools.styling.NamedLayer; import org.geotools.styling.PolygonSymbolizer; import org.geotools.styling.Rule; -import org.geotools.styling.SLDTransformer; import org.geotools.styling.Stroke; import org.geotools.styling.Style; import org.geotools.styling.StyledLayerDescriptor; +import org.geotools.xml.styling.SLDTransformer; +import org.locationtech.jts.geom.Coordinate; +import org.locationtech.jts.geom.Envelope; +import org.locationtech.jts.geom.Geometry; +import org.locationtech.jts.geom.Point; import org.opengis.filter.Filter; import org.opengis.filter.FilterFactory2; import org.opengis.feature.simple.SimpleFeature; @@ -61,27 +59,28 @@ import org.opengis.referencing.operation.TransformException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - -import com.vividsolutions.jts.geom.Coordinate; -import com.vividsolutions.jts.geom.Envelope; -import com.vividsolutions.jts.geom.Geometry; -import com.vividsolutions.jts.geom.Point; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; /** * Image Parcelle Controller * - * @author gfi + * @author pierre jego * */ +@Controller public class ImageParcelleController extends CadController { static final Logger logger = LoggerFactory.getLogger(ImageParcelleController.class); private final String URL_GET_CAPABILITIES = "?REQUEST=GetCapabilities&version=1.0.0"; private final String URL_GET_CAPABILITIES_WMS = "?VERSION=1.1.1&Request=GetCapabilities&Service=WMS"; - private final String GET_CAPABILITIES_URL_PARAM = "WFSDataStoreFactory:WFS_GET_CAPABILITIES_URL"; - private final String USERNAME_PARAM = "WFSDataStoreFactory:USERNAME"; - private final String PASSWORD_PARAM = "WFSDataStoreFactory:PASSWORD"; // buffer ratio final private double MAX_PERIMETER = 2000; @@ -100,18 +99,17 @@ public class ImageParcelleController extends CadController { * @param baseMapIndex corresponding of the wanted index in cadastrapp.properties * @return Response with noContent in case of error, png otherwise */ - @GET - @Path("/getImageBordereau") - @Produces("image/png") - public Response createImageBordereauParcellaire(@QueryParam("parcelle") String parcelle, - @DefaultValue("0") @QueryParam("basemapindex") int baseMapIndex, - @DefaultValue("1446DE") @QueryParam("fillcolor") String styleFillColor, - @DefaultValue("0.50") @QueryParam("fillopacity") float styleFillOpacity, - @DefaultValue("10259E") @QueryParam("strokecolor") String styleStrokeColor, - @DefaultValue("2") @QueryParam("strokewidth") int styleStrokeWidth) { + @RequestMapping(path = "/getImageBordereau", produces = {MediaType.IMAGE_PNG_VALUE}, method= {RequestMethod.GET}) + public ResponseEntity createImageBordereauParcellaire( + @RequestParam() String parcelle, + @RequestParam(defaultValue = "0", name ="basemapindex", required = false) int baseMapIndex, + @RequestParam(defaultValue = "1446DE", name ="fillcolor", required = false) String styleFillColor, + @RequestParam(defaultValue = "0.50", name ="fillopacity", required = false) float styleFillOpacity, + @RequestParam(defaultValue = "10259E", name ="strokecolor", required = false) String styleStrokeColor, + @RequestParam(defaultValue = "2", name ="strokewidth", required = false) int styleStrokeWidth) { // Create empty reponse for default value - ResponseBuilder response = Response.noContent(); + ResponseEntity response = new ResponseEntity(HttpStatus.NO_CONTENT); final int parcelleIdLength = Integer.parseInt(CadastrappPlaceHolder.getProperty("parcelleId.length")); @@ -132,31 +130,37 @@ public Response createImageBordereauParcellaire(@QueryParam("parcelle") String p logger.debug("Call WFS with plot Id " + parcelle + " and WFS URL : " + getCapabilities); Map connectionParameters = new HashMap(); - connectionParameters.put(GET_CAPABILITIES_URL_PARAM, getCapabilities); + connectionParameters.put(WFSDataStoreFactory.URL.key, getCapabilities); + connectionParameters.put(WFSDataStoreFactory.TRY_GZIP.key, Boolean.TRUE); // Add basic authent parameter if not empty final String cadastreWFSUsername = CadastrappPlaceHolder.getProperty("cadastre.wfs.username"); final String cadastreWFSPassword = CadastrappPlaceHolder.getProperty("cadastre.wfs.password"); if (cadastreWFSUsername != null && !cadastreWFSUsername.isEmpty()){ - connectionParameters.put(USERNAME_PARAM, cadastreWFSUsername); - connectionParameters.put(PASSWORD_PARAM, cadastreWFSPassword); + connectionParameters.put(WFSDataStoreFactory.USERNAME.key, cadastreWFSUsername); + connectionParameters.put(WFSDataStoreFactory.PASSWORD.key, cadastreWFSPassword); } - - WFSDataStoreFactory dsf = new WFSDataStoreFactory(); - WFSContentDataStore dataStore; + + DataStore dataStore; try { - dataStore = dsf.createDataStore(connectionParameters); + dataStore = DataStoreFinder.getDataStore(connectionParameters); + + // check all typeName, geo_parcelle are sometimes visibile in geoserver but not here + // redeploy in geoserver is needed + if(logger.isDebugEnabled()){ + logger.debug("Datastore name "+ dataStore.getTypeNames()); + for (String typeName : dataStore.getTypeNames()) { + logger.debug("Type name : " + typeName); + } + } SimpleFeatureSource source; - String cadastreWFSLayerNameOri = CadastrappPlaceHolder.getProperty("cadastre.wfs.layer.name"); - - // remove this if not using gt-wfs-ng anymore - // using ng extension : need to be changed by_ - String cadastreWFSLayerName = cadastreWFSLayerNameOri.replaceFirst(":", "_"); + String cadastreWFSLayerName = CadastrappPlaceHolder.getProperty("cadastre.wfs.layer.name"); String cadastreLayerIdParcelle = CadastrappPlaceHolder.getProperty("cadastre.layer.idParcelle"); + logger.debug("Cadastre WFS LayerName "+ cadastreWFSLayerName); source = dataStore.getFeatureSource(cadastreWFSLayerName); // Make sure source have been found before making request filter @@ -291,15 +295,14 @@ public Response createImageBordereauParcellaire(@QueryParam("parcelle") String p if(plotLayerWmsUrl != null && !plotLayerWmsUrl.isEmpty()){ wmsCadastralLayer = createWebMapServer(plotLayerWmsUrl,plotLayerWmsUsername, plotLayerWmsPassword ); - cadastreWFSLayerNameOri = CadastrappPlaceHolder.getProperty("parcelle.wms.layer.name"); //TODO see if specific SRS and format are needed - requestCadastralLayer = createAndConfigureMapRequest(wmsCadastralLayer, cadastralLayerFormat, cadastreWFSLayerNameOri, pdfImagePixelSize, cadastreSRS, bounds); + requestCadastralLayer = createAndConfigureMapRequest(wmsCadastralLayer, cadastralLayerFormat, cadastreWFSLayerName, pdfImagePixelSize, cadastreSRS, bounds); cadastreLayerIdParcelle = CadastrappPlaceHolder.getProperty("parcelle.wms.layer.id"); } logger.debug("Create feature image from WMS"); - StyledLayerDescriptor sld = generateSLD(cadastreWFSLayerNameOri, cadastreLayerIdParcelle, parcelle, styleFillColor, styleFillOpacity, styleStrokeColor, styleStrokeWidth); + StyledLayerDescriptor sld = generateSLD(cadastreWFSLayerName, cadastreLayerIdParcelle, parcelle, styleFillColor, styleFillOpacity, styleStrokeColor, styleStrokeWidth); SLDTransformer styleTransform = new SLDTransformer(); styleTransform.setEncoding(Charset.forName("UTF-8")); @@ -376,14 +379,16 @@ public Response createImageBordereauParcellaire(@QueryParam("parcelle") String p g2.dispose(); - // Get temp folder from properties file - final String tempFolder = CadastrappPlaceHolder.getProperty("tempFolder"); - - File file = new File(tempFolder + File.separator + "BP-" + parcelle + ".png"); - file.deleteOnExit(); - ImageIO.write(finalImage, "png", file); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ImageIO.write(finalImage, "png", baos); + byte[] bytes = baos.toByteArray(); + + // Create response + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.IMAGE_PNG); + headers.setContentDispositionFormData("filename", "BP-" + parcelle + ".png"); - response = Response.ok((Object) file); + response = new ResponseEntity(bytes, headers, HttpStatus.OK); } else { logger.info("No plots corresponding on WFS server"); } @@ -401,7 +406,7 @@ public Response createImageBordereauParcellaire(@QueryParam("parcelle") String p logger.info("No image can be generated with given input parameters"); } - return response.build(); + return response; } /** diff --git a/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/InfoBulleController.java b/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/InfoBulleController.java index d4c371df..bf32906c 100644 --- a/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/InfoBulleController.java +++ b/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/InfoBulleController.java @@ -5,32 +5,25 @@ import java.util.List; import java.util.Map; -import javax.ws.rs.DefaultValue; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.MediaType; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.dao.EmptyResultDataAccessException; +import org.springframework.http.MediaType; import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; - +@Controller public class InfoBulleController extends CadController { final static Logger logger = LoggerFactory.getLogger(InfoBulleController.class); - @Path("/getInfoBulle") - @GET - @Produces(MediaType.APPLICATION_JSON) + @RequestMapping(path = "/getInfoBulle", produces = {MediaType.APPLICATION_JSON_VALUE}, method= {RequestMethod.GET}) /** - * - * @param headers / headers from request used to filter search using LDAP Roles to display only information about parcelle from available cgocommune * * @param parcelle id parcelle * @param infocadastrale 1 to get additional information, 0 to avoid getting additional information (default value 1 if not set) @@ -40,44 +33,38 @@ public class InfoBulleController extends CadController { * * @throws SQLException */ - public Map getInfoBulle( - @Context HttpHeaders headers, - @QueryParam("parcelle") String parcelle, - @DefaultValue("1") @QueryParam("infocadastrale") int infocadastrale, - @DefaultValue("1") @QueryParam("infouf") int infouf) throws SQLException { + public @ResponseBody Map getInfoBulle( + @RequestParam String parcelle, + @RequestParam(defaultValue = "1", required = false) int infocadastrale, + @RequestParam(defaultValue = "1", required = false) int infouf) throws SQLException { Map informations = null; if(infocadastrale == 0 && infouf == 1){ - informations = getInfoBulleUniteFonciere(headers, parcelle); + informations = getInfoBulleUniteFonciere(parcelle); }else if (infocadastrale == 1 && infouf == 0){ - informations = getInfoBulleParcelle(headers, parcelle); + informations = getInfoBulleParcelle(parcelle); }else if (infocadastrale == 0 && infouf == 0){ logger.warn("No information can be serve"); }else{ - informations = getInfoBulleParcelle(headers, parcelle); - informations.putAll(getInfoBulleUniteFonciere(headers, parcelle)); + informations = getInfoBulleParcelle(parcelle); + informations.putAll(getInfoBulleUniteFonciere(parcelle)); } return informations; } - @Path("/getInfobulleParcelle") - @GET - @Produces("application/json") + @RequestMapping(path = "/getInfobulleParcelle", produces = {MediaType.APPLICATION_JSON_VALUE}, method= {RequestMethod.GET}) /** - * - * @param headers / headers from request used to filter search using LDAP Roles to display only information about parcelle from available cgocommune * * @param parcelle id parcelle * @return Data from parcelle view to be display in popup in JSON format * * @throws SQLException */ - public Map getInfoBulleParcelle( - @Context HttpHeaders headers, - @QueryParam("parcelle") String parcelle) throws SQLException { + public @ResponseBody Map getInfoBulleParcelle( + @RequestParam("parcelle") String parcelle) throws SQLException { Map informations = null; @@ -98,7 +85,7 @@ public Map getInfoBulleParcelle( JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); informations = jdbcTemplate.queryForMap(queryBuilder.toString(), parcelle); - if(getUserCNILLevel(headers)>0){ + if(getUserCNILLevel()>0){ List> proprietaires = null; @@ -110,7 +97,7 @@ public Map getInfoBulleParcelle( queryProprietaireBuilder.append(databaseSchema); queryProprietaireBuilder.append(".proprietaire prop "); queryProprietaireBuilder.append(" where proparc.parcelle = ? and proparc.comptecommunal = prop.comptecommunal "); - queryProprietaireBuilder.append(addAuthorizationFiltering(headers, "prop.")); + queryProprietaireBuilder.append(addAuthorizationFiltering("prop.")); queryProprietaireBuilder.append(" LIMIT 9"); JdbcTemplate jdbcTemplateProp = new JdbcTemplate(dataSource); @@ -129,21 +116,16 @@ public Map getInfoBulleParcelle( return informations; } - @Path("/getInfoUniteFonciere") - @GET - @Produces(MediaType.APPLICATION_JSON) + @RequestMapping(path = "/getInfoUniteFonciere", produces = {MediaType.APPLICATION_JSON_VALUE}, method= {RequestMethod.GET}) /** - * - * @param headers / headers from request used to filter search using LDAP Roles to display only information about parcelle from available cgocommune - * + * * @param parcelle id parcelle * @return Data from parcelle view to be display in popup in JSON format * * @throws SQLException */ - public Map getInfoBulleUniteFonciere( - @Context HttpHeaders headers, - @QueryParam("parcelle") String parcelle) throws SQLException { + public @ResponseBody Map getInfoBulleUniteFonciere( + @RequestParam("parcelle") String parcelle) throws SQLException { Map informations = new HashMap(); @@ -163,7 +145,7 @@ public Map getInfoBulleUniteFonciere( // filter on geographical limitation only if search is filtered if(isSearchFiltered){ - queryBuilder.append(addAuthorizationFiltering(headers, "p.")); + queryBuilder.append(addAuthorizationFiltering("p.")); } queryBuilder.append("GROUP BY uf.uf, uf.comptecommunal;"); diff --git a/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/ParcelleController.java b/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/ParcelleController.java index fb58a9df..81e00ed9 100644 --- a/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/ParcelleController.java +++ b/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/ParcelleController.java @@ -10,35 +10,38 @@ import java.util.List; import java.util.Map; -import javax.ws.rs.Consumes; -import javax.ws.rs.DefaultValue; -import javax.ws.rs.FormParam; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.ResponseBuilder; - -import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; -import org.codehaus.jackson.map.ObjectMapper; -import org.codehaus.jackson.map.ObjectWriter; import org.georchestra.cadastrapp.model.pdf.ExtFormResult; import org.georchestra.cadastrapp.service.export.ExportHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Controller; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectWriter; + +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; /** * Parcelle controller expose all rest service for plots information */ +@Api( description="Récupération des informations de parcelles") +@Controller public class ParcelleController extends CadController { static final Logger logger = LoggerFactory.getLogger(ParcelleController.class); @@ -46,48 +49,33 @@ public class ParcelleController extends CadController { @Autowired ExportHelper exportHelper; - @GET - @Path("/getParcelle") - @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Récupère la liste des parcelles") + @RequestMapping(path = "/getParcelle", produces = {MediaType.APPLICATION_JSON_VALUE}, method = { RequestMethod.GET, RequestMethod.POST }) /** * Works like {@link #getParcelle} */ - public List> getParcelleGET(@Context HttpHeaders headers, @QueryParam("parcelle") final List parcelleList, @DefaultValue("0") @QueryParam("details") int details, @QueryParam("cgocommune") String cgoCommune, @QueryParam("ccopre") String ccopre, @QueryParam("ccosec") String ccosec, @QueryParam("dnupla") String dnupla, - @QueryParam("dnvoiri") String dnvoiri, @QueryParam("dlindic") String dindic, @QueryParam("cconvo") String cconvo, @QueryParam("dvoilib") String dvoilib, @QueryParam("comptecommunal") final List comptecommunalList, @DefaultValue("0") @QueryParam("unitefonciere") int uf) throws SQLException { - - return getParcelle(headers, parcelleList, details, cgoCommune, ccopre, ccosec, dnupla, dnvoiri, dindic, cconvo, dvoilib, comptecommunalList, uf); - } - - @POST - @Path("/getParcelle") - @Produces(MediaType.APPLICATION_JSON) - /** - * Works like {@link #getParcelle} - */ - public List> getParcellePOST(@Context HttpHeaders headers, - @FormParam("parcelle") final List parcelleList, - @DefaultValue("0") @FormParam("details") int details, - @FormParam("cgocommune") String cgoCommune, - @FormParam("ccopre") String ccopre, - @FormParam("ccosec") String ccosec, - @FormParam("dnupla") String dnupla, - @FormParam("dnvoiri") String dnvoiri, - @FormParam("dlindic") String dindic, - @FormParam("cconvo") String cconvo, - @FormParam("dvoilib") String dvoilib, - @FormParam("comptecommunal") final List comptecommunalList, - @DefaultValue("0") @FormParam("unitefonciere") int uf) throws SQLException { - - return getParcelle(headers, parcelleList, details, cgoCommune, ccopre, ccosec, dnupla, dnvoiri, dindic, cconvo, dvoilib, comptecommunalList, uf); - + public @ResponseBody List> getParcelleEntrypoint( + @RequestParam(name = "parcelle", required = false) final List parcelleList, + @RequestParam(defaultValue = "0", required = false) int details, + @RequestParam(name ="cgocommune", required = false) String cgoCommune, + @RequestParam(required = false) String ccopre, + @RequestParam(required = false) String ccosec, + @RequestParam(required = false) String dnupla, + @RequestParam(required = false) String dnvoiri, + @RequestParam(name = "dlindic", required = false) String dindic, + @RequestParam(required = false) String cconvo, + @RequestParam(required = false) String dvoilib, + @RequestParam(name = "comptecommunal", required = false) final List comptecommunalList, + @RequestParam(name = "unitefonciere", defaultValue = "0", required = false) int uf) throws SQLException { + + return getParcelle(parcelleList, details, cgoCommune, ccopre, ccosec, dnupla, dnvoiri, dindic, cconvo, dvoilib, comptecommunalList, uf); } - + /** * * getParcelle * - * @param headers http headers, used to get ldap role information about the user group * @param parcelleList * could be LIST if one or more element, if only one in the list, * this element could contains list of parcelleids separated by @@ -118,7 +106,7 @@ public List> getParcellePOST(@Context HttpHeaders headers, * * @throws SQLException */ - private List> getParcelle(HttpHeaders headers,final List parcelleList, int details,String cgoCommune, + private List> getParcelle(final List parcelleList, int details,String cgoCommune, String ccopre, String ccosec, String dnupla, String dnvoiri, String dindic, String cconvo, String dvoilib, final List comptecommunalList, int uf) throws SQLException { List> parcellesResult = new ArrayList>(); @@ -127,17 +115,17 @@ private List> getParcelle(HttpHeaders headers,final List parsedParcelleList = prepareParcelleList(parcelleList); - parcellesResult = getParcellesById(parsedParcelleList, details, getUserCNILLevel(headers)); + parcellesResult = getParcellesById(parsedParcelleList, details, getUserCNILLevel()); // Search by Proprietaire } else if (comptecommunalList != null && !comptecommunalList.isEmpty()) { - parcellesResult = getParcellesByProprietaire(comptecommunalList, details, getUserCNILLevel(headers)); + parcellesResult = getParcellesByProprietaire(comptecommunalList, details, getUserCNILLevel()); // Search by unitefonciere } else if (uf != 0) { - parcellesResult = getParcellesByUniteFonciere(uf, details, getUserCNILLevel(headers)); + parcellesResult = getParcellesByUniteFonciere(uf, details, getUserCNILLevel()); // Search by attributes } else { @@ -380,17 +368,18 @@ private String createSelectParcelleQuery(int details) { /** * Service witch use csv file as input * - * @param headers http headers information + * @param roleList fromhttp headers information * @param fileContent * parcelleId separated by space, ',' or ';' * * @return Json data, with corresponding parcelleId information * */ - @POST - @Path("/fromParcellesFile") - @Consumes(MediaType.MULTIPART_FORM_DATA) - public Response getFromParcellesFile(@Context HttpHeaders headers, @FormParam("filePath") String fileContent) { + @RequestMapping(path = "/fromParcellesFile", consumes = {"multipart/form-data" }, method = {RequestMethod.POST }) + public ResponseEntity getFromParcellesFile( + @RequestParam(name = "filePath") String fileContent) { + + ResponseEntity response = new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); // space, , or ; String delimitersRegex = "[\\s\\;\\,\\n]"; @@ -425,7 +414,7 @@ public Response getFromParcellesFile(@Context HttpHeaders headers, @FormParam("f // Avoid make request if no parcelle id is given if (parcelleList != null && !parcelleList.isEmpty()) { - parcellesResult = getParcellesById(parcelleList, 0, getUserCNILLevel(headers)); + parcellesResult = getParcellesById(parcelleList, 0, getUserCNILLevel()); } else { logger.warn("No information given to create csv"); } @@ -434,32 +423,37 @@ public Response getFromParcellesFile(@Context HttpHeaders headers, @FormParam("f // success=true) ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter(); String json = ow.writeValueAsString(new ExtFormResult(true, parcellesResult)); - return Response.ok(json, MediaType.TEXT_HTML).build(); + + // Create response + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.TEXT_HTML); + response = new ResponseEntity<>(json, headers, HttpStatus.OK); } catch (IOException e) { logger.error("Error while trying to read input data ", e); - return Response.serverError().build(); } catch (SQLException e) { logger.error("Error while trying to get information from database ", e); - return Response.serverError().build(); } + return response; } /** * Get export of parcelle for given comptecommunal * - * @param headers + * @param rolesList * make sure user have CNIL level * @param details 1 to have detailed information * @param city cgocommune information from form * @param fileContent file content * @return form validation */ - @POST - @Path("/fromProprietairesFile") - @Consumes(MediaType.MULTIPART_FORM_DATA) - public Response getFromProprietairesFile(@Context HttpHeaders headers, @DefaultValue("0") @FormParam("details") int details, @FormParam("cgocommune") String city, @FormParam("filePath") String fileContent) { + @RequestMapping(path = "/fromProprietairesFile", consumes = {"multipart/form-data"}, method = {RequestMethod.POST }) + public ResponseEntity getFromProprietairesFile( + @RequestParam(defaultValue = "0", required = false) int details, + @RequestParam(name = "filePath") String fileContent) { + + ResponseEntity response = new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); if (logger.isDebugEnabled()) { logger.debug("csv content : " + fileContent); @@ -493,7 +487,7 @@ public Response getFromProprietairesFile(@Context HttpHeaders headers, @DefaultV // Avoid call without parameter if (proprietaireList != null && !proprietaireList.isEmpty()) { - ownersResult = getParcellesByProprietaire(proprietaireList, details, getUserCNILLevel(headers)); + ownersResult = getParcellesByProprietaire(proprietaireList, details, getUserCNILLevel()); } else { logger.warn("No information given to get CompteCommunal information"); } @@ -501,21 +495,24 @@ public Response getFromProprietairesFile(@Context HttpHeaders headers, @DefaultV // les forms ExtJs attendent du JSON sous format TEXT/HTML... (avec success=true) ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter(); String json = ow.writeValueAsString(new ExtFormResult(true, ownersResult)); - return Response.ok(json, MediaType.TEXT_HTML).build(); + + // Create response + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.TEXT_HTML); + response = new ResponseEntity<>(json, headers, HttpStatus.OK); + } catch (IOException e) { logger.error("Error while trying to read input data ", e); - return Response.serverError().build(); } + return response; } - @GET - @Path("/getDnuplaList") - @Produces("application/json") + @ResponseBody + @RequestMapping(path = "/getDnuplaList", produces = {MediaType.APPLICATION_JSON_VALUE}, method = { RequestMethod.GET}) /** * Return only dnupla list from a section of a commune * - * @param headers http headers, used to get ldap role information about the user group * @param cgocommune code commune INSEE * @param ccopre prefix de section * @param ccosec code de section @@ -523,7 +520,10 @@ public Response getFromProprietairesFile(@Context HttpHeaders headers, @DefaultV * * @throws SQLException */ - public List> getDnuplaList(@Context HttpHeaders headers, @QueryParam("cgocommune") String cgoCommune, @QueryParam("ccopre") String ccopre, @QueryParam("ccosec") String ccosec) throws SQLException { + public List> getDnuplaList( + @RequestParam(name= "cgocommune", required= false) String cgoCommune, + @RequestParam(required= false) String ccopre, + @RequestParam(required= false) String ccosec) throws SQLException { List> dnuplaList = null; List queryParams = new ArrayList(); @@ -543,26 +543,22 @@ public List> getDnuplaList(@Context HttpHeaders headers, @Qu return dnuplaList; } - - @POST - @Path("/exportParcellesAsCSV") - @Produces("text/csv") + + @RequestMapping(path = "/exportParcellesAsCSV", produces = {"text/csv;charset=utf-8"}, method = {RequestMethod.POST }) /** * Create a csv file from given parcelles id * - * @param headers Used to filter displayed information * @param parcelles list of parcelle separated by a coma * * @return csv containing list of owners * * @throws SQLException */ - public Response exportParcellesAsSCV( - @Context HttpHeaders headers, - @FormParam("parcelles") String parcelles) throws SQLException { + public ResponseEntity exportParcellesAsSCV( + @RequestParam String parcelles) throws SQLException { // Create empty content - ResponseBuilder response = Response.noContent(); + ResponseEntity response = new ResponseEntity<>(HttpStatus.NO_CONTENT); String entete = "parcelle; commune;voie_adr;voie_adr_cplmt;voie_type;voie_nom;section_prefixe;section;parcelle_num;contenance"; @@ -575,15 +571,18 @@ public Response exportParcellesAsSCV( logger.debug("Nb of parcelles to search in : " + parcelleList.size()); // Get value from database - List> parcellesResult = getParcellesById(parcelleList, 0, getUserCNILLevel(headers)); + List> parcellesResult = getParcellesById(parcelleList, 0, getUserCNILLevel()); File file = null; try{ file = exportHelper.createCSV(parcellesResult, entete); // build csv response - response = Response.ok((Object) file); - response.header("Content-Disposition", "attachment; filename=" + file.getName()); + // build csv response + HttpHeaders headers = new HttpHeaders(); + headers.setContentDispositionFormData("filename", file.getName()); + response = new ResponseEntity<>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK); + }catch (IOException e) { logger.error("Error while creating CSV files ", e); } finally { @@ -597,7 +596,7 @@ public Response exportParcellesAsSCV( logger.info("Parcelle Id List is empty nothing to search"); } - return response.build(); + return response; } } diff --git a/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/ProprietaireController.java b/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/ProprietaireController.java index f23e36fc..0785cd51 100644 --- a/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/ProprietaireController.java +++ b/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/ProprietaireController.java @@ -8,28 +8,28 @@ import java.util.List; import java.util.Map; -import javax.ws.rs.DefaultValue; -import javax.ws.rs.FormParam; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.ResponseBuilder; - +import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import org.georchestra.cadastrapp.configuration.CadastrappPlaceHolder; import org.georchestra.cadastrapp.helper.ProprietaireHelper; import org.georchestra.cadastrapp.service.export.ExportHelper; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ContentDisposition; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; +@Controller public class ProprietaireController extends CadController{ static final Logger logger = LoggerFactory.getLogger(ProprietaireController.class); @@ -41,9 +41,7 @@ public class ProprietaireController extends CadController{ @Autowired ProprietaireHelper proprietaireHelper; - @GET - @Path("/getProprietaire") - @Produces(MediaType.APPLICATION_JSON) + @RequestMapping(path = "/getProprietaire", produces = {MediaType.APPLICATION_JSON_VALUE}, method= {RequestMethod.GET}) /** * This will return information about owners in JSON format * @@ -74,16 +72,15 @@ public class ProprietaireController extends CadController{ * * @throws SQLException */ - public List> getProprietairesList( - @Context HttpHeaders headers, - @QueryParam("dnomlp") String dnomlp, - @QueryParam("cgocommune") String cgocommune, - @QueryParam("dnupro") final List dnuproList, - @QueryParam("comptecommunal") String compteCommunal, - @QueryParam("globalname") String globalName, - @QueryParam("ddenom") String ddenom, - @DefaultValue("false") @QueryParam("birthsearch") boolean isBirthSearch, - @DefaultValue("0") @QueryParam("details") int details + public @ResponseBody List> getProprietairesList( + @RequestParam(required = false) String dnomlp, + @RequestParam(required = false) String cgocommune, + @RequestParam(name= "dnupro", required = false) final List dnuproList, + @RequestParam(name= "comptecommunal", required = false) String compteCommunal, + @RequestParam(name= "globalname", required = false) String globalName, + @RequestParam(required = false) String ddenom, + @RequestParam(defaultValue = "0", name ="birthsearch", required = false) boolean isBirthSearch, + @RequestParam(defaultValue = "0", required = false) int details ) throws SQLException { // Init list to return response even if nothing in it. @@ -92,13 +89,13 @@ public List> getProprietairesList( logger.info("details : " + details); // User need to be at least CNIL1 level - if (getUserCNILLevel(headers)>0){ + if (getUserCNILLevel()>0){ int cgoCommuneLength = Integer.parseInt(CadastrappPlaceHolder.getProperty("cgoCommune.length")); - // No search if all parameters are null or dnomlpPariel less than n char + // No search if all parameters are null or dnomlp ddenom less than n char // when searching by dnupro, cgocommune is mandatory - // when searching bu dnomlp, cgocommune is mandatory + // when searching by dnomlp, cgocommune is mandatory if((dnomlp != null && !dnomlp.isEmpty() && minNbCharForSearch <= dnomlp.length() && cgocommune!=null && cgoCommuneLength == cgocommune.length()) || (globalName != null && !globalName.isEmpty() && minNbCharForSearch <= globalName.length() && cgocommune!=null && cgoCommuneLength == cgocommune.length()) || (ddenom != null && !ddenom.isEmpty() && minNbCharForSearch <= ddenom.length() && cgocommune!=null && cgoCommuneLength == cgocommune.length()) @@ -162,7 +159,7 @@ else if(details == 1){ isWhereAdded = createEqualsClauseRequest(isWhereAdded, queryBuilder, "comptecommunal", compteCommunal, queryParams); - queryBuilder.append(addAuthorizationFiltering(headers)); + queryBuilder.append(addAuthorizationFiltering()); if(details != 2){ queryBuilder.append("order by app_nom_usage, app_nom_naissance limit 25 "); @@ -182,15 +179,10 @@ else if(details == 1){ return proprietaires; } - - @GET - @Path("/getProprietairesByParcelles") - @Produces("application/json") + @RequestMapping(path = "/getProprietairesByParcelles", produces = {MediaType.APPLICATION_JSON_VALUE}, method= {RequestMethod.GET}) /** * This will return information about owners in JSON format * - * - * @param headers headers from request used to filter search using LDAP Roles * @param parcelleList * * @@ -198,22 +190,17 @@ else if(details == 1){ * * @throws SQLException */ - public List> getProprietairesByParcelle( - @Context HttpHeaders headers, - @QueryParam("parcelles") List parcelleList + public @ResponseBody List> getProprietairesByParcelle( + @RequestParam("parcelles") List parcelleList ) throws SQLException { - return proprietaireHelper.getProprietairesByParcelles(headers, parcelleList, true); + return proprietaireHelper.getProprietairesByParcelles(parcelleList, true); } - @GET - @Path("/getProprietairesByInfoParcelles") - @Produces("application/json") + @RequestMapping(path = "/getProprietairesByInfoParcelles", produces = {MediaType.APPLICATION_JSON_VALUE}, method= {RequestMethod.GET}) /** * This will return information about co-owners in JSON format * - * - * @param headers headers from request used to filter search using LDAP Roles * @param commune * @param section containing ccopre+ccosec * @param numero @@ -223,23 +210,20 @@ public List> getProprietairesByParcelle( * * @throws SQLException */ - public List> getProprietairesByInfoParcelle( - @Context HttpHeaders headers, - @QueryParam("commune") String commune, - @QueryParam("section") String section, - @QueryParam("numero") String numero, - @QueryParam("ddenom") String ddenom + public @ResponseBody List> getProprietairesByInfoParcelle( + @RequestParam(required = true) String commune, + @RequestParam(required = true) String section, + @RequestParam(required = true) String numero, + @RequestParam(required = false) String ddenom ) throws SQLException { // Init list to return response even if nothing in it. List> proprietaires = new ArrayList>();; // User need to be at least CNIL1 level - if (getUserCNILLevel(headers)>0){ + if (getUserCNILLevel()>0){ - // if search by dnuproList or comptecommunal - // directly search in view parcelle - if(commune != null || section != null || numero != null){ + if(commune != null && section != null && numero != null){ StringBuilder queryBuilder = new StringBuilder(); List queryParams = new ArrayList(); queryBuilder.append("select distinct "); @@ -280,32 +264,28 @@ public List> getProprietairesByInfoParcelle( return proprietaires; } - - @POST - @Path("/exportProprietaireByParcelles") - @Produces("text/csv") + @RequestMapping(path = "/exportProprietaireByParcelles", produces = {"text/csv"}, method= {RequestMethod.POST}) /** * Create a csv file from given parcelles id * - * @param headers Used to filter displayed information + * @param rolesList Used to filter displayed information * @param parcelles list of parcelle separated by a coma * * @return csv containing list of owners * * @throws SQLException */ - public Response exportProprietaireByParcelles( - @Context HttpHeaders headers, - @FormParam("parcelles") String parcelles) throws SQLException { + public ResponseEntity exportProprietaireByParcelles( + @RequestParam String parcelles) throws SQLException { // Create empty content - ResponseBuilder response = Response.noContent(); + ResponseEntity response = new ResponseEntity(HttpStatus.NO_CONTENT); // User need to be at least CNIL1 level - if (getUserCNILLevel(headers)>0){ + if (getUserCNILLevel()>0){ String entete = "proprio_id;droit_reel_libelle;denomination_usage;parcelles;civilite;nom_usage;prenom_usage;denomination_naissance;nom_naissance;prenom_naissance;adresse_ligne3;adresse_ligne4;adresse_ligne5;adresse_ligne6;forme_juridique"; - if(getUserCNILLevel(headers)>1){ + if(getUserCNILLevel()>1){ entete = entete + ";lieu_naissance; date_naissance"; } @@ -322,7 +302,7 @@ public Response exportProprietaireByParcelles( queryBuilder.append("select prop.comptecommunal, ccodro_lib, app_nom_usage, string_agg(parcelle, ','), ccoqua_lib, dnomus, dprnus, ddenom, dnomlp, dprnlp, dlign3, dlign4, dlign5, dlign6, dformjur "); // If user is CNIL2 add birth information - if(getUserCNILLevel(headers)>1){ + if(getUserCNILLevel()>1){ queryBuilder.append(", dldnss, jdatnss "); } queryBuilder.append("from "); @@ -332,10 +312,10 @@ public Response exportProprietaireByParcelles( queryBuilder.append(".proprietaire_parcelle proparc "); queryBuilder.append(createWhereInQuery(parcelleList.length, "proparc.parcelle")); queryBuilder.append(" and prop.comptecommunal = proparc.comptecommunal "); - queryBuilder.append(addAuthorizationFiltering(headers)); + queryBuilder.append(addAuthorizationFiltering()); queryBuilder.append("GROUP BY prop.comptecommunal, ccodro_lib, app_nom_usage, ccoqua_lib, dnomus, dprnus, ddenom, dnomlp, dprnlp, dlign3, dlign4, dlign5, dlign6, dformjur"); // If user is CNIL2 add birth information - if(getUserCNILLevel(headers)>1){ + if(getUserCNILLevel()>1){ queryBuilder.append(", dldnss, jdatnss "); } queryBuilder.append(" ORDER BY prop.comptecommunal"); @@ -348,8 +328,16 @@ public Response exportProprietaireByParcelles( file = exportHelper.createCSV(proprietaires, entete); // build csv response - response = Response.ok((Object) file); - response.header("Content-Disposition", "attachment; filename=" + file.getName()); + // Create response + ContentDisposition contentDisposition = ContentDisposition.builder("attachment") + .filename(file.getName()) + .build(); + + HttpHeaders headers = new HttpHeaders(); + headers.setContentDisposition(contentDisposition); + + response = new ResponseEntity(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK); + }catch (IOException e) { logger.error("Error while creating CSV files ", e); } finally { @@ -366,7 +354,7 @@ public Response exportProprietaireByParcelles( logger.info(ACCES_ERROR_LOG); } - return response.build(); + return response; } } diff --git a/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/RequestInformationController.java b/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/RequestInformationController.java index 4188e9d5..709099ba 100644 --- a/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/RequestInformationController.java +++ b/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/RequestInformationController.java @@ -10,14 +10,6 @@ import java.util.Map; import java.util.Set; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.MediaType; - import org.georchestra.cadastrapp.model.request.InformationRequest; import org.georchestra.cadastrapp.model.request.ObjectRequest; import org.georchestra.cadastrapp.model.request.UserRequest; @@ -27,8 +19,15 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; -public class RequestInformationController { +@Controller +public class RequestInformationController extends CadController{ final static Logger logger = LoggerFactory.getLogger(RequestInformationController.class); @@ -52,9 +51,7 @@ public class RequestInformationController { @Autowired UserRequestRepository userRepository; - @GET - @Path("/checkRequestLimitation") - @Produces(MediaType.APPLICATION_JSON) + @RequestMapping(path = "/checkRequestLimitation", produces = {MediaType.APPLICATION_JSON_VALUE}, method= {RequestMethod.GET}) /** * /checkRequestLimitation * @@ -68,7 +65,9 @@ public class RequestInformationController { * * @throws SQLException */ - public Map checkRequestLimitation(@QueryParam("cni") String cni, @QueryParam("type") String type, @Context HttpHeaders headers) throws SQLException { + public @ResponseBody Map checkRequestLimitation( + @RequestParam String cni, + @RequestParam String type) throws SQLException { Map result = new HashMap(); @@ -124,9 +123,7 @@ public Map checkRequestLimitation(@QueryParam("cni") String cni, return result; } - @GET - @Path("/saveInformationRequest") - @Produces(MediaType.APPLICATION_JSON) + @RequestMapping(path = "/saveInformationRequest", produces = {MediaType.APPLICATION_JSON_VALUE}, method= { RequestMethod.GET}) /** * /** * /saveInformationRequest @@ -159,18 +156,30 @@ public Map checkRequestLimitation(@QueryParam("cni") String cni, * @param coProprietes - liste de lot de coproprietés et des documents souhaités pour chaque parcelle 0 non, 1 oui * exemple pour une copropriete : 2015xxxxA00300|2015xxxxxx000ZK0026|0|1 <-> comptecommunal|parcelleid|borderauParcellaire|releveDePropriete * @param lotCoproprietes - * @param askby - * @param responseby - * @param headers + * @param askby - 1 Guichet, 2 Courrier, 3 Mail + * @param responseby - 1 Guichet, 2 Courrier, 3 Mail * * @return JSON * * @throws SQLException */ - public Map saveInformationRequest(@QueryParam("cni") String cni, @QueryParam("type") String type, @QueryParam("adress") String adress, @QueryParam("commune") String commune, @QueryParam("codepostal") String codePostal, @QueryParam("firstname") String firstname, @QueryParam("lastname") String lastname, @QueryParam("mail") String mail, - @QueryParam("comptecommunaux") List compteCommunaux, @QueryParam("parcelleIds") List parcelleIds, @QueryParam("proprietaires") List proprietaires, @QueryParam("parcelles") List parcelles, @QueryParam("coproprietes") List coProprietes, @QueryParam("proprietaireLots") List lotCoproprietes, @QueryParam("askby") int askby, @QueryParam("responseby") int responseby, @Context HttpHeaders headers) throws SQLException { - - // todo recheck value + public @ResponseBody Map saveInformationRequest( + @RequestParam("cni") String cni, + @RequestParam("type") String type, + @RequestParam(name= "adress", required= false) String adress, + @RequestParam(name= "commune", required= false) String commune, + @RequestParam(name= "codepostal", required= false) String codePostal, + @RequestParam(name= "firstname", required= false) String firstname, + @RequestParam(name= "lastname", required= false) String lastname, + @RequestParam(name= "mail", required= false) String mail, + @RequestParam(name= "comptecommunaux", required= false) List compteCommunaux, + @RequestParam(name= "parcelleIds", required= false) List parcelleIds, + @RequestParam(name= "proprietaires", required= false) List proprietaires, + @RequestParam(name= "parcelles", required= false) List parcelles, + @RequestParam(name= "coproprietes", required= false) List coProprietes, + @RequestParam(name= "proprietaireLots", required= false) List lotCoproprietes, + @RequestParam(name= "askby", required= false, defaultValue = "0") int askby, + @RequestParam(name= "responseby", required= false, defaultValue = "0") int responseby) throws SQLException { Map resultInformation = new HashMap(); String result = "KO"; diff --git a/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/SectionController.java b/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/SectionController.java index cc5da5d8..dac27fc1 100644 --- a/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/SectionController.java +++ b/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/SectionController.java @@ -1,37 +1,36 @@ package org.georchestra.cadastrapp.service; + import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Map; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.MediaType; +import org.georchestra.cadastrapp.service.constants.CadastrappConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.http.MediaType; import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RequestHeader; - +@Controller public class SectionController extends CadController { final static Logger logger = LoggerFactory.getLogger(SectionController.class); - - @GET - @Path("/getSection") - @Produces(MediaType.APPLICATION_JSON) + + @RequestMapping(path = "/getSection", produces = {MediaType.APPLICATION_JSON_VALUE}, method= { RequestMethod.GET}) /** * /getSection * * return information about section from view section using parameter given. * results will be filtered with user group geographical limitation * - * @param headers headers from request used to filter search using LDAP Roles * @param cgocommune code geographique officil commune like 630103 (codep + codir + cocom) * cgocommune should be on 6 char, if only 5 we deduce that codir is not present and we replace it in the request * @param ccopre partial code pre section exemple A for AP or AC, could be the full code pre @@ -41,11 +40,10 @@ public class SectionController extends CadController { * * @throws SQLException */ - public List> getSectionList( - @Context HttpHeaders headers, - @QueryParam("cgocommune") String cgoCommune, - @QueryParam("ccopre") String ccopre, - @QueryParam("ccosec") String ccosec) throws SQLException { + public @ResponseBody List> getSectionList( + @RequestParam(name= "cgocommune") String cgoCommune, + @RequestParam(required = false) String ccopre, + @RequestParam(required = false) String ccosec) throws SQLException { // Create empty List to send empty reponse if SQL value is empty. (List instead of null in http response) List> sections = new ArrayList>(); @@ -72,7 +70,7 @@ public List> getSectionList( isWhereAdded = createLikeClauseRequest(isWhereAdded, queryBuilder, "ccopre", ccopre, queryParams); isWhereAdded = createLikeClauseRequest(isWhereAdded, queryBuilder, "ccosec", ccosec, queryParams); if(isSearchFiltered){ - queryBuilder.append(addAuthorizationFiltering(headers)); + queryBuilder.append(addAuthorizationFiltering()); } queryBuilder.append(" ORDER BY ccopre, ccosec "); diff --git a/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/UniteCadastraleController.java b/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/UniteCadastraleController.java index b9805f45..6e6020df 100644 --- a/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/UniteCadastraleController.java +++ b/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/UniteCadastraleController.java @@ -4,22 +4,20 @@ import java.util.List; import java.util.Map; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.MediaType; - import org.georchestra.cadastrapp.helper.BatimentHelper; import org.georchestra.cadastrapp.helper.ProprietaireHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; - +@Controller public class UniteCadastraleController extends CadController { final static Logger logger = LoggerFactory.getLogger(UniteCadastraleController.class); @@ -30,15 +28,12 @@ public class UniteCadastraleController extends CadController { @Autowired ProprietaireHelper proprietaireHelper; - @Path("/getFIC") - @GET - @Produces(MediaType.APPLICATION_JSON) + @RequestMapping(path = "/getFIC", produces = {MediaType.APPLICATION_JSON_VALUE}, method = { RequestMethod.GET }) /** * TODO change this to 5 separated services * * Return all information need to fill cadastre information panel * - * @param headers used to verify user group to check CNIL level and geographic limitation * @param parcelle Id Parcelle unique in all country exemple : 2014630103000AP0025 * @param part (for 0 to 5) * 0 -> Parcelle Information @@ -48,9 +43,9 @@ public class UniteCadastraleController extends CadController { * 4 - > Historical information * @return Json object corresponding on wanted part */ - public List> getInformationCadastrale(@Context HttpHeaders headers, - @QueryParam("parcelle") String parcelle, - @QueryParam("onglet") int onglet) { + public @ResponseBody List> getInformationCadastrale( + @RequestParam String parcelle, + @RequestParam int onglet) { logger.debug(" parcelle : " + parcelle + " onglet : " + onglet); @@ -58,33 +53,33 @@ public List> getInformationCadastrale(@Context HttpHeaders h switch (onglet) { case 0: - information = infoOngletParcelle(parcelle, headers); + information = infoOngletParcelle(parcelle); break; case 1: // Get information about plot owner List parcelles = new ArrayList(); parcelles.add(parcelle); - information = proprietaireHelper.getProprietairesByParcelles(headers, parcelles, false); + information = proprietaireHelper.getProprietairesByParcelles(parcelles, false); logger.warn("Deprecated service, use getProprietairesByParcelle instead"); break; case 2: - if (getUserCNILLevel(headers)>1){ - information = batimentHelper.getBuildings(parcelle, headers); + if (getUserCNILLevel()>1){ + information = batimentHelper.getBuildings(parcelle); } else{ logger.info("User does not have enough right to see information about batiment"); } break; case 3: - if (getUserCNILLevel(headers)>1){ - information = infoOngletSubdivision(parcelle, headers); + if (getUserCNILLevel()>1){ + information = infoOngletSubdivision(parcelle); } else{ logger.info("User does not have enough right to see information about subdivision"); } break; case 4: - information = infoOngletHistorique(parcelle, headers); + information = infoOngletHistorique(parcelle); break; default: logger.error(" No values to return for onglet : " + onglet); @@ -100,11 +95,10 @@ public List> getInformationCadastrale(@Context HttpHeaders h * infoOngletParcelle * * @param String parcelle / Id Parcelle exemple : 2014630103000AP0025 - * @param HttpHeaders headers * * @return List> */ - private List> infoOngletParcelle(String parcelle, HttpHeaders headers){ + private List> infoOngletParcelle(String parcelle){ logger.debug("infoOngletParcelle - parcelle : " + parcelle); @@ -130,11 +124,10 @@ private List> infoOngletParcelle(String parcelle, HttpHeader * call to this method should only be done by CNIL2 level user with geographical rights * * @param String parcelle / Id Parcelle exemple : 2014630103000AP0025 - * @param HttpHeaders headers * * @return List> containing Lettre indicative, Contenance, Code Nature de culture et Revenu au 01/01 */ - private List> infoOngletSubdivision(String parcelle, HttpHeaders headers ){ + private List> infoOngletSubdivision(String parcelle){ logger.debug("infoOngletSubdivision - parcelle : " + parcelle); @@ -145,7 +138,7 @@ private List> infoOngletSubdivision(String parcelle, HttpHea subDivisionqueryBuilder.append(databaseSchema); subDivisionqueryBuilder.append(".proprietenonbatie pnb "); subDivisionqueryBuilder.append(" where pnb.parcelle = ? "); - subDivisionqueryBuilder.append(addAuthorizationFiltering(headers, "pnb.")); + subDivisionqueryBuilder.append(addAuthorizationFiltering("pnb.")); // init jdbc template JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); @@ -161,7 +154,7 @@ private List> infoOngletSubdivision(String parcelle, HttpHea * @param HttpHeaders headers * @return List> */ - private List> infoOngletHistorique(String parcelle, HttpHeaders headers){ + private List> infoOngletHistorique(String parcelle){ logger.debug("infoOngletHistorique - parcelle : " + parcelle); @@ -174,7 +167,7 @@ private List> infoOngletHistorique(String parcelle, HttpHead queryBuilder.append(databaseSchema); queryBuilder.append(".prop_type_filiation prop "); queryBuilder.append("where p.parcelle = ? and p.type_filiation = prop.filiation "); - queryBuilder.append(addAuthorizationFiltering(headers, "p.")); + queryBuilder.append(addAuthorizationFiltering("p.")); JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); return jdbcTemplate.queryForList(queryBuilder.toString(), parcelle); diff --git a/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/VoieController.java b/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/VoieController.java index 8da2035c..7fe20772 100644 --- a/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/VoieController.java +++ b/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/VoieController.java @@ -5,25 +5,23 @@ import java.util.List; import java.util.Map; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.MediaType; - import org.georchestra.cadastrapp.configuration.CadastrappPlaceHolder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.http.MediaType; import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; - +@Controller public class VoieController extends CadController { final static Logger logger = LoggerFactory.getLogger(VoieController.class); - - @GET - @Path("/getVoie") - @Produces(MediaType.APPLICATION_JSON) + + @RequestMapping(path ="/getVoie", produces = {MediaType.APPLICATION_JSON_VALUE}, method = { RequestMethod.GET}) /** * /getVoie * @@ -41,9 +39,9 @@ public class VoieController extends CadController { * * @throws SQLException */ - public List> getVoie( - @QueryParam("cgocommune") String cgoCommune, - @QueryParam("dvoilib") String dvoilib) throws SQLException { + public @ResponseBody List> getVoie( + @RequestParam(name= "cgocommune") String cgoCommune, + @RequestParam(name= "dvoilib") String dvoilib) throws SQLException { List> voies = new ArrayList>(); List queryParams = new ArrayList(); @@ -70,7 +68,7 @@ public List> getVoie( voies = jdbcTemplate.queryForList(queryBuilder.toString(), queryParams.toArray()); } else{ - logger.info("Missing mandatory parameter cgocommune and dvoilib to launch request"); + logger.info("Error in mandatory parameter cgocommune or dvoilib to launch request"); } return voies; diff --git a/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/constants/CadastrappConstants.java b/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/constants/CadastrappConstants.java index f63060d7..7b574044 100644 --- a/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/constants/CadastrappConstants.java +++ b/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/constants/CadastrappConstants.java @@ -90,5 +90,10 @@ private CadastrappConstants() { //message erreur public static final String GENERATING_PICTURE_ERROR = "Problème lors de la création de l'image du bordereau."; + //header groups + public static final String HTTP_HEADER_ROLES = "sec-roles"; + public static final String HTTP_HEADER_ORGANISME = "sec-org"; + public static final String HTTP_HEADER_USERNAME = "sec-username"; + } diff --git a/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/export/CSVExportController.java b/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/export/CSVExportController.java index cb85fdbd..81309e7b 100644 --- a/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/export/CSVExportController.java +++ b/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/export/CSVExportController.java @@ -6,18 +6,21 @@ import java.util.Date; import java.util.List; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.ResponseBuilder; - +import org.apache.commons.io.FileUtils; import org.georchestra.cadastrapp.configuration.CadastrappPlaceHolder; import org.georchestra.cadastrapp.service.CadController; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - +import org.springframework.http.ContentDisposition; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; + +@Controller public class CSVExportController extends CadController { static final Logger logger = LoggerFactory.getLogger(CSVExportController.class); @@ -35,12 +38,10 @@ public class CSVExportController extends CadController { * same number of value, the corresponding line won't be added to * csv */ - @GET - @Path("/exportAsCsv") - @Produces({ "text/csv" }) - public Response cSVExport(@QueryParam("data") List values) { + @RequestMapping(path = "/exportAsCsv", produces = "text/csv", method= {RequestMethod.GET}) + public ResponseEntity cSVExport(@RequestParam(name = "data") List values) { - ResponseBuilder response = Response.serverError(); + ResponseEntity response = new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); if (values != null && !values.isEmpty()) { @@ -77,8 +78,14 @@ public Response cSVExport(@QueryParam("data") List values) { fileWriter.flush(); fileWriter.close(); - response = Response.ok((Object) file); - response.header("Content-Disposition", "attachment; filename=" + file.getName()); + ContentDisposition contentDisposition = ContentDisposition.builder("attachment") + .filename(file.getName()) + .build(); + + HttpHeaders headers = new HttpHeaders(); + headers.setContentDisposition(contentDisposition); + + response = new ResponseEntity(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK); } catch (IOException e) { logger.error("Error while creating CSV files ", e); @@ -89,7 +96,7 @@ public Response cSVExport(@QueryParam("data") List values) { } } - return response.build(); + return response; } } diff --git a/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/pdf/BordereauParcellaireController.java b/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/pdf/BordereauParcellaireController.java index 68dfdff1..de8f0957 100644 --- a/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/pdf/BordereauParcellaireController.java +++ b/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/pdf/BordereauParcellaireController.java @@ -1,26 +1,16 @@ package org.georchestra.cadastrapp.service.pdf; -import java.io.BufferedOutputStream; import java.io.File; import java.io.FileNotFoundException; -import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.StringWriter; +import java.io.ByteArrayOutputStream; import java.util.Arrays; import java.util.Date; import java.util.List; -import javax.ws.rs.DefaultValue; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.ResponseBuilder; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; @@ -46,7 +36,17 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; - +import org.springframework.http.ContentDisposition; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; + +@Controller public class BordereauParcellaireController extends CadController { final static Logger logger = LoggerFactory.getLogger(BordereauParcellaireController.class); @@ -61,7 +61,6 @@ public class BordereauParcellaireController extends CadController { * data is retrieved from database and a FO is created using the xsl template. * Once the fo file is create we then create the PDF file * - * @param headers, use for CNIL level limitation * @param parcelleList, list of parcelleId you want to export * @param personalData, 0 no owners information * 1 owners information in page @@ -73,19 +72,17 @@ public class BordereauParcellaireController extends CadController { * @param baseMapIndex corresponding of the wanted index in cadastrapp.properties * @return BP pdf */ - @GET - @Path("/createBordereauParcellaire") - @Produces("application/pdf") - public Response createBordereauParcellaire(@Context HttpHeaders headers, - @QueryParam("parcelle") final List parcelleList, - @DefaultValue("0") @QueryParam("personaldata") int personalData, - @DefaultValue("0") @QueryParam("basemapindex") int baseMapIndex, - @DefaultValue("#1446DE") @QueryParam("fillcolor") String styleFillColor, - @DefaultValue("0.50") @QueryParam("opacity") float styleFillOpacity, - @DefaultValue("#10259E") @QueryParam("strokecolor") String styleStrokeColor, - @DefaultValue("2") @QueryParam("strokewidth") int styleStrokeWidth) { - - ResponseBuilder response = Response.noContent(); + @RequestMapping(path = "/createBordereauParcellaire", produces ={MediaType.APPLICATION_PDF_VALUE}, method= {RequestMethod.GET}) + public ResponseEntity createBordereauParcellaire( + @RequestParam(name= "parcelle") final List parcelleList, + @RequestParam(name= "personaldata", defaultValue = "0", required= false) int personalData, + @RequestParam(name= "basemapindex", defaultValue = "0", required= false) int baseMapIndex, + @RequestParam(name= "fillcolor", defaultValue = "#1446DE", required= false) String styleFillColor, + @RequestParam(name= "opacity", defaultValue = "0.50", required= false) float styleFillOpacity, + @RequestParam(name= "strokecolor", defaultValue = "#10259E", required= false) String styleStrokeColor, + @RequestParam(name= "strokewidth", defaultValue = "2", required= false) int styleStrokeWidth) { + + ResponseEntity response = new ResponseEntity(HttpStatus.NO_CONTENT); // Check if parcelle list is not empty if (parcelleList != null && !parcelleList.isEmpty()) { @@ -98,7 +95,8 @@ public Response createBordereauParcellaire(@Context HttpHeaders headers, String tempFolder = CadastrappPlaceHolder.getProperty("tempFolder"); // Pdf temporary filename using tmp folder and timestamp - final String pdfTmpFileName = tempFolder+File.separator+"BP"+new Date().getTime(); + final long key = new Date().getTime(); + final String pdfTmpFileName = tempFolder+File.separator+"BP-"+key; InputStream xsl = Thread.currentThread().getContextClassLoader().getResourceAsStream(xslTemplate); // Setup XSLT @@ -108,21 +106,16 @@ public Response createBordereauParcellaire(@Context HttpHeaders headers, Transformer transformerPDF; JAXBContext jaxbContext; Marshaller jaxbMarshaller; - File pdfResult; - OutputStream out; + ByteArrayOutputStream out; Fop fop; try { transformerXSLT = factory.newTransformer(new StreamSource(xsl)); transformerPDF = factory.newTransformer(); - - // Create Empyt PDF File will be erase after - pdfResult = new File(pdfTmpFileName+".pdf"); - pdfResult.deleteOnExit(); - out = new BufferedOutputStream(new FileOutputStream(pdfResult)); + out = new ByteArrayOutputStream(); - FopFactoryBuilder builder = new FopFactoryBuilder(pdfResult.toURI()); + FopFactoryBuilder builder = new FopFactoryBuilder(new File(tempFolder+File.separator+".").toURI()); // get DPI from comfig file int dpi=Integer.parseInt(CadastrappPlaceHolder.getProperty("pdf.dpi")); @@ -148,7 +141,7 @@ public Response createBordereauParcellaire(@Context HttpHeaders headers, plotsStyle.setStrokeWidth(styleStrokeWidth); // Get bordereau parcellaire information - BordereauParcellaire bordereauParcellaire = bordereauParcellaireHelper.getBordereauParcellaireInformation(newParcelleList, personalData, headers, false, plotsStyle, baseMapIndex); + BordereauParcellaire bordereauParcellaire = bordereauParcellaireHelper.getBordereauParcellaireInformation(newParcelleList, personalData, false, plotsStyle, baseMapIndex); File xmlfile = null; File foFile = null; OutputStream foOutPutStream = null; @@ -188,13 +181,18 @@ public Response createBordereauParcellaire(@Context HttpHeaders headers, // Start PDF transformation and FOP processing transformerPDF.transform(src, res); - + byte[] bytes = out.toByteArray(); out.close(); - - // Create response - response = Response.ok((Object) pdfResult); - response.header("Content-Disposition", "attachment; filename=" + pdfResult.getName()); + ContentDisposition contentDisposition = ContentDisposition.builder("attachment") + .filename("BP-"+key+".pdf") + .build(); + + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_PDF); + headers.setContentDisposition(contentDisposition); + + response = new ResponseEntity(bytes, headers, HttpStatus.OK); } catch (JAXBException jaxbException) { logger.warn("Error during converting object to xml : " + jaxbException); } catch (TransformerException transformerException) { @@ -231,8 +229,7 @@ public Response createBordereauParcellaire(@Context HttpHeaders headers, } else { logger.warn("Required parameter missing"); } - return response.build(); + return response; } - } diff --git a/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/pdf/BordereauParcellaireHelper.java b/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/pdf/BordereauParcellaireHelper.java index 55c125d3..4025ab84 100644 --- a/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/pdf/BordereauParcellaireHelper.java +++ b/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/pdf/BordereauParcellaireHelper.java @@ -13,7 +13,6 @@ import java.util.List; import java.util.Map; -import javax.ws.rs.core.HttpHeaders; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; @@ -60,7 +59,6 @@ public final class BordereauParcellaireHelper extends CadController{ /** * Get all information from database for all parcelle list * - * @param headers use for CNIL level limitation * @param isCoPro get copro BP information if true * @param parcelleList * List of parcelle id, like @@ -70,14 +68,13 @@ public final class BordereauParcellaireHelper extends CadController{ * * @return BordereauParcellaire witch contains list of parcelle */ - public BordereauParcellaire getBordereauParcellaireInformation(List parcelleList, int personalData, HttpHeaders headers, boolean isCoPro) { - return getBordereauParcellaireInformation(parcelleList, personalData, headers, isCoPro, null, 0); + public BordereauParcellaire getBordereauParcellaireInformation(List parcelleList, int personalData, boolean isCoPro) { + return getBordereauParcellaireInformation(parcelleList, personalData, isCoPro, null, 0); } /** * Get all information from database for all parcelle list * - * @param headers use for CNIL level limitation * @param isCoPro get copro BP information if true * @param parcelleList * List of parcelle id, like @@ -89,7 +86,7 @@ public BordereauParcellaire getBordereauParcellaireInformation(List parc * * @return BordereauParcellaire witch contains list of parcelle */ - public BordereauParcellaire getBordereauParcellaireInformation(List parcelleList, int personalData, HttpHeaders headers, boolean isCoPro, Style plotStyle, int baseMapIndex) { + public BordereauParcellaire getBordereauParcellaireInformation(List parcelleList, int personalData, boolean isCoPro, Style plotStyle, int baseMapIndex) { BordereauParcellaire bordereauParcellaire = new BordereauParcellaire(); @@ -142,7 +139,7 @@ public BordereauParcellaire getBordereauParcellaireInformation(List parc logger.debug("Parcelle information : " + parcelle); - if (personalData > 0 && getUserCNILLevel(headers)>0) { + if (personalData > 0 && getUserCNILLevel()>0) { List proprietaires = new ArrayList(); String tableName = (isCoPro)?tableCoProprietaire:tableProprietaire; @@ -157,7 +154,7 @@ public BordereauParcellaire getBordereauParcellaireInformation(List parc queryBuilderProprietaire.append(tableName); queryBuilderProprietaire.append(" proparc "); queryBuilderProprietaire.append("where proparc.parcelle = ? and prop.comptecommunal = proparc.comptecommunal"); - queryBuilderProprietaire.append(addAuthorizationFiltering(headers)); + queryBuilderProprietaire.append(addAuthorizationFiltering()); List> proprietairesResult = jdbcTemplate.queryForList(queryBuilderProprietaire.toString(), row.get("parcelle")); @@ -252,6 +249,7 @@ public File generatePDF(BordereauParcellaire bp, boolean noData) throws Cadastra Transformer transformerPDF; JAXBContext jaxbContext; Marshaller jaxbMarshaller; + File pdfResult; OutputStream out; Fop fop; @@ -266,7 +264,7 @@ public File generatePDF(BordereauParcellaire bp, boolean noData) throws Cadastra out = new BufferedOutputStream(new FileOutputStream(pdfResult)); - FopFactoryBuilder builder = new FopFactoryBuilder(pdfResult.toURI()); + FopFactoryBuilder builder = new FopFactoryBuilder(new File(tempFolder+File.separator+".").toURI()); // get DPI from comfig file int dpi=Integer.parseInt(CadastrappPlaceHolder.getProperty("pdf.dpi")); diff --git a/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/pdf/DemandeController.java b/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/pdf/DemandeController.java index ef833807..2db4adb8 100644 --- a/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/pdf/DemandeController.java +++ b/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/pdf/DemandeController.java @@ -7,15 +7,7 @@ import java.util.List; import java.util.Map; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.ResponseBuilder; - +import org.apache.commons.io.FileUtils; import org.apache.pdfbox.io.MemoryUsageSetting; import org.apache.pdfbox.multipdf.PDFMergerUtility; import org.georchestra.cadastrapp.configuration.CadastrappPlaceHolder; @@ -30,7 +22,17 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; - +import org.springframework.http.ContentDisposition; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; + +@Controller public class DemandeController extends CadController { static final Logger logger = LoggerFactory.getLogger(DemandeController.class); @@ -48,17 +50,15 @@ public class DemandeController extends CadController { /** * Create a PDF using a request id * - * @param headers to verify CNIL level information * @param requestId user request Id * @return pdf demande resume * @throws IOException if an input or output exception occured */ - @GET - @Path("/createDemandeFromObj") - @Produces("application/pdf") - public Response createDemandeFromObj(@Context HttpHeaders headers, @QueryParam("requestid") long requestId) throws IOException { + @RequestMapping(path = "/createDemandeFromObj", produces ={MediaType.APPLICATION_PDF_VALUE}, method= {RequestMethod.GET}) + public ResponseEntity createDemandeFromObj( + @RequestParam(name="requestid") long requestId) throws IOException { - ResponseBuilder response = Response.noContent(); + ResponseEntity response = new ResponseEntity(HttpStatus.NO_CONTENT); List listPdfPath = new ArrayList(); @@ -82,22 +82,22 @@ public Response createDemandeFromObj(@Context HttpHeaders headers, @QueryParam(" if(objReq.getType() == CadastrappConstants.CODE_DEMANDEUR_COMPTE_COMMUNAL){ //if BP if("1".equals(objReq.getBp())){ - listPdfPath.add(createBordereauParcellaireByCC(objReq.getComptecommunal(),null, headers, false)); + listPdfPath.add(createBordereauParcellaireByCC(objReq.getComptecommunal(),null, false)); } //if RP if("1".equals(objReq.getRp())){ - listPdfPath.add(createReleveProprieteByCC(objReq.getComptecommunal(), headers,isMinimal)); + listPdfPath.add(createReleveProprieteByCC(objReq.getComptecommunal(), isMinimal)); } }else if(objReq.getType() == CadastrappConstants.CODE_DEMANDEUR_PARCELLE_ID){ //if BP if("1".equals(objReq.getBp())){ - listPdfPath.add(createBordereauParcellaireById(objReq.getParcelle(), headers)); + listPdfPath.add(createBordereauParcellaireById(objReq.getParcelle())); } //if RP if("1".equals(objReq.getRp())){ - listPdfPath.add(createReleveProprieteById(objReq.getParcelle(), headers, isMinimal)); + listPdfPath.add(createReleveProprieteById(objReq.getParcelle(), isMinimal)); } @@ -105,11 +105,11 @@ public Response createDemandeFromObj(@Context HttpHeaders headers, @QueryParam(" //if BP if("1".equals(objReq.getBp())){ - listPdfPath.add(createBordereauParcellaireByCC(objReq.getComptecommunal(),objReq.getParcelle(), headers, true)); + listPdfPath.add(createBordereauParcellaireByCC(objReq.getComptecommunal(),objReq.getParcelle(), true)); } //if RP if("1".equals(objReq.getRp())){ - listPdfPath.add(createReleveCoProprieteByCCandParcelle(objReq.getComptecommunal(),objReq.getParcelle(), headers,isMinimal)); + listPdfPath.add(createReleveCoProprieteByCCandParcelle(objReq.getComptecommunal(),objReq.getParcelle(), isMinimal)); } @@ -117,11 +117,11 @@ public Response createDemandeFromObj(@Context HttpHeaders headers, @QueryParam(" }else if(objReq.getType() == CadastrappConstants.CODE_DEMANDEUR_PARCELLE){ //if BP if("1".equals(objReq.getBp())){ - listPdfPath.add(createBordereauParcellaireByInfoParcelle(objReq.getCommune(),objReq.getSection(),objReq.getNumero(), headers)); + listPdfPath.add(createBordereauParcellaireByInfoParcelle(objReq.getCommune(),objReq.getSection(),objReq.getNumero())); } //if RP if("1".equals(objReq.getRp())){ - listPdfPath.add(createReleveProprieteByInfoParcelle(objReq.getCommune(),objReq.getSection(),objReq.getNumero(), headers,isMinimal)); + listPdfPath.add(createReleveProprieteByInfoParcelle(objReq.getCommune(),objReq.getSection(),objReq.getNumero(), isMinimal)); } @@ -129,21 +129,21 @@ public Response createDemandeFromObj(@Context HttpHeaders headers, @QueryParam(" //if BP if("1".equals(objReq.getBp())){ - listPdfPath.add(createBordereauParcellaireByInfoOwner(objReq.getCommune(),objReq.getProprietaire(), headers)); + listPdfPath.add(createBordereauParcellaireByInfoOwner(objReq.getCommune(),objReq.getProprietaire())); } //if RP if("1".equals(objReq.getRp())){ - listPdfPath.add(createReleveProprieteByInfoOwner(objReq.getCommune(),objReq.getProprietaire(), headers,isMinimal)); + listPdfPath.add(createReleveProprieteByInfoOwner(objReq.getCommune(),objReq.getProprietaire(), isMinimal)); } }else if(objReq.getType() == CadastrappConstants.CODE_DEMANDEUR_LOT_COPROPRIETE){ //if BP if("1".equals(objReq.getBp())){ - listPdfPath.add(createBordereauParcellaireLot(objReq.getCommune(),objReq.getSection(),objReq.getNumero(),objReq.getProprietaire(), headers)); + listPdfPath.add(createBordereauParcellaireLot(objReq.getCommune(),objReq.getSection(),objReq.getNumero(),objReq.getProprietaire())); } //if RP if("1".equals(objReq.getRp())){ - listPdfPath.add(createReleveProprieteByInfoLot(objReq.getCommune(),objReq.getSection(),objReq.getNumero(),objReq.getProprietaire(), headers,isMinimal)); + listPdfPath.add(createReleveProprieteByInfoLot(objReq.getCommune(),objReq.getSection(),objReq.getNumero(),objReq.getProprietaire(), isMinimal)); } } @@ -159,30 +159,36 @@ public Response createDemandeFromObj(@Context HttpHeaders headers, @QueryParam(" // Pdf temporary filename using tmp folder and timestamp final String pdfTmpFileName = tempFolder+File.separator+"DEMANDE_"+new Date().getTime(); - ut.setDestinationFileName(pdfTmpFileName); + ut.setDestinationFileName(pdfTmpFileName+".pdf"); ut.mergeDocuments(MemoryUsageSetting.setupTempFileOnly()); File pdfResult = new File(ut.getDestinationFileName()); pdfResult.deleteOnExit(); - response = Response.ok((Object) pdfResult); - response.header("Content-Disposition", "attachment; filename=" + pdfResult.getName() + ".pdf"); + ContentDisposition contentDisposition = ContentDisposition.builder("attachment") + .filename(pdfResult.getName()) + .build(); + + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_PDF); + headers.setContentDisposition(contentDisposition); + + response = new ResponseEntity(FileUtils.readFileToByteArray(pdfResult), headers, HttpStatus.OK); } } - return response.build(); + return response; } /** * Create RP using owner code CC * * @param compteCommunal owner ident - * @param headers http header containing restriction * @param isMinimal if true then only some information will be displayed * @return PDF File RP */ - private File createReleveProprieteByCC(String compteCommunal, HttpHeaders headers, boolean isMinimal) { + private File createReleveProprieteByCC(String compteCommunal, boolean isMinimal) { //Store field search if no data to display => inform on PDF file List fields = new ArrayList(); @@ -190,7 +196,7 @@ private File createReleveProprieteByCC(String compteCommunal, HttpHeaders header List compteCommIds = new ArrayList(); compteCommIds.add(compteCommunal); // Get Releve Propriete information - RelevePropriete relevePropriete = releveProprieteHelper.getReleveProprieteInformation(compteCommIds, headers, new String()); + RelevePropriete relevePropriete = releveProprieteHelper.getReleveProprieteInformation(compteCommIds, new String()); File pdf = null; //generate PDF @@ -209,11 +215,10 @@ private File createReleveProprieteByCC(String compteCommunal, HttpHeaders header * Create RP using parcelle id * * @param parcelle id parcelle - * @param headers http header containing restriction * @param isMinimal if true then only some information will be displayed * @return PDF File RP */ - private File createReleveProprieteById(String parcelle, HttpHeaders headers, boolean isMinimal) { + private File createReleveProprieteById(String parcelle, boolean isMinimal) { //Store field search if no data to display => inform on PDF file List fields = new ArrayList(); @@ -228,7 +233,7 @@ private File createReleveProprieteById(String parcelle, HttpHeaders headers, boo } // Get Releve Propriete information - RelevePropriete relevePropriete = releveProprieteHelper.getReleveProprieteInformation(compteCommunauxList, headers, parcelle); + RelevePropriete relevePropriete = releveProprieteHelper.getReleveProprieteInformation(compteCommunauxList, parcelle); File pdf = null; @@ -249,10 +254,9 @@ private File createReleveProprieteById(String parcelle, HttpHeaders headers, boo * Create borderau parcellaire using parcelle id * * @param parcelle id parcelle - * @param headers http header containing restriction * @return PDF File BP */ - private File createBordereauParcellaireById(String parcelle, HttpHeaders headers) { + private File createBordereauParcellaireById(String parcelle) { //Store field search if no data to display => inform on PDF file List fields = new ArrayList(); @@ -260,7 +264,7 @@ private File createBordereauParcellaireById(String parcelle, HttpHeaders headers parcellId.add(parcelle); // Get bordereau parcellaire information - BordereauParcellaire bordereauParcellaire = bordereauParcellaireHelper.getBordereauParcellaireInformation(parcellId, 1, headers,false); + BordereauParcellaire bordereauParcellaire = bordereauParcellaireHelper.getBordereauParcellaireInformation(parcellId, 1, false); File pdf = null; try { @@ -296,12 +300,11 @@ private File createBordereauParcellaireById(String parcelle, HttpHeaders headers * * @param comptecommunal * @param parcelleId - * @param headers http headers to test wrights * @param isCoPro boolean to check is request is a copropriete * * @return PDF file contening wanted Bordereau Parcellaire */ - private File createBordereauParcellaireByCC(String comptecommunal,String parcelleId, HttpHeaders headers, boolean isCoPro) { + private File createBordereauParcellaireByCC(String comptecommunal,String parcelleId, boolean isCoPro) { // Store field search if no data to display => inform on PDF file List fields = new ArrayList(); @@ -326,7 +329,7 @@ private File createBordereauParcellaireByCC(String comptecommunal,String parcell } // Get bordereau parcellaire information - BordereauParcellaire bordereauParcellaire = bordereauParcellaireHelper.getBordereauParcellaireInformation(parcellesId, 1, headers, isCoPro); + BordereauParcellaire bordereauParcellaire = bordereauParcellaireHelper.getBordereauParcellaireInformation(parcellesId, 1, isCoPro); try { //generate PDF if(bordereauParcellaire.isEmpty()){ @@ -357,11 +360,10 @@ private File createBordereauParcellaireByCC(String comptecommunal,String parcell * * @param compteCommunal * @param parcellaId - * @param headers * @param isMinimal * @return File PDF RP */ - private File createReleveCoProprieteByCCandParcelle(String compteCommunal, String parcelleId, HttpHeaders headers, boolean isMinimal) { + private File createReleveCoProprieteByCCandParcelle(String compteCommunal, String parcelleId, boolean isMinimal) { //Store field search if no data to display => inform on PDF file List fields = new ArrayList(); @@ -369,7 +371,7 @@ private File createReleveCoProprieteByCCandParcelle(String compteCommunal, Strin compteCommIds.add(compteCommunal); // Get Releve Propriete information - RelevePropriete relevePropriete = releveProprieteHelper.getReleveProprieteInformation(compteCommIds, headers, parcelleId); + RelevePropriete relevePropriete = releveProprieteHelper.getReleveProprieteInformation(compteCommIds, parcelleId); File pdf = null; //generate PDF @@ -391,10 +393,9 @@ private File createReleveCoProprieteByCCandParcelle(String compteCommunal, Strin * @param commune * @param section * @param numero - * @param headers * @return File PDF BP */ - private File createBordereauParcellaireByInfoParcelle(String commune, String section, String numero, HttpHeaders headers){ + private File createBordereauParcellaireByInfoParcelle(String commune, String section, String numero){ //Store field search if no data to display => inform on PDF file List fields = new ArrayList(); @@ -408,7 +409,7 @@ private File createBordereauParcellaireByInfoParcelle(String commune, String sec } // Get bordereau parcellaire information - BordereauParcellaire bordereauParcellaire = bordereauParcellaireHelper.getBordereauParcellaireInformation(parcellId, 1, headers,false); + BordereauParcellaire bordereauParcellaire = bordereauParcellaireHelper.getBordereauParcellaireInformation(parcellId, 1, false); File pdf = null; try { //generate PDF @@ -433,11 +434,10 @@ private File createBordereauParcellaireByInfoParcelle(String commune, String sec * @param commune * @param section * @param numero - * @param headers * @param isMinimal * @return File PDF RP */ - private File createReleveProprieteByInfoParcelle(String commune, String section,String numero, HttpHeaders headers, boolean isMinimal) { + private File createReleveProprieteByInfoParcelle(String commune, String section,String numero, boolean isMinimal) { List compteCommunauxList = new ArrayList(); //get compte communal by parcelle @@ -450,7 +450,7 @@ private File createReleveProprieteByInfoParcelle(String commune, String section, } // Get Releve Propriete information - RelevePropriete relevePropriete = releveProprieteHelper.getReleveProprieteInformation(compteCommunauxList, headers, idParcelle); + RelevePropriete relevePropriete = releveProprieteHelper.getReleveProprieteInformation(compteCommunauxList, idParcelle); //generate PDF File pdf = releveProprieteHelper.generatePDF(relevePropriete,isMinimal, false); @@ -464,10 +464,9 @@ private File createReleveProprieteByInfoParcelle(String commune, String section, * * @param commune * @param ownerName - * @param headers * @return */ - private File createBordereauParcellaireByInfoOwner(String commune, String ownerName, HttpHeaders headers){ + private File createBordereauParcellaireByInfoOwner(String commune, String ownerName){ //Store field search if no data to display => inform on PDF file List fields = new ArrayList(); @@ -481,7 +480,7 @@ private File createBordereauParcellaireByInfoOwner(String commune, String ownerN } // Get bordereau parcellaire information - BordereauParcellaire bordereauParcellaire = bordereauParcellaireHelper.getBordereauParcellaireInformation(parcellId, 1, headers,false); + BordereauParcellaire bordereauParcellaire = bordereauParcellaireHelper.getBordereauParcellaireInformation(parcellId, 1, false); File pdf = null; try { //generate PDF @@ -505,11 +504,10 @@ private File createBordereauParcellaireByInfoOwner(String commune, String ownerN * * @param commune * @param ownerName - * @param headers * @param isMinimal * @return File PDF RP */ - private File createReleveProprieteByInfoOwner(String commune, String ownerName, HttpHeaders headers, boolean isMinimal) { + private File createReleveProprieteByInfoOwner(String commune, String ownerName, boolean isMinimal) { List compteCommunauxList = new ArrayList(); //get compte communal by commune and owner @@ -521,7 +519,7 @@ private File createReleveProprieteByInfoOwner(String commune, String ownerName, } // Get Releve Propriete information - RelevePropriete relevePropriete = releveProprieteHelper.getReleveProprieteInformation(compteCommunauxList, headers, new String()); + RelevePropriete relevePropriete = releveProprieteHelper.getReleveProprieteInformation(compteCommunauxList, new String()); //generate PDF File pdf = releveProprieteHelper.generatePDF(relevePropriete,isMinimal, false); @@ -537,10 +535,9 @@ private File createReleveProprieteByInfoOwner(String commune, String ownerName, * @param section * @param numero * @param proprietaire - * @param headers * @return */ - private File createBordereauParcellaireLot(String commune, String section, String numero, String proprietaire, HttpHeaders headers) { + private File createBordereauParcellaireLot(String commune, String section, String numero, String proprietaire) { //Store field search if no data to display => inform on PDF file List fields = new ArrayList(); //get parcelle by commune,section,numero and proprietaire @@ -553,7 +550,7 @@ private File createBordereauParcellaireLot(String commune, String section, Strin } // Get bordereau parcellaire information - BordereauParcellaire bordereauParcellaire = bordereauParcellaireHelper.getBordereauParcellaireInformation(parcellId, 1, headers, false); + BordereauParcellaire bordereauParcellaire = bordereauParcellaireHelper.getBordereauParcellaireInformation(parcellId, 1, false); File pdf = null; try { @@ -578,11 +575,10 @@ private File createBordereauParcellaireLot(String commune, String section, Strin * @param section * @param numero * @param proprietaire - * @param headers * @param isMinimal * @return File PDF RP */ - private File createReleveProprieteByInfoLot(String commune, String section, String numero, String proprietaire, HttpHeaders headers, boolean isMinimal) { + private File createReleveProprieteByInfoLot(String commune, String section, String numero, String proprietaire, boolean isMinimal) { List compteCommunauxList = new ArrayList(); //get compte communal by parcelle commune,section,numero, and proprietaire List> compteCommunaux = releveProprieteHelper.getProprietaireByInfoLot(commune,section,numero,proprietaire); @@ -595,7 +591,7 @@ private File createReleveProprieteByInfoLot(String commune, String section, Stri } // Get Releve Propriete information - RelevePropriete relevePropriete = releveProprieteHelper.getReleveProprieteInformation(compteCommunauxList, headers, parcelleId); + RelevePropriete relevePropriete = releveProprieteHelper.getReleveProprieteInformation(compteCommunauxList, parcelleId); //generate PDF File pdf = releveProprieteHelper.generatePDF(relevePropriete,isMinimal, false); diff --git a/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/pdf/ReleveProprieteController.java b/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/pdf/ReleveProprieteController.java index 78ab809c..3ffc9b4b 100644 --- a/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/pdf/ReleveProprieteController.java +++ b/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/pdf/ReleveProprieteController.java @@ -13,15 +13,7 @@ import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.ResponseBuilder; - +import org.apache.commons.io.FileUtils; import org.georchestra.cadastrapp.configuration.CadastrappPlaceHolder; import org.georchestra.cadastrapp.model.pdf.CompteCommunal; import org.georchestra.cadastrapp.model.pdf.Proprietaire; @@ -38,8 +30,18 @@ import org.supercsv.io.CsvBeanWriter; import org.supercsv.io.ICsvBeanWriter; import org.supercsv.prefs.CsvPreference; +import org.springframework.http.ContentDisposition; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +@Controller public class ReleveProprieteController extends CadController { static final Logger logger = LoggerFactory.getLogger(ReleveProprieteController.class); @@ -50,21 +52,21 @@ public class ReleveProprieteController extends CadController { /** * Create a PDF using a list of comptecommunal * - * @param headers to verify CNIL level information * @param comptesCommunaux List of ids proprietaires - * @param idParcelle plot id + * @param idParcelle plot id for this user * @return pdf generated RP with database information + * @throws IOException */ - @GET - @Path("/createRelevePropriete") - @Produces("application/pdf") - public Response createRelevePDFPropriete(@Context HttpHeaders headers, @QueryParam("compteCommunal") List comptesCommunaux, @QueryParam("parcelleId") String idParcelle) { + @RequestMapping(path = "/createRelevePropriete", produces ={MediaType.APPLICATION_PDF_VALUE}, method= {RequestMethod.GET}) + public ResponseEntity createRelevePDFPropriete( + @RequestParam(name= "compteCommunal") List comptesCommunaux, + @RequestParam(name="parcelleId", required= false) String idParcelle) throws IOException { - ResponseBuilder response = Response.noContent(); + ResponseEntity response = new ResponseEntity(HttpStatus.NO_CONTENT); logger.debug("Controller Parcelle ID (param) : "+idParcelle); - // Check if parcelle list is not empty + // Check if user id list is not empty if (comptesCommunaux != null && !comptesCommunaux.isEmpty()) { // Fixe #329 in some case Extjs return one string with data separated with , instead of a list of data. @@ -72,36 +74,42 @@ public Response createRelevePDFPropriete(@Context HttpHeaders headers, @QueryPar comptesCommunaux = Arrays.asList(comptesCommunaux.get(0).split(",")); } // Get information about releve de propriete - RelevePropriete relevePropriete = releveProprieteHelper.getReleveProprieteInformation(comptesCommunaux, headers, idParcelle); + RelevePropriete relevePropriete = releveProprieteHelper.getReleveProprieteInformation(comptesCommunaux, idParcelle); File pdfResult = releveProprieteHelper.generatePDF(relevePropriete, false, false); // Create response - response = Response.ok((Object) pdfResult); - response.header("Content-Disposition", "attachment; filename=" + pdfResult.getName()); + ContentDisposition contentDisposition = ContentDisposition.builder("attachment") + .filename(pdfResult.getName()) + .build(); + + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_PDF); + headers.setContentDisposition(contentDisposition); + + response = new ResponseEntity(FileUtils.readFileToByteArray(pdfResult), headers, HttpStatus.OK); } else { logger.warn("Required parameter missing"); } - return response.build(); + return response; } /** * Create a zip file, containint several csv using a list of comptecommunal * - * @param headers to verify CNIL level information * @param comptesCommunaux List of ids proprietaires * @param idParcelle plot id * @return zip containing csv file * @throws IOException if an input or output exception occured */ - @GET - @Path("/createReleveProprieteAsCSV") - @Produces("application/zip") - public Response createReleveCSVPropriete(@Context HttpHeaders headers, @QueryParam("compteCommunal") List comptesCommunaux, @QueryParam("parcelleId") String idParcelle) throws IOException { + @RequestMapping(path = "/createReleveProprieteAsCSV", produces = "application/zip", method= {RequestMethod.GET}) + public ResponseEntity createReleveCSVPropriete( + @RequestParam(name= "compteCommunal") List comptesCommunaux, + @RequestParam(name= "parcelleId", required= false) String idParcelle) throws IOException { - ResponseBuilder response = Response.noContent(); + ResponseEntity response = new ResponseEntity(HttpStatus.NO_CONTENT); String tempFolder = CadastrappPlaceHolder.getProperty("tempFolder"); @@ -115,7 +123,7 @@ public Response createReleveCSVPropriete(@Context HttpHeaders headers, @QueryPar comptesCommunaux = Arrays.asList(comptesCommunaux.get(0).split(",")); } // Get information about releve de propriete - RelevePropriete relevePropriete = releveProprieteHelper.getReleveProprieteInformation(comptesCommunaux, headers, idParcelle); + RelevePropriete relevePropriete = releveProprieteHelper.getReleveProprieteInformation(comptesCommunaux, idParcelle); // Define Date for all file name DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH_mm_ss_SSS"); @@ -368,15 +376,21 @@ public Response createReleveCSVPropriete(@Context HttpHeaders headers, @QueryPar } out.close(); - + // Create response - response = Response.ok((Object) finalZip); - response.header("Content-Disposition", "attachment; filename=" + zipFileName); + ContentDisposition contentDisposition = ContentDisposition.builder("attachment") + .filename(zipFileName) + .build(); + + HttpHeaders headers = new HttpHeaders(); + headers.setContentDisposition(contentDisposition); + + response = new ResponseEntity(FileUtils.readFileToByteArray(finalZip), headers, HttpStatus.OK); } else { logger.warn("Required parameter missing"); } - return response.build(); + return response; } } diff --git a/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/pdf/ReleveProprieteHelper.java b/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/pdf/ReleveProprieteHelper.java index 77baf9ba..349e4a2d 100644 --- a/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/pdf/ReleveProprieteHelper.java +++ b/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/pdf/ReleveProprieteHelper.java @@ -13,7 +13,6 @@ import java.util.List; import java.util.Map; -import javax.ws.rs.core.HttpHeaders; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; @@ -59,12 +58,11 @@ public final class ReleveProprieteHelper extends CadController { * Get propertie information using given imput from database * * @param idComptesCommunaux list composed with comptecommunalid - * @param headers HttpHeaders used to verify user privilege * @param idParcelle String plot id * * @return RelevePropriete fill with database information */ - public RelevePropriete getReleveProprieteInformation(List idComptesCommunaux, HttpHeaders headers, String idParcelle) { + public RelevePropriete getReleveProprieteInformation(List idComptesCommunaux, String idParcelle) { RelevePropriete relevePropriete = new RelevePropriete(); @@ -153,7 +151,7 @@ public RelevePropriete getReleveProprieteInformation(List idComptesCommu } // Display information only if at least CNIL level 1 or 2 - if (getUserCNILLevel(headers) > 0) { + if (getUserCNILLevel() > 0) { // Information sur les proprietaires List proprietaires = new ArrayList(); @@ -164,7 +162,7 @@ public RelevePropriete getReleveProprieteInformation(List idComptesCommu queryBuilderProprietaire.append(databaseSchema); queryBuilderProprietaire.append(".proprietaire prop "); queryBuilderProprietaire.append("where prop.comptecommunal = ? "); - queryBuilderProprietaire.append(addAuthorizationFiltering(headers)); + queryBuilderProprietaire.append(addAuthorizationFiltering()); queryBuilderProprietaire.append("order by prop.dnulp ASC "); logger.debug("Get owners information "); @@ -536,12 +534,11 @@ public List> getProprietaireByInfoLot(String commune, String * Create RP without parcelle id. * * @param comptesCommunaux owner id list - * @param headers http headers information to filter result * @return data for releve de propriete */ - public RelevePropriete getReleveProprieteInformation(List comptesCommunaux, HttpHeaders headers) { + public RelevePropriete getReleveProprieteInformation(List comptesCommunaux) { - return getReleveProprieteInformation(comptesCommunaux, headers, null); + return getReleveProprieteInformation(comptesCommunaux, null); } } diff --git a/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/pdf/RequestPDFController.java b/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/pdf/RequestPDFController.java index c089404a..01070320 100644 --- a/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/pdf/RequestPDFController.java +++ b/cadastrapp/src/main/java/org/georchestra/cadastrapp/service/pdf/RequestPDFController.java @@ -10,14 +10,6 @@ import java.io.StringWriter; import java.util.Date; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.ResponseBuilder; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; @@ -31,6 +23,7 @@ import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; +import org.apache.commons.io.FileUtils; import org.apache.fop.apps.FOPException; import org.apache.fop.apps.Fop; import org.apache.fop.apps.FopFactory; @@ -38,11 +31,22 @@ import org.georchestra.cadastrapp.configuration.CadastrappPlaceHolder; import org.georchestra.cadastrapp.model.request.InformationRequest; import org.georchestra.cadastrapp.repository.RequestRepository; +import org.georchestra.cadastrapp.service.CadController; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; - -public class RequestPDFController{ +import org.springframework.http.ContentDisposition; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; + +@Controller +public class RequestPDFController extends CadController{ static final Logger logger = LoggerFactory.getLogger(RequestPDFController.class); @@ -51,12 +55,10 @@ public class RequestPDFController{ @Autowired RequestRepository requestRepository; - @GET - @Path("/printPDFRequest") - @Produces("application/pdf") - public Response printPDFRequest(@Context HttpHeaders headers, @QueryParam("requestid") long requestId) { + @RequestMapping(path = "/printPDFRequest", produces = {MediaType.APPLICATION_PDF_VALUE}, method= {RequestMethod.GET}) + public ResponseEntity printPDFRequest(@RequestParam(name = "requestid") long requestId) { - ResponseBuilder response = Response.noContent(); + ResponseEntity response = new ResponseEntity<>(HttpStatus.NO_CONTENT); // Check if requestId exist if (requestId != 0) { @@ -142,9 +144,17 @@ public Response printPDFRequest(@Context HttpHeaders headers, @QueryParam("reque out.close(); // Create response - response = Response.ok((Object) pdfResult); - response.header("Content-Disposition", "attachment; filename=" + pdfResult.getName()); + ContentDisposition contentDisposition = ContentDisposition.builder("attachment") + .filename(pdfResult.getName()) + .build(); + + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_PDF); + headers.setContentDisposition(contentDisposition); + + response = new ResponseEntity(FileUtils.readFileToByteArray(pdfResult), headers, HttpStatus.OK); + response = new ResponseEntity<>(FileUtils.readFileToByteArray(pdfResult), headers, HttpStatus.OK); } catch (JAXBException jaxbException) { logger.warn("Error during converting object to xml", jaxbException); } catch (TransformerException transformerException) { @@ -177,7 +187,7 @@ public Response printPDFRequest(@Context HttpHeaders headers, @QueryParam("reque } else { logger.warn("Required parameter missing"); } - return response.build(); + return response; } } diff --git a/cadastrapp/src/main/resources/logback.xml b/cadastrapp/src/main/resources/logback.xml index 731e9f71..3736e11d 100644 --- a/cadastrapp/src/main/resources/logback.xml +++ b/cadastrapp/src/main/resources/logback.xml @@ -27,15 +27,18 @@ + + + /tmp/cadastrapp.log - %d [%thread] %-5level /%X{uri} - %X{user:-nouser} - %X{org:-noorg} - %X{roles:-norole} -%logger{36} - %msg%n + %d [%thread] %-5level /%X{uri} - %X{sec-username:-nouser} - %X{sec-roles:-norole} - %X{sec-org:-noorg} -%logger{36} - %msg%n - + - + \ No newline at end of file diff --git a/cadastrapp/src/main/webapp/WEB-INF/beans.xml b/cadastrapp/src/main/webapp/WEB-INF/beans.xml index 7ece8b15..cccccab2 100644 --- a/cadastrapp/src/main/webapp/WEB-INF/beans.xml +++ b/cadastrapp/src/main/webapp/WEB-INF/beans.xml @@ -1,27 +1,25 @@ - - - + - - - + + - + classpath:cadastrapp.properties @@ -34,38 +32,10 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + @@ -76,8 +46,7 @@ - + @@ -128,52 +97,51 @@ - + - + - - - - + + + + - - - - - - - - - + + + + + + + + + - - - - - - - - true - - - - - - - - - - - - - - - - - \ No newline at end of file + + + + + + + + true + + + + + + + + + + + + + + + + + diff --git a/cadastrapp/src/main/webapp/WEB-INF/web.xml b/cadastrapp/src/main/webapp/WEB-INF/web.xml index 73e3872f..dcb7d80b 100644 --- a/cadastrapp/src/main/webapp/WEB-INF/web.xml +++ b/cadastrapp/src/main/webapp/WEB-INF/web.xml @@ -2,55 +2,57 @@ Cadastrapp Webapp supplémentaire pour la visualisation de données cadastrale dans georchestra - + contextConfigLocation WEB-INF/beans.xml - org.georchestra.cadastrapp.logging.ExternalConfigLoaderContextListener + + org.georchestra.cadastrapp.logging.ExternalConfigLoaderContextListener + org.springframework.web.context.ContextLoaderListener + - + org.georchestra.cadastrapp.context.CadastrappContextListener - - - - default - /apidocs/* - - - + + index.jsp - - - + + + - CXFServlet - org.apache.cxf.transport.servlet.CXFServlet + services + org.springframework.web.servlet.DispatcherServlet + + contextConfigLocation + + 1 + - CXFServlet + services /services/* - - + + - Connection Pool - jdbc/cadastrapp - javax.sql.DataSource - Container - - + Connection Pool + jdbc/cadastrapp + javax.sql.DataSource + Container + + diff --git a/cadastrapp/src/main/webapp/index.jsp b/cadastrapp/src/main/webapp/index.jsp index 52a67126..dc1073cb 100644 --- a/cadastrapp/src/main/webapp/index.jsp +++ b/cadastrapp/src/main/webapp/index.jsp @@ -4,22 +4,22 @@ - - - Cadastrapp - services - - -

Cadastrapp

-

- JavaDoc - WADL -

- GitHub Georchestra + + + Cadastrapp - services + + +

Cadastrapp

+

+ GitHub Georchestra +

+ Swagger description +

+ Swagger UI

- SELECT datname FROM pg_database; + SELECT datname FROM pg_database; -
Database link : KO diff --git a/cadastrapp/src/test/java/org/georchestra/cadastrapp/service/CadControllerTest.java b/cadastrapp/src/test/java/org/georchestra/cadastrapp/service/CadControllerTest.java index 7bcb964a..d3007df4 100644 --- a/cadastrapp/src/test/java/org/georchestra/cadastrapp/service/CadControllerTest.java +++ b/cadastrapp/src/test/java/org/georchestra/cadastrapp/service/CadControllerTest.java @@ -3,8 +3,6 @@ */ package org.georchestra.cadastrapp.service; -import static org.junit.Assert.*; - import java.util.ArrayList; import org.georchestra.cadastrapp.service.pdf.BordereauParcellaireHelper; @@ -18,7 +16,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** - * @author gfi + * @author Pierre Jégo * */ @RunWith(SpringJUnit4ClassRunner.class) diff --git a/cadastrapp/src/test/java/org/georchestra/cadastrapp/service/ImageParcelleControllerTest.java b/cadastrapp/src/test/java/org/georchestra/cadastrapp/service/ImageParcelleControllerTest.java index 6095827a..a6422250 100644 --- a/cadastrapp/src/test/java/org/georchestra/cadastrapp/service/ImageParcelleControllerTest.java +++ b/cadastrapp/src/test/java/org/georchestra/cadastrapp/service/ImageParcelleControllerTest.java @@ -4,15 +4,16 @@ package org.georchestra.cadastrapp.service; -import javax.ws.rs.core.Response; +import java.io.File; import org.junit.Test; import org.junit.runner.RunWith; +import org.springframework.http.ResponseEntity; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** - * @author gfi + * @author Pierre Jégo * */ //@RunWith(SpringJUnit4ClassRunner.class) @@ -33,7 +34,7 @@ public void testCreateImageBordereauParcellaire() { ImageParcelleController imageParcelleController = new ImageParcelleController(); - Response response = imageParcelleController.createImageBordereauParcellaire("2014630103000AO0351", 0, "#1446DE", (float) 0.50, "#10259E",2); + ResponseEntity response = imageParcelleController.createImageBordereauParcellaire("2014630103000AO0351", 0, "#1446DE", (float) 0.50, "#10259E",2); } diff --git a/cadastrapp/src/test/resources/test-config.xml b/cadastrapp/src/test/resources/test-config.xml index e48d9b39..d84a37b6 100644 --- a/cadastrapp/src/test/resources/test-config.xml +++ b/cadastrapp/src/test/resources/test-config.xml @@ -4,14 +4,14 @@ xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jpa="http://www.springframework.org/schema/data/jpa" - xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd - http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd + xmlns:mvc="http://www.springframework.org/schema/mvc" + xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd + http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd - http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd - http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd - http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd"> - - + http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.3.xsd + http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd + http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd + http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd"> @@ -31,42 +31,6 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -