New version based on GR "PDF_Exporter_Config"

This commit is contained in:
Francesco Mangiacrapa 2023-11-21 11:58:10 +01:00
parent 051129ae2d
commit 8e7fc50939
9 changed files with 394 additions and 310 deletions

View File

@ -1,27 +1,26 @@
package org.gcube.application.geoportaldatamapper;
package org.gcube.application.geoportaldatamapper.exporter;
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.geoportal.common.model.rest.TempFile;
import org.gcube.application.geoportal.common.utils.StorageUtils;
import org.gcube.application.geoportalcommon.ConvertToDataValueObjectModel;
import org.gcube.application.geoportalcommon.ProjectDVBuilder;
import org.gcube.application.geoportalcommon.geoportal.GeoportalClientCaller;
@ -34,6 +33,12 @@ 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.exporter.beans.Credits;
import org.gcube.application.geoportaldatamapper.exporter.beans.PDFExporterConfig;
import org.gcube.application.geoportaldatamapper.exporter.beans.PageNumber;
import org.gcube.application.geoportaldatamapper.exporter.beans.Watermarker;
import org.gcube.application.geoportaldatamapper.reader.MapBoxEndpointReader;
import org.gcube.application.geoportaldatamapper.reader.ServiceAccessPoint;
import org.gcube.application.geoportaldatamapper.shared.ExporterProjectSource;
@ -93,200 +98,36 @@ import com.itextpdf.layout.renderer.IRenderer;
*
* @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it
*
* Nov 16, 2023
* Nov 21, 2023
*/
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 String PROPERTY_LOGO_ISTI = "LOGO_ISTI";
private static final String PROPERTY_LOGO_CNR = "LOGO_CNR";
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";
public static final String mapSizeWithCentroid = "550x350";
private static Logger LOG = LoggerFactory.getLogger(Geoportal_PDF_Exporter.class);
/**
* The Class Exporter_PDF_Credits.
* Read PDF exporter configs from GR.
*
* @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it
*
* Nov 16, 2023
* @return the PDF exporter config
*/
static class Exporter_PDF_Credits {
private PDFExporterConfig readPDFExporterConfigsFromGR() {
String logoD4GNA = null;
String logoPoweredByD4Science = null;
String linkD4ScienceOrg = null;
String linkGnaD4ScienceOrg = null;
String logoISTI = null;
String logoCNR = null;
PDFExporterConfigProvider credits = new PDFExporterConfigProvider();
PDFExporterConfig paths = null;
try {
/**
* Instantiates a new exporter PD F credits.
*/
public Exporter_PDF_Credits() {
paths = credits.readConfigsFromGR();
} catch (Exception ex) {
LOG.warn("no pdf credits found");
}
/**
* Gets the logo D 4 GNA.
*
* @return the logo D 4 GNA
*/
public String getLogoD4GNA() {
return logoD4GNA;
}
/**
* Gets the logo powered by D 4 science.
*
* @return the logo powered by D 4 science
*/
public String getLogoPoweredByD4Science() {
return logoPoweredByD4Science;
}
/**
* Gets the link D 4 science org.
*
* @return the link D 4 science org
*/
public String getLinkD4ScienceOrg() {
return linkD4ScienceOrg;
}
/**
* Gets the link gna D 4 science org.
*
* @return the link gna D 4 science org
*/
public String getLinkGnaD4ScienceOrg() {
return linkGnaD4ScienceOrg;
}
/**
* Gets the logo ISTI.
*
* @return the logo ISTI
*/
public String getLogoISTI() {
return logoISTI;
}
/**
* Gets the logo CNR.
*
* @return the logo CNR
*/
public String getLogoCNR() {
return logoCNR;
}
/**
* Sets the logo D 4 GNA.
*
* @param logoD4GNA the new logo D 4 GNA
*/
public void setLogoD4GNA(String logoD4GNA) {
this.logoD4GNA = logoD4GNA;
}
/**
* Sets the logo powered by D 4 science.
*
* @param logoPoweredByD4Science the new logo powered by D 4 science
*/
public void setLogoPoweredByD4Science(String logoPoweredByD4Science) {
this.logoPoweredByD4Science = logoPoweredByD4Science;
}
/**
* Sets the link D 4 science org.
*
* @param linkD4ScienceOrg the new link D 4 science org
*/
public void setLinkD4ScienceOrg(String linkD4ScienceOrg) {
this.linkD4ScienceOrg = linkD4ScienceOrg;
}
/**
* Sets the link gna D 4 science org.
*
* @param linkGnaD4ScienceOrg the new link gna D 4 science org
*/
public void setLinkGnaD4ScienceOrg(String linkGnaD4ScienceOrg) {
this.linkGnaD4ScienceOrg = linkGnaD4ScienceOrg;
}
/**
* Sets the logo ISTI.
*
* @param logoISTI the new logo ISTI
*/
public void setLogoISTI(String logoISTI) {
this.logoISTI = logoISTI;
}
/**
* Sets the logo CNR.
*
* @param logoCNR the new logo CNR
*/
public void setLogoCNR(String logoCNR) {
this.logoCNR = logoCNR;
}
}
private ExporterProjectSource exportSource;
/**
* Read credits.
*
* @return the exporter PD F credits
*/
private Exporter_PDF_Credits readCredits() {
Exporter_PDF_Credits credits = null;
// Reading property file with credit references
try (InputStream input = Geoportal_PDF_Exporter.class
.getResourceAsStream(PDF_EXPORTER_CREDITS_PROPERTIES_FILENAME)) {
credits = new Geoportal_PDF_Exporter.Exporter_PDF_Credits();
Properties prop = new Properties();
// load a properties file
prop.load(input);
credits.setLogoD4GNA(prop.getProperty(PROPERTY_LOGO_D4GNA));
credits.setLogoPoweredByD4Science(prop.getProperty(PROPERTY_POWERED_BY_D4SCIENCE_LOGO));
credits.setLinkD4ScienceOrg(prop.getProperty(PROPERTY_WWW_D4SCIENCE_ORG));
credits.setLinkGnaD4ScienceOrg(prop.getProperty(PROPERTY_GNA_D4SCIENCE_ORG));
credits.setLogoISTI(prop.getProperty(PROPERTY_LOGO_ISTI));
credits.setLogoCNR(prop.getProperty(PROPERTY_LOGO_CNR));
// get the property value and print it out
LOG.trace(PROPERTY_LOGO_D4GNA + ": " + credits.getLogoD4GNA());
LOG.trace(PROPERTY_POWERED_BY_D4SCIENCE_LOGO + ": " + credits.getLogoPoweredByD4Science());
LOG.trace(PROPERTY_WWW_D4SCIENCE_ORG + ": " + credits.getLinkD4ScienceOrg());
LOG.trace(PROPERTY_GNA_D4SCIENCE_ORG + ": " + credits.getLinkGnaD4ScienceOrg());
LOG.trace(PROPERTY_LOGO_CNR + ": " + credits.getLogoCNR());
LOG.trace(PROPERTY_LOGO_ISTI + ": " + credits.getLogoISTI());
} catch (IOException ex) {
LOG.error("no file found: " + PDF_EXPORTER_CREDITS_PROPERTIES_FILENAME);
}
return credits;
return paths;
}
/**
@ -298,11 +139,18 @@ public class Geoportal_PDF_Exporter {
* @throws Exception the exception
*/
public String createPDFFile(ExporterProjectSource exportSource) throws Exception {
this.exportSource = exportSource;
String pdfFileURL = null;
Exporter_PDF_Credits credits = readCredits();
PDFExporterConfig pdfExporterConfigs = readPDFExporterConfigsFromGR();
PageNumber pagenumber = null;
Watermarker watermarker = null;
Boolean isAddTimpestampCreatedAt = false;
if (pdfExporterConfigs != null) {
pagenumber = pdfExporterConfigs.getPagenumber();
watermarker = pdfExporterConfigs.getWatermarker();
isAddTimpestampCreatedAt = pdfExporterConfigs.getTimestampCreatedAt();
}
ServiceAccessPoint sap = MapBoxEndpointReader.getMapBoxEndpoint();
@ -331,30 +179,44 @@ public class Geoportal_PDF_Exporter {
// silent
}
if (exportSource.isAddPageNumbers()) {
boolean addPageNumber = false;
try {
addPageNumber = Boolean.parseBoolean(pagenumber.getValue());
} catch (Exception e) {
// TODO: handle exception
}
if (addPageNumber) {
// Creates a header for every page in the document. The PageNumberHandler
// implements
// add page numbers.
pdfDocument.addEventHandler(PdfDocumentEvent.END_PAGE, new PageNumberHandler());
}
if (exportSource.getWatermarkText() != null) {
// pdfDocument = addStringAsWatermark(pdfDocument, document,
// exportSource.getWatermarkText());
pdfDocument.addEventHandler(PdfDocumentEvent.END_PAGE, new WaterMarkerHandler());
pdfDocument.addEventHandler(PdfDocumentEvent.END_PAGE, new PageNumberHandler(pagenumber));
}
String addWatermarker = null;
try {
addWatermarker = watermarker.getValue();
} catch (Exception e) {
// TODO: handle exception
}
if (addWatermarker != null) {
// pdfDocument = addStringAsWatermark(pdfDocument, document,
// exportSource.getWatermarkText());
pdfDocument.addEventHandler(PdfDocumentEvent.END_PAGE, new WaterMarkerHandler(watermarker));
}
// Initialize document
Document document = new Document(pdfDocument);
// Adding logo D4GNA
if (credits != null) {
Image image = toImageFromLink(credits.getLogoD4GNA(), 80);
// image.setMaxHeight(150);
image.setFixedPosition(document.getLeftMargin(),
pdfDocument.getDefaultPageSize().getHeight() - image.getImageHeight() + 90);
document.add(image);
// Adding header (i.e. Logo D4GNA)
if (pdfExporterConfigs != null && pdfExporterConfigs.getCredits() != null) {
Image image = toImageFromLink(pdfExporterConfigs.getCredits().getHeader(), 80);
if (image != null) {
image.setFixedPosition(document.getLeftMargin(),
pdfDocument.getDefaultPageSize().getHeight() - image.getImageHeight() + 90);
document.add(image);
}
}
// Project Name
@ -413,11 +275,11 @@ public class Geoportal_PDF_Exporter {
for (SectionView section : projectView.getListSections()) {
document = appendSubDocumentToPDF(document, section, section.getListSubDocuments(),
exportSource.getGisLink(), sap, credits);
exportSource.getGisLink(), sap, pdfExporterConfigs);
}
// Add timestamp Created at...
if (exportSource.isAddTimpestampCreatedAt()) {
if (isAddTimpestampCreatedAt) {
// TimeStamp - Created at
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
@ -428,10 +290,11 @@ public class Geoportal_PDF_Exporter {
document.add(pt);
}
// Credits
Table tableCredits = addCredits(document, credits);
document.add(tableCredits);
// Add Footer Credits
if (pdfExporterConfigs != null) {
Table tableCredits = addFooterCredits(document, pdfExporterConfigs.getCredits());
document.add(tableCredits);
}
document.close();
@ -440,20 +303,20 @@ public class Geoportal_PDF_Exporter {
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);
// 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());
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) {
@ -478,10 +341,21 @@ public class Geoportal_PDF_Exporter {
*
* @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it
*
* Nov 17, 2023
* Nov 21, 2023
*/
public class PageNumberHandler implements IEventHandler {
private PageNumber pagenumber;
/**
* Instantiates a new page number handler.
*
* @param pagenumber the pagenumber
*/
public PageNumberHandler(PageNumber pagenumber) {
this.pagenumber = pagenumber;
}
/**
* Handle event.
*
@ -498,12 +372,12 @@ public class Geoportal_PDF_Exporter {
Canvas canvas = new Canvas(pdfCanvas, pageSize);
Paragraph p = new Paragraph().add("pg. ").add(String.valueOf(pageNumber));
try {
int fontSize = pagenumber.getFontSize() != null ? pagenumber.getFontSize() : 8;
p.setFontSize(fontSize);
p.setFont(PdfFontFactory.createFont(StandardFonts.TIMES_ITALIC));
p.setFontSize(6);
p.setFontColor(ColorConstants.DARK_GRAY);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
LOG.warn("PageNumberHandler error: " + e1.getMessage());
}
// int x = 565;
// int y = 25;
@ -519,10 +393,21 @@ public class Geoportal_PDF_Exporter {
*
* @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it
*
* Nov 17, 2023
* Nov 21, 2023
*/
public class WaterMarkerHandler implements IEventHandler {
private Watermarker watermarker;
/**
* Instantiates a new water marker handler.
*
* @param watermarker the watermarker
*/
public WaterMarkerHandler(Watermarker watermarker) {
this.watermarker = watermarker;
}
/**
* Handle event.
*
@ -530,6 +415,10 @@ public class Geoportal_PDF_Exporter {
*/
@Override
public void handleEvent(Event event) {
if (watermarker.getValue() == null || watermarker.getValue().isEmpty())
return;
PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
PdfDocument pdf = docEvent.getDocument();
PdfPage page = docEvent.getPage();
@ -543,21 +432,17 @@ public class Geoportal_PDF_Exporter {
try {
font = PdfFontFactory.createFont(StandardFonts.TIMES_ROMAN);
Paragraph paragraph = new Paragraph(exportSource.getWatermarkText()).setFont(font).setFontSize(130)
int fontSize = watermarker.getFontSize() != null ? watermarker.getFontSize() : 100;
Paragraph paragraph = new Paragraph(watermarker.getValue()).setFont(font).setFontSize(fontSize)
.setFontColor(ColorConstants.RED).setOpacity(new Float(0.2));
//PdfExtGState gs1 = new PdfExtGState().setFillOpacity(0.5f);
Canvas canvas = new Canvas(pdfCanvas, pageSize);
float x = (pageSize.getLeft() + pageSize.getRight()) / 2;
float y = (pageSize.getTop() + pageSize.getBottom()) / 2;
//pdfCanvas.saveState();
//pdfCanvas.setExtGState(gs1);
canvas.showTextAligned(paragraph, x, y, pageNumber, TextAlignment.CENTER, VerticalAlignment.TOP, 45);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
LOG.warn("WaterMarkerHandler error: " + e.getMessage());
}
}
}
@ -648,63 +533,40 @@ public class Geoportal_PDF_Exporter {
* @param credits the credits
* @return the table
*/
private Table addCredits(Document document, Exporter_PDF_Credits credits) {
private Table addFooterCredits(Document document, Credits credits) {
if (credits == null)
return null;
Table tableCredits = toTableFixedLayout(document, 4, false);
tableCredits.setTextAlignment(TextAlignment.LEFT);
tableCredits.setFixedPosition(document.getLeftMargin() + 10, 5,
document.getPdfDocument().getDefaultPageSize().getWidth() - 65);
Table tableCredits = new Table(1);
tableCredits.setTextAlignment(TextAlignment.CENTER);
float pageWidthSize = document.getPdfDocument().getDefaultPageSize().getWidth() - 85;
tableCredits.setFixedPosition(document.getLeftMargin(), 20, pageWidthSize);
// Adding logo D4GNA
Table tableD4GNA = new Table(1);
tableD4GNA.setHorizontalBorderSpacing(0);
Image imageLogo = toImageFromLink(credits.getLogoD4GNA(), 40);
Cell cell1D4GNA = new Cell();
cell1D4GNA.add(imageLogo);
// Adding link D4GNA
Cell cell2D4GNA = new Cell();
Link theLinkD4GNA = getLinkFromURL(credits.getLinkGnaD4ScienceOrg(), credits.getLinkGnaD4ScienceOrg(), 0);
theLinkD4GNA.setFontSize(4);
theLinkD4GNA.setFontColor(ColorConstants.DARK_GRAY);
Paragraph p1 = new Paragraph().add(theLinkD4GNA);
cell2D4GNA.add(p1);
tableD4GNA.addCell(cell1D4GNA);
tableD4GNA.addCell(cell2D4GNA);
tableCredits.addCell(tableD4GNA);
Image img = null;
try {
// Adding logo Powered by D4Science
Table tableD4Science = new Table(1);
Image imageLogoPD4S = toImageFromLink(credits.getLogoPoweredByD4Science(), 80);
Cell cell1PD4S = new Cell();
cell1PD4S.add(imageLogoPD4S);
// Adding link D4GNA
Cell cell2PD4S = new Cell();
Link theLinkPD4S = getLinkFromURL(credits.getLinkD4ScienceOrg(), credits.getLinkD4ScienceOrg(), 0);
theLinkPD4S.setFontSize(4);
theLinkPD4S.setFontColor(ColorConstants.DARK_GRAY);
Paragraph p4 = new Paragraph().add(theLinkPD4S);
cell2PD4S.add(p4);
tableD4Science.addCell(cell1PD4S);
tableD4Science.addCell(cell2PD4S);
tableCredits.addCell(tableD4Science);
ImageData data = null;
data = ImageDataFactory.create(new URL(credits.getFooter()));
img = new Image(data);
img.setTextAlignment(TextAlignment.CENTER);
img.setHorizontalAlignment(HorizontalAlignment.CENTER);
img.setMaxHeight(22);
img.setMaxWidth(pageWidthSize);
// img.setBorder(new SolidBorder(1F));
// Adding logo CNR
Image imageLogoCNR = toImageFromLink(credits.getLogoCNR(), 40);
Cell cellLogoCNR = new Cell();
cellLogoCNR.add(imageLogoCNR);
tableCredits.addCell(cellLogoCNR);
} catch (Exception e) {
// silent
// Adding logo ISTI
Image imageLogoISTI = toImageFromLink(credits.getLogoISTI(), 40);
Cell cellLogoISTI = new Cell();
cellLogoISTI.add(imageLogoISTI);
tableCredits.addCell(cellLogoISTI);
}
//
if (img != null) {
Cell cell = new Cell();
cell.setTextAlignment(TextAlignment.CENTER);
cell.add(img);
tableCredits.addCell(cell);
}
removeBorder(tableD4GNA);
removeBorder(tableD4Science);
removeBorder(tableCredits);
return tableCredits;
@ -713,16 +575,17 @@ public class Geoportal_PDF_Exporter {
/**
* 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
* @param credits the credits
* @param document the document
* @param sectionView the section view
* @param subDocuments the sub documents
* @param gisLink the gis link
* @param sap the sap
* @param pdfExporterConfigs the pdf exporter configs
* @return the document
*/
private static Document appendSubDocumentToPDF(Document document, SectionView sectionView,
List<SubDocumentView> subDocuments, String gisLink, ServiceAccessPoint sap, Exporter_PDF_Credits credits) {
List<SubDocumentView> subDocuments, String gisLink, ServiceAccessPoint sap,
PDFExporterConfig pdfExporterConfigs) {
try {
boolean displayAsGallery = false;
@ -870,11 +733,11 @@ public class Geoportal_PDF_Exporter {
if (gisLink != null)
alert += ". See the gis layer at " + gisLink;
else {
try {
alert += ". See the gis layer at " + credits.getLinkGnaD4ScienceOrg();
} catch (Exception e) {
// TODO: handle exception
}
// try {
// alert += ". See the gis layer at " + credits.getLinkGnaD4ScienceOrg();
// } catch (Exception e) {
// // TODO: handle exception
// }
}
paragraph1.add(alert);
@ -1129,8 +992,6 @@ public class Geoportal_PDF_Exporter {
} catch (Exception e) {
// silent
e.printStackTrace();
}
return img;

View File

@ -0,0 +1,148 @@
package org.gcube.application.geoportaldatamapper.exporter;
import static org.gcube.resources.discovery.icclient.ICFactory.client;
import java.io.StringReader;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.gcube.application.geoportaldatamapper.exporter.beans.PDFExporterConfig;
import org.gcube.common.resources.gcore.utils.XPathHelper;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.resources.discovery.client.api.DiscoveryClient;
import org.gcube.resources.discovery.client.queries.api.Query;
import org.gcube.resources.discovery.client.queries.impl.QueryBox;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
/**
* Retrieves available 'PDF Exporter Config' from a single Generic Resource -
* secondary Type : "CMS" - name : "PDF_Exporter_Config".
*
* @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it
*
* Nov 20, 2023
*/
public class PDFExporterConfigProvider {
private static final String GR_SECONDARY_TYPE = "CMS";
private static final String GR_NAME = "PDF_Exporter_Config";
private static final String RESOURCE_PROFILE_BODY = "/Resource/Profile/Body";
private static final String PDF_EXPORTER_CONFIG = "pdf_exporter_config";
private static Logger LOG = LoggerFactory.getLogger(PDFExporterConfigProvider.class);
/**
* Instantiates a new exporter file provider.
*/
public PDFExporterConfigProvider() {
}
/**
* Read configs from GR.
*
* @return the PDF exporter project config
* @throws Exception the exception
*/
protected PDFExporterConfig readConfigsFromGR() throws Exception {
String queryString = getGcubeGenericQueryString(GR_SECONDARY_TYPE, GR_NAME);
LOG.info("Trying to perform query: " + queryString);
String pdf_exporter_onfig = null;
PDFExporterConfig epc = null;
String scope = ScopeProvider.instance.get();
if (scope == null)
throw new Exception("Set the scope into " + ScopeProvider.class.getName());
try {
LOG.info("Trying to fetch GenericResource in the scope: " + scope + ", SecondaryType: " + GR_SECONDARY_TYPE
+ ", Name: " + GR_NAME);
Query q = new QueryBox(queryString);
DiscoveryClient<String> client = client();
List<String> appProfile = client.submit(q);
// String item_fields = "";
if (appProfile == null || appProfile.size() == 0)
LOG.warn("No GenericResource found in the scope: " + scope + ", SecondaryType: " + GR_SECONDARY_TYPE
+ ", Name: " + GR_NAME);
else {
String elem = appProfile.get(0);
DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = docBuilder.parse(new InputSource(new StringReader(elem)));
XPathHelper helper = new XPathHelper(doc.getDocumentElement());
List<String> currValue = null;
String xPathExp = RESOURCE_PROFILE_BODY + "/" + PDF_EXPORTER_CONFIG;
currValue = helper.evaluate(xPathExp);
// System.out.println("currValue is: "+currValue);
if (currValue != null && currValue.size() > 0) {
pdf_exporter_onfig = currValue.get(0);
}
if (pdf_exporter_onfig != null) {
try {
epc = fromXml(pdf_exporter_onfig, PDFExporterConfig.class);
} catch (Exception e) {
e.printStackTrace();
}
}
LOG.info("returning: " + epc);
return epc;
}
} catch (Exception e) {
LOG.error("Error while trying to read the GenericResource with SecondaryType " + GR_SECONDARY_TYPE
+ "and name " + GR_NAME + " from the scope " + scope, e);
} finally {
}
return null;
}
/**
* Gets the gcube generic query string.
*
* @param secondaryType the secondary type
* @param resourceName the resource name
* @return the gcube generic query string
*/
public static String getGcubeGenericQueryString(String secondaryType, String resourceName) {
return "for $profile in collection('/db/Profiles/GenericResource')//Resource "
+ "where $profile/Profile/SecondaryType/string() eq '" + secondaryType
+ "' and $profile/Profile/Name/string() " + " eq '" + resourceName + "'" + "return $profile";
}
/**
* Deserializes a XML text to Object.
*
* @param <T> the generic type
* @param xml the xml
* @param clazz the clazz
* @return the t
*/
public <T> T fromXml(String xml, Class<T> clazz) {
try {
JAXBContext context = JAXBContext.newInstance(clazz);
Unmarshaller unmarshaller = context.createUnmarshaller();
//unmarshaller.setAdapter(new NormalizedStringAdapter());
Object o = unmarshaller.unmarshal(new StringReader(xml));
return clazz.cast(o);
} catch (Exception e) {
throw new IllegalStateException("Error while deserializing a XML text to Object of type " + clazz, e);
}
}
}

View File

@ -0,0 +1,17 @@
package org.gcube.application.geoportaldatamapper.exporter.beans;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import lombok.Data;
@XmlRootElement(name = "credits")
@XmlAccessorType(XmlAccessType.FIELD)
@Data
public class Credits {
String header;
String footer;
}

View File

@ -0,0 +1,26 @@
package org.gcube.application.geoportaldatamapper.exporter.beans;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import lombok.Data;
@XmlRootElement(name = "pdf_exporter_config")
@XmlAccessorType(XmlAccessType.FIELD)
@Data
public class PDFExporterConfig {
private Credits credits;
@XmlElement(required = false)
private Watermarker watermarker;
@XmlElement(required = false)
private PageNumber pagenumber;
@XmlElement(name = "timestamp_created_at", required = false)
private Boolean timestampCreatedAt;
}

View File

@ -0,0 +1,22 @@
package org.gcube.application.geoportaldatamapper.exporter.beans;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;
import lombok.Data;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "pagenumber")
@Data
public class PageNumber {
@XmlValue
private String value;
@XmlAttribute
private Integer fontSize;
}

View File

@ -0,0 +1,22 @@
package org.gcube.application.geoportaldatamapper.exporter.beans;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;
import lombok.Data;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "watermarker")
@Data
public class Watermarker {
@XmlValue
private String value;
@XmlAttribute
private Integer fontSize;
}

View File

@ -1,6 +0,0 @@
LOGO_D4GNA = https://data.d4science.org/shub/E_dmhxT0ZReFpXQ1ZXZUp0M2pXUGhtTEZicHNyMGZUVTB4cTkyc2xqMXFSWmo2Q3o4dWl0dTBmY1p1VTdPN29KMQ==
POWERED_BY_D4SCIENCE_LOGO = https://data.d4science.org/shub/E_UGZUa0Y4ekQ1RVNMRGh2RzlWUkxJcFdhYmEwaVlWY2hxNkJ1dWN6eHBLajQyMWNEcjZ1VmpaQktYM1RYY1RWTA==
WWW_D4SCIENCE_ORG = https://www.d4science.org
GNA_D4SCIENCE_ORG = https://gna.d4science.org
LOGO_ISTI = https://data.d4science.org/shub/E_SnJDdURDbzFQRitXK2s0WEhSYjRVT0JTWUVNSm1McVpieEgzT0ZUR3ZBU1lyOEhjNVRsbHI2VUNhRVpCWm11Rg==
LOGO_CNR = https://data.d4science.org/shub/E_N3hLRUtyaUZQQ1RzcWVzTVFMM3lsNTkzTWwyd1hxR1FOd29DSlhDVyt4UXlRUXhFTnVTdzFPbmRzQTN2WHhzcQ==

View File

@ -7,19 +7,14 @@ import lombok.NoArgsConstructor;
@NoArgsConstructor
public class ExporterProjectSource {
//Required fields
// Required fields
String profileID;
String projectID;
String scope;
//Optional fields
// Optional fields
String profileTitle;
String accountname; //if null the exporter will use PUBLIC ACCESS
String accountname; // if null the exporter will use PUBLIC ACCESS
String gisLink;
String watermarkText;
boolean addTimpestampCreatedAt = true;
boolean addPageNumbers = true;
}

View File

@ -7,7 +7,7 @@ import java.util.Properties;
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.geoportaldatamapper.Geoportal_PDF_Exporter;
import org.gcube.application.geoportaldatamapper.exporter.Geoportal_PDF_Exporter;
import org.gcube.application.geoportaldatamapper.reader.MapBoxEndpointReader;
import org.gcube.application.geoportaldatamapper.reader.ServiceAccessPoint;
import org.gcube.application.geoportaldatamapper.shared.ExporterProjectSource;
@ -38,7 +38,7 @@ public class Geoportal_Export_To_PDF_Tests {
//private static String PROFILE_ID = "concessioni-estere";
private static String PROFILE_ID = "profiledConcessioni";
private static String PROJECT_ID = "64537208d7fb4a4633022039";
private static String PROJECT_ID = "6388e4f8a1e60e66b7b584ac";
// DEV
// 654e07a75bdd5478cca320c0
@ -109,7 +109,7 @@ public class Geoportal_Export_To_PDF_Tests {
/**
* API map box service endpoint reader.
*/
// @Test
//@Test
public void apiMapBoxServiceEndpointReader() {
try {
ServiceAccessPoint se = MapBoxEndpointReader.getMapBoxEndpoint();
@ -137,7 +137,6 @@ public class Geoportal_Export_To_PDF_Tests {
exporterSource.setProjectID(PROJECT_ID);
exporterSource.setProfileTitle("Regime di Concessione");
exporterSource.setScope(CONTEXT);
exporterSource.setWatermarkText("DRAFT");
try {
pdfExporter.createPDFFile(exporterSource);
} catch (Exception e) {