From e81c0c2c17f9fc9291bf1f222b53521ac1b2b4e3 Mon Sep 17 00:00:00 2001 From: "francesco.mangiacrapa" Date: Wed, 15 Nov 2023 17:53:03 +0100 Subject: [PATCH] Export to PDF facility - in progess --- CHANGELOG.md | 4 + pom.xml | 2 +- .../Geoportal_PDF_Exporter.java | 1044 +++++++++++++++++ .../pdf_exporter_credits.properties | 4 + .../reader/MapBoxEndpointReader.java | 84 ++ .../reader/ServiceAccessPoint.java | 12 + .../shared/ExporterProjectSource.java | 17 + .../java/Geoportal_Export_To_PDF_Tests.java | 894 +------------- src/test/resources/.gitignore | 3 + 9 files changed, 1214 insertions(+), 850 deletions(-) create mode 100644 src/main/java/org/gcube/application/geoportaldatamapper/Geoportal_PDF_Exporter.java create mode 100644 src/main/java/org/gcube/application/geoportaldatamapper/pdf_exporter_credits.properties create mode 100644 src/main/java/org/gcube/application/geoportaldatamapper/reader/MapBoxEndpointReader.java create mode 100644 src/main/java/org/gcube/application/geoportaldatamapper/reader/ServiceAccessPoint.java create mode 100644 src/main/java/org/gcube/application/geoportaldatamapper/shared/ExporterProjectSource.java diff --git a/CHANGELOG.md b/CHANGELOG.md index 8af47b6..c484b43 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/pom.xml b/pom.xml index 6fdc174..aea4870 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ org.gcube.application geoportal-data-mapper - 1.0.0 + 1.1.0-SNAPSHOT jar diff --git a/src/main/java/org/gcube/application/geoportaldatamapper/Geoportal_PDF_Exporter.java b/src/main/java/org/gcube/application/geoportaldatamapper/Geoportal_PDF_Exporter.java new file mode 100644 index 0000000..40169c3 --- /dev/null +++ b/src/main/java/org/gcube/application/geoportaldatamapper/Geoportal_PDF_Exporter.java @@ -0,0 +1,1044 @@ +package org.gcube.application.geoportaldatamapper; + +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.nio.file.StandardCopyOption; +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.apache.commons.io.IOUtils; +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.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.reader.MapBoxEndpointReader; +import org.gcube.application.geoportaldatamapper.reader.ServiceAccessPoint; +import org.gcube.application.geoportaldatamapper.shared.ExporterProjectSource; +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.slf4j.Logger; +import org.slf4j.LoggerFactory; + +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.events.Event; +import com.itextpdf.kernel.events.IEventHandler; +import com.itextpdf.kernel.events.PdfDocumentEvent; +import com.itextpdf.kernel.font.PdfFont; +import com.itextpdf.kernel.font.PdfFontFactory; +import com.itextpdf.kernel.geom.Rectangle; +import com.itextpdf.kernel.pdf.PdfAnnotationBorder; +import com.itextpdf.kernel.pdf.PdfDocument; +import com.itextpdf.kernel.pdf.PdfPage; +import com.itextpdf.kernel.pdf.PdfWriter; +import com.itextpdf.kernel.pdf.action.PdfAction; +import com.itextpdf.kernel.pdf.canvas.PdfCanvas; +import com.itextpdf.layout.Canvas; +import com.itextpdf.layout.Document; +import com.itextpdf.layout.Style; +import com.itextpdf.layout.borders.Border; +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; + +public class Geoportal_PDF_Exporter { + + private static final String PDF_EXPORTER_CREDITS_PROPERTIES_FILENAME = "pdf_exporter_credits.properties"; + private static final String PROPERTY_GNA_D4SCIENCE_ORG = "GNA_D4SCIENCE_ORG"; + private static final String PROPERTY_WWW_D4SCIENCE_ORG = "WWW_D4SCIENCE_ORG"; + private static final String PROPERTY_POWERED_BY_D4SCIENCE_LOGO = "POWERED_BY_D4SCIENCE_LOGO"; + private static final String PROPERTY_LOGO_D4GNA = "LOGO_D4GNA"; + + private static final int PARAGRAPH_MARGIN_TOP = 20; + private static final int FONT_SIZE_SECTION_TITLE = 14; + private static final float PARAGRAPH_FONT_SIZE = 9; + + public static final String mapSizeWithCentroid = "500x300"; + + private static Logger LOG = LoggerFactory.getLogger(Geoportal_PDF_Exporter.class); + + + /** + * Creates the PDF file. + * + * @param exportSource the export source. // set ExporterProjectSource.username = null to test PUBLIC ACCESS + * @return the string + * @throws Exception the exception + */ + public String createPDFFile(ExporterProjectSource exportSource) throws Exception { + + String logoD4GNA = null; + String poweredByD4Science = null; + String wwwD4ScienceOrg = null; + String gnaD4ScienceOrg = null; + + String pdfFileURL = null; + + // Reading property file with credit references + try (InputStream input = Geoportal_PDF_Exporter.class + .getResourceAsStream(PDF_EXPORTER_CREDITS_PROPERTIES_FILENAME)) { + + Properties prop = new Properties(); + + // load a properties file + prop.load(input); + + logoD4GNA = prop.getProperty(PROPERTY_LOGO_D4GNA); + poweredByD4Science = prop.getProperty(PROPERTY_POWERED_BY_D4SCIENCE_LOGO); + wwwD4ScienceOrg = prop.getProperty(PROPERTY_WWW_D4SCIENCE_ORG); + gnaD4ScienceOrg = prop.getProperty(PROPERTY_GNA_D4SCIENCE_ORG); + // get the property value and print it out + LOG.trace(PROPERTY_LOGO_D4GNA + ": " + logoD4GNA); + LOG.trace(PROPERTY_POWERED_BY_D4SCIENCE_LOGO + ": " + poweredByD4Science); + LOG.trace(PROPERTY_WWW_D4SCIENCE_ORG + ": " + wwwD4ScienceOrg); + LOG.trace(PROPERTY_GNA_D4SCIENCE_ORG + ": " + gnaD4ScienceOrg); + + } catch (IOException ex) { + LOG.error("no file found: " + PDF_EXPORTER_CREDITS_PROPERTIES_FILENAME); + throw ex; + } + + ServiceAccessPoint sap = MapBoxEndpointReader.getMapBoxEndpoint(); + + PdfDocument pdfDocument = null; + ByteArrayOutputStream out = null; + try { + ProjectsCaller clientProjects = GeoportalClientCaller.projects(); + Project theProject = clientProjects.getProjectByID(exportSource.getProfileID(), + exportSource.getProjectID()); + ProjectDVBuilder projectBuilder = ProjectDVBuilder.newBuilder().fullDocumentMap(true); + projectBuilder.relationships(false); + + ProjectDV theProjectDV = ConvertToDataValueObjectModel.toProjectDV(theProject, projectBuilder); + ProjectView projectView = Geoportal_JSON_Mapper.loadProjectView(theProjectDV, exportSource.getScope(), + exportSource.getAccountname()); + + // CREATING NEW PDF + // Initialize PDF document + out = new ByteArrayOutputStream(); + pdfDocument = new PdfDocument(new PdfWriter(out)); + + String projectTitle = theProjectDV.getId(); + try { + projectTitle = (String) theProjectDV.getTheDocument().getFirstEntryOfMap().getValue(); + } catch (Exception e) { + // silent + } + + // Creates a header for every page in the document + pdfDocument.addEventHandler(PdfDocumentEvent.END_PAGE, new HeaderHandler()); + + // Initialize document + Document document = new Document(pdfDocument); + + // Adding logo D4GNA + Image image = toImageFromLink(logoD4GNA, 80); + // image.setMaxHeight(150); + image.setFixedPosition(document.getLeftMargin(), + pdfDocument.getDefaultPageSize().getHeight() - image.getImageHeight() + 90); + document.add(image); + + // Project Name + PdfFont bold = PdfFontFactory.createFont(StandardFonts.TIMES_BOLD); + + 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 + if (exportSource.getProfileTitle() != null) { + Text projectType = new Text(exportSource.getProfileTitle()).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 + if (exportSource.getGisLink() != null && !exportSource.getGisLink().isEmpty()) { + Link theLink = getLinkFromURL(exportSource.getGisLink(), exportSource.getGisLink(), 5); + theLink.setFontSize(7); + Paragraph p2 = new Paragraph().add(theLink); + document.add(p2); + } + + // Adding centroid MAP + if (theProjectDV.getSpatialReference() != null) { + String geoJSON = theProjectDV.getSpatialReference().getGeoJSON(); + if (geoJSON != null && !geoJSON.isEmpty()) { + String downMapBoxImg = linkToMarkerURLViaMapBoxStaticMap(geoJSON, 7, mapSizeWithCentroid, sap); + if (downMapBoxImg != null) { + Image backgroundImage = toImageFromLink(downMapBoxImg, 250); + if (backgroundImage != null) { + 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(), + exportSource.getGisLink(), sap); + } + + // TimeStamp - Created at + 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.setMarginTop(50); + document.add(pt); + + // Credits + Table tableCredits = getCredits(document, logoD4GNA, poweredByD4Science, wwwD4ScienceOrg, gnaD4ScienceOrg); + document.add(tableCredits); + document.close(); + + // Copying OutputStream into Temp File on Storage + InputStream in = new ByteArrayInputStream(out.toByteArray()); + String projectTitleSanitized = projectTitle.replaceAll("[^a-zA-Z0-9]", "_"); + + // Save PDF on storage VOLATILE +// StorageUtils storage = new StorageUtils(); +// TempFile tempFile = storage.putOntoStorage(in, projectTitleSanitized + ".pdf"); +// String storageURL = storage.getURL(tempFile.getId()); +// LOG.trace("mongo pdf ID: " + tempFile.getId()); +// LOG.trace("mongo pdf filename: " + tempFile.getFilename()); +// +// pdfFileURL = String.format("%s?contentType=%s&fileName=%s&content-disposition=%s", storageURL, +// "application/pdf", tempFile.getFilename(), "inline"); +// LOG.info("returning pdf URL: " + pdfFileURL); + + // TEST save file locally + File targetFile = new File(projectTitleSanitized + ".pdf"); + java.nio.file.Files.copy(in, targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING); + LOG.info("targetFile at: " + targetFile.getAbsolutePath()); + + IOUtils.closeQuietly(in); + } catch (Exception e) { + LOG.error("Error on generating the pdf file: ", e); + throw new Exception("Error on generating the pdf file", e); + } finally { + + if (pdfDocument != null) { + try { + pdfDocument.close(); + } catch (Exception e) { + // silent + } + } + } + + return pdfFileURL; + } + + /** + * The Class HeaderHandler. + * + * @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it + * + * Nov 15, 2023 + */ + public class HeaderHandler implements IEventHandler { + + /** + * Handle event. + * + * @param event the event + */ + @Override + public void handleEvent(Event event) { + PdfDocumentEvent docEvent = (PdfDocumentEvent) event; + PdfDocument pdf = docEvent.getDocument(); + PdfPage page = docEvent.getPage(); + int pageNumber = pdf.getPageNumber(page); + Rectangle pageSize = page.getPageSize(); + PdfCanvas pdfCanvas = new PdfCanvas(page.newContentStreamBefore(), page.getResources(), pdf); + Canvas canvas = new Canvas(pdfCanvas, pageSize); + Paragraph p = new Paragraph().add("Pg. ").add(String.valueOf(pageNumber)); + try { + p.setFont(PdfFontFactory.createFont(StandardFonts.HELVETICA_OBLIQUE)); + p.setFontSize(7); + p.setFontColor(ColorConstants.DARK_GRAY); + } catch (IOException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + int x = 565; + int y = 25; + canvas.showTextAligned(p, x, y, TextAlignment.RIGHT); + pdfCanvas.release(); + } + } + + /** + * Link to marker URL via map box static map. + * + * @param geoJSON the geo JSON + * @param zoom the zoom + * @param widthXheight the width xheight + * @param serviceAP the service AP + * @return the string + */ + private static String linkToMarkerURLViaMapBoxStaticMap(String geoJSON, int zoom, String widthXheight, + ServiceAccessPoint serviceAP) { + + try { + + JSONObject theGeoJSONObj = new JSONObject(geoJSON); + String pointCoordinates = theGeoJSONObj.getString(GeoJSON.COORDINATES); + + String geojson = String.format("geojson({\"type\":\"Point\",\"coordinates\":%s})", 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?%s=%s", serviceAP.getUrl(), geojson, + pointCoordinates.replaceAll("\\[", "").replaceAll("\\]", ""), widthXheight, + serviceAP.getApiTokenName(), serviceAP.getApiTokenPwd()); + + LOG.trace("linkToMarkerURLViaMapBoxStaticMap IMAGE: " + downMapBoxImg); + + return downMapBoxImg; + + } catch (JSONException e) { + LOG.warn("JSONException: " + e); + } catch (Exception e) { + LOG.warn("Error: " + e); + } + + 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, ServiceAccessPoint serviceAP) { + + try { + + String downMapBoxImg = String.format("%s/[%s]/%s?%s=%s", serviceAP.getUrl(), bbox, widthXheight, + serviceAP.getApiTokenName(), serviceAP.getApiTokenPwd()); + + LOG.trace("linkToMapBoxStaticMap IMAGE: " + downMapBoxImg); + + return downMapBoxImg; + + } catch (Exception e) { + LOG.warn("Error: " + e); + } + + 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, String wwwD4ScienceOrg, + String gnaD4ScienceOrg) { + + 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(gnaD4ScienceOrg, gnaD4ScienceOrg, 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(wwwD4ScienceOrg, wwwD4ScienceOrg, 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 + * @param gisLink the gis link + * @param sap the sap + * @return the document + */ + private static Document appendSubDocumentToPDF(Document document, SectionView sectionView, + List subDocuments, String gisLink, ServiceAccessPoint sap) { + try { + + boolean displayAsGallery = false; + + for (SubDocumentView subDocumentView : subDocuments) { + if (subDocumentView.getListImages() != null && subDocumentView.getListImages().size() > 0) { + LOG.debug("Section with images: " + subDocumentView.getListImages()); + displayAsGallery = true; + break; + } + } + + boolean displayAsMapOfLayers = false; + for (SubDocumentView subDocumentView : subDocuments) { + if (subDocumentView.getListLayers() != null && subDocumentView.getListLayers().size() > 0) { + LOG.debug("Section with layers: " + subDocumentView.getListLayers()); + displayAsMapOfLayers = true; + break; + } + } + + // Displaying the whole section as a Gallery + if (displayAsGallery) { + try { + PdfFont bold = PdfFontFactory.createFont(StandardFonts.TIMES_BOLD); + Paragraph paragraph = new Paragraph().add(sectionView.getSectionTitle()).setFont(bold) + .setFontSize(FONT_SIZE_SECTION_TITLE); + paragraph.setMarginTop(PARAGRAPH_MARGIN_TOP); + // document.add(new AreaBreak()); + document.add(paragraph); + LOG.debug("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 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 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); + + } + } catch (Exception e) { + LOG.warn("Error on rendering the gallery section: " + sectionView); + } + + // Displaying the whole section as a Map of Layers + } else if (displayAsMapOfLayers) { + try { + PdfFont bold = PdfFontFactory.createFont(StandardFonts.TIMES_BOLD); + Paragraph paragraph = new Paragraph().add(sectionView.getSectionTitle()).setFont(bold) + .setFontSize(FONT_SIZE_SECTION_TITLE); + paragraph.setMarginTop(PARAGRAPH_MARGIN_TOP); + // document.add(new AreaBreak()); + document.add(paragraph); + LOG.trace("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 layers = subDocumentView.getListLayers(); + Table tableI = new Table(2); + if (layers != null) { + for (GCubeSDIViewerLayerDV gCubeLayer : layers) { + tableI.setTextAlignment(TextAlignment.CENTER); + String wmsLink = gCubeLayer.getWMSLink(); + LOG.trace("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); + LOG.trace("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 bboxOffset = 0.003; + double lowerXR = theBBOX.getLowerLeftX() - bboxOffset; + double lowerYR = theBBOX.getLowerLeftY() - bboxOffset; + double upperXR = theBBOX.getUpperRightX() + bboxOffset; + double upperYR = theBBOX.getUpperRightY() + bboxOffset; + + 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"; + LOG.trace("wmsLink cell 2: " + wmsLink); + Image image2 = toImageFromLink(wmsLinkTol, null, null); + + // MapBox static as background + String linkToMapBox = linkToMapBoxStaticMap(parmBBOX, expWidth + "x" + expHeight, sap); + LOG.trace("linkToMapBox: " + linkToMapBox); + + Image backImg = toImageFromLink(linkToMapBox, null, null); + + Cell mapCell = new Cell(); + mapCell.setNextRenderer(new ImageBackgroundCellRenderer(mapCell, backImg)); + + mapCell.add(image2); + + tableI.addCell(mapCell); + + } + } + +// Table tableInfo = toTableFixedLayout(document, 1, true); +// tableInfo.setBorder(Border.NO_BORDER); + PdfFont ho = PdfFontFactory.createFont(StandardFonts.HELVETICA_OBLIQUE); + + Paragraph paragraph1 = new Paragraph(); + String alert = "NB. The layer preview could be scratched"; + + if (gisLink != null) + alert += "See the gis layer at " + gisLink; + + paragraph1.add(alert); + + paragraph1.setFont(bold).setFontSize(6); + paragraph1.setBorder(Border.NO_BORDER); + paragraph1.setFont(ho); + + // Row with layers + tableContainerL.addCell(tableI); + // Row with alert message + tableContainerL.addCell(paragraph1); + // Row with layer metadata + tableContainerL.addCell(tableMeta); + + document.add(tableContainerL); + } + } catch (Exception e) { + LOG.warn("Error on rendering the layer section: " + sectionView); + } + + } else { + try { + PdfFont bold = PdfFontFactory.createFont(StandardFonts.TIMES_BOLD); + Paragraph paragraph = new Paragraph().add(sectionView.getSectionTitle()).setFont(bold) + .setFontSize(FONT_SIZE_SECTION_TITLE); + paragraph.setMarginTop(PARAGRAPH_MARGIN_TOP); + document.add(paragraph); + LOG.debug("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 files = subDocumentView.getListFiles(); + if (files != null) { + for (FilesetDV fileset : files) { + Paragraph paragraphInt = new Paragraph(fileset.getGcubeProfileFieldName()); + paragraphInt.setFontSize(PARAGRAPH_FONT_SIZE); + List listLinks = toPDFLinks(fileset.getListPayload(), 5); + for (Link anchor : listLinks) { + paragraphInt.add(anchor); + } + document.add(paragraphInt); + } + } + } + } catch (Exception e) { + LOG.warn("Error on rendering the default section: " + sectionView); + } + } + } catch (Exception e) { + LOG.warn("Error on rendering the whole section: " + sectionView); + } + + return document; + + } + + /** + * The Class ImageBackgroundCellRenderer. + * + * @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it + * + * Nov 15, 2023 + */ + private static class ImageBackgroundCellRenderer extends CellRenderer { + protected Image img; + + /** + * Instantiates a new image background cell renderer. + * + * @param modelElement the model element + * @param img the 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 + /** + * Gets the next renderer. + * + * @return the next renderer + */ + // renderer will be created + @Override + public IRenderer getNextRenderer() { + return new ImageBackgroundCellRenderer((Cell) modelElement, img); + } + + /** + * Draw. + * + * @param drawContext the draw context + */ + @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 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); + LOG.debug("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 toImages(List payloads, Integer maxWidth) throws IOException { + + List listImages = new ArrayList(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 + + } + + return img; + } + + /** + * To image from link. + * + * @param link the link + * @param width the width + * @param height the height + * @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 toPDFLinks(List payloads, Integer marginLeft) throws IOException { + + List listLinks = new ArrayList(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 { + if (obj instanceof JsonObject) { + JsonObject jsonObject = (JsonObject) obj; + // String[] keys = JSONObject.getNames(jsonObject); + + Set> entrySet = jsonObject.entrySet(); + if (entrySet.size() > 0) { + for (Map.Entry 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 { + 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; + } + +} diff --git a/src/main/java/org/gcube/application/geoportaldatamapper/pdf_exporter_credits.properties b/src/main/java/org/gcube/application/geoportaldatamapper/pdf_exporter_credits.properties new file mode 100644 index 0000000..ef78934 --- /dev/null +++ b/src/main/java/org/gcube/application/geoportaldatamapper/pdf_exporter_credits.properties @@ -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 \ No newline at end of file diff --git a/src/main/java/org/gcube/application/geoportaldatamapper/reader/MapBoxEndpointReader.java b/src/main/java/org/gcube/application/geoportaldatamapper/reader/MapBoxEndpointReader.java new file mode 100644 index 0000000..cb471c3 --- /dev/null +++ b/src/main/java/org/gcube/application/geoportaldatamapper/reader/MapBoxEndpointReader.java @@ -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 client = clientFor(ServiceEndpoint.class); + List 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 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; + } +} diff --git a/src/main/java/org/gcube/application/geoportaldatamapper/reader/ServiceAccessPoint.java b/src/main/java/org/gcube/application/geoportaldatamapper/reader/ServiceAccessPoint.java new file mode 100644 index 0000000..92766be --- /dev/null +++ b/src/main/java/org/gcube/application/geoportaldatamapper/reader/ServiceAccessPoint.java @@ -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; +} \ No newline at end of file diff --git a/src/main/java/org/gcube/application/geoportaldatamapper/shared/ExporterProjectSource.java b/src/main/java/org/gcube/application/geoportaldatamapper/shared/ExporterProjectSource.java new file mode 100644 index 0000000..f20404a --- /dev/null +++ b/src/main/java/org/gcube/application/geoportaldatamapper/shared/ExporterProjectSource.java @@ -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; + +} diff --git a/src/test/java/Geoportal_Export_To_PDF_Tests.java b/src/test/java/Geoportal_Export_To_PDF_Tests.java index 76103ae..513f124 100644 --- a/src/test/java/Geoportal_Export_To_PDF_Tests.java +++ b/src/test/java/Geoportal_Export_To_PDF_Tests.java @@ -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 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 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 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 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 files = subDocumentView.getListFiles(); - if (files != null) { - for (FilesetDV fileset : files) { - Paragraph paragraphInt = new Paragraph(fileset.getGcubeProfileFieldName()); - paragraphInt.setFontSize(PARAGRAPH_FONT_SIZE); - List 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 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 toImages(List payloads, Integer maxWidth) throws IOException { - - List listImages = new ArrayList(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 toPDFLinks(List payloads, Integer marginLeft) throws IOException { - - List listLinks = new ArrayList(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> entrySet = jsonObject.entrySet(); - if (entrySet.size() > 0) { - for (Map.Entry 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; } } diff --git a/src/test/resources/.gitignore b/src/test/resources/.gitignore index c336e9b..bcb0b99 100644 --- a/src/test/resources/.gitignore +++ b/src/test/resources/.gitignore @@ -1,2 +1,5 @@ /gcube_config.properties /log4j.properties +/D4OS.gcubekey +/devsec.gcubekey +/gcube.gcubekey