Export to PDF facility - in progess

This commit is contained in:
Francesco Mangiacrapa 2023-11-15 17:53:03 +01:00
parent 6523b98860
commit e81c0c2c17
9 changed files with 1214 additions and 850 deletions

View File

@ -4,6 +4,10 @@
All notable changes to this project will be documented in this file.
This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [v1.1.0-SNAPSHOT]
- Added Export to PDF facility
## [v1.0.0]
- Fixed #25201

View File

@ -10,7 +10,7 @@
<groupId>org.gcube.application</groupId>
<artifactId>geoportal-data-mapper</artifactId>
<version>1.0.0</version>
<version>1.1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<scm>

View File

@ -0,0 +1,4 @@
LOGO_D4GNA = https://data.d4science.org/shub/E_dmhxT0ZReFpXQ1ZXZUp0M2pXUGhtTEZicHNyMGZUVTB4cTkyc2xqMXFSWmo2Q3o4dWl0dTBmY1p1VTdPN29KMQ==
POWERED_BY_D4SCIENCE_LOGO = https://data.d4science.org/shub/E_cndCWGYxbFc3QVBKUnFvS1g1dy9ULzNqLzB4SXVKMldhRUQzTjV3MmJUV0pjVUFnWndHNnJ4bGNtTHZTR1hlaA==
WWW_D4SCIENCE_ORG = https://www.d4science.org
GNA_D4SCIENCE_ORG = https://gna.d4science.org

View File

@ -0,0 +1,84 @@
package org.gcube.application.geoportaldatamapper.reader;
import static org.gcube.resources.discovery.icclient.ICFactory.clientFor;
import static org.gcube.resources.discovery.icclient.ICFactory.queryFor;
import java.util.Collection;
import java.util.List;
import org.gcube.common.encryption.StringEncrypter;
import org.gcube.common.resources.gcore.ServiceEndpoint;
import org.gcube.common.resources.gcore.ServiceEndpoint.AccessPoint;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.resources.discovery.client.api.DiscoveryClient;
import org.gcube.resources.discovery.client.queries.api.SimpleQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MapBoxEndpointReader {
private static Logger LOG = LoggerFactory.getLogger(MapBoxEndpointReader.class);
private static final String SE_PROFILE_NAME = "API_MapBox";
private static final String SE_CATEGORY_NAME = "OnlineService";
/**
* Gets the list base maps.
*
* @return the list base maps
* @throws Exception the exception
*/
public static ServiceAccessPoint getMapBoxEndpoint() throws Exception {
LOG.info("Searching SE in the scope: " + ScopeProvider.instance.get() + " with profile name: " + SE_PROFILE_NAME
+ " and category name: " + SE_CATEGORY_NAME);
ServiceAccessPoint ap = new ServiceAccessPoint();
SimpleQuery query = queryFor(ServiceEndpoint.class);
query.addCondition("$resource/Profile/Name/text() eq '" + SE_PROFILE_NAME + "'");
query.addCondition("$resource/Profile/Category/text() eq '" + SE_CATEGORY_NAME + "'");
DiscoveryClient<ServiceEndpoint> client = clientFor(ServiceEndpoint.class);
List<ServiceEndpoint> resources = client.submit(query);
if (resources.size() > 0)
LOG.info("The query returned " + resources.size() + " ServiceEndpoint/s");
else
throw new RuntimeException("ServiceEndpoint not found. Searching for profile name: " + SE_PROFILE_NAME
+ " and category name: " + SE_CATEGORY_NAME + ", in the scope: " + ScopeProvider.instance.get());
ServiceEndpoint se = resources.get(0);
Collection<AccessPoint> theAccessPoints = se.profile().accessPoints().asCollection();
for (AccessPoint accessPoint : theAccessPoints) {
String url = accessPoint.address();
String apiTokenName = accessPoint.username();
String apiTokenPwd = accessPoint.password();
LOG.debug("Found API_TOKEN name: " + apiTokenName + ", encrypted token: " + apiTokenPwd);
// decrypting the pwd
try {
if (isValorized(apiTokenPwd)) {
apiTokenPwd = StringEncrypter.getEncrypter().decrypt(apiTokenPwd);
LOG.debug("Token decrypted is: " + apiTokenPwd.substring(0, apiTokenPwd.length() / 2)
+ "_MASKED_TOKEN_");
}
} catch (Exception e) {
throw new RuntimeException("Error on decrypting the pwd: ", e);
}
ap.setUrl(url);
ap.setApiTokenName(apiTokenName);
ap.setApiTokenPwd(apiTokenPwd);
}
return ap;
}
private static boolean isValorized(String value) {
if (value != null && !value.isEmpty()) {
return true;
}
return false;
}
}

View File

@ -0,0 +1,12 @@
package org.gcube.application.geoportaldatamapper.reader;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
public class ServiceAccessPoint {
String url;
String apiTokenName;
String apiTokenPwd;
}

View File

@ -0,0 +1,17 @@
package org.gcube.application.geoportaldatamapper.shared;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
public class ExporterProjectSource {
String profileID;
String projectID;
String profileTitle;
String scope;
String accountname; //if null the exporter will use PUBLIC ACCESS
String gisLink;
}

View File

@ -1,94 +1,31 @@
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.stream.Collectors;
import org.gcube.application.geoportal.common.model.document.Project;
import org.gcube.application.geoportalcommon.ConvertToDataValueObjectModel;
import org.gcube.application.geoportalcommon.ProjectDVBuilder;
import org.gcube.application.geoportalcommon.geoportal.GeoportalClientCaller;
import org.gcube.application.geoportalcommon.geoportal.ProjectsCaller;
import org.gcube.application.geoportalcommon.geoportal.UseCaseDescriptorCaller;
import org.gcube.application.geoportalcommon.shared.geoportal.geojson.GeoJSON;
import org.gcube.application.geoportalcommon.shared.geoportal.materialization.GCubeSDIViewerLayerDV;
import org.gcube.application.geoportalcommon.shared.geoportal.materialization.innerobject.FilesetDV;
import org.gcube.application.geoportalcommon.shared.geoportal.materialization.innerobject.PayloadDV;
import org.gcube.application.geoportalcommon.shared.geoportal.project.ProjectDV;
import org.gcube.application.geoportalcommon.shared.geoportal.view.ProjectView;
import org.gcube.application.geoportalcommon.shared.geoportal.view.SectionView;
import org.gcube.application.geoportalcommon.shared.geoportal.view.SubDocumentView;
import org.gcube.application.geoportaldatamapper.Geoportal_JSON_Mapper;
import org.gcube.application.geoportaldatamapper.URLParserUtil;
import org.gcube.application.geoportaldatamapper.Geoportal_PDF_Exporter;
import org.gcube.application.geoportaldatamapper.reader.MapBoxEndpointReader;
import org.gcube.application.geoportaldatamapper.reader.ServiceAccessPoint;
import org.gcube.application.geoportaldatamapper.shared.ExporterProjectSource;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.spatial.data.geoutility.bean.WmsParameters;
import org.gcube.spatial.data.geoutility.shared.BBOX;
import org.gcube.spatial.data.geoutility.shared.wfs.WFSParameter;
import org.gcube.spatial.data.geoutility.wfs.WFSQueryBuilder;
//import org.imgscalr.Scalr;
//import org.imgscalr.Scalr.Method;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.itextpdf.io.font.constants.StandardFonts;
import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.colors.ColorConstants;
import com.itextpdf.kernel.colors.DeviceRgb;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.PdfAnnotationBorder;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.action.PdfAction;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.Style;
import com.itextpdf.layout.borders.Border;
import com.itextpdf.layout.element.AreaBreak;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Image;
import com.itextpdf.layout.element.Link;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.element.Text;
import com.itextpdf.layout.properties.HorizontalAlignment;
import com.itextpdf.layout.properties.TextAlignment;
import com.itextpdf.layout.renderer.CellRenderer;
import com.itextpdf.layout.renderer.DrawContext;
import com.itextpdf.layout.renderer.IRenderer;
/**
* The Class Geoportal_Export_To_PDF_Tests.
*
* @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it
*
* Dec 5, 2022
* Nov 15, 2023
*/
public class Geoportal_Export_To_PDF_Tests {
private static final int FONT_SIZE_SECTION_TITLE = 14;
private static final String GCUBE_CONFIG_PROPERTIES_FILENAME = "gcube_config.properties";
private static final float PARAGRAPH_FONT_SIZE = 9;
// APP Working Directory + /src/test/resources must be the location of
// gcube_config.properties
private static String gcube_config_path = String.format("%s/%s",
@ -99,35 +36,32 @@ public class Geoportal_Export_To_PDF_Tests {
private UseCaseDescriptorCaller clientUCD;
private ProjectsCaller clientProjects;
// private static String PROFILE_ID = "concessioni-estere";
//private static String PROFILE_ID = "concessioni-estere";
private static String PROFILE_ID = "profiledConcessioni";
private static String PROJECT_ID = "646353c5d7fb4a4633022803"; // "6384ae78308f5c28c5ee08aa"; //PRE
//6388e4f8a1e60e66b7b584ac Ficocle-Cervia Vecchia
//6388d9b3a1e60e66b7b5843a
//646353c5d7fb4a4633022803 Villa Romana del Capo di Sorrento
private static String PROJECT_ID = "64a2c5c6a827c620191599ff";
// DEV
// 654e07a75bdd5478cca320c0
// 655489965bdd5478cca320ea
// 6388e4f8a1e60e66b7b584ac Ficocle-Cervia Vecchia
// 6388d9b3a1e60e66b7b5843a
// 646353c5d7fb4a4633022803 Villa Romana del Capo di Sorrento
// 63f8c481e9d6ac16f394f1e6
// PROD
// 63d011c4dcac4551b9a6b930
// //6442653ac6a0422d9e9042e0
// //6399de3ca0a4545420373251
// 645a152fd7fb4a463302240d
// 63f8c481e9d6ac16f394f1e6
// PROD concessione-estere
// 64a2c5c6a827c620191599ff
// IMPORTANT!!!! #NB SET USERNAME = null to test PUBLIC ACCESS
private static String USERNAME = "francesco.mangiacrapa";
// private static String OSM_DOWNLOAD_ENDPOINT =
// "https://render.openstreetmap.org/cgi-bin/export";
// https://api.mapbox.com/styles/v1/mapbox/streets-v12/static/geojson({"type":"Point","coordinates":[-73.99,40.7]})/-73.99,40.70,12/500x300?access_token=pk.eyJ1IjoiZXhhbXBsZXMiLCJhIjoiY2p0MG01MXRqMW45cjQzb2R6b2ptc3J4MSJ9.zA2W0IkI0c6KaAhJfk9bWg
private static String MAP_BOX_STATIC_API_ENDPOINT = "https://api.mapbox.com/styles/v1/mapbox/streets-v12/static";
private static String MAP_BOX_GEOJSON_PARAMETER = "geojson({\"type\":\"Point\",\"coordinates\":%s})";
// private static String MAP_BOX_ACCESS_TOKEN = "access_token=%s";
private static String mapBoxAccessToken = "";
private static String mapSize = "500x300";
private static String USERNAME = null;
/**
* Read context settings.
@ -167,780 +101,42 @@ public class Geoportal_Export_To_PDF_Tests {
clientProjects = GeoportalClientCaller.projects();
}
/**
* Api map box service endpoint reader.
*/
// @Test
public void apiMapBoxServiceEndpointReader() {
try {
ServiceAccessPoint se = MapBoxEndpointReader.getMapBoxEndpoint();
System.out.println(se);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Test read project view.
*/
@Test
public void testExportToPDF() {
ScopeProvider.instance.set(CONTEXT);
SecurityTokenProvider.instance.set(TOKEN);
Geoportal_PDF_Exporter pdfExporter = new Geoportal_PDF_Exporter();
ExporterProjectSource exporterSource = new ExporterProjectSource();
exporterSource.setAccountname(USERNAME);
exporterSource.setProfileID(PROFILE_ID);
exporterSource.setProjectID(PROJECT_ID);
exporterSource.setProfileTitle("Regime di Concessione");
exporterSource.setScope(CONTEXT);
try {
ScopeProvider.instance.set(CONTEXT);
SecurityTokenProvider.instance.set(TOKEN);
Project theProject = clientProjects.getProjectByID(PROFILE_ID, PROJECT_ID);
ProjectDVBuilder projectBuilder = ProjectDVBuilder.newBuilder().fullDocumentMap(true);
projectBuilder.relationships(true);
String logoD4GNA = "https://data.d4science.org/shub/E_dmhxT0ZReFpXQ1ZXZUp0M2pXUGhtTEZicHNyMGZUVTB4cTkyc2xqMXFSWmo2Q3o4dWl0dTBmY1p1VTdPN29KMQ==";
String profileTitle = "Indagine svolta in regime di Concessione";
String gisLink = "https://My GIS Link";
String poweredByD4Science = "https://data.d4science.org/shub/E_cndCWGYxbFc3QVBKUnFvS1g1dy9ULzNqLzB4SXVKMldhRUQzTjV3MmJUV0pjVUFnWndHNnJ4bGNtTHZTR1hlaA==";
System.out.println("project json: " + theProject.getTheDocument().toJson());
ProjectDV theProjectDV = ConvertToDataValueObjectModel.toProjectDV(theProject, projectBuilder);
ProjectView projectView = Geoportal_JSON_Mapper.loadProjectView(theProjectDV, CONTEXT, USERNAME);
// Geoportal_JSON_Mapper.prettyPrintProjectView(projectView);
// CREATING NEW PDF
// Initialize PDF document
PdfDocument pdf = new PdfDocument(new PdfWriter("iTextSTART.pdf"));
// Initialize document
Document document = new Document(pdf);
// Adding logo D4GNA
Image image = toImageFromLink(logoD4GNA, 80);
// image.setMaxHeight(150);
image.setFixedPosition(document.getLeftMargin(),
pdf.getDefaultPageSize().getHeight() - image.getImageHeight() + 90);
document.add(image);
// Project Name
PdfFont bold = PdfFontFactory.createFont(StandardFonts.TIMES_BOLD);
String projectTitle = "";
try {
projectTitle = (String) theProjectDV.getTheDocument().getFirstEntryOfMap().getValue();
} catch (Exception e) {
// TODO: handle exception
}
Text title = new Text(projectTitle).setFont(bold);
Style style = new Style();
style.setPaddingTop(20);
style.setTextAlignment(TextAlignment.LEFT);
Paragraph p = new Paragraph().add(title).addStyle(style).setFontSize(17);
document.add(p);
// Project Type
Text projectType = new Text(profileTitle).setFontColor(ColorConstants.WHITE)
.setTextAlignment(TextAlignment.CENTER).setFontSize(8);
Style marginLeft = new Style().setMarginLeft(10);
projectType.addStyle(marginLeft);
// Adding type
Paragraph preface = new Paragraph();
preface.setHorizontalAlignment(HorizontalAlignment.CENTER);
DeviceRgb rgbColor = new DeviceRgb(0, 60, 136);
preface.setBackgroundColor(rgbColor);
preface.add(projectType);
document.add(preface);
// GIS LINK
Link theLink = getLinkFromURL(gisLink, gisLink, 5);
theLink.setFontSize(7);
Paragraph p2 = new Paragraph().add(theLink);
document.add(p2);
// Adding centroid MAP
String geoJSON = theProjectDV.getSpatialReference().getGeoJSON();
String downMapBoxImg = linkToMarkerURLViaMapBoxStaticMap(geoJSON, 7, mapSize, mapBoxAccessToken);
Image backgroundImage = toImageFromLink(downMapBoxImg, 250);
Table tableI = new Table(1);
tableI.setTextAlignment(TextAlignment.CENTER);
tableI.addCell(backgroundImage);
Paragraph pCentroid = new Paragraph();
pCentroid.setTextAlignment(TextAlignment.CENTER);
pCentroid.add(tableI);
document.add(pCentroid);
for (SectionView section : projectView.getListSections()) {
document = appendSubDocumentToPDF(document, section, section.getListSubDocuments());
}
// TimeStamp
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
PdfFont font = PdfFontFactory.createFont(StandardFonts.COURIER_OBLIQUE);
Style style2 = new Style().setFont(font).setFontSize(8);
Paragraph pt = new Paragraph().add("Created at " + now.format(dtf)).addStyle(style2);
// pt.setFixedPosition(document.getLeftMargin() + 30, 50,
// document.getPdfDocument().getDefaultPageSize().getWidth() - 75);
pt.setMarginTop(50);
document.add(pt);
// Credits
Table tableCredits = getCredits(document, logoD4GNA, poweredByD4Science);
document.add(tableCredits);
document.close();
System.out.println("\n\n testReadProjectView terminated!!!");
} catch (Exception e) {
System.err.println("Error");
e.printStackTrace();
}
}
/**
* Link to marker URL via map box static map.
*
* @param geoJSON the geo JSON
* @param zoom the zoom
* @param widthXheight the width xheight
* @param accessTokenValue the access token value
* @return the string
*/
private static String linkToMarkerURLViaMapBoxStaticMap(String geoJSON, int zoom, String widthXheight,
String accessTokenValue) {
// String geoJSON = theProjectDV.getSpatialReference().getGeoJSON();
try {
JSONObject theGeoJSONObj = new JSONObject(geoJSON);
String pointCoordinates = theGeoJSONObj.getString(GeoJSON.COORDINATES);
String geojson = String.format(MAP_BOX_GEOJSON_PARAMETER, pointCoordinates);
JSONArray jsonArray = new JSONArray(pointCoordinates);
if (zoom < 0)
zoom = 7;
jsonArray.put(jsonArray.length() - 1, zoom);
pointCoordinates = jsonArray.toString();
String downMapBoxImg = String.format("%s/%s/%s/%s?access_token=%s", MAP_BOX_STATIC_API_ENDPOINT, geojson,
pointCoordinates.replaceAll("\\[", "").replaceAll("\\]", ""), widthXheight, accessTokenValue);
System.out.println("DOWN IMAGE: " + downMapBoxImg);
return downMapBoxImg;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
pdfExporter.createPDFFile(exporterSource);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* Link to map box static map.
*
* @param bbox the bbox
* @param widthXheight the width xheight
* @param accessTokenValue the access token value
* @return the string
*/
private static String linkToMapBoxStaticMap(String bbox, String widthXheight, String accessTokenValue) {
try {
String downMapBoxImg = String.format("%s/[%s]/%s?access_token=%s", MAP_BOX_STATIC_API_ENDPOINT, bbox,
widthXheight, accessTokenValue);
System.out.println("DOWN IMAGE: " + downMapBoxImg);
return downMapBoxImg;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* Gets the credits.
*
* @param document the document
* @param logoD4GNA the logo D 4 GNA
* @param logoPoweredByD4Science the logo powered by D 4 science
* @return the credits
*/
private Table getCredits(Document document, String logoD4GNA, String logoPoweredByD4Science) {
Table tableCredits = toTableFixedLayout(document, 4, false);
tableCredits.setBorder(Border.NO_BORDER);
tableCredits.setTextAlignment(TextAlignment.LEFT);
// tableCredits.setFixedLayout();
tableCredits.setFixedPosition(document.getLeftMargin() + 30, 15,
document.getPdfDocument().getDefaultPageSize().getWidth() - 75);
// Adding logo D4GNA
Image imageLogo = toImageFromLink(logoD4GNA, 40);
Cell cell1 = new Cell();
cell1.setBorder(Border.NO_BORDER);
cell1.add(imageLogo);
tableCredits.addCell(cell1);
// Adding LINK D4GNA
Cell cell2 = new Cell();
Link theLinkD4GNA = getLinkFromURL("https://gna.d4science.org/", "https://gna.d4science.org/", 0);
theLinkD4GNA.setFontSize(5);
Paragraph p3 = new Paragraph().add(theLinkD4GNA);
cell2.setBorder(Border.NO_BORDER);
cell2.add(p3);
tableCredits.addCell(cell2);
// Adding logo Powered By D4Science
Image poweredByLink = toImageFromLink(logoPoweredByD4Science, 80);
Cell cell3 = new Cell();
cell3.setBorder(Border.NO_BORDER);
cell3.add(poweredByLink);
tableCredits.addCell(cell3);
// Adding LINK d4science
Cell cell4 = new Cell();
Link theLinkD4Science = getLinkFromURL("https://www.d4science.org/", "https://www.d4science.org/", 0);
theLinkD4Science.setFontSize(5);
Paragraph p4 = new Paragraph().add(theLinkD4Science);
cell4.setBorder(Border.NO_BORDER);
cell4.add(p4);
tableCredits.addCell(cell4);
return tableCredits;
}
/**
* Append sub document to PDF.
*
* @param document the document
* @param sectionView the section view
* @param subDocuments the sub documents
* @return the document
*/
private static Document appendSubDocumentToPDF(Document document, SectionView sectionView,
List<SubDocumentView> subDocuments) {
try {
boolean displayAsGallery = false;
for (SubDocumentView subDocumentView : subDocuments) {
if (subDocumentView.getListImages() != null && subDocumentView.getListImages().size() > 0) {
System.out.println("Section with images: " + subDocumentView.getListImages());
displayAsGallery = true;
break;
}
}
boolean displayAsMapOfLayers = false;
for (SubDocumentView subDocumentView : subDocuments) {
if (subDocumentView.getListLayers() != null && subDocumentView.getListLayers().size() > 0) {
System.out.println("Section with layers: " + subDocumentView.getListLayers());
displayAsMapOfLayers = true;
break;
}
}
// Displaying the whole section as a Gallery
if (displayAsGallery) {
PdfFont bold = PdfFontFactory.createFont(StandardFonts.TIMES_BOLD);
Paragraph paragraph = new Paragraph().add(sectionView.getSectionTitle()).setFont(bold)
.setFontSize(FONT_SIZE_SECTION_TITLE);
// paragraph.setMarginTop(10);
document.add(new AreaBreak());
document.add(paragraph);
System.out.println("displayAsGallery the: " + sectionView);
for (SubDocumentView subDocumentView : subDocuments) {
JsonObject jsonObject = new JsonParser().parse(subDocumentView.getMetadataAsJSON())
.getAsJsonObject();
Table tableContainer = toTableFixedLayout(document, 2, true);
// tableContainer.setBorder(Border.NO_BORDER);
Table tableMeta = new Table(2);
tableMeta = jsonToTable(tableMeta, 1, "", jsonObject);
// tableMeta.setBorder(Border.NO_BORDER);
List<FilesetDV> files = subDocumentView.getListImages();
Table tableI = new Table(1);
// tableI.setTextAlignment(TextAlignment.CENTER);
// tableI.setBorder(Border.NO_BORDER);
if (files != null) {
for (FilesetDV fileset : files) {
// Paragraph paragraphInt = new Paragraph(fileset.getGcubeProfileFieldName());
List<Image> listLinks = toImages(fileset.getListPayload(), 250);
for (Image image : listLinks) {
image.setBorder(Border.NO_BORDER);
tableI.addCell(image);
}
}
}
tableContainer.addCell(tableMeta);
tableContainer.addCell(tableI);
document.add(tableContainer);
}
// Displaying the whole section as a Map of Layers
} else if (displayAsMapOfLayers) {
PdfFont bold = PdfFontFactory.createFont(StandardFonts.TIMES_BOLD);
Paragraph paragraph = new Paragraph().add(sectionView.getSectionTitle()).setFont(bold)
.setFontSize(FONT_SIZE_SECTION_TITLE);
// paragraph.setMarginTop(10);
document.add(new AreaBreak());
document.add(paragraph);
System.out.println("displayAsMapOfLayers the: " + sectionView);
for (SubDocumentView subDocumentView : subDocuments) {
JsonObject jsonObject = new JsonParser().parse(subDocumentView.getMetadataAsJSON())
.getAsJsonObject();
Table tableContainerL = toTableFixedLayout(document, 1, true);
Table tableMeta = new Table(2);
tableMeta = jsonToTable(tableMeta, 1, "", jsonObject);
List<GCubeSDIViewerLayerDV> layers = subDocumentView.getListLayers();
Table tableI = new Table(2);
if (layers != null) {
for (GCubeSDIViewerLayerDV gCubeLayer : layers) {
tableI.setTextAlignment(TextAlignment.CENTER);
String wmsLink = gCubeLayer.getWMSLink();
System.out.println("wmsLink(1): " + wmsLink);
wmsLink = URLParserUtil.setValueOfParameter("format", wmsLink, "image/png", true);
String bbox = URLParserUtil.extractValueOfParameterFromURL("bbox", wmsLink);
String wmsVersion = URLParserUtil.extractValueOfParameterFromURL("version", wmsLink);
Integer expWidth = 600;
Integer expHeight = 600;
wmsLink = URLParserUtil.setValueOfParameter("width", wmsLink, expWidth+"", true);
wmsLink = URLParserUtil.setValueOfParameter("height", wmsLink, expHeight+"", true);
Image image = toImageFromLink(wmsLink, null);
System.out.println("wmsLink cell 1: " + wmsLink);
tableI.addCell(image);
BBOX.COORDINATE_FORMAT bboxFormat = wmsVersion.contains("1.3") ? BBOX.COORDINATE_FORMAT.YX
: BBOX.COORDINATE_FORMAT.XY;
BBOX theBBOX = new BBOX(bbox, bboxFormat);
double tolerance = 0.003;
double lowerXR = theBBOX.getLowerLeftX() - tolerance;
double lowerYR = theBBOX.getLowerLeftY() - tolerance;
double upperXR = theBBOX.getUpperRightX() + tolerance;
double upperYR = theBBOX.getUpperRightY() + tolerance;
String parmBBOX = BBOX.toBBOXString(new BBOX(lowerXR, lowerYR, upperXR, upperYR, ""),
bboxFormat);
//Layer with background color
String wmsLinkTol = URLParserUtil.setValueOfParameter("bbox", wmsLink, parmBBOX, false);
wmsLinkTol+="&TRANSPARENT=TRUE";
System.out.println("wmsLink cell 2: " + wmsLink);
Image image2 = toImageFromLink(wmsLinkTol, null, null);
//MapBox static as background
String linkToMapBox = linkToMapBoxStaticMap(parmBBOX, expWidth+"x"+expHeight, mapBoxAccessToken);
System.out.println("linkToMapBox: " + linkToMapBox);
Image backImg = toImageFromLink(linkToMapBox, null, null);
Cell mapCell = new Cell();
mapCell.setNextRenderer(new ImageBackgroundCellRenderer(mapCell, backImg));
mapCell.add(image2);
tableI.addCell(mapCell);
}
}
tableContainerL.addCell(tableI);
tableContainerL.addCell(tableMeta);
document.add(tableContainerL);
}
} else {
PdfFont bold = PdfFontFactory.createFont(StandardFonts.TIMES_BOLD);
Paragraph paragraph = new Paragraph().add(sectionView.getSectionTitle()).setFont(bold)
.setFontSize(FONT_SIZE_SECTION_TITLE);
paragraph.setMarginTop(10);
document.add(paragraph);
System.out.println("displaying default the: " + sectionView);
for (SubDocumentView subDocumentView : subDocuments) {
JsonObject jsonObject = new JsonParser().parse(subDocumentView.getMetadataAsJSON())
.getAsJsonObject();
Table table = toTableFixedLayout(document, 2, false);
table = jsonToTable(table, 1, "", jsonObject);
int rows = table.getNumberOfRows();
for (int i = 1; i < rows; i++) {
Cell cell1 = table.getCell(i, 0);
cell1.setMinWidth(80);
// cell1.setMaxWidth(100);
}
document.add(table);
List<FilesetDV> files = subDocumentView.getListFiles();
if (files != null) {
for (FilesetDV fileset : files) {
Paragraph paragraphInt = new Paragraph(fileset.getGcubeProfileFieldName());
paragraphInt.setFontSize(PARAGRAPH_FONT_SIZE);
List<Link> listLinks = toPDFLinks(fileset.getListPayload(), 5);
for (Link anchor : listLinks) {
paragraphInt.add(anchor);
}
document.add(paragraphInt);
}
}
}
}
} catch (Exception e) {
System.out.println("Error on rendering the section: " + e.getMessage());
e.printStackTrace();
}
return document;
}
private static class ImageBackgroundCellRenderer extends CellRenderer {
protected Image img;
public ImageBackgroundCellRenderer(Cell modelElement, Image img) {
super(modelElement);
this.img = img;
}
// If a renderer overflows on the next area, iText uses #getNextRenderer() method to create a new renderer for the overflow part.
// If #getNextRenderer() isn't overridden, the default method will be used and thus the default rather than the custom
// renderer will be created
@Override
public IRenderer getNextRenderer() {
return new ImageBackgroundCellRenderer((Cell) modelElement, img);
}
@Override
public void draw(DrawContext drawContext) {
img.scaleToFit(getOccupiedAreaBBox().getWidth(), getOccupiedAreaBBox().getHeight());
drawContext.getCanvas().addXObjectFittedIntoRectangle(img.getXObject(), getOccupiedAreaBBox());
super.draw(drawContext);
}
}
/**
* Wms link to WFS request.
*
* @param wmsLink the wms link
* @return the string
*/
private static String wmsLinkToWFSRequest(String wmsLink) {
String endpoint = wmsLink.substring(0, wmsLink.indexOf("?"));
WFSQueryBuilder builder = new WFSQueryBuilder();
HashMap<WFSParameter, String> defaultR = builder.getDefaultWFSGetFeatureRequest();
wmsLink = URLParserUtil.setValueOfParameter("format", wmsLink, "application/json", true);
defaultR.put(WFSParameter.TYPENAME,
URLParserUtil.extractValueOfParameterFromURL(WmsParameters.LAYERS.getParameter(), wmsLink));
String crs = URLParserUtil.extractValueOfParameterFromURL(WmsParameters.CRS.getParameter(), wmsLink);
if (crs != null && !crs.isEmpty())
defaultR.put(WFSParameter.CRS, crs);
String srs = URLParserUtil.extractValueOfParameterFromURL(WmsParameters.SRS.getParameter(), wmsLink);
if (srs != null && !srs.isEmpty())
defaultR.put(WFSParameter.SRSNAME, srs);
String version = URLParserUtil.extractValueOfParameterFromURL(WmsParameters.VERSION.getParameter(), wmsLink);
if (version != null && !version.isEmpty())
defaultR.put(WFSParameter.VERSION, version);
// String bbox = URLParserUtil.extractValueOfParameterFromURL(WmsParameters.BBOX.getParameter(), wmsLink);
// if(bbox!=null && !bbox.isEmpty())
defaultR.put(WFSParameter.BBOX, null); // all features of the layers
String cqlFilter = URLParserUtil.extractValueOfParameterFromURL(WmsParameters.CQL_FILTER.getParameter(),
wmsLink);
if (cqlFilter != null && !cqlFilter.isEmpty())
defaultR.put(WFSParameter.CQL_FILTER, cqlFilter);
defaultR.put(WFSParameter.OUTPUTFORMAT, "application/json");
String wfsURL = builder.buildWFSFeatureQuery(endpoint, defaultR);
System.out.println("wfsLink:" + wfsURL);
return wfsURL;
}
/**
* To table fixed layout.
*
* @param document the document
* @param column the column
* @param maxWidthToPageSize the max width to page size
* @return the table
*/
private static Table toTableFixedLayout(Document document, int column, boolean maxWidthToPageSize) {
Table table = new Table(column);
table.setFixedLayout();
if (maxWidthToPageSize)
table.setWidth(document.getPdfDocument().getDefaultPageSize().getWidth() - 75);
return table;
}
/**
* To images.
*
* @param payloads the payloads
* @param maxWidth the max width
* @return the list
* @throws IOException Signals that an I/O exception has occurred.
*/
private static List<Image> toImages(List<PayloadDV> payloads, Integer maxWidth) throws IOException {
List<Image> listImages = new ArrayList<Image>(payloads.size());
for (PayloadDV payloadDV : payloads) {
Image img = toImageFromLink(payloadDV.getLink(), maxWidth);
if (img != null)
listImages.add(img);
}
return listImages;
}
/**
* To image from link.
*
* @param link the link
* @param maxWidth the max width
* @return the image
*/
private static Image toImageFromLink(String link, Integer maxWidth) {
Image img = null;
try {
ImageData data = null;
data = ImageDataFactory.create(new URL(link));
img = new Image(data);
if (maxWidth != null)
img.setMaxWidth(maxWidth);
else
img.setAutoScaleWidth(true);
} catch (Exception e) {
// silent
e.printStackTrace();
}
return img;
}
/**
* To image from link.
*
* @param link the link
* @param maxWidth the max width
* @return the image
*/
private static Image toImageFromLink(String link, Integer width, Integer height) {
Image img = null;
try {
ImageData data = null;
data = ImageDataFactory.create(new URL(link));
img = new Image(data);
if (width != null && height!=null) {
img.setWidth(width);
img.setHeight(height);
}
else {
img.setAutoScaleWidth(true);
//img.setAutoScaleHeight(true);
}
} catch (Exception e) {
// silent
e.printStackTrace();
}
return img;
}
/*
* private static Image toImageFromLink(String link, Integer maxWidth, boolean
* scaleImg) { Image img = null; try {
*
* ImageData data = null; if (scaleImg) { final InputStream is = new
* URL(link).openStream(); BufferedImage inputImage = ImageIO.read(is);
* BufferedImage out = simpleResizeImage(inputImage, maxWidth); data =
* ImageDataFactory.create(out, Color.WHITE); is.close(); } else { data =
* ImageDataFactory.create(new URL(link)); }
*
* img = new Image(data);
*
* if (maxWidth != null) img.setMaxWidth(maxWidth); else
* img.setAutoScaleWidth(true);
*
* } catch (Exception e) { // silent e.printStackTrace();
*
* }
*
* return img; }
*/
/**
* To string from link.
*
* @param link the link
* @return the string
*/
private static String toStringFromLink(String link) {
String text = null;
try {
ImageData data = null;
final InputStream is = new URL(link).openStream();
text = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8)).lines()
.collect(Collectors.joining("\n"));
} catch (Exception e) {
// silent
e.printStackTrace();
}
return text;
}
// private static BufferedImage simpleResizeImage(BufferedImage originalImage, int targetWidth) throws Exception {
// if (targetWidth > 0) {
// return Scalr.resize(originalImage, Method.QUALITY, targetWidth);
// }
// return originalImage;
// }
/**
* To PDF links.
*
* @param payloads the payloads
* @param marginLeft the margin left
* @return the list
* @throws IOException Signals that an I/O exception has occurred.
*/
private static List<Link> toPDFLinks(List<PayloadDV> payloads, Integer marginLeft) throws IOException {
List<Link> listLinks = new ArrayList<Link>(payloads.size());
for (PayloadDV payloadDV : payloads) {
Link theLink = getLinkFromURL(payloadDV.getName(), payloadDV.getLink(), 5);
listLinks.add(theLink);
}
return listLinks;
}
/**
* Gets the link from URL.
*
* @param linkTxt the link txt
* @param url the url
* @param marginLeft the margin left
* @return the link from URL
*/
private static Link getLinkFromURL(String linkTxt, String url, Integer marginLeft) {
Link theLink = new Link(linkTxt, PdfAction.createURI(url));
theLink.setFontSize(PARAGRAPH_FONT_SIZE);
theLink.setFontColor(ColorConstants.BLUE);
theLink.getLinkAnnotation().setBorder(new PdfAnnotationBorder(0, 0, 0));
Style style = new Style();
if (marginLeft != null)
style.setMarginLeft(marginLeft);
theLink.addStyle(style);
return theLink;
}
/**
* convert json Data to structured Html text.
*
* @param table the table
* @param deep the deep
* @param key the key
* @param obj the obj
* @return string
*/
private static Table jsonToTable(Table table, int deep, String key, Object obj) {
try {
// System.out.println("obj is istance of: " + obj.getClass());
if (obj instanceof JsonObject) {
JsonObject jsonObject = (JsonObject) obj;
// String[] keys = JSONObject.getNames(jsonObject);
Set<Map.Entry<String, JsonElement>> entrySet = jsonObject.entrySet();
if (entrySet.size() > 0) {
for (Map.Entry<String, JsonElement> entry : entrySet) {
// System.out.println("Adding entry: " + entry);
table = jsonToTable(table, deep++, entry.getKey(), entry.getValue());
}
}
} else if (obj instanceof JsonArray) {
JsonArray array = (JsonArray) obj;
for (int i = 0; i < array.size(); i++) {
// recursive call
String arrayKey = key;
if (i > 0)
arrayKey = "";
table = jsonToTable(table, deep++, arrayKey, array.get(i));
}
} else {
// System.out.println("Adding key: " + key);
// System.out.println("Adding obj: " + obj.toString());
Cell cell1 = createContentCell(2);
cell1.setFontColor(ColorConstants.GRAY);
// cell1.setMinWidth(100);
// cell1.setMaxWidth(150);
cell1.add(new Paragraph(key));
table.addCell(cell1);
// row.add(key);
Cell cell2 = createContentCell(2);
JsonElement value = (JsonElement) obj;
Paragraph content = new Paragraph(value.getAsString());
content.setTextAlignment(TextAlignment.JUSTIFIED);
cell2.add(content);
table.addCell(cell2);
}
} catch (Exception e) {
e.printStackTrace();
}
return table;
}
/**
* Creates the content cell.
*
* @param paddingTop the padding top
* @return the cell
*/
private static Cell createContentCell(Integer paddingTop) {
Cell cell = new Cell();
cell.setBorder(Border.NO_BORDER);
cell.setTextAlignment(TextAlignment.LEFT);
if (paddingTop != null)
cell.setPaddingTop(paddingTop);
cell.setFontSize(PARAGRAPH_FONT_SIZE);
return cell;
}
}

View File

@ -1,2 +1,5 @@
/gcube_config.properties
/log4j.properties
/D4OS.gcubekey
/devsec.gcubekey
/gcube.gcubekey