diff --git a/package/resources/Baseline HTML.dpf b/package/resources/Baseline HTML.dpf index 5858b14e..07844519 100644 --- a/package/resources/Baseline HTML.dpf +++ b/package/resources/Baseline HTML.dpf @@ -1,2 +1,13 @@ -ISO Baseline -FORMAT HTML + + + 3 + + TIFF_Baseline_Core_6_0 + + + HTML + + + + + diff --git a/pom.xml b/pom.xml index 7b0ed9c7..97647352 100644 --- a/pom.xml +++ b/pom.xml @@ -7,7 +7,7 @@ com.easyinnova dpf_manager jar - 3.4 + 3.5 @@ -227,19 +227,19 @@ com.easyinnova tifflibrary4java - 1.9.2 + 1.9.6 com.easyinnova tiffimplementationchecker - 1.2.2 + 1.2.6 com.easyinnova tiffpolicychecker - 1.1 + 1.1.4 diff --git a/src/main/java/dpfmanager/conformancechecker/configuration/Configuration.java b/src/main/java/dpfmanager/conformancechecker/configuration/Configuration.java index 58d3f64d..50a35801 100644 --- a/src/main/java/dpfmanager/conformancechecker/configuration/Configuration.java +++ b/src/main/java/dpfmanager/conformancechecker/configuration/Configuration.java @@ -83,6 +83,12 @@ }) @XmlRootElement(name = "configuration") public class Configuration implements Serializable { + + /** + * Do not modify! + */ + private static final long serialVersionUID = -1010943725602839341L; + private ArrayList isos; private Map> modifiedIsos; private Rules rules; @@ -125,6 +131,23 @@ public Configuration(Rules rules, Fixes fixes, ArrayList formats) { modifiedIsos = new HashMap<>(); } + /** + * Instantiates a new clone Configuration. + */ + public Configuration(Configuration c) { + this.isos = new ArrayList<>(c.isos); + this.modifiedIsos = new HashMap<>(c.modifiedIsos); + this.rules = c.rules; + this.formats = new ArrayList<>(c.formats); + this.fixes = c.fixes; + this.output = c.output; + this.description = c.description; + this.version = c.version; + this.quick = c.quick; + this.bundle = c.bundle; + this.isDefault = c.isDefault; + } + /** * Set the default values for a new configuration */ diff --git a/src/main/java/dpfmanager/conformancechecker/tiff/TiffConformanceChecker.java b/src/main/java/dpfmanager/conformancechecker/tiff/TiffConformanceChecker.java index 7a3717f1..508929a1 100644 --- a/src/main/java/dpfmanager/conformancechecker/tiff/TiffConformanceChecker.java +++ b/src/main/java/dpfmanager/conformancechecker/tiff/TiffConformanceChecker.java @@ -514,7 +514,7 @@ private Map getValidationResults(TiffReader tr, Config @Override public Configuration getDefaultConfiguration() { - return checkConfig; + return new Configuration(checkConfig); } /** diff --git a/src/main/java/dpfmanager/conformancechecker/tiff/reporting/HtmlReport.java b/src/main/java/dpfmanager/conformancechecker/tiff/reporting/HtmlReport.java index 3cba0ce5..e4401b6f 100644 --- a/src/main/java/dpfmanager/conformancechecker/tiff/reporting/HtmlReport.java +++ b/src/main/java/dpfmanager/conformancechecker/tiff/reporting/HtmlReport.java @@ -522,7 +522,7 @@ private String generateTagsDivs(IndividualReport ir) { row = row.replace("##LINE##", ""); } row = row.replace("##ATTR##", key); - row = row.replace("##VALUE##", value); + row = row.replace("##VALUE##", value.replaceAll("", "")); String rows = tagsMap.containsKey(mapIdH) ? tagsMap.get(mapIdH) : ""; tagsMap.put(mapIdH, rows + row); } @@ -568,7 +568,7 @@ private String generateTagsDivs(IndividualReport ir) { row = row.replace("##ICON##", ""); row = row.replace("##ID##", tv.getId() + ""); row = row.replace("##KEY##", (tv.getName().equals(tv.getId() + "") ? "Private tag" : tv.getName())); - row = row.replace("##VALUE##", tv.getFirstTextReadValue()); + row = row.replace("##VALUE##", tv.getFirstTextReadValue().replaceAll("", "")); String rows = tagsMap.containsKey(mapId) ? tagsMap.get(mapId) : ""; tagsMap.put(mapId, rows + row); } @@ -617,7 +617,7 @@ else if (tag.dif > 0) { String val = (tag.isDefault) ? tag.defaultValue : tag.tv.getFirstTextReadValue(); if (val.length() > 200) val = val.substring(0, 200) + "..."; - row = row.replace("##VALUE##", val); + row = row.replace("##VALUE##", val.replaceAll("", "")); String rows = tagsMap.containsKey(mapId) ? tagsMap.get(mapId) : ""; tagsMap.put(mapId, rows + row); } @@ -626,13 +626,7 @@ else if (tag.dif > 0) { * Generate divs */ String finalResult = ""; - String expertCheckTmpl = "" + - ""; - String defaultCheckTmpl = "" + - ""; - String checkBoxTmpl = "
##CHECK_EXPERT####CHECK_DEFAULT##
"; - String genTmpl = "
\n" + - "\t\t\t\t\t##CHECKBOXS##\n" + + String genTmpl = "
\n" + "\t\t\t\t\t

##TITLE##

\n" + "\t\t\t\t\t\n" + "\t\t\t\t \n" + @@ -647,8 +641,7 @@ else if (tag.dif > 0) { String subTmpl = StringUtils.replace(genTmpl, "##TITLE##", "Sub IFD Tags"); String ifdTmpl = StringUtils.replace(genTmpl, "##TITLE##", "IFD Tags"); String exifTmpl = StringUtils.replace(genTmpl, "##TITLE##", "EXIF"); - String iptcTmpl = "
\n" + - "\t\t\t\t\t##CHECKBOXS##\n" + + String iptcTmpl = "
\n" + "\t\t\t\t\t

IPTC

\n" + "\t\t\t\t\t
\n" + "\t\t\t\t \n" + @@ -658,8 +651,7 @@ else if (tag.dif > 0) { "\t\t\t\t ##ROWS##\n" + "\t\t\t\t\t
\n" + "\t\t\t\t
"; - String xmpTmpl = "
\n" + - "\t\t\t\t\t##CHECKBOXS##\n" + + String xmpTmpl = "
\n" + "\t\t\t\t\t

XMP

\n" + "\t\t\t\t\t\n" + "\t\t\t\t \n" + @@ -692,16 +684,9 @@ else if (tag.dif > 0) { for (String key : tagsMap.keySet()) { if (key.endsWith("h")) continue; String type = key.substring(0, 3); - String display = "none;", checkBoxs = ""; + String display = "none;"; if (key.equals("ifd0")) display = "block;"; - String expert = (hasExpert.containsKey(key)) ? expertCheckTmpl : ""; - String defaultCheck = (hasDefault.containsKey(key)) ? defaultCheckTmpl : ""; - if (expert.length() > 0 || defaultCheck.length() > 0) { - checkBoxs = StringUtils.replace(checkBoxTmpl, "##CHECK_EXPERT##", expert); - checkBoxs = StringUtils.replace(checkBoxs, "##CHECK_DEFAULT##", defaultCheck); - } String tmpl = templates.get(type); - tmpl = StringUtils.replace(tmpl, "##CHECKBOXS##", checkBoxs); tmpl = StringUtils.replace(tmpl, "##INDEX##", key); tmpl = StringUtils.replace(tmpl, "##DISPLAY##", display); if (key.startsWith("ipt")) { diff --git a/src/main/java/dpfmanager/conformancechecker/tiff/reporting/MetsReport.java b/src/main/java/dpfmanager/conformancechecker/tiff/reporting/MetsReport.java index 2ed2c704..29e9abda 100644 --- a/src/main/java/dpfmanager/conformancechecker/tiff/reporting/MetsReport.java +++ b/src/main/java/dpfmanager/conformancechecker/tiff/reporting/MetsReport.java @@ -121,6 +121,8 @@ import com.easyinnova.tiff.model.types.XMP; import com.easyinnova.tiff.model.types.abstractTiffType; +import org.apache.camel.ExchangeException; + import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; @@ -249,9 +251,13 @@ private String getImageDate(IFD ifd, String filepath) { } else { try { File file = new File(filepath); - Path filePath = file.toPath(); - BasicFileAttributes attr = Files.readAttributes(filePath, BasicFileAttributes.class); - return attr.creationTime().toString(); + if (file.exists()) { + Path filePath = file.toPath(); + BasicFileAttributes attr = Files.readAttributes(filePath, BasicFileAttributes.class); + return attr.creationTime().toString(); + } else { + return ""; + } } catch (IOException e) { e.printStackTrace(); return ""; @@ -311,21 +317,23 @@ private BasicImageInformationType createNisoBasicImageInformation(IFD ifd) { photometricInterpretation.setColorSpace(colorSpace); //7.1.3.2.1 Icc profile - if (ifd.getMetadata().get("ICCProfile") != null) { + if (ifd.getMetadata().get("ICCProfile") != null && ifd.getMetadata().get("ICCProfile").getCardinality() > 0) { BasicImageInformationType.BasicImageCharacteristics.PhotometricInterpretation.ColorProfile colorProfile = new BasicImageInformationType.BasicImageCharacteristics.PhotometricInterpretation.ColorProfile(); BasicImageInformationType.BasicImageCharacteristics.PhotometricInterpretation.ColorProfile.IccProfile iccProfile = new BasicImageInformationType.BasicImageCharacteristics.PhotometricInterpretation.ColorProfile.IccProfile(); abstractTiffType iccProfileFromIfd = ifd.getMetadata().get("ICCProfile").getValue().get(0); - IccProfile icc = (IccProfile) iccProfileFromIfd; - StringType iccVersion = new StringType(); - iccVersion.setUse("System"); - iccVersion.setValue(icc.getVersion()); - iccProfile.setIccProfileVersion(iccVersion); - StringType iccName = new StringType(); - iccName.setUse("System"); - iccName.setValue(icc.getDescription()); - iccProfile.setIccProfileName(iccName); - colorProfile.setIccProfile(iccProfile); - photometricInterpretation.setColorProfile(colorProfile); + if (iccProfileFromIfd instanceof IccProfile) { + IccProfile icc = (IccProfile) iccProfileFromIfd; + StringType iccVersion = new StringType(); + iccVersion.setUse("System"); + iccVersion.setValue(icc.getVersion()); + iccProfile.setIccProfileVersion(iccVersion); + StringType iccName = new StringType(); + iccName.setUse("System"); + iccName.setValue(icc.getDescription()); + iccProfile.setIccProfileName(iccName); + colorProfile.setIccProfile(iccProfile); + photometricInterpretation.setColorProfile(colorProfile); + } } //7.1.3.3 YcbCr image @@ -428,23 +436,30 @@ private ImageCaptureMetadataType.DigitalCameraCapture.CameraCaptureSettings.GPSD } if (ir.getTiffModel().getMetadata().contains("GPSLatitude")) { ImageCaptureMetadataType.DigitalCameraCapture.CameraCaptureSettings.GPSData.GPSLatitude latitude = new ImageCaptureMetadataType.DigitalCameraCapture.CameraCaptureSettings.GPSData.GPSLatitude(); - List gpsLatitudeList = (List) ir.getTiffModel().getMetadata().get("GPSLatitude"); - RationalType degreesValue = new RationalType(); - degreesValue.setUse("System"); - degreesValue.setNumerator(BigInteger.valueOf(gpsLatitudeList.get(0).getNumerator())); - degreesValue.setDenominator(BigInteger.valueOf(gpsLatitudeList.get(0).getDenominator())); - latitude.setDegrees(degreesValue); - RationalType minutesValue = new RationalType(); - minutesValue.setUse("System"); - minutesValue.setNumerator(BigInteger.valueOf(gpsLatitudeList.get(1).getNumerator())); - minutesValue.setDenominator(BigInteger.valueOf(gpsLatitudeList.get(1).getDenominator())); - latitude.setMinutes(minutesValue); - RationalType secondsValue = new RationalType(); - secondsValue.setUse("System"); - secondsValue.setNumerator(BigInteger.valueOf(gpsLatitudeList.get(2).getNumerator())); - secondsValue.setDenominator(BigInteger.valueOf(gpsLatitudeList.get(2).getDenominator())); - latitude.setSeconds(secondsValue); - gpsData.setGPSLatitude(latitude); + List gpsLatitudeList = null; + try { + gpsLatitudeList = (List) ir.getTiffModel().getMetadata().get("GPSLatitude"); + } catch ( Exception ex) { + + } + if (gpsLatitudeList != null && gpsLatitudeList.size() > 2) { + RationalType degreesValue = new RationalType(); + degreesValue.setUse("System"); + degreesValue.setNumerator(BigInteger.valueOf(gpsLatitudeList.get(0).getNumerator())); + degreesValue.setDenominator(BigInteger.valueOf(gpsLatitudeList.get(0).getDenominator())); + latitude.setDegrees(degreesValue); + RationalType minutesValue = new RationalType(); + minutesValue.setUse("System"); + minutesValue.setNumerator(BigInteger.valueOf(gpsLatitudeList.get(1).getNumerator())); + minutesValue.setDenominator(BigInteger.valueOf(gpsLatitudeList.get(1).getDenominator())); + latitude.setMinutes(minutesValue); + RationalType secondsValue = new RationalType(); + secondsValue.setUse("System"); + secondsValue.setNumerator(BigInteger.valueOf(gpsLatitudeList.get(2).getNumerator())); + secondsValue.setDenominator(BigInteger.valueOf(gpsLatitudeList.get(2).getDenominator())); + latitude.setSeconds(secondsValue); + gpsData.setGPSLatitude(latitude); + } } if (ir.getTiffModel().getMetadata().contains("GPSLongitudeRef") && GpsLongitudeRefType.verifyTag(ir.getTiffModel().getMetadata().get("GPSLongitudeRef").toString())) { TypeOfgpsLongitudeRefType gpsLongitudRefType = new TypeOfgpsLongitudeRefType(); @@ -689,160 +704,236 @@ private ImageCaptureMetadataType.DigitalCameraCapture.CameraCaptureSettings.GPSD private ImageCaptureMetadataType.DigitalCameraCapture.CameraCaptureSettings.ImageData createNisoImageData(IndividualReport ir, IFD ifd) { ImageCaptureMetadataType.DigitalCameraCapture.CameraCaptureSettings.ImageData imageData = new ImageCaptureMetadataType.DigitalCameraCapture.CameraCaptureSettings.ImageData(); if (ir.getTiffModel().getMetadata() != null) { - if (ir.getTiffModel().getMetadata().contains("FNumber")) { - TypeOfNonNegativeRealType fnumber = new TypeOfNonNegativeRealType(); - fnumber.setUse("Manager"); - Rational fnumberValue = (Rational) ir.getTiffModel().getMetadata().get("FNumber"); - fnumber.setValue(fnumberValue.getFloatValue()); - imageData.setFNumber(fnumber); + try { + if (ir.getTiffModel().getMetadata().contains("FNumber") && ir.getTiffModel().getMetadata().get("FNumber") instanceof Rational) { + TypeOfNonNegativeRealType fnumber = new TypeOfNonNegativeRealType(); + fnumber.setUse("Manager"); + Rational fnumberValue = (Rational) ir.getTiffModel().getMetadata().get("FNumber"); + fnumber.setValue(fnumberValue.getFloatValue()); + imageData.setFNumber(fnumber); + } + } catch (Exception ex) { + ex.printStackTrace(); } - if (ir.getTiffModel().getMetadata().contains("ExposureTime")) { - TypeOfNonNegativeRealType exposureTime = new TypeOfNonNegativeRealType(); - exposureTime.setUse("Manager"); - Rational exposure = (Rational) ir.getTiffModel().getMetadata().get("ExposureTime"); - exposureTime.setValue(exposure.getFloatValue()); - imageData.setExposureTime(exposureTime); + try { + if (ir.getTiffModel().getMetadata().contains("ExposureTime") && ir.getTiffModel().getMetadata().get("ExposureTime") instanceof Rational) { + TypeOfNonNegativeRealType exposureTime = new TypeOfNonNegativeRealType(); + exposureTime.setUse("Manager"); + Rational exposure = (Rational) ir.getTiffModel().getMetadata().get("ExposureTime"); + exposureTime.setValue(exposure.getFloatValue()); + imageData.setExposureTime(exposureTime); + } + } catch (Exception ex) { + ex.printStackTrace(); } - if (ir.getTiffModel().getMetadata().contains("ExposureProgram") && ExposureProgramType.verifyTag(ir.getTiffModel().getMetadata().get("ExposureProgram").toString())) { - TypeOfExposureProgramType exposureProgram = new TypeOfExposureProgramType(); - exposureProgram.setUse("Manager"); - exposureProgram.setValue(ExposureProgramType.fromValue(ir.getTiffModel().getMetadata().get("ExposureProgram").toString())); - imageData.setExposureProgram(exposureProgram); + try { + if (ir.getTiffModel().getMetadata().contains("ExposureProgram") && ExposureProgramType.verifyTag(ir.getTiffModel().getMetadata().get("ExposureProgram").toString())) { + TypeOfExposureProgramType exposureProgram = new TypeOfExposureProgramType(); + exposureProgram.setUse("Manager"); + exposureProgram.setValue(ExposureProgramType.fromValue(ir.getTiffModel().getMetadata().get("ExposureProgram").toString())); + imageData.setExposureProgram(exposureProgram); + } + } catch (Exception ex) { + ex.printStackTrace(); } - if (ir.getTiffModel().getMetadata().contains("SpectralSensitivity")) { - StringType spectralSensivity = new StringType(); - spectralSensivity.setUse("Manager"); - spectralSensivity.setValue(ir.getTiffModel().getMetadata().get("SpectralSensitivity").toString()); - imageData.setSpectralSensitivity(spectralSensivity); - + try { + if (ir.getTiffModel().getMetadata().contains("SpectralSensitivity")) { + StringType spectralSensivity = new StringType(); + spectralSensivity.setUse("Manager"); + spectralSensivity.setValue(ir.getTiffModel().getMetadata().get("SpectralSensitivity").toString()); + imageData.setSpectralSensitivity(spectralSensivity); + } + } catch (Exception ex) { + ex.printStackTrace(); } - if (ir.getTiffModel().getMetadata().contains("ISOSpeedRatings")) { - PositiveIntegerType iosSpeed = new PositiveIntegerType(); - iosSpeed.setUse("Manager"); - Short speedRatingValue = (Short) ir.getTiffModel().getMetadata().get("ISOSpeedRatings"); - iosSpeed.setValue(BigInteger.valueOf(speedRatingValue.getValue())); - imageData.setIsoSpeedRatings(iosSpeed); + try { + if (ir.getTiffModel().getMetadata().contains("ISOSpeedRatings") && ir.getTiffModel().getMetadata().get("ISOSpeedRatings") instanceof Short) { + PositiveIntegerType iosSpeed = new PositiveIntegerType(); + iosSpeed.setUse("Manager"); + Short speedRatingValue = (Short) ir.getTiffModel().getMetadata().get("ISOSpeedRatings"); + iosSpeed.setValue(BigInteger.valueOf(speedRatingValue.getValue())); + imageData.setIsoSpeedRatings(iosSpeed); + } + } catch (Exception ex) { + ex.printStackTrace(); } - TypeOfExifVersionType exifVersion = new TypeOfExifVersionType(); - exifVersion.setUse("System"); - if (ifd.getMetadata().containsTagId(TiffTags.getTagId("ExifVersion"))) { - exifVersion.setValue(ifd.getMetadata().get("ExifVersion").getValue().toString()); - } else if (ifd.containsTagId(34665)) { //If contains EXIF but version is not included - exifVersion.setValue("0220"); + try { + TypeOfExifVersionType exifVersion = new TypeOfExifVersionType(); + exifVersion.setUse("System"); + if (ifd.getMetadata().containsTagId(TiffTags.getTagId("ExifVersion"))) { + exifVersion.setValue(ifd.getMetadata().get("ExifVersion").getValue().toString()); + } else if (ifd.containsTagId(34665)) { //If contains EXIF but version is not included + exifVersion.setValue("0220"); + } + imageData.setExifVersion(exifVersion); + } catch (Exception ex) { + ex.printStackTrace(); } - imageData.setExifVersion(exifVersion); - if (ir.getTiffModel().getMetadata().contains("ShutterSpeedValue")) { - RationalType shutterSpeedValue = new RationalType(); - shutterSpeedValue.setUse("Manager"); - SRational speedTagValue = (SRational) ir.getTiffModel().getMetadata().get("ShutterSpeedValue"); - shutterSpeedValue.setDenominator(BigInteger.valueOf(speedTagValue.getDenominator())); - shutterSpeedValue.setNumerator(BigInteger.valueOf(speedTagValue.getNumerator())); - imageData.setShutterSpeedValue(shutterSpeedValue); + try { + if (ir.getTiffModel().getMetadata().contains("ShutterSpeedValue") && ir.getTiffModel().getMetadata().get("ShutterSpeedValue") instanceof SRational) { + RationalType shutterSpeedValue = new RationalType(); + shutterSpeedValue.setUse("Manager"); + SRational speedTagValue = (SRational) ir.getTiffModel().getMetadata().get("ShutterSpeedValue"); + shutterSpeedValue.setDenominator(BigInteger.valueOf(speedTagValue.getDenominator())); + shutterSpeedValue.setNumerator(BigInteger.valueOf(speedTagValue.getNumerator())); + imageData.setShutterSpeedValue(shutterSpeedValue); + } + } catch (Exception ex) { + ex.printStackTrace(); } - if (ir.getTiffModel().getMetadata().contains("ApertureValue")) { - RationalType apertureValue = new RationalType(); - apertureValue.setUse("Manager"); - Rational apertureTagValue = (Rational) ir.getTiffModel().getMetadata().get("ApertureValue"); - apertureValue.setDenominator(BigInteger.valueOf(apertureTagValue.getDenominator())); - apertureValue.setNumerator(BigInteger.valueOf(apertureTagValue.getNumerator())); - imageData.setApertureValue(apertureValue); + try { + if (ir.getTiffModel().getMetadata().contains("ApertureValue") && ir.getTiffModel().getMetadata().get("ApertureValue") instanceof Rational) { + RationalType apertureValue = new RationalType(); + apertureValue.setUse("Manager"); + if (ir.getTiffModel().getMetadata().get("ApertureValue") instanceof Rational) { + Rational apertureTagValue = (Rational) ir.getTiffModel().getMetadata().get("ApertureValue"); + apertureValue.setDenominator(BigInteger.valueOf(apertureTagValue.getDenominator())); + apertureValue.setNumerator(BigInteger.valueOf(apertureTagValue.getNumerator())); + imageData.setApertureValue(apertureValue); + } + } + } catch (Exception ex) { + ex.printStackTrace(); } - if (ir.getTiffModel().getMetadata().contains("BrightnessValue")) { - RationalType bightnessValue = new RationalType(); - bightnessValue.setUse("Manager"); - try { + try { + if (ir.getTiffModel().getMetadata().contains("BrightnessValue") && ir.getTiffModel().getMetadata().get("BrightnessValue") instanceof SRational) { + RationalType bightnessValue = new RationalType(); + bightnessValue.setUse("Manager"); SRational brightnessTagValue = (SRational) ir.getTiffModel().getMetadata().get("BrightnessValue"); bightnessValue.setDenominator(BigInteger.valueOf(brightnessTagValue.getDenominator())); bightnessValue.setNumerator(BigInteger.valueOf(brightnessTagValue.getNumerator())); imageData.setBrightnessValue(bightnessValue); - } catch (Exception e) { - } + } catch (Exception ex) { + ex.printStackTrace(); } - if (ir.getTiffModel().getMetadata().contains("ExposureBiasValue")) { - RationalType exposureBias = new RationalType(); - exposureBias.setUse("Manager"); - SRational exposureTagValue = (SRational) ir.getTiffModel().getMetadata().get("ExposureBiasValue"); - exposureBias.setDenominator(BigInteger.valueOf(exposureTagValue.getDenominator())); - exposureBias.setNumerator(BigInteger.valueOf(exposureTagValue.getNumerator())); - imageData.setExposureBiasValue(exposureBias); + try { + if (ir.getTiffModel().getMetadata().contains("ExposureBiasValue") && ir.getTiffModel().getMetadata().get("ExposureBiasValue") instanceof SRational) { + RationalType exposureBias = new RationalType(); + exposureBias.setUse("Manager"); + SRational exposureTagValue = (SRational) ir.getTiffModel().getMetadata().get("ExposureBiasValue"); + exposureBias.setDenominator(BigInteger.valueOf(exposureTagValue.getDenominator())); + exposureBias.setNumerator(BigInteger.valueOf(exposureTagValue.getNumerator())); + imageData.setExposureBiasValue(exposureBias); + } + } catch (Exception ex) { + ex.printStackTrace(); } - if (ir.getTiffModel().getMetadata().contains("MaxApertureValue")) { - RationalType maxAperture = new RationalType(); - maxAperture.setUse("Manager"); - SRational maxApertureTagValue = (SRational) ir.getTiffModel().getMetadata().get("MaxApertureValue"); - maxAperture.setDenominator(BigInteger.valueOf(maxApertureTagValue.getDenominator())); - maxAperture.setNumerator(BigInteger.valueOf(maxApertureTagValue.getNumerator())); - imageData.setMaxApertureValue(maxAperture); + try { + if (ir.getTiffModel().getMetadata().contains("MaxApertureValue") && ir.getTiffModel().getMetadata().get("MaxApertureValue") instanceof SRational) { + RationalType maxAperture = new RationalType(); + maxAperture.setUse("Manager"); + if (ir.getTiffModel().getMetadata().get("MaxApertureValue") instanceof SRational) { + SRational maxApertureTagValue = (SRational) ir.getTiffModel().getMetadata().get("MaxApertureValue"); + maxAperture.setDenominator(BigInteger.valueOf(maxApertureTagValue.getDenominator())); + maxAperture.setNumerator(BigInteger.valueOf(maxApertureTagValue.getNumerator())); + imageData.setMaxApertureValue(maxAperture); + } + } + } catch (Exception ex) { + ex.printStackTrace(); } - if (ir.getTiffModel().getMetadata().contains("SubjectDistance")) { - ImageCaptureMetadataType.DigitalCameraCapture.CameraCaptureSettings.ImageData.SubjectDistance subjectDistance = new ImageCaptureMetadataType.DigitalCameraCapture.CameraCaptureSettings.ImageData.SubjectDistance(); - TypeOfNonNegativeDecimalType distance = new TypeOfNonNegativeDecimalType(); - distance.setUse("Manager"); - TiffObject to = ir.getTiffModel().getMetadata().get("SubjectDistance"); - if (to instanceof Long) { - Long subjectLongValue = (Long) to; - distance.setValue(BigDecimal.valueOf(subjectLongValue.getValue())); - subjectDistance.setDistance(distance); - imageData.setSubjectDistance(subjectDistance); + try { + if (ir.getTiffModel().getMetadata().contains("SubjectDistance")) { + ImageCaptureMetadataType.DigitalCameraCapture.CameraCaptureSettings.ImageData.SubjectDistance subjectDistance = new ImageCaptureMetadataType.DigitalCameraCapture.CameraCaptureSettings.ImageData.SubjectDistance(); + TypeOfNonNegativeDecimalType distance = new TypeOfNonNegativeDecimalType(); + distance.setUse("Manager"); + TiffObject to = ir.getTiffModel().getMetadata().get("SubjectDistance"); + if (to instanceof Long) { + Long subjectLongValue = (Long) to; + distance.setValue(BigDecimal.valueOf(subjectLongValue.getValue())); + subjectDistance.setDistance(distance); + imageData.setSubjectDistance(subjectDistance); + } } + } catch (Exception ex) { + ex.printStackTrace(); } - if (ir.getTiffModel().getMetadata().contains("MeteringMode") && MeteringModeType.verifyTag(ir.getTiffModel().getMetadata().get("MeteringMode").toString())) { - TypeOfMeteringModeType meteringModeType = new TypeOfMeteringModeType(); - meteringModeType.setUse("Manager"); - meteringModeType.setValue(MeteringModeType.fromValue(ir.getTiffModel().getMetadata().get("MeteringMode").toString())); - imageData.setMeteringMode(meteringModeType); + try { + if (ir.getTiffModel().getMetadata().contains("MeteringMode") && MeteringModeType.verifyTag(ir.getTiffModel().getMetadata().get("MeteringMode").toString())) { + TypeOfMeteringModeType meteringModeType = new TypeOfMeteringModeType(); + meteringModeType.setUse("Manager"); + meteringModeType.setValue(MeteringModeType.fromValue(ir.getTiffModel().getMetadata().get("MeteringMode").toString())); + imageData.setMeteringMode(meteringModeType); + } + } catch (Exception ex) { + ex.printStackTrace(); } - if (ir.getTiffModel().getMetadata().contains("LightSource") && LightSourceType.verifyTag(ir.getTiffModel().getMetadata().get("LightSource").toString())) { - TypeOfLightSourceType lightSourceType = new TypeOfLightSourceType(); - lightSourceType.setUse("Manager"); - lightSourceType.setValue(LightSourceType.fromValue(ir.getTiffModel().getMetadata().get("LightSource").toString())); - imageData.setLightSource(lightSourceType); + try { + if (ir.getTiffModel().getMetadata().contains("LightSource") && LightSourceType.verifyTag(ir.getTiffModel().getMetadata().get("LightSource").toString())) { + TypeOfLightSourceType lightSourceType = new TypeOfLightSourceType(); + lightSourceType.setUse("Manager"); + lightSourceType.setValue(LightSourceType.fromValue(ir.getTiffModel().getMetadata().get("LightSource").toString())); + imageData.setLightSource(lightSourceType); + } + } catch (Exception ex) { + ex.printStackTrace(); } - if (ir.getTiffModel().getMetadata().contains("Flash")) { - TypeOfFlashType flashType = new TypeOfFlashType(); - flashType.setUse("Manager"); - Integer hexFlashInt = Integer.parseInt(ir.getTiffModel().getMetadata().get("Flash").toString()); - String hexFlash = String.format("%04X", hexFlashInt); - if (FlashType.verifyTag(hexFlash)) { - flashType.setValue(FlashType.fromValue(hexFlash)); - imageData.setFlash(flashType); + try { + if (ir.getTiffModel().getMetadata().contains("Flash")) { + TypeOfFlashType flashType = new TypeOfFlashType(); + flashType.setUse("Manager"); + Integer hexFlashInt = Integer.parseInt(ir.getTiffModel().getMetadata().get("Flash").toString()); + String hexFlash = String.format("%04X", hexFlashInt); + if (FlashType.verifyTag(hexFlash)) { + flashType.setValue(FlashType.fromValue(hexFlash)); + imageData.setFlash(flashType); + } } - + } catch (Exception ex) { + ex.printStackTrace(); } - if (ir.getTiffModel().getMetadata().contains("FlashEnergy")) { - RationalType flashEnergy = new RationalType(); - flashEnergy.setUse("Manager"); - Rational flashEnergyTagValue = (Rational) ir.getTiffModel().getMetadata().get("FlashEnergy"); - flashEnergy.setDenominator(BigInteger.valueOf(flashEnergyTagValue.getDenominator())); - flashEnergy.setNumerator(BigInteger.valueOf(flashEnergyTagValue.getNumerator())); - imageData.setFlashEnergy(flashEnergy); + try { + if (ir.getTiffModel().getMetadata().contains("FlashEnergy")) { + RationalType flashEnergy = new RationalType(); + flashEnergy.setUse("Manager"); + Rational flashEnergyTagValue = (Rational) ir.getTiffModel().getMetadata().get("FlashEnergy"); + flashEnergy.setDenominator(BigInteger.valueOf(flashEnergyTagValue.getDenominator())); + flashEnergy.setNumerator(BigInteger.valueOf(flashEnergyTagValue.getNumerator())); + imageData.setFlashEnergy(flashEnergy); + } + } catch (Exception ex) { + ex.printStackTrace(); } - if (ir.getTiffModel().getMetadata().contains("ExposureIndex")) { - TypeOfPositiveRealType exposureIndex = new TypeOfPositiveRealType(); - exposureIndex.setUse("Manager"); - Rational exposureTagValue = (Rational) ir.getTiffModel().getMetadata().get("ExposureIndex"); - exposureIndex.setValue(exposureTagValue.getFloatValue()); - imageData.setExposureIndex(exposureIndex); + try { + if (ir.getTiffModel().getMetadata().contains("ExposureIndex")) { + TypeOfPositiveRealType exposureIndex = new TypeOfPositiveRealType(); + exposureIndex.setUse("Manager"); + Rational exposureTagValue = (Rational) ir.getTiffModel().getMetadata().get("ExposureIndex"); + exposureIndex.setValue(exposureTagValue.getFloatValue()); + imageData.setExposureIndex(exposureIndex); + } + } catch (Exception ex) { + ex.printStackTrace(); } - if (ir.getTiffModel().getMetadata().contains("SensingMethod")) { - TypeOfSensingMethodType exposureIndex = new TypeOfSensingMethodType(); - exposureIndex.setUse("Manager"); - Short exposureTagValue = (Short) ir.getTiffModel().getMetadata().get("SensingMethod"); - if (SensingMethodType.verifyTag(exposureTagValue.toString())) { - exposureIndex.setValue(SensingMethodType.fromValue(exposureTagValue.toString())); - imageData.setSensingMethod(exposureIndex); + try { + if (ir.getTiffModel().getMetadata().contains("SensingMethod")) { + TypeOfSensingMethodType exposureIndex = new TypeOfSensingMethodType(); + exposureIndex.setUse("Manager"); + Short exposureTagValue = (Short) ir.getTiffModel().getMetadata().get("SensingMethod"); + if (SensingMethodType.verifyTag(exposureTagValue.toString())) { + exposureIndex.setValue(SensingMethodType.fromValue(exposureTagValue.toString())); + imageData.setSensingMethod(exposureIndex); + } } + } catch (Exception ex) { + ex.printStackTrace(); } - if (ir.getTiffModel().getMetadata().contains("CFAPattern")) { - IntegerType cfaPattern = new IntegerType(); - cfaPattern.setUse("Manager"); - try { - cfaPattern.setValue(new BigInteger(ir.getTiffModel().getMetadata().get("CFAPattern").toString().replace("[", "").replace("]", "").replace(",", ""))); - imageData.setCfaPattern(cfaPattern); - } catch (Exception ex) { - //ex.printStackTrace(); + try { + if (ir.getTiffModel().getMetadata().contains("CFAPattern")) { + IntegerType cfaPattern = new IntegerType(); + cfaPattern.setUse("Manager"); + String val = ir.getTiffModel().getMetadata().get("CFAPattern").toString().replace("[", "").replace("]", "").replace(",", ""); + try { + BigInteger bi = new BigInteger(val); + cfaPattern.setValue(bi); + imageData.setCfaPattern(cfaPattern); + } catch (Exception ex) { + // Not an integer + } } + } catch (Exception ex) { + ex.printStackTrace(); } } return imageData; @@ -867,16 +958,18 @@ private ImageCaptureMetadataType createNisoImageCaptureMetadata(IFD ifd, Individ ImageCaptureMetadataType.SourceInformation.SourceSize.SourceXDimension sourceXDimension = new ImageCaptureMetadataType.SourceInformation.SourceSize.SourceXDimension(); TypeOfNonNegativeRealType xDValue = new TypeOfNonNegativeRealType(); xDValue.setUse("System"); - Rational xResolutionValue = (Rational) (ifd.getMetadata().get("XResolution").getValue().get(0)); - xDValue.setValue(xResolutionValue.getFloatValue()); - sourceXDimension.setSourceXDimensionValue(xDValue); + if (ifd.getMetadata().get("XResolution").getCardinality() > 0 && ifd.getMetadata().get("XResolution").getValue().get(0) instanceof Rational) { + Rational xResolutionValue = (Rational) (ifd.getMetadata().get("XResolution").getValue().get(0)); + xDValue.setValue(xResolutionValue.getFloatValue()); + sourceXDimension.setSourceXDimensionValue(xDValue); + } TypeOfsourceDimensionUnitType dimensionUnit = new TypeOfsourceDimensionUnitType(); dimensionUnit.setUse("System"); dimensionUnit.setValue(SourceDimensionUnitType.fromValue(ifd.getMetadata().get("ResolutionUnit").toString())); sourceXDimension.setSourceXDimensionUnit(dimensionUnit); sourceSize.setSourceXDimension(sourceXDimension); - }catch (Exception e) { - + } catch (Exception e) { + e.printStackTrace(); } } if (ifd.getMetadata().containsTagId(TiffTags.getTagId("YResolution")) && ifd.getMetadata().containsTagId(TiffTags.getTagId("ResolutionUnit")) && SourceDimensionUnitType.verifyTag(ifd.getMetadata().get("ResolutionUnit").toString())) { @@ -884,16 +977,18 @@ private ImageCaptureMetadataType createNisoImageCaptureMetadata(IFD ifd, Individ ImageCaptureMetadataType.SourceInformation.SourceSize.SourceYDimension sourceYDimension = new ImageCaptureMetadataType.SourceInformation.SourceSize.SourceYDimension(); TypeOfNonNegativeRealType yDValue = new TypeOfNonNegativeRealType(); yDValue.setUse("System"); - Rational yResolutionValue = (Rational) (ifd.getMetadata().get("YResolution").getValue().get(0)); - yDValue.setValue(yResolutionValue.getFloatValue()); - sourceYDimension.setSourceYDimensionValue(yDValue); + if ((ifd.getMetadata().get("YResolution").getCardinality() > 0 && ifd.getMetadata().get("YResolution").getValue().get(0) instanceof Rational)) { + Rational yResolutionValue = (Rational) (ifd.getMetadata().get("YResolution").getValue().get(0)); + yDValue.setValue(yResolutionValue.getFloatValue()); + sourceYDimension.setSourceYDimensionValue(yDValue); + } TypeOfsourceDimensionUnitType dimensionUnit = new TypeOfsourceDimensionUnitType(); dimensionUnit.setUse("System"); dimensionUnit.setValue(SourceDimensionUnitType.fromValue(ifd.getMetadata().get("ResolutionUnit").toString())); sourceYDimension.setSourceYDimensionUnit(dimensionUnit); sourceSize.setSourceYDimension(sourceYDimension); } catch (Exception e) { - + e.printStackTrace(); } } @@ -901,61 +996,89 @@ private ImageCaptureMetadataType createNisoImageCaptureMetadata(IFD ifd, Individ imageCapture.setSourceInformation(sourceInformation); //8.2 General capture information - ImageCaptureMetadataType.GeneralCaptureInformation generalCaptureInformation = new ImageCaptureMetadataType.GeneralCaptureInformation(); - TypeOfDateType creationDate = new TypeOfDateType(); - creationDate.setUse("Manager"); - creationDate.setValue(getImageDate(ifd, ir.getFilePath())); - generalCaptureInformation.setDateTimeCreated(creationDate); - if (ifd.getMetadata().containsTagId(TiffTags.getTagId("Artist"))) { - Ascii artist = (Ascii) ifd.getMetadata().get("Artist").getValue().get(0); - StringType producer = new StringType(); - producer.setUse("Manager"); - producer.setValue(artist.toString()); - generalCaptureInformation.setImageProducer(producer); + try { + ImageCaptureMetadataType.GeneralCaptureInformation generalCaptureInformation = new ImageCaptureMetadataType.GeneralCaptureInformation(); + TypeOfDateType creationDate = new TypeOfDateType(); + creationDate.setUse("Manager"); + creationDate.setValue(getImageDate(ifd, ir.getFilePath())); + generalCaptureInformation.setDateTimeCreated(creationDate); + if (ifd.getMetadata().containsTagId(TiffTags.getTagId("Artist")) && ifd.getMetadata().get("Artist").getCardinality() > 0) { + Ascii artist = (Ascii) ifd.getMetadata().get("Artist").getValue().get(0); + StringType producer = new StringType(); + producer.setUse("Manager"); + producer.setValue(artist.toString()); + generalCaptureInformation.setImageProducer(producer); + } + imageCapture.setGeneralCaptureInformation(generalCaptureInformation); + } catch (Exception ex) { + ex.printStackTrace(); } - imageCapture.setGeneralCaptureInformation(generalCaptureInformation); //8.4 Digital Camera Capture ImageCaptureMetadataType.DigitalCameraCapture digitalCameraCapture = new ImageCaptureMetadataType.DigitalCameraCapture(); - if (ifd.getMetadata().containsTagId(TiffTags.getTagId("Make"))) { - StringType manufacturer = new StringType(); - manufacturer.setUse("Manager"); - manufacturer.setValue(ifd.getMetadata().get("Make").toString()); - digitalCameraCapture.setDigitalCameraManufacturer(manufacturer); + try { + if (ifd.getMetadata().containsTagId(TiffTags.getTagId("Make"))) { + StringType manufacturer = new StringType(); + manufacturer.setUse("Manager"); + manufacturer.setValue(ifd.getMetadata().get("Make").toString()); + digitalCameraCapture.setDigitalCameraManufacturer(manufacturer); + } + } catch (Exception ex) { + ex.printStackTrace(); } - if (ifd.getMetadata().containsTagId(TiffTags.getTagId("Model"))) { - ImageCaptureMetadataType.DigitalCameraCapture.DigitalCameraModel cameraModel = new ImageCaptureMetadataType.DigitalCameraCapture.DigitalCameraModel(); - StringType model = new StringType(); - model.setUse("Manager"); - model.setValue(ifd.getMetadata().get("Model").toString()); - cameraModel.setDigitalCameraModelName(model); - digitalCameraCapture.setDigitalCameraModel(cameraModel); + try { + if (ifd.getMetadata().containsTagId(TiffTags.getTagId("Model"))) { + ImageCaptureMetadataType.DigitalCameraCapture.DigitalCameraModel cameraModel = new ImageCaptureMetadataType.DigitalCameraCapture.DigitalCameraModel(); + StringType model = new StringType(); + model.setUse("Manager"); + model.setValue(ifd.getMetadata().get("Model").toString()); + cameraModel.setDigitalCameraModelName(model); + digitalCameraCapture.setDigitalCameraModel(cameraModel); + } + } catch (Exception ex) { + ex.printStackTrace(); } - if (ifd.getMetadata().containsTagId(TiffTags.getTagId("SensingMethod")) && CameraSensorType.verifyTag(ifd.getMetadata().get("SensingMethod").getValue().toString())) { - TypeOfCameraSensorType cameraSensor = new TypeOfCameraSensorType(); - cameraSensor.setUse("Manager"); - cameraSensor.setValue(CameraSensorType.fromValue(ifd.getMetadata().get("SensingMethod").getValue().toString())); - digitalCameraCapture.setCameraSensor(cameraSensor); + try { + if (ifd.getMetadata().containsTagId(TiffTags.getTagId("SensingMethod")) && CameraSensorType.verifyTag(ifd.getMetadata().get("SensingMethod").getValue().toString())) { + TypeOfCameraSensorType cameraSensor = new TypeOfCameraSensorType(); + cameraSensor.setUse("Manager"); + cameraSensor.setValue(CameraSensorType.fromValue(ifd.getMetadata().get("SensingMethod").getValue().toString())); + digitalCameraCapture.setCameraSensor(cameraSensor); + } + } catch (Exception ex) { + ex.printStackTrace(); } //8.4.4 Camera Capture Settings //8.4.4.1 Image Data ImageCaptureMetadataType.DigitalCameraCapture.CameraCaptureSettings cameraSettings = new ImageCaptureMetadataType.DigitalCameraCapture.CameraCaptureSettings(); - ImageCaptureMetadataType.DigitalCameraCapture.CameraCaptureSettings.ImageData imageData = createNisoImageData(ir, ifd); - cameraSettings.setImageData(imageData); + try { + ImageCaptureMetadataType.DigitalCameraCapture.CameraCaptureSettings.ImageData imageData = createNisoImageData(ir, ifd); + cameraSettings.setImageData(imageData); + } catch (Exception ex) { + ex.printStackTrace(); + } //8.4.4.2 GPSData - ImageCaptureMetadataType.DigitalCameraCapture.CameraCaptureSettings.GPSData gpsData = createNisoGPSData(ir); - cameraSettings.setGPSData(gpsData); - digitalCameraCapture.setCameraCaptureSettings(cameraSettings); - imageCapture.setDigitalCameraCapture(digitalCameraCapture); + try { + ImageCaptureMetadataType.DigitalCameraCapture.CameraCaptureSettings.GPSData gpsData = createNisoGPSData(ir); + cameraSettings.setGPSData(gpsData); + digitalCameraCapture.setCameraCaptureSettings(cameraSettings); + imageCapture.setDigitalCameraCapture(digitalCameraCapture); + } catch (Exception ex) { + ex.printStackTrace(); + } //8.5 orientation - if (ifd.getMetadata().containsTagId(TiffTags.getTagId("Orientation")) && OrientationType.verifyTag(ifd.getMetadata().get("Orientation").toString())) { - TypeOfOrientationType typeOfOrientationType = new TypeOfOrientationType(); - typeOfOrientationType.setUse("System"); - typeOfOrientationType.setValue(OrientationType.fromValue(ifd.getMetadata().get("Orientation").toString())); - imageCapture.setOrientation(typeOfOrientationType); + try { + if (ifd.getMetadata().containsTagId(TiffTags.getTagId("Orientation")) && OrientationType.verifyTag(ifd.getMetadata().get("Orientation").toString())) { + TypeOfOrientationType typeOfOrientationType = new TypeOfOrientationType(); + typeOfOrientationType.setUse("System"); + typeOfOrientationType.setValue(OrientationType.fromValue(ifd.getMetadata().get("Orientation").toString())); + imageCapture.setOrientation(typeOfOrientationType); + } + } catch (Exception ex) { + ex.printStackTrace(); } } @@ -1033,7 +1156,7 @@ private ImageAssessmentMetadataType createNisoImageAssessmentMetadata(IFD ifd) { imageColorEncoding.setGrayResponse(grayResponse); } } - if (ifd.getMetadata().containsTagId(TiffTags.getTagId("WhitePoint"))) { + if (ifd.getMetadata().containsTagId(TiffTags.getTagId("WhitePoint")) && ifd.getMetadata().containsTagId(TiffTags.getTagId("GrayResponseUnit"))) { ImageAssessmentMetadataType.ImageColorEncoding.WhitePoint whitePoint = new ImageAssessmentMetadataType.ImageColorEncoding.WhitePoint(); //x value RationalType whitePointXValue = new RationalType(); @@ -1196,7 +1319,6 @@ private MdSecType.MdWrap constructTechMdWrap(IndividualReport ir) { mdwrap.setMIMETYPE("text/xml"); try { - Date today = new Date(); GregorianCalendar gregory = new GregorianCalendar(); gregory.setTime(today); @@ -1241,52 +1363,72 @@ private MdSecType.MdWrap constructTechMdWrap(IndividualReport ir) { objectId.setObjectIdentifierValue(objIddValue); //fileSize - NonNegativeIntegerType fileSize = new NonNegativeIntegerType(); - fileSize.setUse("System"); - fileSize.setValue(BigInteger.valueOf(2 + (ifd.getTags().getTags().size() * 12) + 4)); - digitalObject.setFileSize(fileSize); + try { + NonNegativeIntegerType fileSize = new NonNegativeIntegerType(); + fileSize.setUse("System"); + fileSize.setValue(BigInteger.valueOf(2 + (ifd.getTags().getTags().size() * 12) + 4)); + digitalObject.setFileSize(fileSize); + } catch (Exception ex) { + ex.printStackTrace(); + } //formatDesignation - BasicDigitalObjectInformationType.FormatDesignation formatDesign = new BasicDigitalObjectInformationType.FormatDesignation(); StringType formatType = new StringType(); - formatType.setUse("System"); - formatType.setValue("image/tiff"); - StringType formatVersion = new StringType(); - formatType.setUse("System"); - formatType.setValue("6.0"); - formatDesign.setFormatName(formatType); - formatDesign.setFormatVersion(formatVersion); - digitalObject.setFormatDesignation(formatDesign); + try { + BasicDigitalObjectInformationType.FormatDesignation formatDesign = new BasicDigitalObjectInformationType.FormatDesignation(); + formatType.setUse("System"); + formatType.setValue("image/tiff"); + StringType formatVersion = new StringType(); + formatType.setUse("System"); + formatType.setValue("6.0"); + formatDesign.setFormatName(formatType); + formatDesign.setFormatVersion(formatVersion); + digitalObject.setFormatDesignation(formatDesign); + } catch (Exception ex) { + ex.printStackTrace(); + } //formatRegistry is optional - BasicDigitalObjectInformationType.FormatRegistry formatReg = new BasicDigitalObjectInformationType.FormatRegistry(); - StringType formatReyKey = new StringType(); - formatType.setUse("System"); - formatType.setValue("TIFF/6.0"); - formatReg.setFormatRegistryKey(formatReyKey); - digitalObject.setFormatRegistry(formatReg); + try { + BasicDigitalObjectInformationType.FormatRegistry formatReg = new BasicDigitalObjectInformationType.FormatRegistry(); + StringType formatReyKey = new StringType(); + formatType.setUse("System"); + formatType.setValue("TIFF/6.0"); + formatReg.setFormatRegistryKey(formatReyKey); + digitalObject.setFormatRegistry(formatReg); + } catch (Exception ex) { + ex.printStackTrace(); + } //byteOrder - if (ByteOrderType.verifyTag(byteOrder)) { - TypeOfByteOrderType orderType = new TypeOfByteOrderType(); - orderType.setUse("System"); - orderType.setValue(ByteOrderType.fromValue(byteOrder)); - digitalObject.setByteOrder(orderType); + try { + if (ByteOrderType.verifyTag(byteOrder)) { + TypeOfByteOrderType orderType = new TypeOfByteOrderType(); + orderType.setUse("System"); + orderType.setValue(ByteOrderType.fromValue(byteOrder)); + digitalObject.setByteOrder(orderType); + } + } catch (Exception ex) { + ex.printStackTrace(); } //compression - if (ifd.getMetadata().containsTagId(TiffTags.getTagId("Compression"))) { - BasicDigitalObjectInformationType.Compression compression = new BasicDigitalObjectInformationType.Compression(); - StringType comprScheme = new StringType(); - comprScheme.setUse("System"); - int icomp = 0; - try { - icomp = Integer.parseInt(ifd.getMetadata().get("Compression").toString()); - } catch (Exception e) { + try { + if (ifd.getMetadata().containsTagId(TiffTags.getTagId("Compression"))) { + BasicDigitalObjectInformationType.Compression compression = new BasicDigitalObjectInformationType.Compression(); + StringType comprScheme = new StringType(); + comprScheme.setUse("System"); + int icomp = 0; + try { + icomp = Integer.parseInt(ifd.getMetadata().get("Compression").toString()); + } catch (Exception e) { + } + comprScheme.setValue(PolicyConstants.compressionName(icomp)); + compression.setCompressionScheme(comprScheme); + digitalObject.setCompression(compression); } - comprScheme.setValue(PolicyConstants.compressionName(icomp)); - compression.setCompressionScheme(comprScheme); - digitalObject.setCompression(compression); + } catch (Exception ex) { + ex.printStackTrace(); } mix.setBasicDigitalObjectInformation(digitalObject); @@ -1294,65 +1436,78 @@ private MdSecType.MdWrap constructTechMdWrap(IndividualReport ir) { /** * 7 Basic Image Information */ - - BasicImageInformationType basicImage = createNisoBasicImageInformation(ifd); - mix.setBasicImageInformation(basicImage); + try { + BasicImageInformationType basicImage = createNisoBasicImageInformation(ifd); + mix.setBasicImageInformation(basicImage); + } catch (Exception ex) { + ex.printStackTrace(); + } /** * 8 Image Capture Metadata */ - ImageCaptureMetadataType imageCapture = createNisoImageCaptureMetadata(ifd, ir); - if (imageCapture == null) { - return mdwrap; + try { + ImageCaptureMetadataType imageCapture = createNisoImageCaptureMetadata(ifd, ir); + if (imageCapture != null) { + mix.setImageCaptureMetadata(imageCapture); + } + } catch (Exception ex) { + ex.printStackTrace(); } - mix.setImageCaptureMetadata(imageCapture); /** * 9 Image Assessment Metadata */ - ImageAssessmentMetadataType imageAssessmentMetadata = createNisoImageAssessmentMetadata(ifd); - mix.setImageAssessmentMetadata(imageAssessmentMetadata); + try { + ImageAssessmentMetadataType imageAssessmentMetadata = createNisoImageAssessmentMetadata(ifd); + mix.setImageAssessmentMetadata(imageAssessmentMetadata); + } catch (Exception ex) { + ex.printStackTrace(); + } /** * 10 Change history */ - if (ifd.containsTagId(700)) { //XMP - ChangeHistoryType changeHistoryType = new ChangeHistoryType(); - XMP xmp = (XMP) ifd.getTag("XMP").getValue().get(0); - List> xmpHistoryList = xmp.getHistory(); - if (xmpHistoryList != null) { - Iterator> iteratorXmpHistory = xmpHistoryList.iterator(); - while (iteratorXmpHistory.hasNext()) { - ChangeHistoryType.ImageProcessing imageProcessing = new ChangeHistoryType.ImageProcessing(); - Hashtable xmpHistory = iteratorXmpHistory.next(); - if (xmpHistory.containsKey("when")) { - TypeOfDateType dateType = new TypeOfDateType(); - dateType.setUse("Manager"); - dateType.setValue(xmpHistory.get("when")); - imageProcessing.setDateTimeProcessed(dateType); - } - if (xmpHistory.containsKey("softwareAgent")) { - ChangeHistoryType.ImageProcessing.ProcessingSoftware processingSoftware = new ChangeHistoryType.ImageProcessing.ProcessingSoftware(); - StringType softwareName = new StringType(); - softwareName.setUse("Manager"); - softwareName.setValue(xmpHistory.get("softwareAgent")); - processingSoftware.setProcessingSoftwareName(softwareName); - imageProcessing.setProcessingSoftware(processingSoftware); - } - if (xmpHistory.containsKey("action")) { - StringType action = new StringType(); - action.setUse("Manager"); - action.setValue(xmpHistory.get("action")); - imageProcessing.setProcessingActions(action); + try { + if (ifd.containsTagId(700) && ifd.getTag("XMP").getCardinality() > 0 && ifd.getTag("XMP").getValue().get(0) instanceof XMP) { //XMP + ChangeHistoryType changeHistoryType = new ChangeHistoryType(); + XMP xmp = (XMP) ifd.getTag("XMP").getValue().get(0); + List> xmpHistoryList = xmp.getHistory(); + if (xmpHistoryList != null) { + Iterator> iteratorXmpHistory = xmpHistoryList.iterator(); + while (iteratorXmpHistory.hasNext()) { + ChangeHistoryType.ImageProcessing imageProcessing = new ChangeHistoryType.ImageProcessing(); + Hashtable xmpHistory = iteratorXmpHistory.next(); + if (xmpHistory.containsKey("when")) { + TypeOfDateType dateType = new TypeOfDateType(); + dateType.setUse("Manager"); + dateType.setValue(xmpHistory.get("when")); + imageProcessing.setDateTimeProcessed(dateType); + } + if (xmpHistory.containsKey("softwareAgent")) { + ChangeHistoryType.ImageProcessing.ProcessingSoftware processingSoftware = new ChangeHistoryType.ImageProcessing.ProcessingSoftware(); + StringType softwareName = new StringType(); + softwareName.setUse("Manager"); + softwareName.setValue(xmpHistory.get("softwareAgent")); + processingSoftware.setProcessingSoftwareName(softwareName); + imageProcessing.setProcessingSoftware(processingSoftware); + } + if (xmpHistory.containsKey("action")) { + StringType action = new StringType(); + action.setUse("Manager"); + action.setValue(xmpHistory.get("action")); + imageProcessing.setProcessingActions(action); + } + + changeHistoryType.setImageProcessing(imageProcessing); } - - changeHistoryType.setImageProcessing(imageProcessing); + mix.setChangeHistory(changeHistoryType); } - mix.setChangeHistory(changeHistoryType); } + } catch (Exception ex) { + ex.printStackTrace(); } - } ifd = ifd.getNextIFD(); @@ -1581,12 +1736,15 @@ private Mets buildReportIndividual(IndividualReport ir, Configuration config) { //mets dmdSec - MdSecType dmdSec = new MdSecType(); - dmdSec.setID("D" + ir.hashCode()); - dmdSec.setSTATUS(""); - dmdSec.setMdWrap(constructDmdMdWrap(ir)); - mets.setDmdSec(dmdSec); + try { + MdSecType dmdSec = new MdSecType(); + dmdSec.setID("D" + ir.hashCode()); + dmdSec.setSTATUS(""); + dmdSec.setMdWrap(constructDmdMdWrap(ir)); + mets.setDmdSec(dmdSec); + } catch (Exception ex) { + } //mets amdSec AmdSecType amdsec = new AmdSecType(); @@ -1668,12 +1826,12 @@ public String parseIndividual(IndividualReport ir, Configuration config) { } catch (JAXBException e) { // TODO: Something //System.err.println("Error generating METS report"); -// e.printStackTrace(); + e.printStackTrace(); return null; } catch (Exception e) { // TODO: Something //System.err.println("Error generating METS report"); -// e.printStackTrace(); + e.printStackTrace(); return null; } diff --git a/src/main/java/dpfmanager/conformancechecker/tiff/reporting/XmlReport.java b/src/main/java/dpfmanager/conformancechecker/tiff/reporting/XmlReport.java index 3f76e5ee..1e6464ef 100644 --- a/src/main/java/dpfmanager/conformancechecker/tiff/reporting/XmlReport.java +++ b/src/main/java/dpfmanager/conformancechecker/tiff/reporting/XmlReport.java @@ -920,7 +920,6 @@ public String parseIndividual(IndividualReport ir, Rules rules) { transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); // To String - transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(doc), new StreamResult(writer)); return writer.getBuffer().toString(); diff --git a/src/main/java/dpfmanager/shell/core/adapter/DpfAbstractPerspective.java b/src/main/java/dpfmanager/shell/core/adapter/DpfAbstractPerspective.java index badb8739..b7c63bb3 100644 --- a/src/main/java/dpfmanager/shell/core/adapter/DpfAbstractPerspective.java +++ b/src/main/java/dpfmanager/shell/core/adapter/DpfAbstractPerspective.java @@ -40,6 +40,7 @@ import javafx.scene.layout.AnchorPane; import javafx.scene.layout.BorderPane; import javafx.scene.layout.ColumnConstraints; +import javafx.scene.layout.FlowPane; import javafx.scene.layout.GridPane; import javafx.scene.layout.Priority; import javafx.scene.layout.StackPane; @@ -118,6 +119,8 @@ public void onShow(){ } public void onReload(){ + getContext().getManagedFragmentHandler(TopFragment.class).getController().setCurrentToggle(getContext().getId()); + showHideBottomPane(getContext().getManagedFragmentHandler(BarFragment.class).getController().isVisible()); onReloadCustom(); } @@ -225,6 +228,31 @@ protected AnchorPane constructMainPane(SplitPane mainSplit, Node bar) { return mainPane; } + protected AnchorPane constructMainPaneWithBread(SplitPane mainSplit, Node bread, Node bar) { + AnchorPane mainPane = new AnchorPane(); + mainPane.setCenterShape(true); + mainPane.setId("mainPane"); + mainPane.getStyleClass().add("background-main"); + + mainPane.getChildren().add(mainSplit); + AnchorPane.setTopAnchor(mainSplit, 20.0); + AnchorPane.setBottomAnchor(mainSplit, 21.0); + AnchorPane.setLeftAnchor(mainSplit, 0.0); + AnchorPane.setRightAnchor(mainSplit, 0.0); + + mainPane.getChildren().add(bread); + AnchorPane.setTopAnchor(bread, 0.0); + AnchorPane.setRightAnchor(bread, 0.0); + AnchorPane.setLeftAnchor(bread, 0.0); + + mainPane.getChildren().add(bar); + AnchorPane.setBottomAnchor(bar, 0.0); + AnchorPane.setRightAnchor(bar, 0.0); + AnchorPane.setLeftAnchor(bar, 0.0); + + return mainPane; + } + protected Node getDivider() { if (divider == null) { divider = mainPane.lookup("#mainSplit > .split-pane-divider"); diff --git a/src/main/java/dpfmanager/shell/core/config/GuiConfig.java b/src/main/java/dpfmanager/shell/core/config/GuiConfig.java index bd457e79..9d8dab9d 100644 --- a/src/main/java/dpfmanager/shell/core/config/GuiConfig.java +++ b/src/main/java/dpfmanager/shell/core/config/GuiConfig.java @@ -31,6 +31,7 @@ public class GuiConfig { public static final String PERSPECTIVE_PERIODICAL = "p007"; public static final String PERSPECTIVE_INTEROPERABILITY = "p008"; public static final String PERSPECTIVE_STATISTICS = "p009"; + public static final String PERSPECTIVE_GLOBAL = "p010"; /** Components */ public static final String COMPONENT_TOP = "id001"; @@ -45,6 +46,8 @@ public class GuiConfig { public static final String COMPONENT_PERIODICAL = "id010"; public static final String COMPONENT_INTEROPERABILITY = "id011"; public static final String COMPONENT_STATISTICS = "id012"; + public static final String COMPONENT_GLOBAL = "id013"; + public static final String COMPONENT_NAV = "id014"; /** Target containers */ public static final String TARGET_CONTAINER_TOP = "tc001"; @@ -59,6 +62,8 @@ public class GuiConfig { public static final String TARGET_CONTAINER_PERIODICAL = "tc010"; public static final String TARGET_CONTAINER_INTEROPERABILITY = "tc011"; public static final String TARGET_CONTAINER_STATISTICS = "tc012"; + public static final String TARGET_CONTAINER_GLOBAL = "tc013"; + public static final String TARGET_CONTAINER_NAV = "tc014"; /** Fragments */ public static final String FRAGMENT_BOTTOM = "f001"; @@ -80,4 +85,6 @@ public class GuiConfig { public static final String FRAGMENT_ISO = "f017"; public static final String FRAGMENT_RULE = "f018"; public static final String FRAGMENT_ERRORS_LIST = "f019"; + public static final String FRAGMENT_INDIVIDUAL = "f020"; + public static final String FRAGMENT_BREAD = "f021"; } diff --git a/src/main/java/dpfmanager/shell/core/messages/NavMessage.java b/src/main/java/dpfmanager/shell/core/messages/NavMessage.java new file mode 100644 index 00000000..9ba8f995 --- /dev/null +++ b/src/main/java/dpfmanager/shell/core/messages/NavMessage.java @@ -0,0 +1,93 @@ +/** + *

ReportsMessage.java

This program is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as published by the Free + * Software Foundation, either version 3 of the License, or (at your option) any later version; or, + * at your choice, under the terms of the Mozilla Public License, v. 2.0. SPDX GPL-3.0+ or MPL-2.0+. + *

This program is distributed in the hope that it will be useful, but WITHOUT ANY + * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + * PURPOSE. See the GNU General Public License and the Mozilla Public License for more details.

+ *

You should have received a copy of the GNU General Public License and the Mozilla Public + * License along with this program. If not, see http://www.gnu.org/licenses/ + * and at http://mozilla.org/MPL/2.0 .

NB: for the + * © statement, include Easy Innova SL or other company/Person contributing the code.

© + * 2015 Easy Innova, SL

+ * + * @author Adria Llorens + * @version 1.0 + * @since 23/7/2015 + */ + +package dpfmanager.shell.core.messages; + +import dpfmanager.shell.modules.report.util.ReportGui; + +/** + * Created by Adria Llorens on 04/03/2016. + */ +public class NavMessage extends DpfMessage { + + public enum Selected { + TABLE, + REPORT, + SPECIFIC, + TEXT, + PDF, + RELOAD + } + + private Selected selected; + private String text; + private Integer count; + private Integer max; + + public NavMessage(Selected s) { + selected = s; + } + + public NavMessage(String s) { + selected = Selected.TEXT; + text = s; + } + + public NavMessage(Integer c, Integer m) { + selected = Selected.PDF; + count = c; + max = m; + } + + public String getText() { + return text; + } + + public boolean isTable() { + return selected.equals(Selected.TABLE); + } + + public boolean isReport() { + return selected.equals(Selected.REPORT); + } + + public boolean isSpecific() { + return selected.equals(Selected.SPECIFIC); + } + + public boolean isText() { + return selected.equals(Selected.TEXT); + } + + public boolean isPdf() { + return selected.equals(Selected.PDF); + } + + public boolean isReload() { + return selected.equals(Selected.RELOAD); + } + + public Integer getCount() { + return count; + } + + public Integer getMax() { + return max; + } +} \ No newline at end of file diff --git a/src/main/java/dpfmanager/shell/core/messages/ReportsMessage.java b/src/main/java/dpfmanager/shell/core/messages/ReportsMessage.java index fc5c0b51..d77c8b9b 100644 --- a/src/main/java/dpfmanager/shell/core/messages/ReportsMessage.java +++ b/src/main/java/dpfmanager/shell/core/messages/ReportsMessage.java @@ -30,15 +30,17 @@ public enum Type { READ, DELETE, ADD, - SIZE + SIZE, + SORT } private Type type; private String uuid; private ReportGui report; private Long size; + private String vboxId; - // READ & RELOAD + // READ & RELOAD & SORT public ReportsMessage(Type t) { type = t; } @@ -50,8 +52,9 @@ public ReportsMessage(Type t, String u) { } // ADD - public ReportsMessage(Type t, ReportGui r) { + public ReportsMessage(Type t, String i, ReportGui r) { type = t; + vboxId = i; report = r; } @@ -86,6 +89,10 @@ public boolean isSize() { return type.equals(Type.SIZE); } + public boolean isSort() { + return type.equals(Type.SORT); + } + public String getUuid() { return uuid; } @@ -97,4 +104,8 @@ public ReportGui getReportGui() { public Long getSize() { return size; } + + public String getVboxId() { + return vboxId; + } } \ No newline at end of file diff --git a/src/main/java/dpfmanager/shell/core/messages/ShowMessage.java b/src/main/java/dpfmanager/shell/core/messages/ShowMessage.java index 362b955a..df16670a 100644 --- a/src/main/java/dpfmanager/shell/core/messages/ShowMessage.java +++ b/src/main/java/dpfmanager/shell/core/messages/ShowMessage.java @@ -19,8 +19,12 @@ package dpfmanager.shell.core.messages; +import dpfmanager.conformancechecker.configuration.Configuration; import dpfmanager.shell.modules.report.core.GlobalReport; import dpfmanager.shell.modules.report.runnable.MakeReportRunnable; +import dpfmanager.shell.modules.report.util.ReportGui; + +import java.util.List; /** * Created by Adria Llorens on 04/03/2016. @@ -28,11 +32,12 @@ public class ShowMessage extends DpfMessage { public enum Type { - SHOW, GENERATE, UPDATE, INIT + SHOW, GENERATE, UPDATE, INIT, INDIVIDUAL, LOAD } private Type internalType; private String type; + private List types = null; private String path; private GlobalReport globalReport; private int number; @@ -40,6 +45,14 @@ public enum Type { private MakeReportRunnable makeReportRunnable; private Long uuid; private String internal; + private boolean onlyGlobal; + private Configuration config; + private ReportGui info; + + // Load + public ShowMessage(Type internalType) { + this.internalType = internalType; + } // Show public ShowMessage(Long u, String t, String p) { @@ -48,6 +61,8 @@ public ShowMessage(Long u, String t, String p) { path = p; internalType = Type.SHOW; } + + // Show public ShowMessage(String t, String p) { type = t; uuid = null; @@ -55,15 +70,43 @@ public ShowMessage(String t, String p) { internalType = Type.SHOW; } + // Show + public ShowMessage(Long u, ReportGui i) { + uuid = u; + info = i; + internalType = Type.SHOW; + } + // Generate - public ShowMessage(Long u, String t, GlobalReport gr, String i) { + public ShowMessage(Long u, String t, ReportGui info, boolean o) { + this.info = info; type = t; uuid = u; - internal = i; - globalReport = gr; + internal = info.getInternalReportFolder(); + globalReport = info.getGlobalReport(); + onlyGlobal = o; + internalType = Type.GENERATE; + } + + // Generate + public ShowMessage(Long u, List t, ReportGui info, boolean o) { + this.info = info; + types = t; + uuid = u; + internal = info.getInternalReportFolder(); + globalReport = info.getGlobalReport(); + onlyGlobal = o; internalType = Type.GENERATE; } + // Individual + public ShowMessage(String t, String p, Configuration c) { + type = t; + path = p; + config = c; + internalType = Type.INDIVIDUAL; + } + // Init public ShowMessage(Long u, int m, int v, MakeReportRunnable mrr) { uuid = u; @@ -112,6 +155,10 @@ public boolean isShow() { return internalType.equals(Type.SHOW); } + public boolean isIndividual() { + return internalType.equals(Type.INDIVIDUAL); + } + public boolean isUpdate() { return internalType.equals(Type.UPDATE); } @@ -127,4 +174,24 @@ public Long getUuid() { public String getInternal() { return internal; } + + public boolean isOnlyGlobal() { + return onlyGlobal; + } + + public Configuration getConfig() { + return config; + } + + public ReportGui getInfo() { + return info; + } + + public List getTypes() { + return types; + } + + public boolean isLoad(){ + return internalType.equals(Type.LOAD); + } } \ No newline at end of file diff --git a/src/main/java/dpfmanager/shell/interfaces/gui/component/dessign/DessignView.java b/src/main/java/dpfmanager/shell/interfaces/gui/component/dessign/DessignView.java index 1f0464d4..7b893028 100644 --- a/src/main/java/dpfmanager/shell/interfaces/gui/component/dessign/DessignView.java +++ b/src/main/java/dpfmanager/shell/interfaces/gui/component/dessign/DessignView.java @@ -192,6 +192,7 @@ public void onPostConstructComponent(FXComponentLayout layout, ResourceBundle re Class.forName("com.easyinnova.policy_checker" + "." + className); } } catch (Exception e) { + //e.printStackTrace(); } // Set model and controller diff --git a/src/main/java/dpfmanager/shell/interfaces/gui/component/global/GlobalController.java b/src/main/java/dpfmanager/shell/interfaces/gui/component/global/GlobalController.java new file mode 100644 index 00000000..41c2cb3e --- /dev/null +++ b/src/main/java/dpfmanager/shell/interfaces/gui/component/global/GlobalController.java @@ -0,0 +1,272 @@ +/** + *

ReportsController.java

This program is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as published by the Free Software + * Foundation, either version 3 of the License, or (at your option) any later version; or, at your + * choice, under the terms of the Mozilla Public License, v. 2.0. SPDX GPL-3.0+ or MPL-2.0+.

+ *

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License and the Mozilla Public License for more details.

You should + * have received a copy of the GNU General Public License and the Mozilla Public License along with + * this program. If not, see http://www.gnu.org/licenses/ + * and at http://mozilla.org/MPL/2.0 .

NB: for the + * © statement, include Easy Innova SL or other company/Person contributing the code.

© + * 2015 Easy Innova, SL

+ * + * @author Adria Llorens + * @version 1.0 + * @since 23/7/2015 + */ + +package dpfmanager.shell.interfaces.gui.component.global; + +import dpfmanager.conformancechecker.configuration.Configuration; +import dpfmanager.shell.core.DPFManagerProperties; +import dpfmanager.shell.core.config.BasicConfig; +import dpfmanager.shell.core.config.GuiConfig; +import dpfmanager.shell.core.mvc.DpfController; +import dpfmanager.shell.interfaces.gui.component.global.comparators.IndividualComparator; +import dpfmanager.shell.interfaces.gui.component.global.messages.GuiGlobalMessage; +import dpfmanager.shell.interfaces.gui.workbench.GuiWorkbench; +import dpfmanager.shell.modules.conformancechecker.messages.ConformanceMessage; +import dpfmanager.shell.modules.messages.messages.AlertMessage; +import dpfmanager.shell.modules.report.core.GlobalReport; +import dpfmanager.shell.modules.report.core.SmallIndividualReport; +import dpfmanager.shell.modules.report.util.ReportGui; +import dpfmanager.shell.modules.report.util.ReportIndividualGui; +import javafx.stage.FileChooser; + +import org.apache.commons.io.FileUtils; + +import java.io.File; +import java.io.FilenameFilter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Created by Adria Llorens on 07/03/2016. + */ +public class GlobalController extends DpfController { + + public static Integer itemsPerPage = 12; + + private List individuals; + + public GlobalController() { + } + + public void readIndividualReports(ReportGui reportGui){ + individuals = new ArrayList<>(); + GlobalReport global = reportGui.getGlobalReport(); + if (global == null) { + // Old report format, read from dir + Integer count = 0; + List idsFound = new ArrayList<>(); + File reportDir = new File(reportGui.getInternalReportFolder()); + File htmlDir = new File(reportGui.getInternalReportFolder() + "/html"); + // Search in report dir + if (reportDir.exists() && reportDir.isDirectory()) { + for (File individualReport : reportDir.listFiles()) { + String name = individualReport.getName(); + if (individualReport.exists() && individualReport.isFile() && !name.startsWith("summary") && !name.startsWith("report")) { + String id = name.substring(0, name.indexOf("-")); + if (!idsFound.contains(id)) { + individuals.add(new ReportIndividualGui(individualReport.getAbsolutePath(), count)); + idsFound.add(id); + count++; + } + } + } + } + // Search in html dir if no reports found + if (count == 0 && htmlDir.exists() && htmlDir.isDirectory()) { + for (File individualReport : htmlDir.listFiles()) { + String name = individualReport.getName(); + if (individualReport.exists() && individualReport.isFile() && !name.startsWith("summary") && !name.startsWith("report")) { + String id = name.substring(0, name.indexOf("-")); + if (!idsFound.contains(id)) { + individuals.add(new ReportIndividualGui(individualReport.getAbsolutePath(), count)); + idsFound.add(id); + count++; + } + } + } + } + return; + } + Configuration config = global.getConfig(); + String internal = reportGui.getInternalReportFolder(); + if (global.getVersion() >= 3) { + Integer count = 0; + for (SmallIndividualReport sir : global.getIndividualReports()) { + String serPath = sir.getSerPath(); + if (serPath == null || serPath.isEmpty()){ + String filenameNorm = sir.getFileName().replaceAll("\\\\", "/"); + String serFileName = sir.getIdReport() + "-" +filenameNorm.substring(filenameNorm.lastIndexOf("/") + 1) + ".ser"; + serPath = internal + "/serialized/" + serFileName; + } + File individualSer = new File(serPath); + if (individualSer.exists() && individualSer.isFile() && individualSer.getName().endsWith(".ser")){ + individuals.add(new ReportIndividualGui(global, sir, config, count)); + count++; + } + } + } else { + Integer count = 0; + File serializedDirectory = new File(internal + "/serialized"); + if (serializedDirectory.exists() && serializedDirectory.isDirectory()) { + for (File individualSer : serializedDirectory.listFiles()) { + if (individualSer.exists() && individualSer.isFile() && individualSer.getName().endsWith(".ser")) { + individuals.add(new ReportIndividualGui(individualSer.getAbsolutePath(), global, count)); + count++; + } + } + } + } + sortIndividuals(); + } + + public void sortIndividuals(){ + individuals.sort(new IndividualComparator(getView().getCurrentMode(), getView().getCurrentOrder())); + } + + public void loadAndPrintIndividuals(String vboxId, int page){ + int init = page * itemsPerPage; + int end = init + itemsPerPage; + int i = init; + while (i < individuals.size() && i < end) { + ReportIndividualGui rig = individuals.get(i); + rig.setLast(i == individuals.size() - 1 || i == end - 1); + getContext().send(GuiConfig.COMPONENT_GLOBAL, new GuiGlobalMessage(GuiGlobalMessage.Type.ADD_INDIVIDUAL, vboxId, rig)); + i++; + } + } + + public List getIndividualReports(){ + return individuals; + } + + public Integer getPagesCount(){ + int size = individuals.size(); + int pages = size / itemsPerPage; + if (size % itemsPerPage > 0) pages++; + return pages; + } + + /** + * Starts a new full check based on this quick check. + */ + public boolean transformReport(){ + GlobalReport global = getView().getInfo().getGlobalReport(); + Configuration config = new Configuration(global.getConfig()); + if (config.isQuick()){ + config.setQuick(false); + config.setFormats(new ArrayList<>(Arrays.asList("HTML"))); + List inputFiles = getInputFiles(getView().isErrors(), getView().isCorrect(), true); + List inputNotFound = getInputFiles(getView().isErrors(), getView().isCorrect(), false); + if (inputFiles.size() == 0) { + getContext().send(BasicConfig.MODULE_MESSAGE, new AlertMessage(AlertMessage.Type.INFO, getBundle().getString("filesEmpty"))); + } else { + getContext().send(BasicConfig.MODULE_CONFORMANCE, new ConformanceMessage(String.join(";", inputFiles), config, 100, false, false)); + return true; + } + if (inputNotFound.size() > 0) { + getContext().send(BasicConfig.MODULE_MESSAGE, new AlertMessage(AlertMessage.Type.ALERT, getBundle().getString("filesNotFound"), String.join("\n", inputNotFound))); + } + } + return false; + } + + private List getInputFiles(boolean err, boolean pas, boolean found){ + List inputFiles = new ArrayList<>(); + GlobalReport global = getView().getInfo().getGlobalReport(); + for (SmallIndividualReport individual : global.getIndividualReports()){ + int errors = 0; + int warnings = 0; + for (String iso : global.getSelectedIsos()){ + if (err && individual.getNErrors(iso) > 0) errors++; + else if (individual.getNWarnings(iso) > 0) warnings++; + } + if ((err && errors > 0) || (pas && errors == 0 && warnings == 0)) { + String filePath = readZipOrFilePath(global, individual.getFilePath()); + if (new File(filePath).exists() == found){ + if (!inputFiles.contains(filePath)){ + inputFiles.add(filePath); + } + } + } + } + return inputFiles; + } + + private String readZipOrFilePath(GlobalReport global, String filePath){ + for (String key : global.getZipsPaths().keySet()){ + if (filePath.contains("/" + key + "/") || filePath.contains("\\" + key + "\\")) { + return global.getZipsPaths().get(key); + } + } + return filePath; + } + + public void downloadReport(String path){ + File src = new File(path); + if (!src.exists() || !src.isFile()) return; + + String name = src.getName().substring(0, src.getName().indexOf(".")); + String extension = src.getName().substring(src.getName().indexOf(".")); + + FileChooser fileChooser = new FileChooser(); + + //Set extension filter + FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter(extension.toLowerCase().substring(1, extension.length() -1) + " files (*"+extension+")", "*" + extension); + fileChooser.getExtensionFilters().add(extFilter); + fileChooser.setInitialFileName(name); + + //Show save file dialog + File dest = fileChooser.showSaveDialog(GuiWorkbench.getMyStage()); + + if(dest != null){ + try { + FileUtils.copyFile(src, dest); + } catch (Exception e) { + getContext().send(BasicConfig.MODULE_MESSAGE, new AlertMessage(AlertMessage.Type.ERROR, getBundle().getString("errorSavingReport"))); + } + } + } + + public boolean allReportsDone(GlobalReport global, String internal, String format){ + if (global.getConfig().getFormats().contains(format.toUpperCase())) { + return true; + } + File htmlGlobal = new File(internal + File.separator + "report.html"); + String search = format.equals("mets") ? ".mets.xml" : "." + format; + File dir = format.equals("html") ? new File(internal + File.separator + "html") : new File(internal); + Integer expectedSize = global.getIndividualReports().size(); + if (!format.equals("mets") && !format.equals("html")) { + expectedSize += 1; + } + File[] files = dir.listFiles(new FilenameFilter() { + public boolean accept(File dir, String name) { + return name.toLowerCase().endsWith(search); + } + }); + if (files == null) return false; + int files_size = files.length; + if (format.equals("xml")){ + File[] filesMets = dir.listFiles(new FilenameFilter() { + public boolean accept(File dir, String name) { + return name.toLowerCase().endsWith(".mets.xml"); + } + }); + files_size -= filesMets.length; + } + return (format.equals("html") && files_size == expectedSize && htmlGlobal.exists()) || (!format.equals("html") && files_size == expectedSize); + } + + public boolean allReportsDone(GlobalReport global, String internal){ + return allReportsDone(global, internal, "html") && allReportsDone(global, internal, "xml") + && allReportsDone(global, internal, "pdf") && allReportsDone(global, internal, "mets") + && allReportsDone(global, internal, "json"); + } + +} diff --git a/src/main/java/dpfmanager/shell/interfaces/gui/component/global/GlobalModel.java b/src/main/java/dpfmanager/shell/interfaces/gui/component/global/GlobalModel.java new file mode 100644 index 00000000..bc8a0dff --- /dev/null +++ b/src/main/java/dpfmanager/shell/interfaces/gui/component/global/GlobalModel.java @@ -0,0 +1,45 @@ +/** + *

ReportsModel.java

This program is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as published by the Free Software + * Foundation, either version 3 of the License, or (at your option) any later version; or, at your + * choice, under the terms of the Mozilla Public License, v. 2.0. SPDX GPL-3.0+ or MPL-2.0+.

+ *

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License and the Mozilla Public License for more details.

You should + * have received a copy of the GNU General Public License and the Mozilla Public License along with + * this program. If not, see http://www.gnu.org/licenses/ + * and at http://mozilla.org/MPL/2.0 .

NB: for the + * © statement, include Easy Innova SL or other company/Person contributing the code.

© + * 2015 Easy Innova, SL

+ * + * @author Adria Llorens + * @version 1.0 + * @since 23/7/2015 + */ + +package dpfmanager.shell.interfaces.gui.component.global; + +import dpfmanager.shell.core.DPFManagerProperties; +import dpfmanager.shell.core.mvc.DpfModel; + +import org.jacpfx.rcp.context.Context; + +import java.util.ResourceBundle; + +/** + * Created by Adria Llorens on 04/03/2016. + */ +public class GlobalModel extends DpfModel { + + private Context context; + private ResourceBundle bundle; + + /** + * Constructor + */ + public GlobalModel(Context ctx) { + context = ctx; + bundle = DPFManagerProperties.getBundle(); + } + +} diff --git a/src/main/java/dpfmanager/shell/interfaces/gui/component/global/GlobalView.java b/src/main/java/dpfmanager/shell/interfaces/gui/component/global/GlobalView.java new file mode 100644 index 00000000..3e484adc --- /dev/null +++ b/src/main/java/dpfmanager/shell/interfaces/gui/component/global/GlobalView.java @@ -0,0 +1,815 @@ +/** + *

ReportsView.java

This program is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as published by the Free Software + * Foundation, either version 3 of the License, or (at your option) any later version; or, at your + * choice, under the terms of the Mozilla Public License, v. 2.0. SPDX GPL-3.0+ or MPL-2.0+.

+ *

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License and the Mozilla Public License for more details.

You should + * have received a copy of the GNU General Public License and the Mozilla Public License along with + * this program. If not, see http://www.gnu.org/licenses/ + * and at http://mozilla.org/MPL/2.0 .

NB: for the + * © statement, include Easy Innova SL or other company/Person contributing the code.

© + * 2015 Easy Innova, SL

+ * + * @author Adria Llorens + * @version 1.0 + * @since 23/7/2015 + */ + +package dpfmanager.shell.interfaces.gui.component.global; + +import dpfmanager.shell.core.config.BasicConfig; +import dpfmanager.shell.core.config.GuiConfig; +import dpfmanager.shell.core.messages.ArrayMessage; +import dpfmanager.shell.core.messages.DpfMessage; +import dpfmanager.shell.core.messages.NavMessage; +import dpfmanager.shell.core.messages.ShowMessage; +import dpfmanager.shell.core.messages.UiMessage; +import dpfmanager.shell.core.mvc.DpfView; +import dpfmanager.shell.core.util.NodeUtil; +import dpfmanager.shell.interfaces.gui.component.global.comparators.IndividualComparator; +import dpfmanager.shell.interfaces.gui.component.global.messages.GuiGlobalMessage; +import dpfmanager.shell.interfaces.gui.fragment.global.IndividualFragment; +import dpfmanager.shell.modules.conformancechecker.messages.ConformanceMessage; +import dpfmanager.shell.modules.messages.messages.AlertMessage; +import dpfmanager.shell.modules.report.core.GlobalReport; +import dpfmanager.shell.modules.report.util.ReportGui; +import dpfmanager.shell.modules.report.util.ReportIndividualGui; +import javafx.collections.FXCollections; +import javafx.collections.ObservableList; +import javafx.event.ActionEvent; +import javafx.event.EventHandler; +import javafx.fxml.FXML; +import javafx.scene.Cursor; +import javafx.scene.Node; +import javafx.scene.chart.PieChart; +import javafx.scene.control.Button; +import javafx.scene.control.CheckBox; +import javafx.scene.control.ContextMenu; +import javafx.scene.control.Control; +import javafx.scene.control.Label; +import javafx.scene.control.MenuItem; +import javafx.scene.control.Pagination; +import javafx.scene.control.ProgressIndicator; +import javafx.scene.control.Tooltip; +import javafx.scene.image.Image; +import javafx.scene.image.ImageView; +import javafx.scene.input.MouseButton; +import javafx.scene.input.MouseEvent; +import javafx.scene.layout.GridPane; +import javafx.scene.layout.HBox; +import javafx.scene.layout.StackPane; +import javafx.scene.layout.VBox; +import javafx.scene.paint.Color; +import javafx.stage.WindowEvent; +import javafx.util.Callback; + +import org.apache.commons.io.FileUtils; +import org.jacpfx.api.annotations.Resource; +import org.jacpfx.api.annotations.component.DeclarativeView; +import org.jacpfx.api.annotations.lifecycle.PostConstruct; +import org.jacpfx.rcp.componentLayout.FXComponentLayout; +import org.jacpfx.rcp.components.managedFragment.ManagedFragmentHandler; +import org.jacpfx.rcp.context.Context; + +import java.awt.*; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.ResourceBundle; + +/** + * Created by Adria Llorens on 25/02/2016. + */ +@DeclarativeView(id = GuiConfig.COMPONENT_GLOBAL, + name = GuiConfig.COMPONENT_GLOBAL, + viewLocation = "/fxml/global.fxml", + active = true, + resourceBundleLocation = "bundles.language", + initialTargetLayoutId = GuiConfig.TARGET_CONTAINER_GLOBAL) +public class GlobalView extends DpfView { + + @Resource + private Context context; + @Resource + private ResourceBundle bundle; + + private ReportGui info; + @FXML + private CheckBox htmlCheck; + @FXML + private CheckBox xmlCheck; + @FXML + private CheckBox metsCheck; + @FXML + private CheckBox pdfCheck; + @FXML + private CheckBox jsonCheck; + @FXML + private CheckBox checkError; + @FXML + private CheckBox checkCorrect; + + /** + * Global report elements + */ + @FXML + private ProgressIndicator progressGlobal; + @FXML + private VBox vboxGlobal; + @FXML + private ImageView globalImage; + @FXML + private Label resultLabel; + @FXML + private VBox globalVBox; + @FXML + private Label globalDate; + @FXML + private Label globalScore; + @FXML + private Label globalDuration; + @FXML + private Label globalFiles; + @FXML + private Label globalErrors; + @FXML + private Label globalWarnings; + @FXML + private Label globalPassed; + @FXML + private HBox globalScoreBox; + @FXML + private HBox globalFormatsBox; + @FXML + private HBox globalActionsBox; + + /** + * Individual reports elements + */ + @FXML + private GridPane gridHeadersFull; + @FXML + private GridPane gridHeadersQuick; + @FXML + private VBox individualsVBox; + @FXML + private Pagination pagination; + @FXML + private ProgressIndicator indicator; + @FXML + private StackPane gridStackPane; + @FXML + private Label labelOld; + + private Map> individualHandlers; + + @Override + public void sendMessage(String target, Object dpfMessage) { + context.send(target, dpfMessage); + } + + public Context getContext() { + return context; + } + + @Override + public void handleMessageOnWorker(DpfMessage message) { + if (message != null && message.isTypeOf(GuiGlobalMessage.class)) { + GuiGlobalMessage gMessage = message.getTypedMessage(GuiGlobalMessage.class); + if (gMessage.isRead()) { + individualHandlers = new HashMap<>(); + currentMode = IndividualComparator.Mode.ERRORS; + currentOrder = IndividualComparator.Order.DESC; + gMessage.getReportGui().load(); + getController().readIndividualReports(gMessage.getReportGui()); + } else if (gMessage.isAddIndividual()) { + gMessage.getReportIndividualGui().load(); + gMessage.getReportIndividualGui().loadFormats(); + } else if (gMessage.isSort()){ + getController().sortIndividuals(); + } + } + } + + @Override + public Node handleMessageOnFX(DpfMessage message) { + if (message != null && message.isTypeOf(GuiGlobalMessage.class)) { + GuiGlobalMessage gMessage = message.getTypedMessage(GuiGlobalMessage.class); + if (gMessage.isInit()) { + showLoading(); + gMessage.setType(GuiGlobalMessage.Type.READ); + context.send(gMessage); + } else if (gMessage.isRead()) { + initGlobalReport(gMessage.getReportGui()); + initPagination(); + } else if (gMessage.isAddIndividual()) { + addIndividualReport(gMessage.getVboxId(), gMessage.getReportIndividualGui()); + } else if (gMessage.isSort()){ + if (pagination.getCurrentPageIndex() != 0) { + pagination.setCurrentPageIndex(0); + } else { + reloadFirstPage(); + } + } + } else if (message != null && message.isTypeOf(AlertMessage.class)) { + AlertMessage am = message.getTypedMessage(AlertMessage.class); + if (am.hasResult() && am.getResult()) { + File dir = new File(info.getInternalReportFolder()); + try { + FileUtils.deleteDirectory(dir); + } catch (IOException e) { + e.printStackTrace(); + } + context.send(GuiConfig.PERSPECTIVE_REPORTS, new UiMessage()); + } + } else if (message != null && message.isTypeOf(UiMessage.class)) { + info.readFormats(); + addFormatIcons(info); + updateIndividualsReports(); + } + return null; + } + + @PostConstruct + public void onPostConstructComponent(FXComponentLayout layout, ResourceBundle resourceBundle) { + // Init MVC + setModel(new GlobalModel(context)); + setController(new GlobalController()); + getModel().setResourcebundle(bundle); + getController().setResourcebundle(bundle); + individualHandlers = new HashMap<>(); + pagination.setSkin(new PaginationBetterSkin(pagination)); + indicator.setProgress(-1); + progressGlobal.setProgress(-1); + } + + /** + * Global report + */ + private void initGlobalReport(ReportGui info) { + this.info = info; + NodeUtil.hideNode(gridHeadersQuick); + NodeUtil.hideNode(gridHeadersFull); + NodeUtil.hideNode(labelOld); + info.readFormats(); + if (info.getErrors() == 0) { + resultLabel.setText(bundle.getString("passedCheck")); + resultLabel.setTextFill(Color.YELLOWGREEN); + globalImage.setImage(new Image("images/icons/ok.png")); + } else { + resultLabel.setText(bundle.getString("errorCheck")); + resultLabel.setTextFill(Color.RED); + globalImage.setImage(new Image("images/icons/ko.png")); + } + globalDate.setText(info.getDate() + " " + info.getTime()); + globalScore.setText(info.getScore() + "%"); + globalFiles.setText(info.getNfiles() + ""); + globalErrors.setText(bundle.getString("errors").replace("%1", info.getErrors() + "")); + globalWarnings.setText(bundle.getString("passedWithWarnings").replace("%1", "" + info.getWarnings() + "")); + globalPassed.setText(bundle.getString("passed").replace("%1", "" + info.getPassed() + "")); + if (info.getGlobalReport() != null) { + globalDuration.setText(readableDuration(info.getGlobalReport())); + } + if (!isOldReport() && info.getGlobalReport().getConfig().isQuick()) { + NodeUtil.showNode(gridHeadersQuick); + } else { + NodeUtil.showNode(gridHeadersFull); + } + addChartScore(info); + addFormatIcons(info); + addActionsIcons(info); + showLoadingReports(); + } + + private String readableDuration(GlobalReport gr){ + return gr.getDurationHours() + ":" + gr.getDurationMinutes() + ":" + ((gr.getDurationMillis() > 500) ? gr.getDurationSeconds() + 1 : gr.getDurationSeconds()); + } + + private void addChartScore(ReportGui info) { + Double score = info.getScore() * 1.0; + + ObservableList pieChartData = + FXCollections.observableArrayList( + new PieChart.Data("Correct", score), + new PieChart.Data("Error", 100 - score)); + + PieChart chart = new PieChart(pieChartData); + chart.setId("pie_chart_global"); + chart.setMinSize(80, 80); + chart.setMaxSize(80, 80); + + globalScoreBox.getChildren().clear(); + globalScoreBox.getChildren().add(chart); + } + + private void addFormatIcons(ReportGui info) { + Map itemRead = info.getFormats(); + Integer version = info.getReportVersion(); + GlobalReport gr = info.getGlobalReport(); + globalFormatsBox.getChildren().clear(); + List sortedFormats = Arrays.asList("html", "pdf", "xml", "json"); + Map item = new HashMap<>(); + if (version > 0) { + // Transform reports + for (String format : sortedFormats) { + if (!item.containsKey(format)) + item.put(format, (itemRead.containsKey(format)) ? itemRead.get(format) : null); + } + } else { + item = itemRead; + } + for (String i : sortedFormats) { + if (!item.containsKey(i)) continue; + ImageView icon = new ImageView(); + icon.setId("but" + i); + icon.setFitHeight(35); + icon.setFitWidth(35); + icon.setCursor(Cursor.HAND); + icon.setImage(new Image("images/formats/" + i + ".png")); + Tooltip.install(icon, new Tooltip(i.toUpperCase())); + + String path = item.get(i); + ShowMessage sMessage = null; + if (path != null && new File(path).exists()) { + // Show directly + sMessage = new ShowMessage(i, path); + } else if (gr.getVersion() > 1) { + // Transformation need + icon.setOpacity(0.4); + icon.setOnMouseEntered(event -> icon.setOpacity(1.0)); + icon.setOnMouseExited(event -> icon.setOpacity(0.4)); + Long formatUuid = Long.parseLong(info.getUuid() + Character.getNumericValue(i.charAt(0))); + sMessage = new ShowMessage(formatUuid, i, info, true); + } + if (sMessage != null) { + final ShowMessage finalSMessage = sMessage; + icon.setOnMouseClicked(event -> { + if (event.getButton() == MouseButton.PRIMARY) { + ArrayMessage am = new ArrayMessage(); + am.add(GuiConfig.PERSPECTIVE_SHOW, new UiMessage(UiMessage.Type.SHOW)); + am.add(GuiConfig.PERSPECTIVE_SHOW + "." + GuiConfig.COMPONENT_NAV, new NavMessage(i)); + am.add(GuiConfig.PERSPECTIVE_SHOW + "." + GuiConfig.COMPONENT_SHOW, new ShowMessage(ShowMessage.Type.LOAD)); + am.add(GuiConfig.PERSPECTIVE_SHOW + "." + GuiConfig.COMPONENT_SHOW, finalSMessage); + context.send(GuiConfig.PERSPECTIVE_SHOW, am); + } + }); + + ContextMenu contextMenu = new ContextMenu(); + MenuItem itemShow = new MenuItem(bundle.getString("showReport")); + itemShow.setOnAction(new EventHandler() { + public void handle(ActionEvent e) { + ArrayMessage am = new ArrayMessage(); + am.add(GuiConfig.PERSPECTIVE_SHOW, new UiMessage(UiMessage.Type.SHOW)); + am.add(GuiConfig.PERSPECTIVE_SHOW + "." + GuiConfig.COMPONENT_NAV, new NavMessage(i)); + am.add(GuiConfig.PERSPECTIVE_SHOW + "." + GuiConfig.COMPONENT_SHOW, new ShowMessage(ShowMessage.Type.LOAD)); + am.add(GuiConfig.PERSPECTIVE_SHOW + "." + GuiConfig.COMPONENT_SHOW, finalSMessage); + context.send(GuiConfig.PERSPECTIVE_SHOW, am); + } + }); + MenuItem itemGenerate = new MenuItem(bundle.getString("generateReport")); + itemGenerate.setOnAction(new EventHandler() { + public void handle(ActionEvent e) { + ArrayMessage am = new ArrayMessage(); + am.add(GuiConfig.PERSPECTIVE_SHOW, new UiMessage(UiMessage.Type.SHOW)); + am.add(GuiConfig.PERSPECTIVE_SHOW + "." + GuiConfig.COMPONENT_NAV, new NavMessage(i)); + am.add(GuiConfig.PERSPECTIVE_SHOW + "." + GuiConfig.COMPONENT_SHOW, new ShowMessage(ShowMessage.Type.LOAD)); + am.add(GuiConfig.PERSPECTIVE_SHOW + "." + GuiConfig.COMPONENT_SHOW, finalSMessage); + context.send(GuiConfig.PERSPECTIVE_SHOW, am); + } + }); + MenuItem itemDownload = new MenuItem(bundle.getString("downloadReport")); + itemDownload.setOnAction(new EventHandler() { + public void handle(ActionEvent e) { + getController().downloadReport(path); + } + }); + + if (path == null) { + contextMenu.getItems().addAll(itemGenerate); + } else { + contextMenu.getItems().addAll(itemShow, itemDownload); + } + + icon.setOnContextMenuRequested(e -> contextMenu.show(icon, e.getScreenX(), e.getScreenY())); + globalFormatsBox.getChildren().add(icon); + } + } + } + + public void addActionsIcons(ReportGui info) { + globalActionsBox.getChildren().clear(); + String path = info.getDeletePath(); + Integer size = 25; + + // Open folder button + Button iconFolder = new Button(); + iconFolder.setMinHeight(size); + iconFolder.setPrefHeight(size); + iconFolder.setMaxHeight(size); + iconFolder.setMinWidth(size); + iconFolder.setPrefWidth(size); + iconFolder.setMaxWidth(size); + iconFolder.getStyleClass().addAll("folder-img", "icon-img"); + iconFolder.setCursor(Cursor.HAND); + iconFolder.setOnMouseClicked(new EventHandler() { + @Override + public void handle(MouseEvent event) { + // Open folder + File file = new File(path); + File dir = new File(file.getParent()); + if (Desktop.isDesktopSupported()) { + new Thread(() -> { + try { + Desktop.getDesktop().open(dir); + } catch (Exception e) { + e.printStackTrace(); + } + }).start(); + } + } + }); + globalActionsBox.getChildren().add(iconFolder); + + // Trash button + Button icon = new Button(); + icon.setMinHeight(size); + icon.setPrefHeight(size); + icon.setMaxHeight(size); + icon.setMinWidth(size); + icon.setPrefWidth(size); + icon.setMaxWidth(size); + icon.getStyleClass().addAll("delete-img", "icon-img"); + icon.setCursor(Cursor.HAND); + icon.setOnMouseClicked(new EventHandler() { + @Override + public void handle(MouseEvent event) { + // Alert confirmation + AlertMessage am = new AlertMessage(AlertMessage.Type.CONFIRMATION, bundle.getString("deleteConfirmationGlobal"), bundle.getString("deleteInfoGlobal")); + am.setTitle(bundle.getString("deleteTitle")); + getContext().send(BasicConfig.MODULE_MESSAGE, am); + } + }); + globalActionsBox.getChildren().add(icon); + } + + /** + * Individual reports + */ + + boolean paginationInitiated = false; + + public void initPagination() { + Integer oldPageCount = pagination.getPageCount(); + Integer oldPageIndex = pagination.getCurrentPageIndex(); + pagination.setPageCount(getController().getPagesCount()); + pagination.setCurrentPageIndex(0); + if (paginationInitiated) { + if (oldPageCount.equals(getController().getPagesCount()) && oldPageIndex.equals(0)) { + reloadFirstPage(); + } + } else { + paginationInitiated = true; + pagination.setPageFactory(new Callback() { + @Override + public Node call(Integer pageIndex) { + return createPage(pageIndex); + } + }); + } + } + + public void reloadFirstPage() { + Node node = pagination.lookup("#vboxIndividuals0"); + if (node != null) { + VBox vbox = (VBox) node; + vbox.getChildren().clear(); + getController().loadAndPrintIndividuals("#vboxIndividuals0", 0); + } + } + + public VBox createPage(Integer pageIndex) { + String id = "vboxIndividuals" + pageIndex; + VBox box = new VBox(); + box.setId(id); + box.setStyle("-fx-padding: 0 0 10 0;"); + getController().loadAndPrintIndividuals("#" + id, pageIndex); + return box; + } + + private void addIndividualReport(String vboxId, ReportIndividualGui rig) { + hideLoadingReports(); + Node node = pagination.lookup(vboxId); + if (node != null) { + VBox vbox = (VBox) node; + ManagedFragmentHandler handler; + if (individualHandlers.containsKey(rig.getId())) { + handler = individualHandlers.get(rig.getId()); + handler.getController().updateIcons(); + } else { + handler = context.getManagedFragmentHandler(IndividualFragment.class); + handler.getController().init(rig); + individualHandlers.put(rig.getId(), handler); + } + vbox.getChildren().add(handler.getFragmentNode()); + if (rig.isLast()) showBottom(); + } + } + + private void updateIndividualsReports() { + for (ManagedFragmentHandler handler : individualHandlers.values()) { + handler.getController().updateIcons(); + } + } + + private IndividualComparator.Mode currentMode; + private IndividualComparator.Order currentOrder; + + /** + * Quick sort + */ + @FXML + private HBox hboxNameQ; + @FXML + private HBox hboxPathQ; + @FXML + private HBox hboxResultQ; + + @FXML + protected void clickedColNameQ(MouseEvent event) throws Exception { + clickedCol(hboxNameQ, IndividualComparator.Mode.NAME); + } + + @FXML + protected void clickedColPathQ(MouseEvent event) throws Exception { + clickedCol(hboxPathQ, IndividualComparator.Mode.PATH); + } + + @FXML + protected void clickedColResultQ(MouseEvent event) throws Exception { + clickedCol(hboxResultQ, IndividualComparator.Mode.RESULT); + } + + /** + * Full sort + */ + @FXML + private HBox hboxNameF; + @FXML + private HBox hboxPathF; + @FXML + private HBox hboxResultF; + @FXML + private HBox hboxErrorsF; + @FXML + private HBox hboxWarningsF; + + @FXML + protected void clickedColNameF(MouseEvent event) throws Exception { + clickedCol(hboxNameF, IndividualComparator.Mode.NAME); + } + @FXML + protected void clickedColPathF(MouseEvent event) throws Exception { + clickedCol(hboxPathF, IndividualComparator.Mode.PATH); + } + @FXML + protected void clickedColResultF(MouseEvent event) throws Exception { + clickedCol(hboxResultF, IndividualComparator.Mode.RESULT); + } + @FXML + protected void clickedColErrorsF(MouseEvent event) throws Exception { + clickedCol(hboxErrorsF, IndividualComparator.Mode.ERRORS); + } + @FXML + protected void clickedColWarningsF(MouseEvent event) throws Exception { + clickedCol(hboxWarningsF, IndividualComparator.Mode.WARNINGS); + } + + private void clickedCol(HBox hbox, IndividualComparator.Mode mode){ + if (indicator.isVisible()) return; + + // Visual sort + removeArrows(); + if (currentMode.equals(mode)) { + swapOrder(); + } else { + currentOrder = getDefaultOrder(mode); + } + currentMode = mode; + addArrow(hbox); + + // Show loading + showLoadingReports(); + context.send(GuiConfig.COMPONENT_GLOBAL, new GuiGlobalMessage(GuiGlobalMessage.Type.SORT)); + } + + public void showLoading() { + showLoadingReports(); + NodeUtil.showNode(progressGlobal); + NodeUtil.hideNode(vboxGlobal); + } + + public void showLoadingReports() { + NodeUtil.showNode(vboxGlobal); + NodeUtil.hideNode(progressGlobal); + NodeUtil.hideNode(pagination); + NodeUtil.showNode(indicator); + NodeUtil.hideNode(labelOld); + hideBottom(); + } + + public void hideLoadingReports() { + NodeUtil.showNode(pagination); + NodeUtil.hideNode(indicator); + if (isOldReport()) { + NodeUtil.showNode(labelOld); + } else { + NodeUtil.hideNode(labelOld); + } + } + + private void addArrow(HBox hbox) { + String type = (currentOrder.equals(IndividualComparator.Order.ASC)) ? "up" : "down"; + ImageView icon = new ImageView(); + icon.setFitHeight(10); + icon.setFitWidth(10); + icon.setImage(new Image("images/icons/caret-" + type + ".png")); + hbox.getChildren().add(icon); + } + + private void removeArrows() { + hboxNameQ.getChildren().remove(1, hboxNameQ.getChildren().size()); + hboxResultQ.getChildren().remove(1, hboxResultQ.getChildren().size()); + hboxPathQ.getChildren().remove(1, hboxPathQ.getChildren().size()); + + hboxNameF.getChildren().remove(1, hboxNameF.getChildren().size()); + hboxErrorsF.getChildren().remove(1, hboxErrorsF.getChildren().size()); + hboxWarningsF.getChildren().remove(1, hboxWarningsF.getChildren().size()); + hboxResultF.getChildren().remove(1, hboxResultF.getChildren().size()); + hboxPathF.getChildren().remove(1, hboxPathF.getChildren().size()); + } + + public IndividualComparator.Order getDefaultOrder(IndividualComparator.Mode mode){ + if (mode.equals(IndividualComparator.Mode.NAME)) return IndividualComparator.Order.ASC; + return IndividualComparator.Order.DESC; + } + + /** + * Generate all reports + */ + + @FXML + private VBox vboxGenerators; + @FXML + private VBox vboxTransforms; + @FXML + private Button buttonTransforms; + @FXML + private Button buttonGenerate; + + @FXML + protected void showGenerate(ActionEvent event) throws Exception { + boolean checked = getController().allReportsDone(info.getGlobalReport(), info.getInternalReportFolder(), "html"); + htmlCheck.setSelected(checked); + htmlCheck.setDisable(checked); + checked = getController().allReportsDone(info.getGlobalReport(), info.getInternalReportFolder(), "xml"); + xmlCheck.setSelected(checked); + xmlCheck.setDisable(checked); + checked = getController().allReportsDone(info.getGlobalReport(), info.getInternalReportFolder(), "mets"); + metsCheck.setSelected(checked); + metsCheck.setDisable(checked); + checked = getController().allReportsDone(info.getGlobalReport(), info.getInternalReportFolder(), "json"); + jsonCheck.setSelected(checked); + jsonCheck.setDisable(checked); + checked = getController().allReportsDone(info.getGlobalReport(), info.getInternalReportFolder(), "pdf"); + pdfCheck.setSelected(checked); + pdfCheck.setDisable(checked); + NodeUtil.showNode(vboxGenerators); + NodeUtil.hideNode(buttonGenerate); + } + + @FXML + protected void showTransform(ActionEvent event) throws Exception { + checkError.setSelected(true); + checkCorrect.setSelected(false); + NodeUtil.showNode(vboxTransforms); + NodeUtil.hideNode(buttonTransforms); + } + + @FXML + protected void hideGenerate(ActionEvent event) throws Exception { + hideGenerate(); + } + + private void hideGenerate() { + NodeUtil.hideNode(vboxGenerators); + NodeUtil.showNode(buttonGenerate); + } + + @FXML + protected void hideTransforms(ActionEvent event) throws Exception { + hideTransforms(); + } + + private void hideTransforms() { + NodeUtil.hideNode(vboxTransforms); + NodeUtil.showNode(buttonTransforms); + } + + @FXML + protected void generateReportsClicked(ActionEvent event) throws Exception { + String uuidStr = info.getUuid(); + for (String i : getSelectedFormats()) { + uuidStr += getNumericValue(i.charAt(0)); + } + ShowMessage sMessage = new ShowMessage(Long.parseLong(uuidStr), getSelectedFormats(), info, false); + ArrayMessage am = new ArrayMessage(); + am.add(GuiConfig.PERSPECTIVE_SHOW, new UiMessage()); + am.add(GuiConfig.PERSPECTIVE_SHOW + "." + GuiConfig.COMPONENT_SHOW, sMessage); + context.send(GuiConfig.PERSPECTIVE_SHOW, am); + hideGenerate(); + } + + @FXML + protected void transformReports(ActionEvent event) throws Exception { + if (getController().transformReport()) { + context.send(GuiConfig.PERSPECTIVE_GLOBAL + "." + GuiConfig.COMPONENT_NAV, new NavMessage(NavMessage.Selected.RELOAD)); + hideTransforms(); + } + } + + private void hideBottom(){ + NodeUtil.hideNode(vboxTransforms); + NodeUtil.hideNode(buttonTransforms); + NodeUtil.hideNode(vboxGenerators); + NodeUtil.hideNode(buttonGenerate); + } + + private void showBottom(){ + if (!isOldReport()){ + if (info.getGlobalReport().getConfig().isQuick()){ + NodeUtil.showNode(buttonTransforms); + } + if (!getController().allReportsDone(info.getGlobalReport(), info.getInternalReportFolder())) { + NodeUtil.showNode(buttonGenerate); + } + } + } + + private String getNumericValue(Character ch) { + if (ch.equals('h')) return "1"; + if (ch.equals('x')) return "2"; + if (ch.equals('m')) return "3"; + if (ch.equals('p')) return "4"; + if (ch.equals('j')) return "5"; + return "0"; + } + + public List getSelectedFormats() { + List formats = new ArrayList<>(); + if (!htmlCheck.isDisable() && htmlCheck.isSelected()) formats.add("html"); + if (!xmlCheck.isDisable() && xmlCheck.isSelected()) formats.add("xml"); + if (!metsCheck.isDisable() && metsCheck.isSelected()) formats.add("mets"); + if (!pdfCheck.isDisable() && pdfCheck.isSelected()) formats.add("pdf"); + if (!jsonCheck.isDisable() && jsonCheck.isSelected()) formats.add("json"); + return formats; + } + + private void swapOrder(){ + if (currentOrder.equals(IndividualComparator.Order.ASC)) { + currentOrder = IndividualComparator.Order.DESC; + } else { + currentOrder = IndividualComparator.Order.ASC; + } + } + + public IndividualComparator.Mode getCurrentMode() { + return currentMode; + } + + public IndividualComparator.Order getCurrentOrder() { + return currentOrder; + } + + public ReportGui getInfo() { + return info; + } + + public boolean isErrors(){ + return checkError.isSelected(); + } + + public boolean isCorrect(){ + return checkCorrect.isSelected(); + } + + public boolean isOldReport() { + return info.getGlobalReport() == null; + } + +} diff --git a/src/main/java/dpfmanager/shell/interfaces/gui/component/global/PaginationBetterSkin.java b/src/main/java/dpfmanager/shell/interfaces/gui/component/global/PaginationBetterSkin.java new file mode 100644 index 00000000..f9a331c0 --- /dev/null +++ b/src/main/java/dpfmanager/shell/interfaces/gui/component/global/PaginationBetterSkin.java @@ -0,0 +1,110 @@ +package dpfmanager.shell.interfaces.gui.component.global; + +import dpfmanager.shell.core.util.NodeUtil; +import javafx.beans.binding.Bindings; +import javafx.collections.ListChangeListener; +import javafx.scene.Node; +import javafx.scene.control.Button; +import javafx.scene.control.Label; +import javafx.scene.control.Pagination; +import javafx.scene.layout.HBox; +import javafx.scene.layout.StackPane; + +import com.sun.javafx.scene.control.skin.PaginationSkin; + +/** + * Created by Adrià Llorens on 06/07/2017. + */ +public class PaginationBetterSkin extends PaginationSkin { + + private HBox controlBox; + private Label pageInformation; + private Node controlNav; + private Button prev; + private Button next; + private Button first; + private Button last; + + /** + * @param pagination + */ + public PaginationBetterSkin(Pagination pagination) { + super(pagination); + patchNavigation(); + } + + private void patchNavigation() { + Pagination pagination = getSkinnable(); + Node control = pagination.lookup(".control-box"); + Node navControl = pagination.lookup(".pagination-control"); + if (!(control instanceof HBox) || navControl == null) return; + + controlBox = (HBox) control; + controlNav = navControl; + prev = (Button) controlBox.getChildren().get(0); + next = (Button) controlBox.getChildren().get(controlBox.getChildren().size() - 1); + + // Remove label + pageInformation = (Label) pagination.lookup(".page-information"); + pageInformation.setMinHeight(0.0); + pageInformation.setPrefHeight(0.0); + pageInformation.setMaxHeight(0.0); + + first = new Button(""); + first.getStyleClass().add("arrows-buttons"); + first.setGraphic(createArrows("left-arrow")); + first.setOnAction(e -> { + pagination.setCurrentPageIndex(0); + }); + first.disableProperty().bind(pagination.currentPageIndexProperty().isEqualTo(0)); + + last = new Button(""); + last.getStyleClass().add("arrows-buttons"); + last.setGraphic(createArrows("right-arrow")); + last.setOnAction(e -> { + pagination.setCurrentPageIndex(pagination.getPageCount()); + }); + last.disableProperty().bind(pagination.currentPageIndexProperty().isEqualTo(Bindings.add(-1,pagination.pageCountProperty()))); + + ListChangeListener childrenListener = c -> { + while (c.next()) { + // implementation detail: when nextButton is added, the setup is complete + if (c.wasAdded() && !c.wasRemoved() // real addition + && c.getAddedSize() == 1 // single addition + && c.getAddedSubList().get(0) == next) { + addCustomNodes(); + } + } + }; + controlBox.getChildren().addListener(childrenListener); + addCustomNodes(); + } + + private Node createArrows(String clazz){ + StackPane arrow1 = new StackPane(); + arrow1.getStyleClass().add(clazz); + StackPane arrow2 = new StackPane(); + arrow2.getStyleClass().add(clazz); + HBox hbox = new HBox(); + hbox.setMinHeight(9.0); + hbox.setPrefHeight(9.0); + hbox.setMaxHeight(9.0); + hbox.getChildren().addAll(arrow1, arrow2); + return hbox; + } + + protected void addCustomNodes() { + if (getSkinnable().getPageCount() == 1) { + NodeUtil.hideNode(controlNav); + } else { + NodeUtil.showNode(controlNav); + NodeUtil.hideNode(pageInformation); + } + + if (first.getParent() != controlBox) { + controlBox.getChildren().add(0, first); + controlBox.getChildren().add(last); + } + } + +} diff --git a/src/main/java/dpfmanager/shell/interfaces/gui/component/global/comparators/IndividualComparator.java b/src/main/java/dpfmanager/shell/interfaces/gui/component/global/comparators/IndividualComparator.java new file mode 100644 index 00000000..26d70fac --- /dev/null +++ b/src/main/java/dpfmanager/shell/interfaces/gui/component/global/comparators/IndividualComparator.java @@ -0,0 +1,102 @@ +package dpfmanager.shell.interfaces.gui.component.global.comparators; + +import dpfmanager.shell.modules.report.util.ReportIndividualGui; +import dpfmanager.shell.modules.statistics.model.StatisticsIso; + +import java.util.Comparator; + +/** + * Created by Adrià Llorens on 26/05/2017. + */ +public class IndividualComparator implements Comparator { + + public enum Mode { + ERRORS, WARNINGS, NAME, RESULT, PATH + } + + public enum Order { + ASC, DESC + } + + private Mode mode; + + private Order order; + + public IndividualComparator(Mode m, Order o){ + mode = m; + order = o; + } + + /** + * Negative = o1 < o2 + * Positive = o1 > o2 + */ + @Override + public int compare(ReportIndividualGui o1, ReportIndividualGui o2) { + if (!mode.equals(Mode.NAME)) { + o1.load(); + o2.load(); + } + Integer compare = 0; + switch (mode){ + case ERRORS: + if (order.equals(Order.ASC)){ + compare = o1.getErrors().compareTo(o2.getErrors()); + } else { + compare = o2.getErrors().compareTo(o1.getErrors()); + } + break; + case WARNINGS: + if (order.equals(Order.ASC)){ + if (onlyWarnigns(o1) && !onlyWarnigns(o2)) { + compare = -1; + } else if (!onlyWarnigns(o1) && onlyWarnigns(o2)) { + compare = 1; + } else { + compare = o1.getWarnings().compareTo(o2.getWarnings()); + } + } else { + if (onlyWarnigns(o1) && !onlyWarnigns(o2)) { + compare = -1; + } else if (!onlyWarnigns(o1) && onlyWarnigns(o2)) { + compare = 1; + } else { + compare = o2.getWarnings().compareTo(o1.getWarnings()); + } + } + break; + case RESULT: + if (order.equals(Order.ASC)){ + compare = o1.getErrors().compareTo(o2.getErrors()); + } else { + compare = o2.getErrors().compareTo(o1.getErrors()); + } + break; + case NAME: + if (order.equals(Order.ASC)){ + compare = o1.getLowerName().compareTo(o2.getLowerName()); + } else { + compare = o2.getLowerName().compareTo(o1.getLowerName()); + } + break; + case PATH: + if (order.equals(Order.ASC)){ + compare = o1.getShowFilePath().toLowerCase().compareTo(o2.getShowFilePath().toLowerCase()); + } else { + compare = o2.getShowFilePath().toLowerCase().compareTo(o1.getShowFilePath().toLowerCase()); + } + break; + } + + // If equals, default NAME ASC + if (compare == 0){ + compare = o1.getLowerName().compareTo(o2.getLowerName()); + } + return compare; + } + + private boolean onlyWarnigns(ReportIndividualGui o) { + return o.getErrors() == 0 && o.getWarnings() > 0; + } + +} diff --git a/src/main/java/dpfmanager/shell/interfaces/gui/component/global/messages/GuiGlobalMessage.java b/src/main/java/dpfmanager/shell/interfaces/gui/component/global/messages/GuiGlobalMessage.java new file mode 100644 index 00000000..0002f29a --- /dev/null +++ b/src/main/java/dpfmanager/shell/interfaces/gui/component/global/messages/GuiGlobalMessage.java @@ -0,0 +1,90 @@ +/** + *

GlobalReportMessage.java

This program is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as published by the Free + * Software Foundation, either version 3 of the License, or (at your option) any later version; or, + * at your choice, under the terms of the Mozilla Public License, v. 2.0. SPDX GPL-3.0+ or MPL-2.0+. + *

This program is distributed in the hope that it will be useful, but WITHOUT ANY + * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + * PURPOSE. See the GNU General Public License and the Mozilla Public License for more details.

+ *

You should have received a copy of the GNU General Public License and the Mozilla Public + * License along with this program. If not, see http://www.gnu.org/licenses/ + * and at http://mozilla.org/MPL/2.0 .

NB: for the + * © statement, include Easy Innova SL or other company/Person contributing the code.

© + * 2015 Easy Innova, SL

+ * + * @author Adria Llorens + * @version 1.0 + * @since 23/7/2015 + */ + +package dpfmanager.shell.interfaces.gui.component.global.messages; + +import dpfmanager.shell.core.messages.DpfMessage; +import dpfmanager.shell.modules.report.util.ReportGui; +import dpfmanager.shell.modules.report.util.ReportIndividualGui; + +/** + * Created by Adria Llorens on 24/03/2016. + */ +public class GuiGlobalMessage extends DpfMessage { + + public enum Type { + INIT, SORT, ADD_INDIVIDUAL, READ + } + + private Type type; + private ReportGui reportGui; + private String vboxId; + private ReportIndividualGui reportIndividualGui; + + // Init + public GuiGlobalMessage(Type t, ReportGui rg) { + type = t; + reportGui = rg; + } + + // Add individual + public GuiGlobalMessage(Type t, String i, ReportIndividualGui rig) { + type = t; + vboxId = i; + reportIndividualGui = rig; + } + + // Sort + public GuiGlobalMessage(Type t) { + type = t; + } + + // Read + public void setType(Type type) { + this.type = type; + } + + public boolean isInit(){ + return type.equals(Type.INIT); + } + + public boolean isRead(){ + return type.equals(Type.READ); + } + + public boolean isSort(){ + return type.equals(Type.SORT); + } + + public boolean isAddIndividual(){ + return type.equals(Type.ADD_INDIVIDUAL); + } + + public ReportGui getReportGui() { + return reportGui; + } + + public ReportIndividualGui getReportIndividualGui() { + return reportIndividualGui; + } + + public String getVboxId() { + return vboxId; + } +} diff --git a/src/main/java/dpfmanager/shell/interfaces/gui/component/report/ReportsController.java b/src/main/java/dpfmanager/shell/interfaces/gui/component/report/ReportsController.java index aabfbec7..93c1f0dc 100644 --- a/src/main/java/dpfmanager/shell/interfaces/gui/component/report/ReportsController.java +++ b/src/main/java/dpfmanager/shell/interfaces/gui/component/report/ReportsController.java @@ -20,7 +20,11 @@ package dpfmanager.shell.interfaces.gui.component.report; import dpfmanager.shell.core.DPFManagerProperties; +import dpfmanager.shell.core.messages.ReportsMessage; import dpfmanager.shell.core.mvc.DpfController; +import dpfmanager.shell.interfaces.gui.component.report.comparators.ReportsComparator; +import dpfmanager.shell.modules.report.core.ReportGenerator; +import dpfmanager.shell.modules.report.util.ReportGui; import org.apache.commons.io.FileUtils; import org.apache.commons.io.filefilter.DirectoryFileFilter; @@ -29,14 +33,24 @@ import java.io.FileFilter; import java.time.LocalDate; import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; /** * Created by Adria Llorens on 07/03/2016. */ public class ReportsController extends DpfController { - public ReportsController() { + public static Integer itemsPerPage = 15; + + private Map dataCache; + private List data; + public ReportsController() { + data = new ArrayList<>(); + dataCache = new HashMap<>(); } public boolean clearReports(LocalDate date) { @@ -62,4 +76,67 @@ private LocalDate parseFolderName(String folder) { } } + public void readReports(){ + data.clear(); + String baseDir = ReportGenerator.getReportsFolder(); + File reportsDir = new File(baseDir); + if (reportsDir.exists()) { + String[] directories = reportsDir.list((current, name) -> new File(current, name).isDirectory()); + for (int i = 0; i < directories.length; i++) { + String reportDay = directories[i]; + File reportDayFile = new File(baseDir + "/" + reportDay); + String[] directoriesDay = reportDayFile.list((current, name) -> new File(current, name).isDirectory()); + for (int j = 0; j < directoriesDay.length; j++) { + String reportDir = directoriesDay[j]; + ReportGui rg = new ReportGui(baseDir, reportDay, reportDir); + if (dataCache.containsKey(rg.getUuid())) { + data.add(dataCache.get(rg.getUuid())); + } else if (rg.exists()) { + dataCache.put(rg.getUuid(), rg); + data.add(rg); + } + } + } + } + sortReports(); + } + + public void removeReport(String uuid){ + ReportGui rg = dataCache.get(uuid); + if (rg != null){ + data.remove(rg); + dataCache.remove(uuid); + } + } + + public void sortReports(){ + data.sort(new ReportsComparator(getView().getCurrentMode(), getView().getCurrentOrder())); + } + + public void loadAndPrintReports(String vboxId, int page){ + int init = page * itemsPerPage; + int end = init + itemsPerPage; + int i = init; + while (i < data.size() && i < end) { + ReportGui rg = data.get(i); + rg.setLast(i == data.size() - 1 || i == end - 1); + getContext().send(new ReportsMessage(ReportsMessage.Type.ADD, vboxId, rg)); + i++; + } + } + + public Integer getPagesCount(){ + int size = data.size(); + int pages = size / itemsPerPage; + if (size % itemsPerPage > 0) pages++; + return pages; + } + + public boolean isEmpty() { + return data.isEmpty(); + } + + public void clearData() { + data.clear(); + } } diff --git a/src/main/java/dpfmanager/shell/interfaces/gui/component/report/ReportsModel.java b/src/main/java/dpfmanager/shell/interfaces/gui/component/report/ReportsModel.java index 129fbcdf..21078556 100644 --- a/src/main/java/dpfmanager/shell/interfaces/gui/component/report/ReportsModel.java +++ b/src/main/java/dpfmanager/shell/interfaces/gui/component/report/ReportsModel.java @@ -49,121 +49,24 @@ public class ReportsModel extends DpfModel { private Context context; private ResourceBundle bundle; - private Map dataCache; - private SortedSet data; - private List> reportsFragments; - - private int reports_loaded = 0; - public static int reports_to_load = 25; - /** * Constructor */ public ReportsModel(Context ctx) { context = ctx; + sizeTime = 0L; bundle = DPFManagerProperties.getBundle(); - data = new TreeSet<>(); - reportsFragments = new ArrayList<>(); - dataCache = new HashMap<>(); - loadReportsFromDir(); - } - - public void addReportFragment(ManagedFragmentHandler handler) { - reportsFragments.add(handler); - } - - public void removeReportFragment(ManagedFragmentHandler handler) { - reportsFragments.remove(handler); - } - - public ManagedFragmentHandler getReportGuiByUuid(String uuid) { - for (ManagedFragmentHandler handler : reportsFragments) { - if (handler.getController().getUuid().equals(uuid)) { - return handler; - } - } - return null; - } - - public void loadReportsFromDir() { - data.clear(); - String baseDir = ReportGenerator.getReportsFolder(); - File reportsDir = new File(baseDir); - if (reportsDir.exists()) { - String[] directories = reportsDir.list((current, name) -> new File(current, name).isDirectory()); - for (int i = 0; i < directories.length; i++) { - String reportDay = directories[i]; - File reportDayFile = new File(baseDir + "/" + reportDay); - String[] directoriesDay = reportDayFile.list((current, name) -> new File(current, name).isDirectory()); - for (int j = 0; j < directoriesDay.length; j++) { - String reportDir = directoriesDay[j]; - ReportGui rg = new ReportGui(baseDir, reportDay, reportDir); - if (dataCache.containsKey(rg.getTimestamp())) { - data.add(dataCache.get(rg.getTimestamp())); - } else if (rg.exists()) { - dataCache.put(rg.getTimestamp(), rg); - data.add(rg); - } - } - } - } - } - - public void removeReport(ReportGui rg) { - if (data.contains(rg)) { - data.remove(rg); - } - } - - public void printReports() { - printReports(0, reports_to_load); - } - - public void printMoreReports() { - printReports(reports_loaded, reports_loaded + reports_to_load); - } - - public void printReports(int from, int to) { - int index = 0; - int loaded = 0; - Iterator it = data.iterator(); - while (it.hasNext()) { - ReportGui rg = it.next(); - if (index >= from && index < to) { - rg.load(); - rg.setLast(!it.hasNext() || index == to - 1); - getView().getContext().send(new ReportsMessage(ReportsMessage.Type.ADD, rg)); - reports_loaded++; - loaded++; - } - index++; - } - if (loaded == 0) { - getView().hideLoading(); - getView().calculateMinHeight(); - } - } - - public boolean isAllReportsLoaded() { - return reports_loaded == data.size(); - } - - public boolean isEmpty() { - return data.isEmpty(); - } - - public void clearData() { - data.clear(); - } - - public void clearReportsLoaded() { - reports_loaded = 0; } private Long reportsSize; + private Long sizeTime; public void readReportsSize() { - reportsSize = FileUtils.sizeOfDirectory(new File(DPFManagerProperties.getReportsDir())); + Long currentTime = System.currentTimeMillis(); + if ((currentTime - sizeTime) > 60000L){ + reportsSize = FileUtils.sizeOfDirectory(new File(DPFManagerProperties.getReportsDir())); + sizeTime = currentTime; + } } public Long getReportsSize() { diff --git a/src/main/java/dpfmanager/shell/interfaces/gui/component/report/ReportsView.java b/src/main/java/dpfmanager/shell/interfaces/gui/component/report/ReportsView.java index 39863bd4..85045254 100644 --- a/src/main/java/dpfmanager/shell/interfaces/gui/component/report/ReportsView.java +++ b/src/main/java/dpfmanager/shell/interfaces/gui/component/report/ReportsView.java @@ -25,23 +25,29 @@ import dpfmanager.shell.core.messages.ReportsMessage; import dpfmanager.shell.core.mvc.DpfView; import dpfmanager.shell.core.util.NodeUtil; +import dpfmanager.shell.interfaces.gui.component.global.PaginationBetterSkin; +import dpfmanager.shell.interfaces.gui.component.global.comparators.IndividualComparator; +import dpfmanager.shell.interfaces.gui.component.report.comparators.ReportsComparator; import dpfmanager.shell.interfaces.gui.fragment.ReportFragment; import dpfmanager.shell.modules.messages.messages.AlertMessage; import dpfmanager.shell.modules.report.util.ReportGui; -import dpfmanager.shell.modules.statistics.messages.StatisticsMessage; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.Node; import javafx.scene.control.Button; import javafx.scene.control.DatePicker; import javafx.scene.control.Label; +import javafx.scene.control.Pagination; import javafx.scene.control.ProgressIndicator; import javafx.scene.control.RadioButton; -import javafx.scene.control.ScrollPane; import javafx.scene.control.ToggleGroup; +import javafx.scene.image.Image; +import javafx.scene.image.ImageView; +import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; +import javafx.util.Callback; import org.jacpfx.api.annotations.Resource; import org.jacpfx.api.annotations.component.DeclarativeView; @@ -52,6 +58,8 @@ import java.text.DecimalFormat; import java.time.LocalDate; +import java.util.HashMap; +import java.util.Map; import java.util.ResourceBundle; /** @@ -76,14 +84,14 @@ public class ReportsView extends DpfView { @FXML private AnchorPane paneStatistics; @FXML - private ScrollPane scrollPane; + private Pagination pagination; + @FXML + private Button reloadButton2; // View elements @FXML private VBox reportsVbox; @FXML - private Button loadMore; - @FXML private VBox vboxReports; @FXML private Label labelEmpty; @@ -94,7 +102,7 @@ public class ReportsView extends DpfView { @FXML private HBox hboxSize; @FXML - private HBox hboxOptions; + private VBox hboxOptions; @FXML private Button clearOptionsButton; @FXML @@ -106,6 +114,8 @@ public class ReportsView extends DpfView { @FXML private DatePicker datePicker; + private Map> reportHandlers; + @Override public void sendMessage(String target, Object dpfMessage) { context.send(target, dpfMessage); @@ -116,10 +126,15 @@ public void handleMessageOnWorker(DpfMessage message) { if (message != null && message.isTypeOf(ReportsMessage.class)) { ReportsMessage rMessage = message.getTypedMessage(ReportsMessage.class); if (rMessage.isRead()) { - getModel().loadReportsFromDir(); - getModel().printReports(); + currentMode = ReportsComparator.Mode.DATE; + currentOrder = ReportsComparator.Order.DESC; + getController().readReports(); } else if (rMessage.isSize()) { getModel().readReportsSize(); + } else if (rMessage.isAdd()) { + rMessage.getReportGui().load(); + } else if (rMessage.isSort()){ + getController().sortReports(); } } } @@ -130,17 +145,24 @@ public Node handleMessageOnFX(DpfMessage message) { ReportsMessage rMessage = message.getTypedMessage(ReportsMessage.class); if (rMessage.isReload()) { showLoading(); - mainVBox.getChildren().clear(); - getModel().clearReportsLoaded(); context.send(new ReportsMessage(ReportsMessage.Type.READ)); } else if (rMessage.isRead()) { - loadReportsSize(); + initPagination(); + if (getController().isEmpty()) { + hideLoading(); + } } else if (rMessage.isSize()) { printSize(getModel().getReportsSize()); } else if (rMessage.isDelete()) { deleteReportGui(rMessage.getUuid()); } else if (rMessage.isAdd()) { - addReportGui(rMessage.getReportGui()); + addReportGui(rMessage.getVboxId(), rMessage.getReportGui()); + } else if (rMessage.isSort()){ + if (pagination.getCurrentPageIndex() != 0) { + pagination.setCurrentPageIndex(0); + } else { + reloadPage(0); + } } } return null; @@ -153,35 +175,8 @@ public void onPostConstructComponent(FXComponentLayout layout, ResourceBundle re setController(new ReportsController()); getModel().setResourcebundle(bundle); hideClearOptions(); - } - - public void addReportGui(ReportGui row) { - ManagedFragmentHandler handler = getModel().getReportGuiByUuid(row.getUuid()); - if (handler == null){ - if (row.isLoaded()){ - handler = context.getManagedFragmentHandler(ReportFragment.class); - getModel().addReportFragment(handler); - handler.getController().init(row); - } - } else { - handler.getController().updateIcons(); - } - if (row.isLoaded()) { - if (!mainVBox.getChildren().contains(handler.getFragmentNode())){ - mainVBox.getChildren().add(handler.getFragmentNode()); - hideLoading(); - } - } - calculateMinHeight(); - } - - private void deleteReportGui(String uuid) { - ManagedFragmentHandler toDelete = getModel().getReportGuiByUuid(uuid); - if (toDelete != null) { - mainVBox.getChildren().remove(toDelete.getFragmentNode()); - getModel().removeReport(toDelete.getController().getInfo()); - getModel().removeReportFragment(toDelete); - } + reportHandlers = new HashMap<>(); + pagination.setSkin(new PaginationBetterSkin(pagination)); } /** @@ -217,42 +212,30 @@ private void showLoading() { indicator.setProgress(-1.0); NodeUtil.showNode(indicator); NodeUtil.hideNode(vboxReports); + NodeUtil.hideNode(reloadButton2); + NodeUtil.hideNode(pagination); NodeUtil.hideNode(labelEmpty); - NodeUtil.hideNode(loadMore); NodeUtil.hideNode(hboxSize); } public void hideLoading() { NodeUtil.hideNode(indicator); NodeUtil.showNode(vboxReports); + NodeUtil.showNode(reloadButton2); - if (getModel().isEmpty()) { - NodeUtil.hideNode(loadMore); + if (getController().isEmpty()) { NodeUtil.showNode(labelEmpty); NodeUtil.hideNode(hboxSize); - } else if (getModel().isAllReportsLoaded()) { - NodeUtil.hideNode(labelEmpty); - NodeUtil.hideNode(loadMore); - NodeUtil.showNode(hboxSize); + NodeUtil.hideNode(pagination); } else { - NodeUtil.showNode(loadMore); NodeUtil.showNode(hboxSize); NodeUtil.hideNode(labelEmpty); + NodeUtil.showNode(pagination); } } - public void calculateMinHeight(){ - int currentRows = mainVBox.getChildren().size(); - int rows = (currentRows > 16) ? 16 : currentRows; - int height = 2 + rows * 30; - scrollPane.setMinHeight(height); - scrollPane.setMaxHeight(height); - scrollPane.setPrefHeight(height); - } - @FXML protected void loadMoreReports(ActionEvent event) throws Exception { - getModel().printMoreReports(); } @FXML @@ -266,6 +249,7 @@ protected void clearOptions(ActionEvent event) throws Exception { hideClearOptions(); } else { showClearOptions(); + loadReportsSize(); } } @@ -285,7 +269,7 @@ protected void clearReports(ActionEvent event) throws Exception { // All ok, delete if (getController().clearReports(date)){ - getModel().clearData(); + getController().clearData(); showLoading(); hideClearOptions(); getContext().send(new ReportsMessage(ReportsMessage.Type.READ)); @@ -300,12 +284,187 @@ public ToggleGroup getToggleClear() { return toggleClear; } - public void hideLoadMore() { - NodeUtil.hideNode(loadMore); - } - public Context getContext() { return context; } + /** + * Pagination + */ + + boolean paginationInitiated = false; + + public void initPagination() { + Integer oldPageCount = pagination.getPageCount(); + Integer oldPageIndex = pagination.getCurrentPageIndex(); + pagination.setPageCount(getController().getPagesCount()); + pagination.setCurrentPageIndex(0); + if (paginationInitiated) { + if (oldPageCount.equals(getController().getPagesCount()) && oldPageIndex.equals(0)) { + reloadPage(0); + } + } else { + paginationInitiated = true; + pagination.setPageFactory(new Callback() { + @Override + public Node call(Integer pageIndex) { + return createPage(pageIndex); + } + }); + } + } + + public VBox createPage(Integer pageIndex) { + String id = "vboxReports" + pageIndex; + VBox box = new VBox(); + box.setId(id); + box.setStyle("-fx-padding: 0 0 10 0;"); + getController().loadAndPrintReports("#" + id, pageIndex); + return box; + } + + public void addReportGui(String vboxId, ReportGui row) { + hideLoading(); + Node node = pagination.lookup(vboxId); + if (node != null) { + VBox vbox = (VBox) node; + ManagedFragmentHandler handler; + if (reportHandlers.containsKey(row.getUuid())) { + handler = reportHandlers.get(row.getUuid()); + handler.getController().setLast(row.isLast()); + } else { + handler = context.getManagedFragmentHandler(ReportFragment.class); + handler.getController().init(row); + reportHandlers.put(row.getUuid(), handler); + } + vbox.getChildren().add(handler.getFragmentNode()); + } + } + + private void deleteReportGui(String uuid) { + if (reportHandlers.containsKey(uuid)){ + reportHandlers.remove(uuid); + } + getController().removeReport(uuid); + showLoading(); + context.send(new ReportsMessage(ReportsMessage.Type.READ)); + } + + public void reloadPage(int index) { + Node node = pagination.lookup("#vboxReports" + index); + if (node != null) { + VBox vbox = (VBox) node; + vbox.getChildren().clear(); + getController().loadAndPrintReports("#vboxReports" + index, index); + } + } + + /** + * Sort reports + */ + + private ReportsComparator.Mode currentMode; + private ReportsComparator.Order currentOrder; + + @FXML private HBox hboxName; + @FXML private HBox hboxPassed; + @FXML private HBox hboxFiles; + @FXML private HBox hboxErrors; + @FXML private HBox hboxWarnings; + @FXML private HBox hboxResult; + @FXML private HBox hboxDate; + @FXML private HBox hboxScore; + + @FXML + protected void clickedColDate(MouseEvent event) throws Exception { + clickedCol(hboxDate, ReportsComparator.Mode.DATE); + } + @FXML + protected void clickedColName(MouseEvent event) throws Exception { + clickedCol(hboxName, ReportsComparator.Mode.NAME); + } + @FXML + protected void clickedColErrors(MouseEvent event) throws Exception { + clickedCol(hboxErrors, ReportsComparator.Mode.ERRORS); + } + @FXML + protected void clickedColWarnings(MouseEvent event) throws Exception { + clickedCol(hboxWarnings, ReportsComparator.Mode.WARNINGS); + } + @FXML + protected void clickedColResult(MouseEvent event) throws Exception { + clickedCol(hboxResult, ReportsComparator.Mode.RESULT); + } + @FXML + protected void clickedColPassed(MouseEvent event) throws Exception { + clickedCol(hboxPassed, ReportsComparator.Mode.PASSED); + } + @FXML + protected void clickedColScore(MouseEvent event) throws Exception { + clickedCol(hboxScore, ReportsComparator.Mode.SCORE); + } + @FXML + protected void clickedColFiles(MouseEvent event) throws Exception { + clickedCol(hboxFiles, ReportsComparator.Mode.FILES); + } + + private void clickedCol(HBox hbox, ReportsComparator.Mode mode){ + if (indicator.isVisible()) return; + + // Visual sort + removeArrows(); + if (currentMode.equals(mode)) { + swapOrder(); + } else { + currentOrder = getDefaultOrder(mode); + } + currentMode = mode; + addArrow(hbox); + + // Show loading + showLoading(); + context.send(GuiConfig.COMPONENT_REPORTS, new ReportsMessage(ReportsMessage.Type.SORT)); + } + + private void addArrow(HBox hbox) { + String type = (currentOrder.equals(ReportsComparator.Order.ASC)) ? "up" : "down"; + ImageView icon = new ImageView(); + icon.setFitHeight(10); + icon.setFitWidth(10); + icon.setImage(new Image("images/icons/caret-" + type + ".png")); + hbox.getChildren().add(icon); + } + + private void removeArrows() { + hboxName.getChildren().remove(1, hboxName.getChildren().size()); + hboxErrors.getChildren().remove(1, hboxErrors.getChildren().size()); + hboxWarnings.getChildren().remove(1, hboxWarnings.getChildren().size()); + hboxResult.getChildren().remove(1, hboxResult.getChildren().size()); + hboxPassed.getChildren().remove(1, hboxPassed.getChildren().size()); + hboxScore.getChildren().remove(1, hboxScore.getChildren().size()); + hboxFiles.getChildren().remove(1, hboxFiles.getChildren().size()); + hboxDate.getChildren().remove(1, hboxDate.getChildren().size()); + } + + public ReportsComparator.Order getDefaultOrder(ReportsComparator.Mode mode){ + if (mode.equals(ReportsComparator.Mode.NAME)) return ReportsComparator.Order.ASC; + return ReportsComparator.Order.DESC; + } + + private void swapOrder(){ + if (currentOrder.equals(ReportsComparator.Order.ASC)){ + currentOrder = ReportsComparator.Order.DESC; + } else { + currentOrder = ReportsComparator.Order.ASC; + } + } + + public ReportsComparator.Mode getCurrentMode() { + return currentMode; + } + + public ReportsComparator.Order getCurrentOrder() { + return currentOrder; + } + } diff --git a/src/main/java/dpfmanager/shell/interfaces/gui/component/report/comparators/ReportsComparator.java b/src/main/java/dpfmanager/shell/interfaces/gui/component/report/comparators/ReportsComparator.java new file mode 100644 index 00000000..c545ee9c --- /dev/null +++ b/src/main/java/dpfmanager/shell/interfaces/gui/component/report/comparators/ReportsComparator.java @@ -0,0 +1,102 @@ +package dpfmanager.shell.interfaces.gui.component.report.comparators; + +import dpfmanager.shell.modules.report.util.ReportGui; +import dpfmanager.shell.modules.report.util.ReportIndividualGui; + +import java.util.Comparator; + +/** + * Created by Adrià Llorens on 26/05/2017. + */ +public class ReportsComparator implements Comparator { + + public enum Mode { + ERRORS, WARNINGS, PASSED, RESULT, DATE, NAME, SCORE, FILES + } + + public enum Order { + ASC, DESC + } + + private Mode mode; + + private Order order; + + public ReportsComparator(Mode m, Order o){ + mode = m; + order = o; + } + + @Override + public int compare(ReportGui o1, ReportGui o2) { + if (!mode.equals(Mode.DATE)) { + o1.load(); + o2.load(); + } + Integer compare = 0; + switch (mode){ + case ERRORS: + if (order.equals(Order.ASC)){ + compare = o1.getErrors().compareTo(o2.getErrors()); + } else { + compare = o2.getErrors().compareTo(o1.getErrors()); + } + break; + case WARNINGS: + if (order.equals(Order.ASC)){ + compare = o1.getWarnings().compareTo(o2.getWarnings()); + } else { + compare = o2.getWarnings().compareTo(o1.getWarnings()); + } + break; + case PASSED: + if (order.equals(Order.ASC)){ + compare = o1.getPassed().compareTo(o2.getPassed()); + } else { + compare = o2.getPassed().compareTo(o1.getPassed()); + } + break; + case RESULT: + if (order.equals(Order.ASC)){ + compare = o1.getErrors().compareTo(o2.getErrors()); + } else { + compare = o2.getErrors().compareTo(o1.getErrors()); + } + break; + case NAME: + if (order.equals(Order.ASC)){ + compare = o1.getInputLower().compareTo(o2.getInputLower()); + } else { + compare = o2.getInputLower().compareTo(o1.getInputLower()); + } + break; + case DATE: + if (order.equals(Order.ASC)){ + compare = o1.getTimestamp().compareTo(o2.getTimestamp()); + } else { + compare = o2.getTimestamp().compareTo(o1.getTimestamp()); + } + break; + case SCORE: + if (order.equals(Order.ASC)){ + compare = o1.getScore().compareTo(o2.getScore()); + } else { + compare = o2.getScore().compareTo(o1.getScore()); + } + break; + case FILES: + if (order.equals(Order.ASC)){ + compare = o1.getNfiles().compareTo(o2.getNfiles()); + } else { + compare = o2.getNfiles().compareTo(o1.getNfiles()); + } + break; + } + + // If equals, default DATE DESC + if (compare == 0){ + compare = o2.getTimestamp().compareTo(o1.getTimestamp()); + } + return compare; + } +} diff --git a/src/main/java/dpfmanager/shell/interfaces/gui/component/show/ShowController.java b/src/main/java/dpfmanager/shell/interfaces/gui/component/show/ShowController.java index f7805d09..67b07e10 100644 --- a/src/main/java/dpfmanager/shell/interfaces/gui/component/show/ShowController.java +++ b/src/main/java/dpfmanager/shell/interfaces/gui/component/show/ShowController.java @@ -19,110 +19,127 @@ package dpfmanager.shell.interfaces.gui.component.show; -import dpfmanager.shell.core.config.BasicConfig; -import dpfmanager.shell.core.config.GuiConfig; -import dpfmanager.shell.core.messages.ReportsMessage; -import dpfmanager.shell.core.messages.UiMessage; import dpfmanager.shell.core.mvc.DpfController; -import dpfmanager.shell.core.util.NodeUtil; -import dpfmanager.shell.modules.messages.messages.AlertMessage; -import dpfmanager.shell.modules.messages.messages.LogMessage; +import javafx.collections.FXCollections; +import javafx.collections.ObservableList; import com.google.gson.GsonBuilder; import com.google.gson.JsonParser; import org.apache.commons.io.FileUtils; import org.apache.commons.io.filefilter.IOFileFilter; -import org.apache.logging.log4j.Level; -import java.awt.*; -import java.io.BufferedReader; import java.io.File; -import java.io.FileReader; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; +import java.util.ArrayList; import java.util.Collection; +import java.util.List; /** * Created by Adria Llorens on 17/03/2016. */ public class ShowController extends DpfController { - public ShowController(){ + Integer count; + public ShowController(){ + count = 0; } public void showSingleReport(String type, String path, boolean completedPath) { - // getContext().send(BasicConfig.MODULE_MESSAGE, new LogMessage(getClass(), Level.DEBUG, "Showing report...")); - getView().hideAll(); + switch (type) { + case "xml": + if (!completedPath) path += "summary.xml"; + loadComboBox(path, "xml"); + break; + case "mets": + loadComboBox(path, "mets.xml"); + break; + case "json": + if (!completedPath) path += "summary.json"; + loadComboBox(path, "json"); + break; + case "pdf": + if (!completedPath) path += "report.pdf"; + loadComboBox(path, "pdf"); + break; + default: + break; + } + } + + public void showSingleReportFX(String type, String path, boolean completedPath) { switch (type) { case "html": if (!completedPath) path += "report.html"; getView().showWebView(path); break; case "xml": - if (!completedPath) path += "summary.xml"; - showComboBox(path,"xml"); getView().showTextArea(); break; case "mets": - showComboBox(path, "mets.xml"); getView().showTextArea(); break; case "json": - if (!completedPath) path += "summary.json"; - showComboBox(path, "json"); getView().showTextArea(); break; case "pdf": if (!completedPath) path += "report.pdf"; - showComboBox(path, "pdf"); getView().showPdfView(path); break; - default: - break; } + + // ComboBox + if (!type.equals("html")) { + getView().clearComboBox(); + getView().addComboChilds(getModel().getComboChilds()); + getView().selectComboChild(getModel().getSelectedChild()); + if (count > 1){ + getView().showComboBox(); + } + } + + getView().hideLoading(); } - public void showComboBox(String folderPath, String extension){ - int count = 0; + public void loadComboBox(String filePath, String extension){ + count = 0; + File file = new File(filePath); + String selectedName = file.getName().replace("." + extension, ""); + File folder = file; + if (folder.isFile()){ + folder = folder.getParentFile(); + } - // Clear comboBox - getView().clearComboBox(); + // ComboBox items + ObservableList comboChilds = FXCollections.observableArrayList(); - // Check if summary - File summary = new File(folderPath); - if (summary.isFile()){ + // First add summary + File summary = new File(folder.getPath() + "/summary." + extension); + if (extension.equals("pdf")){ + summary = new File(folder.getPath() + "/report." + extension); + } + if (summary.exists() && summary.isFile()) { getView().setCurrentReportParams(summary.getParent(), extension); - getView().addComboChild(summary.getName().replace("." + extension, ""), true); + comboChilds.add(summary.getName().replace("." + extension, "")); count++; } // Add all individuals - File folder = new File(folderPath); - if (folder.isFile()){ - folder = folder.getParentFile(); - } getView().setCurrentReportParams(folder.getPath(), extension); - IOFileFilter filter = customFilter(extension); IOFileFilter filterDir = customFilterDir(folder.getPath()); Collection childs = FileUtils.listFiles(folder, filter, filterDir); for (File child : childs){ String onlyName = child.getName().replace("."+extension, ""); - if (count == 0){ - getView().addComboChild(onlyName, true); - } else { - getView().addComboChild(onlyName, false); - } + comboChilds.add(onlyName); count++; } - // Show nodes - if (count > 1){ - getView().showComboBox(); - } + getModel().setComboChilds(comboChilds); + getModel().setSelectedChild(selectedName); } public IOFileFilter customFilter(String extension){ diff --git a/src/main/java/dpfmanager/shell/interfaces/gui/component/show/ShowModel.java b/src/main/java/dpfmanager/shell/interfaces/gui/component/show/ShowModel.java index cf85916d..72fdd903 100644 --- a/src/main/java/dpfmanager/shell/interfaces/gui/component/show/ShowModel.java +++ b/src/main/java/dpfmanager/shell/interfaces/gui/component/show/ShowModel.java @@ -20,13 +20,32 @@ package dpfmanager.shell.interfaces.gui.component.show; import dpfmanager.shell.core.mvc.DpfModel; +import javafx.collections.ObservableList; /** * Created by Adria Llorens on 17/03/2016. */ public class ShowModel extends DpfModel { + private ObservableList comboChilds; + private String selectedChild; + public ShowModel() { } + public ObservableList getComboChilds() { + return comboChilds; + } + + public void setComboChilds(ObservableList comboChilds) { + this.comboChilds = comboChilds; + } + + public String getSelectedChild() { + return selectedChild; + } + + public void setSelectedChild(String selectedChild) { + this.selectedChild = selectedChild; + } } diff --git a/src/main/java/dpfmanager/shell/interfaces/gui/component/show/ShowReport.java b/src/main/java/dpfmanager/shell/interfaces/gui/component/show/ShowReport.java index 22e92e68..368e6c61 100644 --- a/src/main/java/dpfmanager/shell/interfaces/gui/component/show/ShowReport.java +++ b/src/main/java/dpfmanager/shell/interfaces/gui/component/show/ShowReport.java @@ -13,6 +13,7 @@ public class ShowReport { public Integer globalValue = 0; public MakeReportRunnable mrr = null; public boolean finished = false; + public boolean onlyGlobal = false; public ShowReport(Long u){ uuid = u; diff --git a/src/main/java/dpfmanager/shell/interfaces/gui/component/show/ShowView.java b/src/main/java/dpfmanager/shell/interfaces/gui/component/show/ShowView.java index d681c485..310d3e19 100644 --- a/src/main/java/dpfmanager/shell/interfaces/gui/component/show/ShowView.java +++ b/src/main/java/dpfmanager/shell/interfaces/gui/component/show/ShowView.java @@ -21,15 +21,21 @@ import dpfmanager.shell.core.config.BasicConfig; import dpfmanager.shell.core.config.GuiConfig; +import dpfmanager.shell.core.messages.ArrayMessage; import dpfmanager.shell.core.messages.DpfMessage; +import dpfmanager.shell.core.messages.NavMessage; import dpfmanager.shell.core.messages.ShowMessage; +import dpfmanager.shell.core.messages.UiMessage; import dpfmanager.shell.core.mvc.DpfView; import dpfmanager.shell.core.util.NodeUtil; +import dpfmanager.shell.interfaces.gui.component.global.messages.GuiGlobalMessage; +import dpfmanager.shell.interfaces.gui.fragment.TopFragment; +import dpfmanager.shell.modules.report.messages.GenerateIndividualMessage; import dpfmanager.shell.modules.report.messages.GenerateMessage; -import dpfmanager.shell.modules.report.runnable.MakeReportRunnable; import dpfmanager.shell.modules.threading.messages.RunnableMessage; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; +import javafx.collections.ObservableList; import javafx.embed.swing.SwingFXUtils; import javafx.event.ActionEvent; import javafx.event.EventHandler; @@ -39,6 +45,7 @@ import javafx.scene.control.ComboBox; import javafx.scene.control.Label; import javafx.scene.control.ProgressBar; +import javafx.scene.control.ProgressIndicator; import javafx.scene.control.ScrollPane; import javafx.scene.control.TextArea; import javafx.scene.image.ImageView; @@ -93,10 +100,15 @@ public class ShowView extends DpfView { @FXML private Label labelLoading; @FXML + private ProgressIndicator indicator; + @FXML private ProgressBar progressLoading; private Map showReports; private Long currentReport; + private int currentPdfPage; + private Integer currentPdfPageMax; + private String currentPdfPath; @Override public void sendMessage(String target, Object dpfMessage) { @@ -105,38 +117,86 @@ public void sendMessage(String target, Object dpfMessage) { @Override public void handleMessageOnWorker(DpfMessage message) { - } - - @Override - public Node handleMessageOnFX(DpfMessage message) { if (message != null && message.isTypeOf(ShowMessage.class)) { ShowMessage sMessage = message.getTypedMessage(ShowMessage.class); if (sMessage.isShow()) { - if (sMessage.getUuid() == null || sMessage.getUuid().equals(currentReport)){ + if (sMessage.getInfo() != null && sMessage.getUuid().equals(currentReport)) { + } else if (sMessage.getUuid() == null || sMessage.getUuid().equals(currentReport)) { getController().showSingleReport(sMessage.getType(), sMessage.getPath(), true); } } else if (sMessage.isGenerate()) { if (showReports.containsKey(sMessage.getUuid())) { ShowReport sr = showReports.get(sMessage.getUuid()); if (sr.finished) { - // Transformation DONE, do nothing getController().showSingleReport(sMessage.getType(), sMessage.getInternal(), false); + } + } + } + } + } + + @Override + public Node handleMessageOnFX(DpfMessage message) { + if (message != null && message.isTypeOf(ShowMessage.class)) { + ShowMessage sMessage = message.getTypedMessage(ShowMessage.class); + if (sMessage.isLoad()) { + hideAll(); + showLoading(); + } else if (sMessage.isShow()) { + if (sMessage.getInfo() != null && sMessage.getUuid().equals(currentReport)) { + String currentId = context.getManagedFragmentHandler(TopFragment.class).getController().getCurrentId(); + if (currentId.equals(GuiConfig.PERSPECTIVE_SHOW)) { + ArrayMessage am = new ArrayMessage(); + am.add(GuiConfig.PERSPECTIVE_GLOBAL, new UiMessage(UiMessage.Type.SHOW)); + am.add(GuiConfig.PERSPECTIVE_GLOBAL + "." + GuiConfig.COMPONENT_GLOBAL, new GuiGlobalMessage(GuiGlobalMessage.Type.INIT, sMessage.getInfo())); + context.send(GuiConfig.PERSPECTIVE_GLOBAL, am); + } + } else if (sMessage.getUuid() == null || sMessage.getUuid().equals(currentReport)) { + getController().showSingleReportFX(sMessage.getType(), sMessage.getPath(), true); + } + } else if (sMessage.isGenerate()) { + if (showReports.containsKey(sMessage.getUuid())) { + ShowReport sr = showReports.get(sMessage.getUuid()); + if (sr.finished && sMessage.getTypes().size() > 0) { + // Transformation DONE, return to global report + context.send(GuiConfig.PERSPECTIVE_GLOBAL, new UiMessage(UiMessage.Type.SHOW)); + } else if (sr.finished) { + // Transformation DONE, show + hideAll(); + getController().showSingleReportFX(sMessage.getType(), sMessage.getInternal(), false); } else { // Already initiated hideAll(); - showLoading(); + if (sr.onlyGlobal) { + showLoading(); + } else { + showLoadingMultiple(); + } updateLoading(sr.count, sr.max); currentReport = sMessage.getUuid(); } } else { // Init new transformation ShowReport sr = new ShowReport(sMessage.getUuid()); + sr.onlyGlobal = sMessage.isOnlyGlobal(); currentReport = sMessage.getUuid(); showReports.put(sMessage.getUuid(), sr); hideAll(); - showLoading(); - context.send(BasicConfig.MODULE_REPORT, new GenerateMessage(sMessage.getType(), sMessage.getGlobalReport(), sMessage.getUuid())); + if (sMessage.isOnlyGlobal()) { + showLoading(); + } else { + showLoadingMultiple(); + } + if (sMessage.getTypes() != null) { + context.send(BasicConfig.MODULE_REPORT, new GenerateMessage(sMessage.getTypes(), sMessage.getInfo(), sMessage.getUuid(), sMessage.isOnlyGlobal())); + } else { + context.send(BasicConfig.MODULE_REPORT, new GenerateMessage(sMessage.getType(), sMessage.getInfo(), sMessage.getUuid(), sMessage.isOnlyGlobal())); + } } + } else if (sMessage.isIndividual()) { + hideAll(); + showLoading(); + context.send(BasicConfig.MODULE_REPORT, new GenerateIndividualMessage(sMessage.getType(), sMessage.getPath(), sMessage.getConfig())); } else if (sMessage.isInit()) { if (showReports.containsKey(sMessage.getUuid())) { ShowReport sr = showReports.get(sMessage.getUuid()); @@ -146,17 +206,17 @@ public Node handleMessageOnFX(DpfMessage message) { updateLoading(sr.count, sr.max); } } else if (sMessage.isUpdate()) { - if (showReports.containsKey(sMessage.getUuid())){ + if (showReports.containsKey(sMessage.getUuid())) { ShowReport sr = showReports.get(sMessage.getUuid()); sr.count += sMessage.getNumber(); - if (sMessage.getUuid().equals(currentReport)){ + if (sMessage.getUuid().equals(currentReport)) { updateLoading(sr.count, sr.max); } if (sr.count == sr.max) { sr.finished = true; } if (sr.globalValue + sr.count == sr.max && sr.mrr != null) { - context.send(BasicConfig.MODULE_THREADING, new RunnableMessage(sr.uuid, sr.mrr)); + context.send(BasicConfig.MODULE_THREADING, new RunnableMessage(sr.uuid, sr.mrr, "individual")); } } } @@ -170,7 +230,7 @@ public void onPostConstructComponent(FXComponentLayout layout, ResourceBundle re setModel(new ShowModel()); setController(new ShowController()); showReports = new HashMap<>(); - + indicator.setProgress(-1); hideAll(); comboIndividuals.setOnMousePressed(new EventHandler() { @@ -194,9 +254,30 @@ public void changed(ObservableValue observable, Number oldValu scrollPdfPages.setHvalue(0.5); } }); + scrollPdfPages.vvalueProperty().addListener( + (ObservableValue observable, Number oldValue, Number newValue) -> { + if (newValue.doubleValue() == 1.0) { + if (currentPdfPageMax != null && currentPdfPage < currentPdfPageMax) { + currentPdfPage++; + } + nextPdfFilePage(); + } + updatePageIndicator(); + }); } + public void updatePageIndicator() { + if (currentPdfPageMax == null) { + context.send(GuiConfig.COMPONENT_NAV, new NavMessage(0, 0)); + } else { + Double selectedPage = scrollPdfPages.getVvalue() * (currentPdfPage + 1); + Integer count = selectedPage.intValue() + 1; + if (count >= currentPdfPageMax) count = currentPdfPageMax; + context.send(GuiConfig.COMPONENT_NAV, new NavMessage(count, currentPdfPageMax)); + } + } + @Override public Context getContext() { return context; @@ -207,24 +288,28 @@ protected void changeIndividual(ActionEvent event) throws Exception { if (extension != null && extension.equals("pdf") && comboIndividuals.getSelectionModel().getSelectedItem() != null) { String name = (String) comboIndividuals.getSelectionModel().getSelectedItem(); String filename = folderPath + "/" + name + "." + extension; - opePdfFile(filename); + resetScrollPdf(filename); + nextPdfFilePage(); } else { setTextAreaContent(); } } - public void addComboChild(String name, boolean selected) { - comboIndividuals.getItems().add(name); - if (selected) { - comboIndividuals.getSelectionModel().select(name); - } + public void addComboChilds(ObservableList names) { + comboIndividuals.setItems(names); + } + + public void selectComboChild(String name) { + comboIndividuals.setValue(name); } public void clearComboBox() { - comboIndividuals.getItems().clear(); + if (comboIndividuals.getItems() != null){ + comboIndividuals.getItems().clear(); + } } - public void setCurrentReportParams(String path, String ext){ + public void setCurrentReportParams(String path, String ext) { folderPath = path; extension = ext; } @@ -241,15 +326,23 @@ public void setTextAreaContent() { * Show Hide */ - public void showLoading(){ + public void showLoadingMultiple() { NodeUtil.showNode(labelLoading); NodeUtil.showNode(progressLoading); + NodeUtil.hideNode(indicator); progressLoading.setProgress(-1); } - public void hideLoading(){ + public void showLoading() { + NodeUtil.showNode(indicator); + NodeUtil.hideNode(labelLoading); + NodeUtil.hideNode(progressLoading); + } + + public void hideLoading() { NodeUtil.hideNode(labelLoading); NodeUtil.hideNode(progressLoading); + NodeUtil.hideNode(indicator); } public void updateLoading(int count, int max) { @@ -260,11 +353,11 @@ public void updateLoading(int count, int max) { progressLoading.getStyleClass().add("blue-bar"); } } - if (progress == 1.0){ + if (progress == 1.0) { progressLoading.getStyleClass().remove("blue-bar"); progressLoading.getStyleClass().add("green-bar"); } - if (count < 0){ + if (count < 0) { progress = -1; } progressLoading.setProgress(progress); @@ -299,14 +392,22 @@ public void showWebView(String path) { public void hideWebView() { NodeUtil.hideNode(webView); NodeUtil.hideNode(showVBox); - webView.getEngine().load(""); } public void showPdfView(String path) { - opePdfFile(path); + resetScrollPdf(path); + nextPdfFilePage(); NodeUtil.showNode(scrollPdfPages); } + public void resetScrollPdf(String path){ + currentPdfPage = 0; + currentPdfPageMax = null; + currentPdfPath = path; + scrollPdfPages.setVvalue(0.0); + pdfPagesVBox.getChildren().clear(); + } + public void hidePdfView() { pdfPagesVBox.getChildren().clear(); NodeUtil.hideNode(scrollPdfPages); @@ -324,22 +425,36 @@ public void hideAll() { * PDF Viewer */ - private void opePdfFile(String absolutePath) { - // Load PDF codument - pdfPagesVBox.getChildren().clear(); + private void nextPdfFilePage() { + if (currentPdfPageMax != null && currentPdfPage > currentPdfPageMax) return; try { - if (absolutePath == null) System.out.println("NULL!!!!!!!!!!!"); - PDDocument document = PDDocument.load(absolutePath); + pdfPagesVBox.getChildren().add(getIndicatorPdf()); + PDDocument document = PDDocument.load(currentPdfPath); List pages = document.getDocumentCatalog().getAllPages(); - for (PDPage page : pages) { + currentPdfPageMax = pages.size(); + if (currentPdfPage < currentPdfPageMax) { + PDPage page = pages.get(currentPdfPage); BufferedImage pageImage = page.convertToImage(); ImageView imageView = new ImageView(SwingFXUtils.toFXImage(pageImage, null)); + pdfPagesVBox.getChildren().remove(pdfPagesVBox.getChildren().size() - 1); pdfPagesVBox.getChildren().add(imageView); - VBox.setMargin(imageView, new Insets(15,0,15,0)); + VBox.setMargin(imageView, new Insets(0, 0, 30, 0)); + updatePageIndicator(); + } else { + pdfPagesVBox.getChildren().remove(pdfPagesVBox.getChildren().size() - 1); } } catch (Exception ex) { ex.printStackTrace(); } } + private ProgressIndicator getIndicatorPdf() { + ProgressIndicator indicatorPdf = new ProgressIndicator(); + indicatorPdf.setProgress(-1); + indicatorPdf.setMinSize(150, 150); + indicatorPdf.setPrefSize(150, 150); + indicatorPdf.setMaxSize(150, 150); + VBox.setMargin(indicatorPdf, new Insets(20)); + return indicatorPdf; + } } diff --git a/src/main/java/dpfmanager/shell/interfaces/gui/component/top/NavComponent.java b/src/main/java/dpfmanager/shell/interfaces/gui/component/top/NavComponent.java new file mode 100644 index 00000000..2e81a84b --- /dev/null +++ b/src/main/java/dpfmanager/shell/interfaces/gui/component/top/NavComponent.java @@ -0,0 +1,97 @@ +/** + *

TopComponent.java

This program is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as published by the Free + * Software Foundation, either version 3 of the License, or (at your option) any later version; or, + * at your choice, under the terms of the Mozilla Public License, v. 2.0. SPDX GPL-3.0+ or MPL-2.0+. + *

This program is distributed in the hope that it will be useful, but WITHOUT ANY + * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + * PURPOSE. See the GNU General Public License and the Mozilla Public License for more details.

+ *

You should have received a copy of the GNU General Public License and the Mozilla Public + * License along with this program. If not, see http://www.gnu.org/licenses/ + * and at http://mozilla.org/MPL/2.0 .

NB: for the + * © statement, include Easy Innova SL or other company/Person contributing the code.

© + * 2015 Easy Innova, SL

+ * + * @author Adria Llorens + * @version 1.0 + * @since 23/7/2015 + */ + +package dpfmanager.shell.interfaces.gui.component.top; + +import dpfmanager.shell.core.adapter.DpfSimpleView; +import dpfmanager.shell.core.config.GuiConfig; +import dpfmanager.shell.core.messages.DpfMessage; +import dpfmanager.shell.core.messages.NavMessage; +import dpfmanager.shell.interfaces.gui.fragment.NavBarFragment; +import javafx.scene.Node; +import javafx.scene.layout.AnchorPane; + +import org.jacpfx.api.annotations.Resource; +import org.jacpfx.api.annotations.component.View; +import org.jacpfx.api.annotations.lifecycle.PostConstruct; +import org.jacpfx.rcp.componentLayout.FXComponentLayout; +import org.jacpfx.rcp.components.managedFragment.ManagedFragmentHandler; +import org.jacpfx.rcp.context.Context; + +import java.util.ResourceBundle; + +/** + * Created by Adria Llorens on 25/02/2016. + */ +@View(id = GuiConfig.COMPONENT_NAV, + name = GuiConfig.COMPONENT_NAV, + active = true, + resourceBundleLocation = "bundles.language", + initialTargetLayoutId = GuiConfig.TARGET_CONTAINER_NAV) +public class NavComponent extends DpfSimpleView { + + private AnchorPane anchorPane; + + @Resource + private Context context; + @Resource + private ResourceBundle bundle; + + private ManagedFragmentHandler handler; + + @Override + public void handleMessageOnWorker(DpfMessage message) { + } + + @Override + public Node handleMessageOnFX(DpfMessage message) { + if (message != null && message.isTypeOf(NavMessage.class)){ + NavMessage nm = message.getTypedMessage(NavMessage.class); + if (nm.isTable()){ + handler.getController().setTable(); + } else if (nm.isReport()){ + handler.getController().setReport(); + } else if (nm.isSpecific()){ + handler.getController().setSpecific(); + } else if (nm.isText()){ + String format = nm.getText().toUpperCase(); + handler.getController().setSpecificText(format); + handler.getController().setSpecific(); + } else if (nm.isPdf()){ + handler.getController().setPdfPage(nm.getCount(), nm.getMax()); + } else if (nm.isReload()){ + handler.getController().setReload(true); + } + } + return anchorPane; + } + + @PostConstruct + public void onPostConstructComponent(FXComponentLayout layout, ResourceBundle resourceBundle) { + handler = context.getManagedFragmentHandler(NavBarFragment.class); + handler.getController().init(); + anchorPane = (AnchorPane) handler.getFragmentNode(); + } + + @Override + public void sendMessage(String target, Object message) { + context.send(target, message); + } + +} diff --git a/src/main/java/dpfmanager/shell/interfaces/gui/fragment/BottomFragment.java b/src/main/java/dpfmanager/shell/interfaces/gui/fragment/BottomFragment.java index 993540b7..7d676934 100644 --- a/src/main/java/dpfmanager/shell/interfaces/gui/fragment/BottomFragment.java +++ b/src/main/java/dpfmanager/shell/interfaces/gui/fragment/BottomFragment.java @@ -191,10 +191,10 @@ public void finishActions(CheckTaskMessage ctm){ ManagedFragmentHandler taskFragment = taskFragments.get(ctm.getUuid()); if (ctm.isPause()){ taskFragment.getController().finishPause(); - context.send(BasicConfig.MODULE_THREADING, new ThreadsMessage(ThreadsMessage.Type.PAUSE, ctm.getUuid(), false)); + context.send(BasicConfig.MODULE_THREADING, new ThreadsMessage(ThreadsMessage.Type.PAUSE, ctm.getUuid(), false, "default")); } else if (ctm.isCancel()){ removeTask(ctm.getUuid()); - context.send(BasicConfig.MODULE_THREADING, new ThreadsMessage(ThreadsMessage.Type.CANCEL, ctm.getUuid(), false)); + context.send(BasicConfig.MODULE_THREADING, new ThreadsMessage(ThreadsMessage.Type.CANCEL, ctm.getUuid(), false, "default")); } } diff --git a/src/main/java/dpfmanager/shell/interfaces/gui/fragment/NavBarFragment.java b/src/main/java/dpfmanager/shell/interfaces/gui/fragment/NavBarFragment.java new file mode 100644 index 00000000..b54e2550 --- /dev/null +++ b/src/main/java/dpfmanager/shell/interfaces/gui/fragment/NavBarFragment.java @@ -0,0 +1,156 @@ +/** + *

BarFragment.java

This program is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as published by the Free Software + * Foundation, either version 3 of the License, or (at your option) any later version; or, at your + * choice, under the terms of the Mozilla Public License, v. 2.0. SPDX GPL-3.0+ or MPL-2.0+.

+ *

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License and the Mozilla Public License for more details.

You should + * have received a copy of the GNU General Public License and the Mozilla Public License along with + * this program. If not, see http://www.gnu.org/licenses/ + * and at http://mozilla.org/MPL/2.0 .

NB: for the + * © statement, include Easy Innova SL or other company/Person contributing the code.

© + * 2015 Easy Innova, SL

+ * + * @author Adria Llorens + * @version 1.0 + * @since 23/7/2015 + */ + +package dpfmanager.shell.interfaces.gui.fragment; + +import dpfmanager.shell.core.config.GuiConfig; +import dpfmanager.shell.core.messages.UiMessage; +import dpfmanager.shell.core.util.NodeUtil; +import dpfmanager.shell.interfaces.gui.component.statistics.comparators.PolicyComparator; +import javafx.event.EventHandler; +import javafx.fxml.FXML; +import javafx.scene.control.Label; +import javafx.scene.control.TreeItem; +import javafx.scene.input.MouseEvent; +import javafx.scene.layout.HBox; + +import org.controlsfx.control.BreadCrumbBar; +import org.jacpfx.api.annotations.Resource; +import org.jacpfx.api.annotations.fragment.Fragment; +import org.jacpfx.api.fragment.Scope; +import org.jacpfx.rcp.context.Context; + +import java.util.ResourceBundle; + +/** + * Created by Adria Llorens on 03/03/2016. + */ +@Fragment(id = GuiConfig.FRAGMENT_BREAD, + viewLocation = "/fxml/fragments/nav.fxml", + resourceBundleLocation = "bundles.language", + scope = Scope.SINGLETON) +public class NavBarFragment { + + @Resource + private Context context; + @Resource + private ResourceBundle bundle; + + @FXML + private Label labelTable; + @FXML + private Label labelSeparator1; + @FXML + private Label labelReport; + @FXML + private Label labelSeparator2; + @FXML + private Label labelSingle; + + @FXML + private Label labelPdf; + + private boolean initiated = false; + private boolean reload = false; + + public void init() { + if (initiated) return; + setTable(); + initiated = true; + } + + public void setTable(){ + NodeUtil.showNode(labelTable); + NodeUtil.hideNode(labelSeparator1); + NodeUtil.hideNode(labelReport); + NodeUtil.hideNode(labelSeparator2); + NodeUtil.hideNode(labelSingle); + NodeUtil.hideNode(labelPdf); + labelTable.getStyleClass().remove("myactive"); + labelReport.getStyleClass().remove("myactive"); + labelSingle.getStyleClass().remove("myactive"); + labelTable.getStyleClass().add("myactive"); + } + + public void setReport(){ + NodeUtil.showNode(labelTable); + NodeUtil.showNode(labelSeparator1); + NodeUtil.showNode(labelReport); + NodeUtil.hideNode(labelSeparator2); + NodeUtil.hideNode(labelSingle); + NodeUtil.hideNode(labelPdf); + labelTable.getStyleClass().remove("myactive"); + labelReport.getStyleClass().remove("myactive"); + labelSingle.getStyleClass().remove("myactive"); + labelReport.getStyleClass().add("myactive"); + } + + public void setSpecific(){ + NodeUtil.showNode(labelTable); + NodeUtil.showNode(labelSeparator1); + NodeUtil.showNode(labelReport); + NodeUtil.showNode(labelSeparator2); + NodeUtil.showNode(labelSingle); + NodeUtil.hideNode(labelPdf); + labelTable.getStyleClass().remove("myactive"); + labelReport.getStyleClass().remove("myactive"); + labelSingle.getStyleClass().remove("myactive"); + labelSingle.getStyleClass().add("myactive"); + } + + public void setPdfPage(int c, int m){ + if (c == 0 && m == 0){ + NodeUtil.hideNode(labelPdf); + } else { + labelPdf.setText(c + "/" + m); + NodeUtil.showNode(labelPdf); + } + } + + public void setSpecificText(String format){ + labelSingle.setText(format); + } + + @FXML + protected void clickedTable(MouseEvent event) throws Exception { + if (!labelTable.getStyleClass().contains("myactive")) { + if (reload) { + setReload(false); + context.send(GuiConfig.PERSPECTIVE_REPORTS, new UiMessage(UiMessage.Type.RELOAD)); + } else { + context.send(GuiConfig.PERSPECTIVE_REPORTS, new UiMessage(UiMessage.Type.SHOW)); + } + } + } + + @FXML + protected void clickedReport(MouseEvent event) throws Exception { + if (!labelReport.getStyleClass().contains("myactive")) { + context.send(GuiConfig.PERSPECTIVE_GLOBAL, new UiMessage(UiMessage.Type.RELOAD)); + } + } + + @FXML + protected void clickedSingle(MouseEvent event) throws Exception { + } + + public void setReload(boolean reload) { + this.reload = reload; + } +} diff --git a/src/main/java/dpfmanager/shell/interfaces/gui/fragment/ReportFragment.java b/src/main/java/dpfmanager/shell/interfaces/gui/fragment/ReportFragment.java index c6f9b4d5..8d513b3b 100644 --- a/src/main/java/dpfmanager/shell/interfaces/gui/fragment/ReportFragment.java +++ b/src/main/java/dpfmanager/shell/interfaces/gui/fragment/ReportFragment.java @@ -22,9 +22,9 @@ import dpfmanager.shell.core.config.GuiConfig; import dpfmanager.shell.core.messages.ArrayMessage; import dpfmanager.shell.core.messages.ReportsMessage; -import dpfmanager.shell.core.messages.ShowMessage; import dpfmanager.shell.core.messages.UiMessage; -import dpfmanager.shell.modules.report.core.GlobalReport; +import dpfmanager.shell.core.util.NodeUtil; +import dpfmanager.shell.interfaces.gui.component.global.messages.GuiGlobalMessage; import dpfmanager.shell.modules.report.util.ReportGui; import javafx.collections.FXCollections; import javafx.collections.ObservableList; @@ -33,10 +33,7 @@ import javafx.scene.Cursor; import javafx.scene.chart.PieChart; import javafx.scene.control.Button; -import javafx.scene.control.ContextMenu; import javafx.scene.control.Label; -import javafx.scene.control.Tooltip; -import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.MouseEvent; import javafx.scene.layout.HBox; @@ -52,10 +49,6 @@ import java.awt.*; import java.io.File; import java.io.IOException; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; import java.util.ResourceBundle; /** @@ -75,12 +68,16 @@ public class ReportFragment { @FXML private Label date; @FXML - private Label time; + private ImageView okImage; + @FXML + private ImageView koImage; @FXML private Label files; @FXML private Label input; @FXML + private Label type; + @FXML private Label errors; @FXML private Label warnings; @@ -96,28 +93,35 @@ public class ReportFragment { /* Report Row info */ private ReportGui info; + private StackPane lastStack; + public void init(ReportGui reportRow) { info = reportRow; loadReportRow(); } - public void updateIcons(){ - info.readFormats(); - formatsBox.getChildren().clear(); - addFormatIcons(info.getFormats(), info.getReportVersion(), info.getGlobalReport()); - } - private void loadReportRow() { info.load(); - date.setText(info.getDate()); - time.setText(info.getTime()); + date.setText(info.getDate() + " " + info.getTime()); files.setText(info.getNfiles() + ""); input.setText(info.getInput()); errors.setText(bundle.getString("errors").replace("%1", info.getErrors() + "")); - warnings.setText(bundle.getString("warnings").replace("%1", "" + info.getWarnings() + "")); + if (info.getErrors() == 0) { + NodeUtil.showNode(okImage); + NodeUtil.hideNode(koImage); + } else { + NodeUtil.hideNode(okImage); + NodeUtil.showNode(koImage); + } + if (info.getGlobalReport() != null && info.isQuick()) { + type.setText(bundle.getString("typeQuick")); + warnings.setText(""); + } else { + type.setText(bundle.getString("typeFull")); + warnings.setText(bundle.getString("warnings").replace("%1", "" + info.getWarnings() + "")); + } passed.setText(bundle.getString("passed").replace("%1", "" + info.getPassed() + "")); addChartScore(info.getScore()); - addFormatIcons(info.getFormats(), info.getReportVersion(), info.getGlobalReport()); addActionsIcons(info.getDelete()); addLastItem(info.isLast()); } @@ -135,65 +139,13 @@ private void addChartScore(Integer scoreInt) { chart.setMinSize(22, 22); chart.setMaxSize(22, 22); - Label score_label = new Label(score + "%"); + Label score_label = new Label(score.intValue() + "%"); score_label.setTextFill(Color.LIGHTGRAY); scoreBox.getChildren().add(chart); scoreBox.getChildren().add(score_label); } - private void addFormatIcons(Map itemRead, Integer version, GlobalReport gr) { - List sortedFormats = Arrays.asList("html","pdf","xml","mets", "json"); - Map item = new HashMap<>(); - if (version > 0) { - // Transform reports - for (String format : sortedFormats){ - if (!item.containsKey(format)) item.put(format, (itemRead.containsKey(format)) ? itemRead.get(format) : null); - } - } else { - item = itemRead; - } - for (String i : sortedFormats) { - if (!item.containsKey(i)) continue; - ImageView icon = new ImageView(); - icon.setId("but" + i); - icon.setFitHeight(20); - icon.setFitWidth(20); - icon.setCursor(Cursor.HAND); - icon.setImage(new Image("images/formats/" + i + ".png")); - Tooltip.install(icon, new Tooltip(i.toUpperCase())); - - String path = item.get(i); - ShowMessage sMessage = null; - if (path != null && new File(path).exists()){ - // Show directly - sMessage = new ShowMessage(i, path); - } else if (gr.getVersion() > 1){ - // Transformation need - icon.setOpacity(0.4); - icon.setOnMouseEntered(event -> icon.setOpacity(1.0)); - icon.setOnMouseExited(event -> icon.setOpacity(0.4)); - Long formatUuid = Long.parseLong(info.getUuid()+Character.getNumericValue(i.charAt(0))); - sMessage = new ShowMessage(formatUuid, i, gr, info.getInternalReportFolder()); - } - if (sMessage != null){ - final ShowMessage finalSMessage = sMessage; - icon.setOnMouseClicked(event -> { - ArrayMessage am = new ArrayMessage(); - am.add(GuiConfig.PERSPECTIVE_SHOW, new UiMessage()); - am.add(GuiConfig.PERSPECTIVE_SHOW + "." + GuiConfig.COMPONENT_SHOW, finalSMessage); - context.send(GuiConfig.PERSPECTIVE_SHOW, am); - }); - - ContextMenu contextMenu = new ContextMenu(); - javafx.scene.control.MenuItem download = new javafx.scene.control.MenuItem("Download report"); - contextMenu.getItems().add(download); - icon.setOnContextMenuRequested(e -> contextMenu.show(icon, e.getScreenX(), e.getScreenY())); - formatsBox.getChildren().add(icon); - } - } - } - public void addActionsIcons(String item) { String path = info.getDeletePath(); @@ -239,6 +191,8 @@ public void handle(MouseEvent event) { icon.setOnMouseClicked(new EventHandler() { @Override public void handle(MouseEvent event) { + // Disable icon + icon.setDisable(true); // Send action to controller context.send(GuiConfig.COMPONENT_REPORTS, new ReportsMessage(ReportsMessage.Type.DELETE, getUuid())); // Delete report @@ -246,27 +200,47 @@ public void handle(MouseEvent event) { File dir = new File(file.getParent()); try { FileUtils.deleteDirectory(dir); + icon.setDisable(false); } catch (IOException e) { e.printStackTrace(); } - - // TODO -// getModel().removeItem(item); } }); actionsBox.getChildren().add(icon); } - public void addLastItem(boolean isLast){ - if (isLast){ - StackPane stack = new StackPane(); - stack.setMaxWidth(0.0); - stack.setMaxHeight(0.0); - stack.setId("lastReportRow"); - actionsBox.getChildren().add(stack); + public void addLastItem(boolean isLast) { + initLastStack(); + if (isLast) { + if (!actionsBox.getChildren().contains(lastStack)) { + actionsBox.getChildren().add(lastStack); + } + } else { + actionsBox.getChildren().remove(lastStack); } } + private void initLastStack() { + if (lastStack != null) return; + lastStack = new StackPane(); + lastStack.setMaxWidth(0.0); + lastStack.setMaxHeight(0.0); + lastStack.setId("lastReportRow"); + } + + @FXML + protected void onGridPaneClicked(MouseEvent event) throws Exception { + ArrayMessage am = new ArrayMessage(); + am.add(GuiConfig.PERSPECTIVE_GLOBAL, new UiMessage(UiMessage.Type.SHOW)); + am.add(GuiConfig.PERSPECTIVE_GLOBAL + "." + GuiConfig.COMPONENT_GLOBAL, new GuiGlobalMessage(GuiGlobalMessage.Type.INIT, info)); + context.send(GuiConfig.PERSPECTIVE_GLOBAL, am); + } + + public void setLast(boolean last) { + info.setLast(last); + addLastItem(last); + } + public String getUuid() { return info.getUuid(); } diff --git a/src/main/java/dpfmanager/shell/interfaces/gui/fragment/TaskFragment.java b/src/main/java/dpfmanager/shell/interfaces/gui/fragment/TaskFragment.java index a226602a..1083c174 100644 --- a/src/main/java/dpfmanager/shell/interfaces/gui/fragment/TaskFragment.java +++ b/src/main/java/dpfmanager/shell/interfaces/gui/fragment/TaskFragment.java @@ -22,11 +22,14 @@ import dpfmanager.shell.core.config.BasicConfig; import dpfmanager.shell.core.config.GuiConfig; import dpfmanager.shell.core.messages.ArrayMessage; +import dpfmanager.shell.core.messages.NavMessage; import dpfmanager.shell.core.messages.ShowMessage; import dpfmanager.shell.core.messages.UiMessage; import dpfmanager.shell.core.util.NodeUtil; +import dpfmanager.shell.interfaces.gui.component.global.messages.GuiGlobalMessage; import dpfmanager.shell.modules.database.tables.Jobs; import dpfmanager.shell.modules.messages.messages.LogMessage; +import dpfmanager.shell.modules.report.util.ReportGui; import dpfmanager.shell.modules.threading.messages.ThreadsMessage; import javafx.fxml.FXML; import javafx.scene.control.Label; @@ -178,17 +181,12 @@ private void showDoneJob(){ getReportsInfo(); NodeUtil.hideNode(resumePauseImage); NodeUtil.hideNode(cancelImage); - if (!type.isEmpty()) { - taskImage.setImage(new Image("images/formats/" + type + ".png")); - timeLabel.setText(getReadableData(job.getFinish() - job.getInit())); - NodeUtil.showNode(taskImage); - NodeUtil.hideNode(reportsImage); - } else { - reportsImage.setImage(new Image("images/formats/reports.png")); - timeLabel.setText(getReadableData(job.getFinish() - job.getInit())); - NodeUtil.showNode(reportsImage); - NodeUtil.hideNode(taskImage); - } + + reportsImage.setImage(new Image("images/formats/report.png")); + timeLabel.setText(getReadableData(job.getFinish() - job.getInit())); + NodeUtil.showNode(reportsImage); + NodeUtil.hideNode(taskImage); + progress.setProgress(job.getProgress()); progress.getStyleClass().remove("blue-bar"); progress.getStyleClass().add("green-bar"); @@ -258,28 +256,8 @@ private String getReadableInput(String input){ } private void getReportsInfo() { - String filefolder = job.getOutput(); - - String htmlPath = filefolder + "report.html"; - String xmlPath = filefolder + "summary.xml"; - String jsonPath = filefolder + "summary.json"; - String pdfPath = filefolder + "report.pdf"; - type = ""; - path = ""; - if (exists(htmlPath)) { - type = "html"; - path = htmlPath; - } else if (exists(xmlPath)) { - type = "xml"; - path = xmlPath; - } else if (exists(jsonPath)) { - type = "json"; - path = jsonPath; - } else if (exists(pdfPath)) { - type = "pdf"; - path = pdfPath; - } + path = job.getOutput(); } @FXML @@ -294,7 +272,12 @@ private void showReport() { @FXML private void showReportsTab() { // Show check - context.send(GuiConfig.PERSPECTIVE_REPORTS, new UiMessage(UiMessage.Type.SHOW)); + ReportGui rg = new ReportGui(path); + ArrayMessage am = new ArrayMessage(); + am.add(GuiConfig.PERSPECTIVE_GLOBAL, new UiMessage(UiMessage.Type.SHOW)); + am.add(GuiConfig.PERSPECTIVE_GLOBAL + "." + GuiConfig.COMPONENT_NAV, new NavMessage(NavMessage.Selected.RELOAD)); + am.add(GuiConfig.PERSPECTIVE_GLOBAL + "." + GuiConfig.COMPONENT_GLOBAL, new GuiGlobalMessage(GuiGlobalMessage.Type.INIT, rg)); + context.send(GuiConfig.PERSPECTIVE_GLOBAL, am); } @FXML @@ -304,12 +287,12 @@ private void resumePause() { showLoadingPause(); mainVbox.setOpacity(opacity); resumePauseImage.setImage(new Image("images/resume.png")); - context.send(BasicConfig.MODULE_THREADING, new ThreadsMessage(ThreadsMessage.Type.PAUSE, job.getId(), true)); + context.send(BasicConfig.MODULE_THREADING, new ThreadsMessage(ThreadsMessage.Type.PAUSE, job.getId(), true, "default")); } else { // Resume check mainVbox.setOpacity(1.0); resumePauseImage.setImage(new Image("images/pause.png")); - context.send(BasicConfig.MODULE_THREADING, new ThreadsMessage(ThreadsMessage.Type.RESUME, job.getId(), true)); + context.send(BasicConfig.MODULE_THREADING, new ThreadsMessage(ThreadsMessage.Type.RESUME, job.getId(), true,"default")); } isPause = !isPause; } @@ -320,7 +303,7 @@ private void cancel() { if (!loadingPause.isVisible()) { NodeUtil.hideNode(resumePauseImage); context.send(BasicConfig.MODULE_MESSAGE, new LogMessage(getClass(), Level.DEBUG, "Cancelled check: "+job.getInput())); - context.send(BasicConfig.MODULE_THREADING, new ThreadsMessage(ThreadsMessage.Type.CANCEL, job.getId(), true)); + context.send(BasicConfig.MODULE_THREADING, new ThreadsMessage(ThreadsMessage.Type.CANCEL, job.getId(), true, "default")); } } diff --git a/src/main/java/dpfmanager/shell/interfaces/gui/fragment/TopFragment.java b/src/main/java/dpfmanager/shell/interfaces/gui/fragment/TopFragment.java index 1670ba15..f412f6bc 100644 --- a/src/main/java/dpfmanager/shell/interfaces/gui/fragment/TopFragment.java +++ b/src/main/java/dpfmanager/shell/interfaces/gui/fragment/TopFragment.java @@ -205,7 +205,7 @@ public void setCurrentToggle(String id) { String finalId = ""; if (id.equals(GuiConfig.PERSPECTIVE_DESSIGN) || id.equals(GuiConfig.PERSPECTIVE_CONFIG)) { finalId = ButDessign; - } else if (id.equals(GuiConfig.PERSPECTIVE_REPORTS) || id.equals(GuiConfig.PERSPECTIVE_SHOW)) { + } else if (id.equals(GuiConfig.PERSPECTIVE_REPORTS) || id.equals(GuiConfig.PERSPECTIVE_SHOW) || id.equals(GuiConfig.PERSPECTIVE_GLOBAL)) { finalId = ButReports; } else if (id.equals(GuiConfig.PERSPECTIVE_STATISTICS)) { finalId = ButStatistics; @@ -283,7 +283,7 @@ private void doShow(String id) { context.send(GuiConfig.PERSPECTIVE_INTEROPERABILITY, new UiMessage(UiMessage.Type.SHOW)); break; case ButReports: - context.send(GuiConfig.PERSPECTIVE_REPORTS, new UiMessage(UiMessage.Type.SHOW)); + context.send(GuiConfig.PERSPECTIVE_REPORTS, new UiMessage(UiMessage.Type.RELOAD)); break; case ButStatistics: context.send(GuiConfig.PERSPECTIVE_STATISTICS, new UiMessage(UiMessage.Type.SHOW)); diff --git a/src/main/java/dpfmanager/shell/interfaces/gui/fragment/global/IndividualFragment.java b/src/main/java/dpfmanager/shell/interfaces/gui/fragment/global/IndividualFragment.java new file mode 100644 index 00000000..05731f17 --- /dev/null +++ b/src/main/java/dpfmanager/shell/interfaces/gui/fragment/global/IndividualFragment.java @@ -0,0 +1,358 @@ +/** + *

PeriodicFragment.java

This program is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as published by the Free Software + * Foundation, either version 3 of the License, or (at your option) any later version; or, at your + * choice, under the terms of the Mozilla Public License, v. 2.0. SPDX GPL-3.0+ or MPL-2.0+.

+ *

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License and the Mozilla Public License for more details.

You should + * have received a copy of the GNU General Public License and the Mozilla Public License along with + * this program. If not, see http://www.gnu.org/licenses/ + * and at http://mozilla.org/MPL/2.0 .

NB: for the + * © statement, include Easy Innova SL or other company/Person contributing the code.

© + * 2015 Easy Innova, SL

+ * + * @author Adria Llorens + * @version 1.0 + * @since 23/7/2015 + */ + +package dpfmanager.shell.interfaces.gui.fragment.global; + +import dpfmanager.conformancechecker.configuration.Configuration; +import dpfmanager.shell.core.config.BasicConfig; +import dpfmanager.shell.core.config.GuiConfig; +import dpfmanager.shell.core.messages.ArrayMessage; +import dpfmanager.shell.core.messages.NavMessage; +import dpfmanager.shell.core.messages.ShowMessage; +import dpfmanager.shell.core.messages.UiMessage; +import dpfmanager.shell.core.util.NodeUtil; +import dpfmanager.shell.interfaces.gui.workbench.GuiWorkbench; +import dpfmanager.shell.modules.conformancechecker.messages.ConformanceMessage; +import dpfmanager.shell.modules.messages.messages.AlertMessage; +import dpfmanager.shell.modules.report.util.ReportIndividualGui; +import javafx.event.ActionEvent; +import javafx.event.EventHandler; +import javafx.fxml.FXML; +import javafx.scene.Cursor; +import javafx.scene.control.ContextMenu; +import javafx.scene.control.Label; +import javafx.scene.control.MenuItem; +import javafx.scene.control.Tooltip; +import javafx.scene.image.Image; +import javafx.scene.image.ImageView; +import javafx.scene.input.MouseButton; +import javafx.scene.layout.GridPane; +import javafx.scene.layout.HBox; +import javafx.scene.paint.Color; +import javafx.stage.FileChooser; + +import org.apache.commons.io.FileUtils; +import org.jacpfx.api.annotations.Resource; +import org.jacpfx.api.annotations.fragment.Fragment; +import org.jacpfx.api.fragment.Scope; +import org.jacpfx.rcp.context.Context; + +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.ResourceBundle; + +/** + * Created by Adria Llorens on 18/04/2016. + */ +@Fragment(id = GuiConfig.FRAGMENT_INDIVIDUAL, + viewLocation = "/fxml/fragments/individual.fxml", + resourceBundleLocation = "bundles.language", + scope = Scope.PROTOTYPE) +public class IndividualFragment { + + @Resource + private Context context; + @Resource + private ResourceBundle bundle; + + + /** + * Full check elements + */ + @FXML + private Label fInput; + @FXML + private Label fPath; + @FXML + private Label fErrors; + @FXML + private Label fWarnings; + @FXML + private HBox fFormatsBox; + @FXML + private ImageView fOkImage; + @FXML + private ImageView fKoImage; + @FXML + private ImageView fQuestionImage; + @FXML + private GridPane gridFull; + + /** + * Quick check elements + */ + @FXML + private Label qInput; + @FXML + private Label qPath; + @FXML + private HBox qFormatsBox; + @FXML + private ImageView qOkImage; + @FXML + private ImageView qKoImage; + @FXML + private GridPane gridQuick; + + + /* Report Row info */ + private ReportIndividualGui info; + + public void init(ReportIndividualGui r) { + info = r; + info.load(); + if (info.isQuick()){ + loadReportRowQuick(); + } else if (!info.isOld()){ + loadReportRowFull(); + } else { + loadReportRowOld(); + } + } + + public void updateIcons(){ + info.readFormats(); + if (info.isQuick()){ + addFormatIcons(qFormatsBox); + } else { + addFormatIcons(fFormatsBox); + } + } + + private void loadReportRowQuick() { + qInput.setText(info.getFilename()); + qPath.setText(info.getShowFilePath()); + + // Result + if (info.getErrors() > 0) { + NodeUtil.showNode(qKoImage); + NodeUtil.hideNode(qOkImage); + } else { + NodeUtil.hideNode(qKoImage); + NodeUtil.showNode(qOkImage); + } + + // Format Icons + addFormatIcons(qFormatsBox); + + // Show + NodeUtil.showNode(gridQuick); + NodeUtil.hideNode(gridFull); + } + + private void loadReportRowFull() { + fInput.setText(info.getFilename()); + fPath.setText(info.getShowFilePath()); + + // Result + NodeUtil.hideNode(fQuestionImage); + if (info.getErrors() > 0) { + NodeUtil.showNode(fKoImage); + NodeUtil.hideNode(fOkImage); + } else { + NodeUtil.hideNode(fKoImage); + NodeUtil.showNode(fOkImage); + } + + // Errors + fErrors.setText(bundle.getString("errors").replace("%1", info.getErrors() + "")); + if (info.getErrors() > 0) { + fErrors.setTextFill(Color.RED); + } else { + fErrors.setTextFill(Color.YELLOWGREEN); + } + + // Warnings + fWarnings.setText(bundle.getString("warnings").replace("%1", "" + info.getWarnings() + "")); + if (info.getWarnings() > 0) { + fWarnings.setTextFill(Color.ORANGE); + } else { + fWarnings.setTextFill(Color.LIGHTGREY); + } + + // Format Icons + addFormatIcons(fFormatsBox); + + // Show + NodeUtil.showNode(gridFull); + NodeUtil.hideNode(gridQuick); + } + + private void loadReportRowOld() { + fInput.setText(info.getFilename()); + fPath.setText(info.getShowFilePath()); + + // Result + NodeUtil.hideNode(fKoImage); + NodeUtil.hideNode(fOkImage); + NodeUtil.showNode(fQuestionImage); + + // Errors + fErrors.setText(""); + + // Warnings + fWarnings.setText(""); + + // Format Icons + addFormatIcons(fFormatsBox); + + // Show + NodeUtil.showNode(gridFull); + NodeUtil.hideNode(gridQuick); + } + + private void addFormatIcons(HBox formatsBox) { + formatsBox.getChildren().clear(); + List sortedFormats = Arrays.asList("html","pdf","xml","mets", "json"); + Map itemRead = info.getFormats(); + Integer version = info.getReportVersion(); + Map item = new HashMap<>(); + if (version > 0) { + // Transform reports + for (String format : sortedFormats){ + if (!item.containsKey(format)) item.put(format, (itemRead.containsKey(format)) ? itemRead.get(format) : null); + } + } else { + item = (itemRead != null) ? itemRead : new HashMap<>(); + } + for (String i : sortedFormats) { + if (!item.containsKey(i)) continue; + ImageView icon = new ImageView(); + icon.setId("but" + i); + icon.setFitHeight(20); + icon.setFitWidth(20); + icon.setCursor(Cursor.HAND); + icon.setImage(new Image("images/formats/" + i + ".png")); + Tooltip.install(icon, new Tooltip(i.toUpperCase())); + + String path = item.get(i); + ShowMessage sMessage = null; + if (path != null && new File(path).exists()){ + // Show directly + sMessage = new ShowMessage(i, path); + } else if (version > 1){ + // Transformation need + icon.setOpacity(0.4); + icon.setOnMouseEntered(event -> icon.setOpacity(1.0)); + icon.setOnMouseExited(event -> icon.setOpacity(0.4)); + sMessage = new ShowMessage(i, info.getPath(), info.getConfig()); + } + if (sMessage != null){ + final ShowMessage finalSMessage = sMessage; + icon.setOnMouseClicked(event -> { + if (event.getButton() == MouseButton.PRIMARY) { + ArrayMessage am = new ArrayMessage(); + am.add(GuiConfig.PERSPECTIVE_SHOW, new UiMessage(UiMessage.Type.SHOW)); + am.add(GuiConfig.PERSPECTIVE_SHOW + "." + GuiConfig.COMPONENT_NAV, new NavMessage(i)); + am.add(GuiConfig.PERSPECTIVE_SHOW + "." + GuiConfig.COMPONENT_SHOW, new ShowMessage(ShowMessage.Type.LOAD)); + am.add(GuiConfig.PERSPECTIVE_SHOW + "." + GuiConfig.COMPONENT_SHOW, finalSMessage); + context.send(GuiConfig.PERSPECTIVE_SHOW, am); + } + }); + + ContextMenu contextMenu = new ContextMenu(); + MenuItem itemShow = new MenuItem(bundle.getString("showReport")); + itemShow.setOnAction(new EventHandler() { + public void handle(ActionEvent e) { + ArrayMessage am = new ArrayMessage(); + am.add(GuiConfig.PERSPECTIVE_SHOW, new UiMessage(UiMessage.Type.SHOW)); + am.add(GuiConfig.PERSPECTIVE_SHOW + "." + GuiConfig.COMPONENT_NAV, new NavMessage(i)); + am.add(GuiConfig.PERSPECTIVE_SHOW + "." + GuiConfig.COMPONENT_SHOW, new ShowMessage(ShowMessage.Type.LOAD)); + am.add(GuiConfig.PERSPECTIVE_SHOW + "." + GuiConfig.COMPONENT_SHOW, finalSMessage); + context.send(GuiConfig.PERSPECTIVE_SHOW, am); + } + }); + MenuItem itemGenerate = new MenuItem(bundle.getString("generateReport")); + itemGenerate.setOnAction(new EventHandler() { + public void handle(ActionEvent e) { + ArrayMessage am = new ArrayMessage(); + am.add(GuiConfig.PERSPECTIVE_SHOW, new UiMessage(UiMessage.Type.SHOW)); + am.add(GuiConfig.PERSPECTIVE_SHOW + "." + GuiConfig.COMPONENT_NAV, new NavMessage(i)); + am.add(GuiConfig.PERSPECTIVE_SHOW + "." + GuiConfig.COMPONENT_SHOW, new ShowMessage(ShowMessage.Type.LOAD)); + am.add(GuiConfig.PERSPECTIVE_SHOW + "." + GuiConfig.COMPONENT_SHOW, finalSMessage); + context.send(GuiConfig.PERSPECTIVE_SHOW, am); + } + }); + MenuItem itemDownload = new MenuItem(bundle.getString("downloadReport")); + itemDownload.setOnAction(new EventHandler() { + public void handle(ActionEvent e) { + downloadReport(path); + } + }); + + if (path == null) { + contextMenu.getItems().addAll(itemGenerate); + } else { + contextMenu.getItems().addAll(itemShow, itemDownload); + } + + icon.setOnContextMenuRequested(e -> contextMenu.show(icon, e.getScreenX(), e.getScreenY())); + formatsBox.getChildren().add(icon); + } + } + } + + public void downloadReport(String path){ + File src = new File(path); + if (!src.exists() || !src.isFile()) return; + + String name = src.getName().substring(0, src.getName().indexOf(".")); + String extension = src.getName().substring(src.getName().indexOf(".")); + + FileChooser fileChooser = new FileChooser(); + + //Set extension filter + FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter(extension.toLowerCase().substring(1, extension.length() -1) + " files (*"+extension+")", "*" + extension); + fileChooser.getExtensionFilters().add(extFilter); + fileChooser.setInitialFileName(name); + + //Show save file dialog + File dest = fileChooser.showSaveDialog(GuiWorkbench.getMyStage()); + + if(dest != null){ + try { + FileUtils.copyFile(src, dest); + } catch (Exception e) { + context.send(BasicConfig.MODULE_MESSAGE, new AlertMessage(AlertMessage.Type.ERROR, bundle.getString("errorSavingReport"))); + } + } + } + + @FXML + protected void makeFullReport(ActionEvent event) throws Exception { + String inputFile = info.getFilePath(); + String zipFile = info.getZipPath(); + Configuration config = new Configuration(info.getConfig()); + config.setQuick(false); + config.setFormats(new ArrayList<>(Arrays.asList("HTML"))); + if (new File(inputFile).exists()) { + context.send(BasicConfig.MODULE_CONFORMANCE, new ConformanceMessage(inputFile, config, 100, false, false)); + } else if (new File(zipFile).exists()) { + context.send(BasicConfig.MODULE_MESSAGE, new AlertMessage(AlertMessage.Type.INFO, bundle.getString("filesAreZip"))); + context.send(BasicConfig.MODULE_CONFORMANCE, new ConformanceMessage(zipFile, config, 100, false, false)); + } else { + context.send(BasicConfig.MODULE_MESSAGE, new AlertMessage(AlertMessage.Type.INFO, bundle.getString("filesNotFound"), inputFile)); + } + } + +} \ No newline at end of file diff --git a/src/main/java/dpfmanager/shell/interfaces/gui/perspective/GlobalPerspective.java b/src/main/java/dpfmanager/shell/interfaces/gui/perspective/GlobalPerspective.java new file mode 100644 index 00000000..70b895b9 --- /dev/null +++ b/src/main/java/dpfmanager/shell/interfaces/gui/perspective/GlobalPerspective.java @@ -0,0 +1,116 @@ +/** + *

ReportsPerspective.java

This program is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as published by the Free + * Software Foundation, either version 3 of the License, or (at your option) any later version; or, + * at your choice, under the terms of the Mozilla Public License, v. 2.0. SPDX GPL-3.0+ or MPL-2.0+. + *

This program is distributed in the hope that it will be useful, but WITHOUT ANY + * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + * PURPOSE. See the GNU General Public License and the Mozilla Public License for more details.

+ *

You should have received a copy of the GNU General Public License and the Mozilla Public + * License along with this program. If not, see http://www.gnu.org/licenses/ + * and at http://mozilla.org/MPL/2.0 .

NB: for the + * © statement, include Easy Innova SL or other company/Person contributing the code.

© + * 2015 Easy Innova, SL

+ * + * @author Adria Llorens + * @version 1.0 + * @since 23/7/2015 + */ + +package dpfmanager.shell.interfaces.gui.perspective; + +import dpfmanager.shell.core.adapter.DpfAbstractPerspective; +import dpfmanager.shell.core.config.BasicConfig; +import dpfmanager.shell.core.config.GuiConfig; +import dpfmanager.shell.core.messages.DpfMessage; +import dpfmanager.shell.core.messages.NavMessage; +import dpfmanager.shell.core.messages.UiMessage; +import javafx.geometry.Pos; +import javafx.scene.layout.StackPane; + +import org.jacpfx.api.annotations.Resource; +import org.jacpfx.api.annotations.lifecycle.PostConstruct; +import org.jacpfx.api.annotations.perspective.Perspective; +import org.jacpfx.rcp.componentLayout.FXComponentLayout; +import org.jacpfx.rcp.componentLayout.PerspectiveLayout; +import org.jacpfx.rcp.context.Context; + +import java.util.ResourceBundle; + +/** + * Created by Adria Llorens on 25/02/2016. + */ +@Perspective(id = GuiConfig.PERSPECTIVE_GLOBAL, + name = GuiConfig.PERSPECTIVE_GLOBAL, + active = false, + components = { + GuiConfig.COMPONENT_TOP, + GuiConfig.COMPONENT_NAV, + GuiConfig.COMPONENT_GLOBAL, + GuiConfig.COMPONENT_PANE, + GuiConfig.COMPONENT_BAR, + BasicConfig.MODULE_MESSAGE, + BasicConfig.MODULE_CONFORMANCE, + BasicConfig.MODULE_THREADING, + BasicConfig.MODULE_REPORT + } +) +public class GlobalPerspective extends DpfAbstractPerspective { + + @Resource + public Context context; + + @Override + public void handleMessage(DpfMessage dpfMessage, PerspectiveLayout layout) { + } + + @Override + public void onShowCustom() { + context.send(GuiConfig.PERSPECTIVE_GLOBAL + "." + GuiConfig.COMPONENT_NAV, new NavMessage(NavMessage.Selected.REPORT)); + } + + @Override + public void onReloadCustom() { + context.send(GuiConfig.PERSPECTIVE_GLOBAL + "." + GuiConfig.COMPONENT_NAV, new NavMessage(NavMessage.Selected.REPORT)); + context.send(GuiConfig.PERSPECTIVE_GLOBAL + "." + GuiConfig.COMPONENT_GLOBAL, new UiMessage(UiMessage.Type.RELOAD)); + } + + @PostConstruct + public void onStartPerspective(PerspectiveLayout perspectiveLayout, FXComponentLayout layout, ResourceBundle resourceBundle) { + // Top Buttons component + StackPane topPane = new StackPane(); + + // Center Component + StackPane centerPane = new StackPane(); + centerPane.setAlignment(Pos.TOP_CENTER); + + // Bottom Component + bottomPane = new StackPane(); + bottomPane.setAlignment(Pos.BOTTOM_CENTER); + + // Bottom Bar Component + bottomBar = new StackPane(); + bottomBar.setAlignment(Pos.BOTTOM_CENTER); + + // Navigation Bar + StackPane navPane = new StackPane(); + centerPane.setAlignment(Pos.TOP_CENTER); + + // Attach to PERSPECTIVE + mainSplit = constructSplitPane(constructScrollPane(centerPane), bottomPane); + mainPane = constructMainPaneWithBread(mainSplit, navPane, bottomBar); + perspectiveLayout.registerTargetLayoutComponent(GuiConfig.TARGET_CONTAINER_TOP, topPane); + perspectiveLayout.registerTargetLayoutComponent(GuiConfig.TARGET_CONTAINER_NAV, navPane); + perspectiveLayout.registerTargetLayoutComponent(GuiConfig.TARGET_CONTAINER_GLOBAL, centerPane); + perspectiveLayout.registerTargetLayoutComponent(GuiConfig.TARGET_CONTAINER_PANE, bottomPane); + perspectiveLayout.registerTargetLayoutComponent(GuiConfig.TARGET_CONTAINER_BAR, bottomBar); + + // Define main pane + borderPane = constructBorderPane(perspectiveLayout, topPane, mainPane); + } + + @Override + public Context getContext() { + return context; + } +} diff --git a/src/main/java/dpfmanager/shell/interfaces/gui/perspective/ReportsPerspective.java b/src/main/java/dpfmanager/shell/interfaces/gui/perspective/ReportsPerspective.java index 717846c0..e8370965 100644 --- a/src/main/java/dpfmanager/shell/interfaces/gui/perspective/ReportsPerspective.java +++ b/src/main/java/dpfmanager/shell/interfaces/gui/perspective/ReportsPerspective.java @@ -23,22 +23,10 @@ import dpfmanager.shell.core.config.BasicConfig; import dpfmanager.shell.core.config.GuiConfig; import dpfmanager.shell.core.messages.DpfMessage; +import dpfmanager.shell.core.messages.NavMessage; import dpfmanager.shell.core.messages.ReportsMessage; -import dpfmanager.shell.core.messages.UiMessage; -import dpfmanager.shell.core.util.NodeUtil; -import dpfmanager.shell.modules.statistics.messages.StatisticsMessage; -import dpfmanager.shell.modules.threading.messages.GlobalStatusMessage; -import dpfmanager.shell.modules.threading.messages.RunnableMessage; -import javafx.event.EventHandler; import javafx.geometry.Pos; -import javafx.scene.Node; -import javafx.scene.control.ScrollPane; -import javafx.scene.input.KeyCode; -import javafx.scene.input.KeyEvent; -import javafx.scene.layout.BorderPane; import javafx.scene.layout.StackPane; -import javafx.scene.layout.VBox; -import javafx.stage.Stage; import org.jacpfx.api.annotations.Resource; import org.jacpfx.api.annotations.lifecycle.PostConstruct; @@ -57,6 +45,7 @@ active = false, components = { GuiConfig.COMPONENT_TOP, + GuiConfig.COMPONENT_NAV, GuiConfig.COMPONENT_REPORTS, GuiConfig.COMPONENT_PANE, GuiConfig.COMPONENT_BAR, @@ -76,6 +65,12 @@ public void handleMessage(DpfMessage dpfMessage, PerspectiveLayout layout) { @Override public void onShowCustom() { + context.send(GuiConfig.PERSPECTIVE_REPORTS + "." + GuiConfig.COMPONENT_NAV, new NavMessage(NavMessage.Selected.TABLE)); + } + + @Override + public void onReloadCustom() { + context.send(GuiConfig.PERSPECTIVE_REPORTS + "." + GuiConfig.COMPONENT_NAV, new NavMessage(NavMessage.Selected.TABLE)); context.send(GuiConfig.PERSPECTIVE_REPORTS + "." + GuiConfig.COMPONENT_REPORTS, new ReportsMessage(ReportsMessage.Type.RELOAD)); } @@ -96,10 +91,15 @@ public void onStartPerspective(PerspectiveLayout perspectiveLayout, FXComponentL bottomBar = new StackPane(); bottomBar.setAlignment(Pos.BOTTOM_CENTER); + // Navigation Bar + StackPane navPane = new StackPane(); + centerPane.setAlignment(Pos.TOP_CENTER); + // Attach to PERSPECTIVE mainSplit = constructSplitPane(constructScrollPane(centerPane), bottomPane); - mainPane = constructMainPane(mainSplit, bottomBar); + mainPane = constructMainPaneWithBread(mainSplit, navPane, bottomBar); perspectiveLayout.registerTargetLayoutComponent(GuiConfig.TARGET_CONTAINER_TOP, topPane); + perspectiveLayout.registerTargetLayoutComponent(GuiConfig.TARGET_CONTAINER_NAV, navPane); perspectiveLayout.registerTargetLayoutComponent(GuiConfig.TARGET_CONTAINER_REPORTS, centerPane); perspectiveLayout.registerTargetLayoutComponent(GuiConfig.TARGET_CONTAINER_PANE, bottomPane); perspectiveLayout.registerTargetLayoutComponent(GuiConfig.TARGET_CONTAINER_BAR, bottomBar); diff --git a/src/main/java/dpfmanager/shell/interfaces/gui/perspective/ShowReportPerspective.java b/src/main/java/dpfmanager/shell/interfaces/gui/perspective/ShowReportPerspective.java index eb1b67ef..3e4b6525 100644 --- a/src/main/java/dpfmanager/shell/interfaces/gui/perspective/ShowReportPerspective.java +++ b/src/main/java/dpfmanager/shell/interfaces/gui/perspective/ShowReportPerspective.java @@ -23,6 +23,7 @@ import dpfmanager.shell.core.config.BasicConfig; import dpfmanager.shell.core.config.GuiConfig; import dpfmanager.shell.core.messages.DpfMessage; +import dpfmanager.shell.core.messages.NavMessage; import javafx.geometry.Pos; import javafx.scene.layout.StackPane; @@ -43,6 +44,7 @@ active = false, components = { GuiConfig.COMPONENT_TOP, + GuiConfig.COMPONENT_NAV, GuiConfig.COMPONENT_SHOW, GuiConfig.COMPONENT_PANE, GuiConfig.COMPONENT_BAR, @@ -60,6 +62,11 @@ public class ShowReportPerspective extends DpfAbstractPerspective { public void handleMessage(DpfMessage dpfMessage, PerspectiveLayout layout) { } + @Override + public void onShowCustom() { + context.send(GuiConfig.PERSPECTIVE_SHOW + "." + GuiConfig.COMPONENT_NAV, new NavMessage(NavMessage.Selected.SPECIFIC)); + } + @PostConstruct public void onStartPerspective(PerspectiveLayout perspectiveLayout, FXComponentLayout layout, ResourceBundle resourceBundle) { // Top Buttons component @@ -77,10 +84,15 @@ public void onStartPerspective(PerspectiveLayout perspectiveLayout, FXComponentL bottomBar = new StackPane(); bottomBar.setAlignment(Pos.BOTTOM_CENTER); + // Navigation Bar + StackPane navPane = new StackPane(); + centerPane.setAlignment(Pos.TOP_CENTER); + // Attach to PERSPECTIVE mainSplit = constructSplitPane(centerPane, bottomPane); - mainPane = constructMainPane(mainSplit, bottomBar); + mainPane = constructMainPaneWithBread(mainSplit, navPane, bottomBar); perspectiveLayout.registerTargetLayoutComponent(GuiConfig.TARGET_CONTAINER_TOP, topPane); + perspectiveLayout.registerTargetLayoutComponent(GuiConfig.TARGET_CONTAINER_NAV, navPane); perspectiveLayout.registerTargetLayoutComponent(GuiConfig.TARGET_CONTAINER_SHOW, centerPane); perspectiveLayout.registerTargetLayoutComponent(GuiConfig.TARGET_CONTAINER_PANE, bottomPane); perspectiveLayout.registerTargetLayoutComponent(GuiConfig.TARGET_CONTAINER_BAR, bottomBar); diff --git a/src/main/java/dpfmanager/shell/interfaces/gui/workbench/GuiWorkbench.java b/src/main/java/dpfmanager/shell/interfaces/gui/workbench/GuiWorkbench.java index 52dd259e..cf4f931c 100644 --- a/src/main/java/dpfmanager/shell/interfaces/gui/workbench/GuiWorkbench.java +++ b/src/main/java/dpfmanager/shell/interfaces/gui/workbench/GuiWorkbench.java @@ -57,7 +57,8 @@ GuiConfig.PERSPECTIVE_SHOW, GuiConfig.PERSPECTIVE_PERIODICAL, GuiConfig.PERSPECTIVE_INTEROPERABILITY, - GuiConfig.PERSPECTIVE_STATISTICS + GuiConfig.PERSPECTIVE_STATISTICS, + GuiConfig.PERSPECTIVE_GLOBAL } ) public class GuiWorkbench implements FXWorkbench { diff --git a/src/main/java/dpfmanager/shell/modules/conformancechecker/ConformanceCheckerModule.java b/src/main/java/dpfmanager/shell/modules/conformancechecker/ConformanceCheckerModule.java index 9debf069..fa2a8b92 100644 --- a/src/main/java/dpfmanager/shell/modules/conformancechecker/ConformanceCheckerModule.java +++ b/src/main/java/dpfmanager/shell/modules/conformancechecker/ConformanceCheckerModule.java @@ -67,19 +67,20 @@ public void handleMessage(DpfMessage dpfMessage) { } else if (cm.isGui()) { String path = cm.getPath(); String input = cm.getInput(); - Configuration config = null; - if (!path.isEmpty()) { - config = service.readConfig(path); - if (config == null) { - getContext().send(BasicConfig.MODULE_MESSAGE, new AlertMessage(AlertMessage.Type.ERROR, DPFManagerProperties.getBundle().getString("errorReadingConfFile"))); - return; + Configuration config = cm.getConfig(); + if (config == null) { + if (!path.isEmpty()) { + config = service.readConfig(path); + if (config == null) { + getContext().send(BasicConfig.MODULE_MESSAGE, new AlertMessage(AlertMessage.Type.ERROR, DPFManagerProperties.getBundle().getString("errorReadingConfFile"))); + return; + } + } else { + config = new Configuration(); + config.setDefault(); } - config.setQuick(cm.isQuick()); - } else { - config = new Configuration(); - config.setDefault(); - config.setQuick(cm.isQuick()); } + config.setQuick(cm.isQuick()); service.initProcessInputRun(input, config, cm.getRecursive()); } } else if (dpfMessage.isTypeOf(ProcessInputMessage.class)) { diff --git a/src/main/java/dpfmanager/shell/modules/conformancechecker/core/ConformanceCheckerService.java b/src/main/java/dpfmanager/shell/modules/conformancechecker/core/ConformanceCheckerService.java index d12b9264..a537d726 100644 --- a/src/main/java/dpfmanager/shell/modules/conformancechecker/core/ConformanceCheckerService.java +++ b/src/main/java/dpfmanager/shell/modules/conformancechecker/core/ConformanceCheckerService.java @@ -169,6 +169,7 @@ synchronized public void tractProcessInputMessage(ProcessInputMessage pim){ } else if (pim.isFile()){ if (filesToCheck.containsKey(pim.getUuid())){ filesToCheck.get(pim.getUuid()).add(pim.getFiles()); + filesToCheck.get(pim.getUuid()).addZipsPath(pim.getZipsPath()); } } @@ -190,10 +191,10 @@ synchronized public void tractProcessInputMessage(ProcessInputMessage pim){ public void startCheck(Long uuid, ProcessInputParameters pip) { // Init - context.send(BasicConfig.MODULE_THREADING, new GlobalStatusMessage(GlobalStatusMessage.Type.INIT, uuid, pip.getFiles().size(), pip.getConfig(), pip.getInternalReportFolder(), pip.getInputStr())); + context.send(BasicConfig.MODULE_THREADING, new GlobalStatusMessage(GlobalStatusMessage.Type.INIT, uuid, pip.getFiles().size(), pip.getConfig(), pip.getInternalReportFolder(), pip.getInputStr(), pip.getZipsPath())); // Now process files - ProcessFiles(uuid, pip.getFiles(), pip.getConfig(), pip.getInternalReportFolder()); + ProcessFiles(uuid, pip.getFiles(), pip.getConfig(), pip.getInternalReportFolder(), pip.getInputStr()); } public void emptyCheck(Long uuid, String internal) { @@ -209,13 +210,13 @@ public void emptyCheck(Long uuid, String internal) { * @param config the config * @return the path to the internal report folder */ - private String ProcessFiles(Long uuid, List files, Configuration config, String internalReportFolder) { + private String ProcessFiles(Long uuid, List files, Configuration config, String internalReportFolder, String inputStr) { // Process each input of the list int idReport = 1; List list = interService.getConformanceCheckers(); for (final String filename : files) { ConformanceRunnable run = new ConformanceRunnable(list, generator); - run.setParameters(filename, idReport, internalReportFolder, config, uuid); + run.setParameters(filename, idReport, internalReportFolder, config, uuid, inputStr); context.send(BasicConfig.MODULE_THREADING, new RunnableMessage(uuid, run)); idReport++; } diff --git a/src/main/java/dpfmanager/shell/modules/conformancechecker/core/ProcessInputParameters.java b/src/main/java/dpfmanager/shell/modules/conformancechecker/core/ProcessInputParameters.java index dd127d3b..2b6a3452 100644 --- a/src/main/java/dpfmanager/shell/modules/conformancechecker/core/ProcessInputParameters.java +++ b/src/main/java/dpfmanager/shell/modules/conformancechecker/core/ProcessInputParameters.java @@ -21,7 +21,9 @@ import dpfmanager.conformancechecker.configuration.Configuration; +import java.util.HashMap; import java.util.List; +import java.util.Map; /** * Created by Adria Llorens on 10/05/2016. @@ -33,6 +35,7 @@ public class ProcessInputParameters { private Configuration config; private int toWait; private List files; + private Map zipsPath; public ProcessInputParameters(String internalReportFolder, String inputStr, Configuration config, int toWait, List files) { this.internalReportFolder = internalReportFolder; @@ -40,6 +43,7 @@ public ProcessInputParameters(String internalReportFolder, String inputStr, Conf this.config = config; this.toWait = toWait; this.files = files; + this.zipsPath = new HashMap<>(); } public String getInternalReportFolder() { @@ -66,4 +70,17 @@ public void add(List files2){ files.addAll(files2); toWait--; } + + public void addZipsPath(Map zipsPath2) { + for (String key : zipsPath2.keySet()) { + if (!zipsPath.containsKey(key)) { + zipsPath.put(key, zipsPath2.get(key)); + } + } + } + + public Map getZipsPath() { + return zipsPath; + } + } diff --git a/src/main/java/dpfmanager/shell/modules/conformancechecker/messages/ConformanceMessage.java b/src/main/java/dpfmanager/shell/modules/conformancechecker/messages/ConformanceMessage.java index 62315896..e31718f8 100644 --- a/src/main/java/dpfmanager/shell/modules/conformancechecker/messages/ConformanceMessage.java +++ b/src/main/java/dpfmanager/shell/modules/conformancechecker/messages/ConformanceMessage.java @@ -50,6 +50,17 @@ public ConformanceMessage(String i, String p, int r, boolean ao, boolean q) { gui = true; askOverwrite = ao; quick = q; + config = null; + } + + public ConformanceMessage(String i, Configuration c, int r, boolean ao, boolean q) { + // Gui + input = i; + config = c; + recursive = r; + gui = true; + askOverwrite = ao; + quick = q; } public ConformanceMessage(Long u, String i, String p) { diff --git a/src/main/java/dpfmanager/shell/modules/conformancechecker/messages/ProcessInputMessage.java b/src/main/java/dpfmanager/shell/modules/conformancechecker/messages/ProcessInputMessage.java index a0fda67f..ce814595 100644 --- a/src/main/java/dpfmanager/shell/modules/conformancechecker/messages/ProcessInputMessage.java +++ b/src/main/java/dpfmanager/shell/modules/conformancechecker/messages/ProcessInputMessage.java @@ -24,6 +24,7 @@ import java.io.File; import java.util.List; +import java.util.Map; /** * Created by Adria Llorens on 09/05/2016. @@ -37,6 +38,7 @@ public class ProcessInputMessage extends DpfMessage { private String internalReportFolder; private String inputStr; private Integer toWait; + private Map zipsPath; public enum Type { WAIT, FILE @@ -53,11 +55,12 @@ public ProcessInputMessage(Type type, Long uuid, List files, Configurati this.toWait = toWait; } - public ProcessInputMessage(Type type, Long uuid, List files){ + public ProcessInputMessage(Type type, Long uuid, List files, Map zipsPath){ // File this.type = type; this.uuid = uuid; this.files = files; + this.zipsPath = zipsPath; } public boolean isWait(){ @@ -91,4 +94,8 @@ public String getInputStr() { public Integer getToWait() { return toWait; } + + public Map getZipsPath() { + return zipsPath; + } } diff --git a/src/main/java/dpfmanager/shell/modules/conformancechecker/runnable/ConformanceRunnable.java b/src/main/java/dpfmanager/shell/modules/conformancechecker/runnable/ConformanceRunnable.java index 6df88573..b5cda839 100644 --- a/src/main/java/dpfmanager/shell/modules/conformancechecker/runnable/ConformanceRunnable.java +++ b/src/main/java/dpfmanager/shell/modules/conformancechecker/runnable/ConformanceRunnable.java @@ -44,6 +44,7 @@ public class ConformanceRunnable extends DpfRunnable { private int id; private long uuid; private ReportGenerator generator; + private String inputStr; public ConformanceRunnable(List list, ReportGenerator gen) { // No context yet @@ -56,12 +57,13 @@ public void handleContext(DpfContext context) { pi.setContext(context); } - public void setParameters(String name, int i, String internal, Configuration conf, long u) { + public void setParameters(String name, int i, String internal, Configuration conf, long u, String in) { filename = name; id = i; internalReportFolder = internal; config = conf; uuid = u; + inputStr = in; } @Override @@ -91,6 +93,7 @@ public void runTask() { // Process the input and get a list of individual reports IndividualReport ir = pi.processFile(filename, internalReportFolder, config, id); if (ir != null && !ir.isError()) { + ir.setInputStr(inputStr); ir.setIdReport(id); ir.setInternalReportFolder(internalReportFolder); ir.setUuid(uuid); @@ -98,6 +101,7 @@ public void runTask() { // Serialize it String filenameNorm = filename.replaceAll("\\\\", "/"); String serFileName = ir.getReportId() + "-" +filenameNorm.substring(filenameNorm.lastIndexOf("/") + 1) + ".ser"; + ir.setSerPath(internalReportFolder + "/serialized/" + serFileName); ir.filter(); ir.write(internalReportFolder + "/serialized", serFileName); ir.defilter(); diff --git a/src/main/java/dpfmanager/shell/modules/conformancechecker/runnable/GetInputRunnable.java b/src/main/java/dpfmanager/shell/modules/conformancechecker/runnable/GetInputRunnable.java index 83c24ad3..a9ace635 100644 --- a/src/main/java/dpfmanager/shell/modules/conformancechecker/runnable/GetInputRunnable.java +++ b/src/main/java/dpfmanager/shell/modules/conformancechecker/runnable/GetInputRunnable.java @@ -35,7 +35,9 @@ import java.io.OutputStream; import java.util.ArrayList; import java.util.Enumeration; +import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; @@ -46,6 +48,7 @@ public class GetInputRunnable extends DpfRunnable { private Long uuid; private List files; + private Map zipsPath; private String internalReportFolder; private File fileZip; @@ -55,6 +58,7 @@ public class GetInputRunnable extends DpfRunnable { @Override public void handleContext(DpfContext context) { files = new ArrayList<>(); + zipsPath = new HashMap<>(); error = false; } @@ -83,7 +87,7 @@ public void runTask() { } // Notify - context.send(BasicConfig.MODULE_CONFORMANCE, new ProcessInputMessage(ProcessInputMessage.Type.FILE, getUuid(), files)); + context.send(BasicConfig.MODULE_CONFORMANCE, new ProcessInputMessage(ProcessInputMessage.Type.FILE, getUuid(), files, zipsPath)); } /** @@ -92,10 +96,8 @@ public void runTask() { private void runZip(){ try { // Create zip folder - File zipFolder = new File(internalReportFolder + "zip/"); - if (!zipFolder.exists()) { - zipFolder.mkdirs(); - } + File zipFolder = getNExtZipFolder(); + zipsPath.put(zipFolder.getName(), fileZip.getAbsolutePath()); // Extract it ZipFile zipFile = new ZipFile(fileZip); @@ -104,7 +106,7 @@ private void runZip(){ // Process each file contained in the compressed file ZipEntry entry = entries.nextElement(); String name = entry.getName(); - File targetFile = new File(internalReportFolder + "zip/" + name); + File targetFile = new File(zipFolder.getPath() + File.separator + name); if (name.endsWith("/")) { // Directory targetFile.mkdirs(); @@ -178,4 +180,17 @@ private String createTempFile(String internal, String name, InputStream stream) return filename; } + synchronized private File getNExtZipFolder(){ + int count = 0; + File zipFolder = new File(internalReportFolder + GetInputRunnable.zipFolderPrefix); + while (zipFolder.exists()){ + count++; + zipFolder = new File(internalReportFolder + GetInputRunnable.zipFolderPrefix + count); + } + zipFolder.mkdirs(); + return zipFolder; + } + + public static String zipFolderPrefix = "zipTmpDpfManager"; + } diff --git a/src/main/java/dpfmanager/shell/modules/report/ReportModule.java b/src/main/java/dpfmanager/shell/modules/report/ReportModule.java index 77fd09c4..4276b269 100644 --- a/src/main/java/dpfmanager/shell/modules/report/ReportModule.java +++ b/src/main/java/dpfmanager/shell/modules/report/ReportModule.java @@ -24,6 +24,7 @@ import dpfmanager.shell.core.context.GuiContext; import dpfmanager.shell.core.messages.DpfMessage; import dpfmanager.shell.modules.report.core.ReportService; +import dpfmanager.shell.modules.report.messages.GenerateIndividualMessage; import dpfmanager.shell.modules.report.messages.GenerateMessage; import dpfmanager.shell.modules.report.messages.GlobalReportMessage; import dpfmanager.shell.modules.report.messages.IndividualReportMessage; @@ -58,6 +59,8 @@ public void handleMessage(DpfMessage dpfMessage) { service.tractGlobalMessage(dpfMessage.getTypedMessage(GlobalReportMessage.class)); } else if (dpfMessage.isTypeOf(GenerateMessage.class)) { service.tractGenerateMessage(dpfMessage.getTypedMessage(GenerateMessage.class)); + } else if (dpfMessage.isTypeOf(GenerateIndividualMessage.class)) { + service.tractGenerateIndividualMessage(dpfMessage.getTypedMessage(GenerateIndividualMessage.class)); } } diff --git a/src/main/java/dpfmanager/shell/modules/report/core/GlobalReport.java b/src/main/java/dpfmanager/shell/modules/report/core/GlobalReport.java index ee5763da..1550a7cb 100644 --- a/src/main/java/dpfmanager/shell/modules/report/core/GlobalReport.java +++ b/src/main/java/dpfmanager/shell/modules/report/core/GlobalReport.java @@ -90,6 +90,16 @@ public class GlobalReport extends ReportSerializable { */ private Configuration config; + /** + * The input string + */ + private String inputStr; + + /** + * The paths where each zip was unzipped + */ + private Map zipsPaths; + /** * Instantiates a new global report. */ @@ -102,7 +112,7 @@ public GlobalReport() { errVal = 0; } - public void init(Configuration c, List ci) { + public void init(Configuration c, List ci, Map z) { this.modifiedIsos = c.getModifiedIsos(); this.selectedIsos = c.getIsos(); if (c.hasRules()) { @@ -110,6 +120,10 @@ public void init(Configuration c, List ci) { } this.checkedIsos = ci; this.config = c; + this.zipsPaths = z; + if (zipsPaths == null) { + zipsPaths = new HashMap<>(); + } } /** @@ -159,6 +173,7 @@ public void generate(Date start) { List toDelete = new ArrayList<>(); Collections.sort(reports); for (SmallIndividualReport ir : reports) { + if (inputStr == null) inputStr = ir.getInputStr(); if (ir.isError()) { toDelete.add(ir); } else { @@ -226,12 +241,18 @@ public int getAllReportsOk() { public int getAllReportsWarnings() { int n = 0; for (SmallIndividualReport rep : reports) { + boolean warn = false; for (String iso : getSelectedIsos()) { - if (rep.getNWarnings(iso) > 0) { - n++; + if (rep.getNErrors(iso) == 0){ + if (rep.getNWarnings(iso) > 0) { + warn = true; + } + } else { + warn = false; break; } } + if (warn) n++; } return n; } @@ -263,7 +284,6 @@ public boolean hasModificationIso(String iso) { * @return the individual reports */ public List getIndividualReports() { - Collections.sort(reports); return reports; } @@ -313,6 +333,7 @@ public Long getDurationMillis() { } public String getInputString(){ + if (inputStr != null && !inputStr.isEmpty()) return inputStr; String name = ""; int index = 0; Iterator it = reports.iterator(); @@ -320,7 +341,12 @@ public String getInputString(){ SmallIndividualReport individual = it.next(); name = (name.length() > 0) ? name + ", " + individual.getFileName() : individual.getFileName(); } - return name; + inputStr = name; + return inputStr; + } + + public Map getZipsPaths() { + return zipsPaths; } public Configuration getConfig() { diff --git a/src/main/java/dpfmanager/shell/modules/report/core/IndividualReport.java b/src/main/java/dpfmanager/shell/modules/report/core/IndividualReport.java index b2724c3f..2b51dc74 100644 --- a/src/main/java/dpfmanager/shell/modules/report/core/IndividualReport.java +++ b/src/main/java/dpfmanager/shell/modules/report/core/IndividualReport.java @@ -148,6 +148,10 @@ public class IndividualReport extends ReportSerializable { private boolean isOriginal = true; + private String inputStr; + + private String serPath; + /** * Error constructor */ @@ -246,6 +250,14 @@ public void setIsosCheck(List isosCheck) { this.checkedIsos = isosCheck; } + public String getInputStr() { + return inputStr; + } + + public void setInputStr(String inputStr) { + this.inputStr = inputStr; + } + public List getSelectedIsos() { if (checkedIsos == null) return new ArrayList<>(); return checkedIsos; @@ -265,6 +277,14 @@ public void setConformanceCheckerReport(String report) { precomputedOutput = true; } + public String getSerPath() { + return serPath; + } + + public void setSerPath(String serPath) { + this.serPath = serPath; + } + public boolean hasPrecomputedOutput() { return precomputedOutput; } diff --git a/src/main/java/dpfmanager/shell/modules/report/core/ReportGenerator.java b/src/main/java/dpfmanager/shell/modules/report/core/ReportGenerator.java index 00e4bae2..0fb1767b 100644 --- a/src/main/java/dpfmanager/shell/modules/report/core/ReportGenerator.java +++ b/src/main/java/dpfmanager/shell/modules/report/core/ReportGenerator.java @@ -34,6 +34,7 @@ import dpfmanager.shell.modules.report.util.ReportJson; import dpfmanager.shell.modules.report.util.ReportPDF; import dpfmanager.shell.modules.report.util.ReportXml; +import edu.emory.mathcs.backport.java.util.Arrays; import org.apache.commons.lang.time.FastDateFormat; import org.apache.logging.log4j.Level; @@ -431,7 +432,7 @@ private void extractFile(ZipInputStream zipIn, String filePath) throws IOExcepti * * @param name the name */ - private void copyHtmlFolder(String name) { + synchronized private void copyHtmlFolder(String name) { // Get the target folder File nameFile = new File(name); String absolutePath = nameFile.getAbsolutePath(); @@ -441,6 +442,10 @@ private void copyHtmlFolder(String name) { target.mkdirs(); } + // Already copied + File testFile = new File(target.getPath() + "/js/bootstrap.min.js"); + if (testFile.exists()) return; + // Copy the html folder to target String pathStr = "./src/main/resources/html"; Path path = Paths.get(pathStr); @@ -627,6 +632,7 @@ private void writeIndividualReport(IndividualReport ir, List formats, Co } if (formats.contains("HTML")) { String htmlFileStr = reportName + ".html"; + copyHtmlFolder(htmlFileStr); HtmlReport htmlReport = new HtmlReport(); String htmlOutput = htmlReport.parseIndividual(ir, ir.getReportId(), ir.getInternalReportFodler()); String name = htmlFileStr.substring(htmlFileStr.lastIndexOf("/") + 1, htmlFileStr.length()); @@ -642,6 +648,7 @@ private void writeIndividualReport(IndividualReport ir, List formats, Co PDDocument pdfDocument = pdfReport.parseIndividual(ir, ir.getReportId(), ir.getInternalReportFodler()); if (pdfDocument != null) { pdfDocument.save(pdfFileStr); + pdfDocument.close(); } } catch (Exception e) { context.send(BasicConfig.MODULE_MESSAGE, new ExceptionMessage("Exception in ReportPDF", e)); @@ -652,34 +659,36 @@ private void writeIndividualReport(IndividualReport ir, List formats, Co public String transformGlobalReport(String internalReportFolder, String format, GlobalReport gr) { String xmlFileStr = internalReportFolder + "summary.xml"; + String xmlTempFileStr = internalReportFolder + "summary.temp.xml"; String jsonFileStr = internalReportFolder + "summary.json"; String htmlFileStr = internalReportFolder + "report.html"; String pdfFileStr = internalReportFolder + "report.pdf"; + List reports = new ArrayList<>(); + reports.addAll(gr.getIndividualReports()); if (format.equals("xml")) { - reportXml.parseGlobal(xmlFileStr, gr, gr.getIndividualReports()); + reportXml.parseGlobal(xmlFileStr, gr, reports); return xmlFileStr; } if (format.equals("json")) { - boolean toDelete = false; File xmlFile = new File(xmlFileStr); - if (!xmlFile.exists()){ - reportXml.parseGlobal(xmlFileStr, gr, gr.getIndividualReports()); - toDelete = true; - } - reportJson.xmlToJsonFile(xmlFileStr, jsonFileStr, this); - if (toDelete && xmlFile.exists()){ - xmlFile.delete(); + File xmlTempFile = new File(xmlTempFileStr); + if (xmlFile.exists()){ + reportJson.xmlToJsonFile(xmlFileStr, jsonFileStr, this); + } else { + reportXml.parseGlobal(xmlTempFileStr, gr, reports); + reportJson.xmlToJsonFile(xmlTempFileStr, jsonFileStr, this); + xmlTempFile.delete(); } return jsonFileStr; } if (format.equals("html")) { copyHtmlFolder(htmlFileStr); - reportHtml.parseGlobal(htmlFileStr, gr, gr.getIndividualReports(), this); + reportHtml.parseGlobal(htmlFileStr, gr, reports, this); return htmlFileStr; } if (format.equals("pdf")) { - reportPdf.parseGlobal(pdfFileStr, gr, gr.getIndividualReports()); + reportPdf.parseGlobal(pdfFileStr, gr, reports); return pdfFileStr; } @@ -701,7 +710,10 @@ public String makeSummaryReport(String internalReportFolder, String htmlFileStr = internalReportFolder + "report.html"; String pdfFileStr = internalReportFolder + "report.pdf"; + SmallGlobalReport sgr = new SmallGlobalReport(gr, internalReportFolder + "/summary.ser"); + gr.write(internalReportFolder, "summary.ser"); + sgr.write(internalReportFolder, "summary.min.ser"); // gr = (GlobalReport) GlobalReport.read(internalReportFolder + "/summary.ser"); if (config.getFormats().contains("XML")) { diff --git a/src/main/java/dpfmanager/shell/modules/report/core/ReportSerializable.java b/src/main/java/dpfmanager/shell/modules/report/core/ReportSerializable.java index dd23480f..80c46f20 100644 --- a/src/main/java/dpfmanager/shell/modules/report/core/ReportSerializable.java +++ b/src/main/java/dpfmanager/shell/modules/report/core/ReportSerializable.java @@ -38,7 +38,7 @@ public Integer getVersion(){ } public void write(String internal, String filename){ - version = 2; + version = 3; try { File internalFile = new File(internal); if (!internalFile.exists()) internalFile.mkdirs(); @@ -70,7 +70,7 @@ public static ReportSerializable read(String file){ fis.close(); } catch(Exception ioe) { System.err.println("Error in file: "+file); - //ioe.printStackTrace(); + System.err.println("Error message: "+ioe.getMessage()); obj = null; } return obj; diff --git a/src/main/java/dpfmanager/shell/modules/report/core/ReportService.java b/src/main/java/dpfmanager/shell/modules/report/core/ReportService.java index b262c662..ee65b3f6 100644 --- a/src/main/java/dpfmanager/shell/modules/report/core/ReportService.java +++ b/src/main/java/dpfmanager/shell/modules/report/core/ReportService.java @@ -27,6 +27,7 @@ import dpfmanager.shell.core.messages.ArrayMessage; import dpfmanager.shell.core.messages.ShowMessage; import dpfmanager.shell.core.messages.UiMessage; +import dpfmanager.shell.modules.report.messages.GenerateIndividualMessage; import dpfmanager.shell.modules.report.messages.GenerateMessage; import dpfmanager.shell.modules.report.messages.GlobalReportMessage; import dpfmanager.shell.modules.report.messages.IndividualReportMessage; @@ -42,6 +43,7 @@ import java.util.ArrayList; import java.util.Date; import java.util.List; +import java.util.Map; import javax.annotation.PostConstruct; @@ -75,7 +77,7 @@ public void tractIndividualMessage(IndividualReportMessage message) { // Main function public void tractGlobalMessage(GlobalReportMessage message) { - createGlobalReports(message.getUuid(), message.getIndividuals(), message.getConfig(), message.getStart(), message.getCheckedIsos()); + createGlobalReports(message.getUuid(), message.getIndividuals(), message.getConfig(), message.getStart(), message.getCheckedIsos(), message.getZipsPaths()); config = message.getConfig(); } @@ -86,44 +88,63 @@ private void createIndividualReports(IndividualReport ir, Configuration config) context.send(BasicConfig.MODULE_THREADING, new RunnableMessage(ir.getUuid(), run)); } - private void createGlobalReports(Long uuid, List individuals, Configuration config, Date start, List checkedIsos) { + private void createGlobalReports(Long uuid, List individuals, Configuration config, Date start, List checkedIsos, Map zipsPaths) { // Create global runnable GlobalReportsRunnable run = new GlobalReportsRunnable(generator); - run.setParameters(individuals, config, start, checkedIsos); + run.setParameters(individuals, config, start, checkedIsos, zipsPaths); context.send(BasicConfig.MODULE_THREADING, new RunnableMessage(uuid, run)); } public void tractGenerateMessage(GenerateMessage gm) { Long uuid = gm.getUuid(); String internalReportFolder = null; - Integer globalValue = gm.getFormat().toLowerCase().equals("mets") ? 0 : 1; - globalValue = 1; - Integer max = gm.getGlobalReport().getIndividualReports().size() + globalValue; + Integer globalValue = 1; + Integer max = (gm.isOnlyGlobal()) ? globalValue : (gm.getInfo().getGlobalReport().getIndividualReports().size() + globalValue) * gm.getFormats().size(); // Transform individual reports runnables List individualsMakers = new ArrayList<>(); - for (SmallIndividualReport sir : gm.getGlobalReport().getIndividualReports()) { - if (internalReportFolder == null) internalReportFolder = sir.getInternalReportFodler(); - sir.predictImagePath(); - + List globalMakers = new ArrayList<>(); + for (String format : gm.getFormats()) { + for (SmallIndividualReport sir : gm.getInfo().getGlobalReport().getIndividualReports()) { + if (internalReportFolder == null) internalReportFolder = sir.getInternalReportFodler(); + sir.predictImagePath(); + + MakeReportRunnable mrr = new MakeReportRunnable(generator); + mrr.setIndividualParameters(sir, gm.getInfo().getGlobalReport(), format); + individualsMakers.add(mrr); + } + + // Transforms global report and show runnable MakeReportRunnable mrr = new MakeReportRunnable(generator); - mrr.setIndividualParameters(sir, gm.getGlobalReport(), gm.getFormat()); - individualsMakers.add(mrr); + mrr.setGlobalParameters(internalReportFolder, gm.getInfo(), globalValue, format, gm.isOnlyGlobal()); + globalMakers.add(mrr); } - // Transforms global report and show runnable - MakeReportRunnable mrr = new MakeReportRunnable(generator); - mrr.setGlobalParameters(internalReportFolder, gm.getGlobalReport(), globalValue, gm.getFormat()); - // Init progress bar + MakeReportRunnable mrr = globalMakers.get(0); + mrr.setShowAtEnd(true); context.send(GuiConfig.PERSPECTIVE_SHOW + "." + GuiConfig.COMPONENT_SHOW, new ShowMessage(uuid, max, globalValue, mrr)); - // Start individual transforms - for (MakeReportRunnable iMrr : individualsMakers){ - context.send(BasicConfig.MODULE_THREADING, new RunnableMessage(uuid, iMrr)); + globalMakers.remove(0); + individualsMakers.addAll(globalMakers); + if (!gm.isOnlyGlobal()){ + // Start individual transforms + for (MakeReportRunnable iMrr : individualsMakers){ + context.send(BasicConfig.MODULE_THREADING, new RunnableMessage(uuid, iMrr, "individual")); + } + } else { + // Start global transforms + context.send(GuiConfig.PERSPECTIVE_SHOW + "." + GuiConfig.COMPONENT_SHOW, new ShowMessage(uuid, 0)); } } + public void tractGenerateIndividualMessage(GenerateIndividualMessage gm) { + IndividualReport ir = (IndividualReport) IndividualReport.read(gm.getPath()); + MakeReportRunnable mrr = new MakeReportRunnable(generator); + mrr.setIndividualParameters(ir, gm.getPath(), gm.getFormat(), gm.getConfig()); + context.send(BasicConfig.MODULE_THREADING, new RunnableMessage(System.currentTimeMillis(), mrr, "individual")); + } + public Configuration getConfig() { return config; } diff --git a/src/main/java/dpfmanager/shell/modules/report/core/SmallGlobalReport.java b/src/main/java/dpfmanager/shell/modules/report/core/SmallGlobalReport.java new file mode 100644 index 00000000..c0daaabf --- /dev/null +++ b/src/main/java/dpfmanager/shell/modules/report/core/SmallGlobalReport.java @@ -0,0 +1,89 @@ +/** + *

ReportGenerator.java

This program is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as published by the Free Software + * Foundation, either version 3 of the License, or (at your option) any later version; or, at your + * choice, under the terms of the Mozilla Public License, v. 2.0. SPDX GPL-3.0+ or MPL-2.0+.

+ *

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License and the Mozilla Public License for more details.

You should + * have received a copy of the GNU General Public License and the Mozilla Public License along with + * this program. If not, see http://www.gnu.org/licenses/ + * and at http://mozilla.org/MPL/2.0 .

NB: for the + * © statement, include Easy Innova SL or other company/Person contributing the code.

© + * 2015 Easy Innova, SL

+ * + * @author Adria Llorens Martinez + * @version 1.0 + * @since 23/6/2015 + */ + +package dpfmanager.shell.modules.report.core; + +/** + * The Class GlobalReport. + */ +public class SmallGlobalReport extends ReportSerializable { + + /** + * Do not modify! + */ + private static final long serialVersionUID = 7845L; + + /** + * The path to global report serialized file + */ + private String serGlobalReportPath; + + private String input; + private boolean quick; + private int nFiles; + private int nErrors; + private int nWarnings; + private int nPassed; + + + /** + * Instantiates a new small global report. + */ + public SmallGlobalReport(GlobalReport gr, String path) { + this.serGlobalReportPath = path; + this.input = gr.getInputString(); + this.quick = gr.getConfig().isQuick(); + this.nFiles = gr.getReportsCount(); + this.nErrors = gr.getAllReportsKo(); + this.nWarnings = gr.getAllReportsWarnings(); + this.nPassed = gr.getAllReportsOk(); + } + + /** + * Getters + */ + + public String getSerGlobalReportPath() { + return serGlobalReportPath; + } + + public String getInput() { + return input; + } + + public boolean isQuick() { + return quick; + } + + public int getnFiles() { + return nFiles; + } + + public int getnErrors() { + return nErrors; + } + + public int getnWarnings() { + return nWarnings; + } + + public int getnPassed() { + return nPassed; + } +} diff --git a/src/main/java/dpfmanager/shell/modules/report/core/SmallIndividualReport.java b/src/main/java/dpfmanager/shell/modules/report/core/SmallIndividualReport.java index 93b68977..f3d2dac2 100644 --- a/src/main/java/dpfmanager/shell/modules/report/core/SmallIndividualReport.java +++ b/src/main/java/dpfmanager/shell/modules/report/core/SmallIndividualReport.java @@ -33,6 +33,12 @@ public class SmallIndividualReport implements Comparable, Serializable { int percentOne; int percent; boolean quick; + String inputStr; + + List selectedIsos; + Integer reportVersion; + String serPath; + int idReport; public SmallIndividualReport(IndividualReport ind) { this.isError = ind.isError(); @@ -45,6 +51,11 @@ public SmallIndividualReport(IndividualReport ind) { this.uuid = ind.getUuid(); this.imagePath = ind.getImagePath(); this.quick = ind.isQuick(); + this.inputStr = ind.getInputStr(); + this.serPath = ind.getSerPath(); + this.idReport = ind.getIdReport(); + this.reportVersion = ind.getVersion(); + this.selectedIsos = ind.getSelectedIsos(); } public void generate(IndividualReport ind){ @@ -67,6 +78,10 @@ public void computePercent(GlobalReport global){ this.percentOne = calculatePercent(global, 1.0); } + public String getInputStr() { + return inputStr; + } + public String getImagePath() { return imagePath; } @@ -109,14 +124,14 @@ public int getNErrorsPolicy(String iso){ if (nErrorsPolicy.containsKey(iso)) { return nErrorsPolicy.get(iso); } - return 0; + return -1; } public int getNWarningsPolicy(String iso){ if (nWarningsPolicy.containsKey(iso)) { return nWarningsPolicy.get(iso); } - return 0; + return -1; } public int getAllNErrorsPolicy(){ @@ -182,6 +197,22 @@ public Long getUuid() { return uuid; } + public String getSerPath() { + return serPath; + } + + public int getIdReport() { + return idReport; + } + + public int getReportVersion() { + return reportVersion; + } + + public List getSelectedIsos() { + return selectedIsos; + } + public boolean isQuick() { return quick; } diff --git a/src/main/java/dpfmanager/shell/modules/report/messages/GenerateIndividualMessage.java b/src/main/java/dpfmanager/shell/modules/report/messages/GenerateIndividualMessage.java new file mode 100644 index 00000000..36f74329 --- /dev/null +++ b/src/main/java/dpfmanager/shell/modules/report/messages/GenerateIndividualMessage.java @@ -0,0 +1,53 @@ +/** + *

IndividualReportMessage.java

This program is free software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License as published by the Free + * Software Foundation, either version 3 of the License, or (at your option) any later version; or, + * at your choice, under the terms of the Mozilla Public License, v. 2.0. SPDX GPL-3.0+ or MPL-2.0+. + *

This program is distributed in the hope that it will be useful, but WITHOUT ANY + * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + * PURPOSE. See the GNU General Public License and the Mozilla Public License for more details.

+ *

You should have received a copy of the GNU General Public License and the Mozilla Public + * License along with this program. If not, see http://www.gnu.org/licenses/ + * and at http://mozilla.org/MPL/2.0 .

NB: for the + * © statement, include Easy Innova SL or other company/Person contributing the code.

© + * 2015 Easy Innova, SL

+ * + * @author Adria Llorens + * @version 1.0 + * @since 23/7/2015 + */ + +package dpfmanager.shell.modules.report.messages; + +import dpfmanager.conformancechecker.configuration.Configuration; +import dpfmanager.shell.core.messages.DpfMessage; +import dpfmanager.shell.modules.report.core.GlobalReport; + +/** + * Created by Adria Llorens on 13/06/2017. + */ +public class GenerateIndividualMessage extends DpfMessage { + + private String format; + private String path; + private Configuration config; + + public GenerateIndividualMessage(String format, String path, Configuration config) { + this.format = format; + this.path = path; + this.config = config; + } + + public String getFormat() { + return format; + } + + public String getPath() { + return path; + } + + public Configuration getConfig() { + return config; + } +} + diff --git a/src/main/java/dpfmanager/shell/modules/report/messages/GenerateMessage.java b/src/main/java/dpfmanager/shell/modules/report/messages/GenerateMessage.java index 378f4bf3..4fd85bb1 100644 --- a/src/main/java/dpfmanager/shell/modules/report/messages/GenerateMessage.java +++ b/src/main/java/dpfmanager/shell/modules/report/messages/GenerateMessage.java @@ -20,33 +20,50 @@ package dpfmanager.shell.modules.report.messages; import dpfmanager.shell.core.messages.DpfMessage; -import dpfmanager.shell.modules.report.core.GlobalReport; +import dpfmanager.shell.modules.report.util.ReportGui; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; /** * Created by Adria Llorens on 13/06/2017. */ public class GenerateMessage extends DpfMessage { - private String format; - private GlobalReport globalReport; + private List formats = null; + private ReportGui info; private Long uuid; + private boolean onlyGlobal; - public GenerateMessage(String format, GlobalReport g, Long uuid) { - this.format = format; - this.globalReport = g; + public GenerateMessage(String format, ReportGui info, Long uuid, boolean onlyGlobal) { + this.formats = Arrays.asList(format); + this.info = info; this.uuid = uuid; + this.onlyGlobal = onlyGlobal; } - public String getFormat() { - return format; + public GenerateMessage(List formats, ReportGui info, Long uuid, boolean onlyGlobal) { + this.formats = formats; + this.info = info; + this.uuid = uuid; + this.onlyGlobal = onlyGlobal; } - public GlobalReport getGlobalReport() { - return globalReport; + public ReportGui getInfo() { + return info; } public Long getUuid() { return uuid; } + + public boolean isOnlyGlobal() { + return onlyGlobal; + } + + public List getFormats() { + return formats; + } } diff --git a/src/main/java/dpfmanager/shell/modules/report/messages/GlobalReportMessage.java b/src/main/java/dpfmanager/shell/modules/report/messages/GlobalReportMessage.java index 0cbe2325..3740c2ff 100644 --- a/src/main/java/dpfmanager/shell/modules/report/messages/GlobalReportMessage.java +++ b/src/main/java/dpfmanager/shell/modules/report/messages/GlobalReportMessage.java @@ -25,6 +25,7 @@ import java.util.Date; import java.util.List; +import java.util.Map; /** * Created by Adria Llorens on 24/03/2016. @@ -36,13 +37,15 @@ public class GlobalReportMessage extends DpfMessage { private Configuration config; private Date start; private List checkedIsos; + private Map zipsPaths; - public GlobalReportMessage(Long u, List i, Configuration c, Date s, List ci) { + public GlobalReportMessage(Long u, List i, Configuration c, Date s, List ci, Map z) { uuid = u; individuals = i; config = c; start = s; checkedIsos = ci; + zipsPaths = z; } public List getIndividuals() { @@ -64,4 +67,9 @@ public Date getStart() { public List getCheckedIsos() { return checkedIsos; } + + public Map getZipsPaths() { + return zipsPaths; + } + } diff --git a/src/main/java/dpfmanager/shell/modules/report/runnable/GlobalReportsRunnable.java b/src/main/java/dpfmanager/shell/modules/report/runnable/GlobalReportsRunnable.java index 773190f5..3324f22a 100644 --- a/src/main/java/dpfmanager/shell/modules/report/runnable/GlobalReportsRunnable.java +++ b/src/main/java/dpfmanager/shell/modules/report/runnable/GlobalReportsRunnable.java @@ -44,6 +44,7 @@ import java.security.NoSuchAlgorithmException; import java.util.Date; import java.util.List; +import java.util.Map; /** * Created by Adria Llorens on 13/04/2016. @@ -55,6 +56,7 @@ public class GlobalReportsRunnable extends DpfRunnable { private Configuration config; private Date start; private List checkedIsos; + private Map zipsPaths; public GlobalReportsRunnable(ReportGenerator g) { // No context yet @@ -65,11 +67,12 @@ public GlobalReportsRunnable(ReportGenerator g) { public void handleContext(DpfContext context) { } - public void setParameters(List i, Configuration c, Date s, List ci) { + public void setParameters(List i, Configuration c, Date s, List ci, Map z) { individuals = i; config = c; start = s; checkedIsos = ci; + zipsPaths = z; } @Override @@ -79,7 +82,7 @@ public void runTask() { // Generate GlobalReport GlobalReport global = new GlobalReport(); - global.init(config, checkedIsos); + global.init(config, checkedIsos, zipsPaths); for (SmallIndividualReport individual : individuals) { global.addIndividual(individual); if (individual != null) { @@ -95,9 +98,8 @@ public void runTask() { if (internalReportFolder != null) { // Create it - String summaryXmlFile = null; try { - summaryXmlFile = generator.makeSummaryReport(internalReportFolder, global, config); + generator.makeSummaryReport(internalReportFolder, global, config); context.send(BasicConfig.MODULE_MESSAGE, new LogMessage(getClass(), Level.DEBUG, bundle.getString("globalReport").replace("%1", config.getOutput() != null ? config.getOutput() : internalReportFolder))); context.send(BasicConfig.MODULE_MESSAGE, new LogMessage(getClass(), Level.DEBUG, bundle.getString("durationReport").replace("%1", global.prettyPrintDuration()))); } catch (OutOfMemoryError e) { @@ -106,8 +108,8 @@ public void runTask() { // Send report over FTP try { - if (DPFManagerProperties.getFeedback() && summaryXmlFile != null) { - sendFtpCamel(summaryXmlFile); + if (DPFManagerProperties.getFeedback()) { + sendFtpCamel(internalReportFolder); } } catch (Exception e) { context.send(BasicConfig.MODULE_MESSAGE, new ExceptionMessage(bundle.getString("exception"), e)); @@ -122,13 +124,12 @@ public void runTask() { /** * Sends the report to the preforma FTP. * - * @param summaryXmlFile the summary xml * @throws NoSuchAlgorithmException An error occurred */ - private void sendFtpCamel(String summaryXmlFile) - throws NoSuchAlgorithmException, IOException { - String summaryXml = FileUtils.readFileToString(new File(summaryXmlFile), "utf-8"); - context.send(BasicConfig.MODULE_MESSAGE, new LogMessage(getClass(), Level.DEBUG, bundle.getString("sendingFeedback"))); + private void sendFtpCamel(String internalReportFolder) throws NoSuchAlgorithmException, IOException { + File serFile = new File(internalReportFolder + "/summary.ser"); + if (!serFile.exists()) return; + String summarySer = FileUtils.readFileToString(serFile, "utf-8"); String ftp = "84.88.145.109"; String user = "preformaapp"; String password = "2.eX#lh>"; @@ -142,7 +143,7 @@ public void configure() { }); ProducerTemplate template = contextcc.createProducerTemplate(); contextcc.start(); - template.sendBody("direct:sendFtp", summaryXml); + template.sendBody("direct:sendFtp", summarySer); contextcc.stop(); } catch (Exception e) { e.printStackTrace(); diff --git a/src/main/java/dpfmanager/shell/modules/report/runnable/MakeReportRunnable.java b/src/main/java/dpfmanager/shell/modules/report/runnable/MakeReportRunnable.java index 40d51d1f..c17c7431 100644 --- a/src/main/java/dpfmanager/shell/modules/report/runnable/MakeReportRunnable.java +++ b/src/main/java/dpfmanager/shell/modules/report/runnable/MakeReportRunnable.java @@ -24,15 +24,19 @@ import dpfmanager.shell.core.config.GuiConfig; import dpfmanager.shell.core.context.DpfContext; import dpfmanager.shell.core.messages.ShowMessage; +import dpfmanager.shell.core.messages.UiMessage; +import dpfmanager.shell.interfaces.gui.component.global.messages.GuiGlobalMessage; import dpfmanager.shell.modules.database.messages.JobsMessage; import dpfmanager.shell.modules.report.core.GlobalReport; import dpfmanager.shell.modules.report.core.IndividualReport; import dpfmanager.shell.modules.report.core.ReportGenerator; import dpfmanager.shell.modules.report.core.SmallIndividualReport; +import dpfmanager.shell.modules.report.util.ReportGui; import dpfmanager.shell.modules.threading.messages.IndividualStatusMessage; import dpfmanager.shell.modules.threading.runnable.DpfRunnable; import java.io.File; +import java.util.List; /** * Created by Adria Llorens on 13/04/2016. @@ -40,13 +44,20 @@ public class MakeReportRunnable extends DpfRunnable { private SmallIndividualReport sir; + private IndividualReport ir; private String format; + private String path; private ReportGenerator generator; private GlobalReport global; + private ReportGui info; private String internalReportFolder; private Integer globalValue; + private Configuration config; private boolean individual = false; + private boolean onlyIndividual = false; + private boolean onlyGlobal = true; + private boolean showAtEnd; public MakeReportRunnable(ReportGenerator g) { // No context yet @@ -64,23 +75,60 @@ public void setIndividualParameters(SmallIndividualReport i, GlobalReport g, Str individual = true; } - public void setGlobalParameters(String i, GlobalReport g, Integer gv, String f) { + public void setIndividualParameters(IndividualReport i, String p, String f, Configuration c) { + ir = i; + path = p; + format = f; + config = c; + onlyIndividual = true; + } + + public void setGlobalParameters(String i, ReportGui in, Integer gv, String f, boolean o) { internalReportFolder = i; - global = g; + info = in; + global = info.getGlobalReport(); format = f; globalValue = gv; + onlyGlobal = o; individual = false; + showAtEnd = false; + } + + public void setShowAtEnd(boolean showAtEnd) { + this.showAtEnd = showAtEnd; } @Override public void runTask() { - if (individual){ + if (onlyIndividual){ + generateOnlyIndividualReport(); + } else if (individual){ generateIndividualReport(); } else { generateGlobalReport(); } } + private void generateOnlyIndividualReport(){ + File reportSerializedFile = new File(path); + if (reportSerializedFile.exists()){ + IndividualReport ir = (IndividualReport) IndividualReport.read(reportSerializedFile.getPath()); + String outputfile = generator.getReportName(ir.getInternalReportFodler(), ir.getReportFileName(), ir.getIdReport()); + generator.transformIndividualReport(outputfile, format, ir, config); + String finalOutput = outputfile; + if (format.toLowerCase().equals("html")){ + String first = outputfile.substring(0, outputfile.lastIndexOf("/")); + String second = outputfile.substring(outputfile.lastIndexOf("/")) + "." + format; + finalOutput = first + "/html" + second; + } else if (format.toLowerCase().equals("mets")) { + finalOutput = outputfile + ".mets.xml"; + } else { + finalOutput = outputfile + "." + format; + } + context.send(GuiConfig.PERSPECTIVE_SHOW + "." + GuiConfig.COMPONENT_SHOW, new ShowMessage(format, finalOutput)); + } + } + private void generateIndividualReport(){ String filename = sir.getReportPath().substring(sir.getReportPath().lastIndexOf("/") + 1); String reportSerialized = sir.getInternalReportFodler() + "serialized/" + filename + ".ser"; @@ -96,11 +144,15 @@ private void generateIndividualReport(){ private void generateGlobalReport(){ String outputPath = generator.transformGlobalReport(internalReportFolder, format, global); context.send(GuiConfig.PERSPECTIVE_SHOW + "." + GuiConfig.COMPONENT_SHOW, new ShowMessage(getUuid(), globalValue)); - if (format.toLowerCase().equals("mets")) { - outputPath = internalReportFolder; - } + if (format.toLowerCase().equals("mets")) outputPath = internalReportFolder; if (outputPath != null){ - context.send(GuiConfig.PERSPECTIVE_SHOW + "." + GuiConfig.COMPONENT_SHOW, new ShowMessage(getUuid(), format, outputPath)); + if (onlyGlobal){ + // Show report + context.send(GuiConfig.PERSPECTIVE_SHOW + "." + GuiConfig.COMPONENT_SHOW, new ShowMessage(getUuid(), format, outputPath)); + } else if (showAtEnd) { + // Show javafx global report + context.send(GuiConfig.PERSPECTIVE_SHOW + "." + GuiConfig.COMPONENT_SHOW, new ShowMessage(getUuid(), info)); + } } } diff --git a/src/main/java/dpfmanager/shell/modules/report/util/ReportGui.java b/src/main/java/dpfmanager/shell/modules/report/util/ReportGui.java index 1d4b184a..627d39f0 100644 --- a/src/main/java/dpfmanager/shell/modules/report/util/ReportGui.java +++ b/src/main/java/dpfmanager/shell/modules/report/util/ReportGui.java @@ -19,15 +19,14 @@ package dpfmanager.shell.modules.report.util; -import dpfmanager.shell.core.DPFManagerProperties; import dpfmanager.shell.modules.report.core.GlobalReport; +import dpfmanager.shell.modules.report.core.SmallGlobalReport; import javafx.beans.property.SimpleMapProperty; import javafx.collections.FXCollections; import com.google.gson.JsonObject; import com.google.gson.JsonParser; -import org.apache.commons.io.FileUtils; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.util.PDFTextStripper; @@ -39,12 +38,10 @@ import java.nio.file.attribute.BasicFileAttributes; import java.text.DateFormat; import java.text.SimpleDateFormat; -import java.util.Collection; import java.util.Date; import java.util.Locale; import java.util.Map; import java.util.Objects; -import java.util.ResourceBundle; /** * Created by easy on 17/09/2015. @@ -58,8 +55,10 @@ public class ReportGui implements Comparable{ private String reportDir; private Long timestamp; private boolean loaded; + private boolean loadedPartial; private boolean error; private boolean last; + private boolean quick; private String date; private Integer nfiles; @@ -73,6 +72,7 @@ public class ReportGui implements Comparable{ private String delete; private String deletePath; + private SmallGlobalReport smallGlobalReport; private GlobalReport globalReport; private Integer reportVersion = 0; @@ -83,11 +83,38 @@ public ReportGui(String baseDir, String reportDay, String reportDir) { this.uuid = reportDay + reportDir; this.loaded = false; this.error = true; + this.loadedPartial = false; readTime(); } + public ReportGui(String path) { + if (path.endsWith("/")){ + path = path.substring(0, path.length() - 1); + } + + this.reportDir = path.substring(path.lastIndexOf("/") + 1); + path = path.substring(0, path.lastIndexOf("/")); + this.reportDay = path.substring(path.lastIndexOf("/") + 1); + this.baseDir = path.substring(0, path.lastIndexOf("/")); + + this.uuid = reportDay + reportDir; + this.loaded = false; + this.error = true; + this.loadedPartial = false; + readTime(); + loadPartial(); + if (!loadedPartial) { + load(); + } + } + public void readTime(){ timestamp = 0L; + File reportSmallSer = new File(baseDir + "/" + reportDay + "/" + reportDir + "/summary.min.ser"); + if (reportSmallSer.exists() && reportSmallSer.length() > 0) { + timestamp = getTimestamp(reportSmallSer.getPath()); + return; + } File reportSer = new File(baseDir + "/" + reportDay + "/" + reportDir + "/summary.ser"); if (reportSer.exists() && reportSer.length() > 0) { timestamp = getTimestamp(reportSer.getPath()); @@ -111,11 +138,14 @@ public void readTime(){ File reportPdf = new File(baseDir + "/" + reportDay + "/" + reportDir + "/report.pdf"); if (reportPdf.exists() && reportPdf.length() > 0) { timestamp = getTimestamp(reportPdf.getPath()); - return; } } public boolean exists(){ + File reportSmallSer = new File(baseDir + "/" + reportDay + "/" + reportDir + "/summary.min.ser"); + if (reportSmallSer.exists() && reportSmallSer.length() > 0) { + return true; + } File reportSer = new File(baseDir + "/" + reportDay + "/" + reportDir + "/summary.ser"); if (reportSer.exists() && reportSer.length() > 0) { return true; @@ -139,6 +169,16 @@ public boolean exists(){ return false; } + public void loadPartial() { + if (loadedPartial) return; + File reportSmallSer = new File(baseDir + "/" + reportDay + "/" + reportDir + "/summary.min.ser"); + if (reportSmallSer.exists() && reportSmallSer.length() > 0) { + createRowFromSmallSer(reportDay, reportSmallSer); + loadedPartial = true; + } + loadedPartial = true; + } + public void load() { if (loaded) return; File reportSer = new File(baseDir + "/" + reportDay + "/" + reportDir + "/summary.ser"); @@ -161,8 +201,7 @@ public void load() { if (error && reportPdf.exists() && reportPdf.length() > 0) { createRowFromPdf(reportDay, reportPdf); } - - readFormats(); + loaded = true; } public void readFormats() { @@ -179,17 +218,6 @@ public void readFormats() { addFormat(format, report.getPath()); } } - // Add mets - File folder = new File(baseDir + "/" + reportDay + "/" + reportDir + "/"); - if (folder.exists() && folder.isDirectory()) { - String[] filter = {"mets.xml"}; - Collection childs = FileUtils.listFiles(folder, filter, false); - if (childs.size() > 0) { - addFormat("mets", folder.getPath()); - } - } - // All OK - loaded = true; } } @@ -220,6 +248,40 @@ static String readFullFile(String path, Charset encoding) { } } + /** + * Create report row from serialized SmallGlobalReport Object + * + * @param reportDay the report day + * @param file the file + * @return the report row + */ + private void createRowFromSmallSer(String reportDay, File file) { + try { + String sdate = reportDay.substring(6, 8) + "/" + reportDay.substring(4, 6) + "/" + reportDay.substring(0, 4); + SmallGlobalReport sgr = (SmallGlobalReport) GlobalReport.read(file.getAbsolutePath()); + if (sgr == null) { + error = true; + return; + } + + smallGlobalReport = sgr; + if (sgr.getVersion() != null) { + reportVersion = sgr.getVersion(); + } + int n = sgr.getnFiles(); + String stime = getStime(timestamp); + String input = sgr.getInput(); + int passed = sgr.getnPassed(); + int errors = sgr.getnErrors(); + int warnings = sgr.getnWarnings(); + int score = (n > 0) ? (passed) * 100 / n : 0; + + setValues(sdate, stime, input, n, errors, warnings, passed, score, file.getAbsolutePath(), sgr.isQuick()); + } catch (Exception e) { + error = true; + } + } + /** * Create report row from serialized GlobalReport Object * @@ -246,9 +308,9 @@ private void createRowFromSer(String reportDay, File file) { int passed = gr.getAllReportsOk(); int errors = gr.getAllReportsKo(); int warnings = gr.getAllReportsWarnings(); - int score = (n > 0) ? passed * 100 / n : 0; + int score = (n > 0) ? (passed) * 100 / n : 0; - setValues(sdate, stime, input, n, errors, warnings, passed, score, file.getAbsolutePath()); + setValues(sdate, stime, input, n, errors, warnings, passed, score, file.getAbsolutePath(), gr.getConfig().isQuick()); } catch (Exception e) { error = true; } @@ -311,7 +373,7 @@ private void createRowFromXml(String reportDay, File file) { score = passed * 100 / n; } - setValues(sdate, stime, input, n, errors, warnings, passed, score, file.getAbsolutePath()); + setValues(sdate, stime, input, n, errors, warnings, passed, score, file.getAbsolutePath(), false); } catch (Exception e) { error = true; } @@ -399,7 +461,7 @@ private void createRowFromHtml(String reportDay, File file) { } } - setValues(sdate, stime, input, n, errors, warnings, passed, score, file.getAbsolutePath()); + setValues(sdate, stime, input, n, errors, warnings, passed, score, file.getAbsolutePath(), false); } catch (Exception e) { error = true; } @@ -461,7 +523,7 @@ private void createRowFromJson(String reportDay, File file) { } - setValues(sdate, stime, input, n, errors, warnings, passed, score, file.getAbsolutePath()); + setValues(sdate, stime, input, n, errors, warnings, passed, score, file.getAbsolutePath(), false); } catch (Exception e) { error = true; } @@ -513,13 +575,13 @@ private void createRowFromPdf(String reportDay, File file) { } document.close(); - setValues(sdate, stime, input, n, errors, mWarns, passed, score, file.getAbsolutePath()); + setValues(sdate, stime, input, n, errors, mWarns, passed, score, file.getAbsolutePath(), false); } catch (Exception e) { error = true; } } - public void setValues(String sdate, String stime, String input, Integer nFiles, Integer errors, Integer warnings, Integer passed, Integer score, String deletePath) { + public void setValues(String sdate, String stime, String input, Integer nFiles, Integer errors, Integer warnings, Integer passed, Integer score, String deletePath, boolean quick) { this.date = parseDate2Locale(sdate); this.time = stime; this.input = input; @@ -527,11 +589,12 @@ public void setValues(String sdate, String stime, String input, Integer nFiles, this.errors = errors; this.warnings = warnings; this.passed = passed; - this.score = score; + this.score = (score == 0 && this.passed > 0) ? 1 : score; this.formats = new SimpleMapProperty<>(FXCollections.observableHashMap()); this.delete = System.currentTimeMillis() + "";; this.deletePath = deletePath; this.error = false; + this.quick = quick; } private String parseDate2Locale(String sdate) { @@ -594,6 +657,13 @@ public String getInput() { return input; } + public String getInputLower() { + if (input == null) { + String h = ""; + } + return input.toLowerCase(); + } + public void setInput(String input) { this.input = input; } @@ -652,10 +722,6 @@ public void setDeletePath(String deletePath) { this.deletePath = deletePath; } - public boolean isLoaded() { - return loaded; - } - public Integer getScore() { return score; } @@ -716,6 +782,14 @@ public String getInternalReportFolder(){ return baseDir + "/" + reportDay + "/" + reportDir + "/"; } + public boolean isLoaded() { + return loaded; + } + + public boolean isQuick(){ + return quick; + } + /** * Overrides */ diff --git a/src/main/java/dpfmanager/shell/modules/report/util/ReportHtml.java b/src/main/java/dpfmanager/shell/modules/report/util/ReportHtml.java index 6d7f61ad..e87a6be1 100644 --- a/src/main/java/dpfmanager/shell/modules/report/util/ReportHtml.java +++ b/src/main/java/dpfmanager/shell/modules/report/util/ReportHtml.java @@ -30,6 +30,7 @@ import org.apache.commons.lang.StringUtils; import java.io.File; +import java.util.Collections; import java.util.List; /** @@ -43,6 +44,7 @@ public class ReportHtml extends ReportGeneric { * @param gr the global report. */ public void parseGlobal(String outputfile, GlobalReport gr, List reports, ReportGenerator generator) { + Collections.sort(reports); String templatePath = "templates/global.html"; String imagePath = "templates/image.html"; diff --git a/src/main/java/dpfmanager/shell/modules/report/util/ReportIndividualGui.java b/src/main/java/dpfmanager/shell/modules/report/util/ReportIndividualGui.java new file mode 100644 index 00000000..7a67d772 --- /dev/null +++ b/src/main/java/dpfmanager/shell/modules/report/util/ReportIndividualGui.java @@ -0,0 +1,288 @@ +/** + *

ReportRow.java

This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by the Free Software + * Foundation, either version 3 of the License, or (at your option) any later version; or, at your + * choice, under the terms of the Mozilla Public License, v. 2.0. SPDX GPL-3.0+ or MPL-2.0+.

+ *

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License and the Mozilla Public License for more details.

You should + * have received a copy of the GNU General Public License and the Mozilla Public License along with + * this program. If not, see http://www.gnu.org/licenses/ + * and at http://mozilla.org/MPL/2.0 .

NB: for the + * © statement, include Easy Innova SL or other company/Person contributing the code.

© + * 2015 Easy Innova, SL

+ * + * @author Adria Llorens + * @version 1.0 + * @since 23/7/2015 + */ + +package dpfmanager.shell.modules.report.util; + +import dpfmanager.conformancechecker.configuration.Configuration; +import dpfmanager.shell.modules.report.core.GlobalReport; +import dpfmanager.shell.modules.report.core.IndividualReport; +import dpfmanager.shell.modules.report.core.SmallIndividualReport; + +import org.apache.commons.io.FileUtils; + +import java.io.File; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Created by easy on 17/09/2015. + */ +public class ReportIndividualGui { + + private String[] available_formats = {"html", "xml", "json", "pdf", "mets.xml"}; + + private Integer id; + private String path; + private String name; + private String filePath; + private boolean loaded; + private boolean error; + private boolean last; + private boolean quick; + private boolean old; + + private String filename; + private String zipPath; + private Integer errors; + private Integer warnings; + private Integer reportId; + private Map formats; + private List modifiedIsos; + private Map zipsPaths; + + private Configuration config; + private Integer reportVersion = 0; + private SmallIndividualReport individual; + + // OLD + public ReportIndividualGui(String path, Integer id) { + this.id = id; + this.path = path; + this.loaded = false; + this.error = false; + this.last = false; + this.old = true; + } + + // SIR + public ReportIndividualGui(GlobalReport global, SmallIndividualReport sir, Configuration config, Integer id) { + this.modifiedIsos = new ArrayList<>(global.getModifiedIsos().keySet()); + this.zipsPaths = global.getZipsPaths(); + this.individual = sir; + this.path = sir.getSerPath(); + this.name = parseFileName(path); + this.config = config; + this.id = id; + this.loaded = false; + this.error = false; + this.last = false; + this.old = false; + } + + // SER + public ReportIndividualGui(String path, GlobalReport global, Integer id) { + this.modifiedIsos = new ArrayList<>(global.getModifiedIsos().keySet()); + this.zipsPaths = global.getZipsPaths(); + this.individual = null; + this.path = path; + this.name = parseFileName(path); + this.config = global.getConfig(); + this.id = id; + this.loaded = false; + this.error = false; + this.last = false; + this.old = false; + } + + public void setLast(boolean last) { + this.last = last; + } + + private String parseFileName(String path){ + String serName = new File(path).getName(); + return serName.substring(serName.indexOf("-") + 1, serName.lastIndexOf(".")); + } + + public void load(){ + if (loaded) return; + resetValues(); + createRow(); + } + + public void loadFormats(){ + if (!loaded) return; + readFormats(); + } + + private void resetValues(){ + errors = 0; + warnings = 0; + filename = ""; + } + + private void createRow(){ + if (old) { + createRowFromOld(); + } else if (individual != null) { + createRowFromSir(); + } else { + createRowFromSer(); + } + } + + private void createRowFromOld(){ + reportVersion = 0; + filePath = path; + name = new File(path).getName(); + reportId = Integer.parseInt(name.substring(0, name.indexOf("-"))); + filename = name.substring(name.indexOf("-") + 1, name.lastIndexOf(".")); + if (filename.endsWith(".mets")) { + filename = filename.substring(0, filename.lastIndexOf(".")); + } + quick = false; + loaded = true; + zipPath = null; + } + + private void createRowFromSir(){ + reportVersion = individual.getReportVersion(); + for (String iso : individual.getSelectedIsos()){ + errors += (modifiedIsos.contains(iso)) ? individual.getNErrorsPolicy(iso) : individual.getNErrors(iso); + warnings += (modifiedIsos.contains(iso)) ? individual.getNWarningsPolicy(iso) : individual.getNWarnings(iso); + } + filename = individual.getFileName(); + reportId = individual.getIdReport(); + filePath = individual.getFilePath(); + zipPath = readZipPath(); + quick = individual.isQuick(); + loaded = true; + } + + private void createRowFromSer(){ + try { + IndividualReport ir = (IndividualReport) IndividualReport.read(path); + if (ir == null) { + error = true; + return; + } + if (ir.getVersion() != null) { + reportVersion = ir.getVersion(); + } + for (String iso : individual.getSelectedIsos()){ + errors += (modifiedIsos.contains(iso)) ? individual.getNErrorsPolicy(iso) : individual.getNErrors(iso); + warnings += (modifiedIsos.contains(iso)) ? individual.getNWarningsPolicy(iso) : individual.getNWarnings(iso); + } + filename = ir.getFileName(); + reportId = ir.getIdReport(); + filePath = ir.getFilePath(); + zipPath = readZipPath(); + quick = ir.isQuick(); + loaded = true; + } catch (Exception e) { + error = true; + } + } + + private String readZipPath(){ + for (String key : zipsPaths.keySet()){ + if (filePath.contains("/" + key + "/") || filePath.contains("\\" + key + "\\")) { + return zipsPaths.get(key); + } + } + return null; + } + + public void readFormats() { + formats = new HashMap<>(); + File pathFile = new File(path); + File baseFile = pathFile.getParentFile(); + if (baseFile.getName().endsWith("serialized")) { + baseFile = baseFile.getParentFile(); + } + if (baseFile.getName().endsWith("html")) { + baseFile = baseFile.getParentFile(); + } + if (!error && baseFile.exists() && baseFile.isDirectory()) { + + // Add formats + for (String format : available_formats) { + File report; + if (format.equals("json") || format.equals("xml") || format.equals("pdf") || format.equals("mets.xml")) { + report = new File(baseFile.getPath() + "/" + reportId + "-" + filename + "." + format); + } else { + report = new File(baseFile.getPath() + "/html/" + reportId + "-" + filename + "." + format); + } + if (report.exists() && report.length() > 0) { + format = format.equals("mets.xml") ? "mets" : format; + formats.put(format, report.getPath()); + } + } + } + } + + public String getShowFilePath() { + if (zipPath != null) return zipPath; + return filePath; + } + + /** + * Getters + */ + + public String getName() { + return name; + } + public String getLowerName() { + return name.toLowerCase(); + } + public String getPath() { + return path; + } + public Integer getErrors() { + return errors; + } + public Integer getWarnings() { + return warnings; + } + public Map getFormats() { + return formats; + } + public String getFilename() { + return filename; + } + public Integer getReportVersion() { + return reportVersion; + } + public Configuration getConfig() { + return config; + } + public Integer getId() { + return id; + } + public boolean isLast() { + return last; + } + public String getFilePath() { + return filePath; + } + public boolean isQuick() { + return quick; + } + public boolean isOld() { + return old; + } + public String getZipPath(){ + return zipPath; + } +} + + diff --git a/src/main/java/dpfmanager/shell/modules/report/util/ReportXml.java b/src/main/java/dpfmanager/shell/modules/report/util/ReportXml.java index 36cb2046..e7935099 100644 --- a/src/main/java/dpfmanager/shell/modules/report/util/ReportXml.java +++ b/src/main/java/dpfmanager/shell/modules/report/util/ReportXml.java @@ -31,14 +31,18 @@ package dpfmanager.shell.modules.report.util; +import dpfmanager.conformancechecker.tiff.TiffConformanceChecker; import dpfmanager.shell.modules.report.core.GlobalReport; import dpfmanager.shell.modules.report.core.ReportGeneric; import dpfmanager.shell.modules.report.core.SmallIndividualReport; +import com.easyinnova.implementation_checker.ImplementationCheckerLoader; + import org.w3c.dom.Document; import org.w3c.dom.Element; import java.io.File; +import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; @@ -60,7 +64,7 @@ public class ReportXml extends ReportGeneric { * @param xmlfile the file name. * @param gr the global report. */ - public void parseGlobal(String xmlfile, GlobalReport gr, java.util.List reports) { + public void parseGlobal(String xmlfile, GlobalReport gr, List reports) { try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); @@ -73,24 +77,75 @@ public void parseGlobal(String xmlfile, GlobalReport gr, java.util.List 0){ + el.setTextContent("Passed with warnings"); + } else { + el.setTextContent("Error"); + } + report.appendChild(el); + + // Image score + el = doc.createElement("score"); + el.setTextContent(ir.getPercent() + "%"); + report.appendChild(el); + + // ISOs list + report.appendChild(isos); + + // Path + el = doc.createElement("path"); + el.setTextContent(ir.getReportPath() + ".xml"); + report.appendChild(el); + + individualreports.appendChild(report); } // Statistics diff --git a/src/main/java/dpfmanager/shell/modules/threading/ThreadingController.java b/src/main/java/dpfmanager/shell/modules/threading/ThreadingController.java index a5b69c73..73ee4313 100644 --- a/src/main/java/dpfmanager/shell/modules/threading/ThreadingController.java +++ b/src/main/java/dpfmanager/shell/modules/threading/ThreadingController.java @@ -72,7 +72,7 @@ synchronized public void handleMessage(DpfMessage dpfMessage) { } } else if (dpfMessage.isTypeOf(RunnableMessage.class)) { RunnableMessage rm = dpfMessage.getTypedMessage(RunnableMessage.class); - service.run(rm.getRunnable(), rm.getUuid()); + service.run(rm.getRunnable(), rm.getUuid(), rm.getPool()); } else if (dpfMessage.isTypeOf(ThreadsMessage.class)) { ThreadsMessage tm = dpfMessage.getTypedMessage(ThreadsMessage.class); service.processThreadMessage(tm); diff --git a/src/main/java/dpfmanager/shell/modules/threading/ThreadingModule.java b/src/main/java/dpfmanager/shell/modules/threading/ThreadingModule.java index 210627ef..5817a286 100644 --- a/src/main/java/dpfmanager/shell/modules/threading/ThreadingModule.java +++ b/src/main/java/dpfmanager/shell/modules/threading/ThreadingModule.java @@ -64,7 +64,7 @@ public void handleMessage(DpfMessage dpfMessage) { service.handleGlobalStatus(gm, false); } else if (dpfMessage.isTypeOf(RunnableMessage.class)) { RunnableMessage rm = dpfMessage.getTypedMessage(RunnableMessage.class); - service.run(rm.getRunnable(), rm.getUuid()); + service.run(rm.getRunnable(), rm.getUuid(), rm.getPool()); } else if (dpfMessage.isTypeOf(ThreadsMessage.class)){ ThreadsMessage tm = dpfMessage.getTypedMessage(ThreadsMessage.class); service.processThreadMessage(tm); diff --git a/src/main/java/dpfmanager/shell/modules/threading/core/FileCheck.java b/src/main/java/dpfmanager/shell/modules/threading/core/FileCheck.java index 44dfc9c1..8a904caa 100644 --- a/src/main/java/dpfmanager/shell/modules/threading/core/FileCheck.java +++ b/src/main/java/dpfmanager/shell/modules/threading/core/FileCheck.java @@ -27,6 +27,7 @@ import java.util.ArrayList; import java.util.Date; import java.util.List; +import java.util.Map; /** * Created by Adria Llorens on 14/04/2016. @@ -41,6 +42,7 @@ public class FileCheck { private String internal; private String input; private Date start; + private Map zipsPaths; private List individuals; @@ -58,11 +60,12 @@ public FileCheck(long u) { start = new Date(); } - public void init(int n, Configuration c, String i, String ri) { + public void init(int n, Configuration c, String i, String ri, Map z) { total = n; config = c; internal = i; input = ri; + zipsPaths = z; } public void addIndividual(IndividualReport ir) { @@ -127,4 +130,7 @@ public Date getStart() { return start; } + public Map getZipsPaths() { + return zipsPaths; + } } diff --git a/src/main/java/dpfmanager/shell/modules/threading/core/ThreadingService.java b/src/main/java/dpfmanager/shell/modules/threading/core/ThreadingService.java index 57b28e1a..a74d191e 100644 --- a/src/main/java/dpfmanager/shell/modules/threading/core/ThreadingService.java +++ b/src/main/java/dpfmanager/shell/modules/threading/core/ThreadingService.java @@ -29,6 +29,7 @@ import dpfmanager.shell.core.messages.ReportsMessage; import dpfmanager.shell.interfaces.console.CheckController; import dpfmanager.shell.interfaces.gui.workbench.GuiWorkbench; +import dpfmanager.shell.modules.conformancechecker.runnable.GetInputRunnable; import dpfmanager.shell.modules.database.messages.CheckTaskMessage; import dpfmanager.shell.modules.database.messages.JobsMessage; import dpfmanager.shell.modules.messages.messages.CloseMessage; @@ -71,7 +72,7 @@ public class ThreadingService extends DpfService { /** * The main executor service */ - private DpfExecutor myExecutor; + private Map myExecutors; /** * The number of threads @@ -98,6 +99,7 @@ public void init() { // No context yet bundle = DPFManagerProperties.getBundle(); checks = new HashMap<>(); + myExecutors = new HashMap<>(); pendingChecks = new LinkedList<>(); needReload = true; totalChecks = 0; @@ -107,7 +109,9 @@ public void init() { @PreDestroy public void finish() { // Finish executor - myExecutor.shutdownNow(); + for (DpfExecutor myExecutor : myExecutors.values()){ + myExecutor.shutdownNow(); + } } @Override @@ -131,27 +135,34 @@ private void initThreads(){ } cores = (specificCores >= 1 && specificCores <= maxCores) ? specificCores : maxCores; - myExecutor = new DpfExecutor(cores); - myExecutor.handleContext(context); } - public void run(DpfRunnable runnable, Long uuid) { + private DpfExecutor getMyExecutor(String pool){ + if (!myExecutors.containsKey(pool)) { + DpfExecutor myExecutor = new DpfExecutor(cores); + myExecutor.handleContext(context); + myExecutors.put(pool, myExecutor); + } + return myExecutors.get(pool); + } + + public void run(DpfRunnable runnable, Long uuid, String pool) { runnable.setContext(getContext()); runnable.setUuid(uuid); - myExecutor.myExecute(runnable); + getMyExecutor(pool).myExecute(runnable); } public void processThreadMessage(ThreadsMessage tm) { if (tm.isPause() && tm.isRequest()) { - myExecutor.pause(tm.getUuid()); + getMyExecutor(tm.getPool()).pause(tm.getUuid()); } else if (tm.isResume()) { context.send(BasicConfig.MODULE_DATABASE, new JobsMessage(JobsMessage.Type.RESUME, tm.getUuid())); - myExecutor.resume(tm.getUuid()); + getMyExecutor(tm.getPool()).resume(tm.getUuid()); } else if (tm.isCancel() && tm.isRequest()) { - cancelRequest(tm.getUuid()); - } else if (tm.isCancel() && !tm.isRequest()) { + cancelRequest(tm.getUuid(), tm.getPool()); + } else if (tm.isCancel()) { cancelFinish(tm.getUuid()); - } else if (tm.isPause() && !tm.isRequest()) { + } else if (tm.isPause()) { pauseFinish(tm.getUuid()); } } @@ -160,7 +171,7 @@ public void closeRequested() { context.send(BasicConfig.MODULE_MESSAGE, new CloseMessage(CloseMessage.Type.THREADING, !checks.isEmpty())); } - private void cancelRequest(Long uuid) { + private void cancelRequest(Long uuid, String pool) { // Check if is pending FileCheck pending = null; for (FileCheck check : pendingChecks) { @@ -175,7 +186,7 @@ private void cancelRequest(Long uuid) { context.send(GuiConfig.COMPONENT_PANE, new CheckTaskMessage(CheckTaskMessage.Target.CANCEL, uuid)); } else { // Cancel threads - myExecutor.cancel(uuid); + getMyExecutor(pool).cancel(uuid); } } @@ -222,7 +233,7 @@ public void handleGlobalStatus(GlobalStatusMessage gm, boolean silence) { } else if (gm.isInit()) { // Init file check FileCheck fc = checks.get(gm.getUuid()); - fc.init(gm.getSize(), gm.getConfig(), gm.getInternal(), gm.getInput()); + fc.init(gm.getSize(), gm.getConfig(), gm.getInternal(), gm.getInput(), gm.getZipsPaths()); context.send(BasicConfig.MODULE_MESSAGE, new LogMessage(getClass(), Level.DEBUG, bundle.getString("startingCheck").replace("%1", gm.getInput()))); context.send(BasicConfig.MODULE_DATABASE, new JobsMessage(JobsMessage.Type.INIT, fc.getUuid(), fc.getTotal(), fc.getInternal())); } else if (gm.isFinish() || gm.isCancel()) { @@ -277,7 +288,7 @@ public void finishIndividual(IndividualReport ir, Long uuid, Configuration confi // Check if all finished if (fc.allFinished()) { // Tell reports module - context.send(BasicConfig.MODULE_REPORT, new GlobalReportMessage(uuid, fc.getIndividuals(), fc.getConfig(), fc.getStart(), ir.getCheckedIsos())); + context.send(BasicConfig.MODULE_REPORT, new GlobalReportMessage(uuid, fc.getIndividuals(), fc.getConfig(), fc.getStart(), ir.getCheckedIsos(), fc.getZipsPaths())); } context.send(BasicConfig.MODULE_DATABASE, new JobsMessage(JobsMessage.Type.UPDATE, uuid)); } @@ -300,24 +311,42 @@ private int runningChecks() { * Remove functions */ public void removeZipFolder(String internal) { - try { - File zipFolder = new File(internal + "zip"); - if (zipFolder.exists() && zipFolder.isDirectory()) { + int count = 0; + File zipFolder = new File(internal + GetInputRunnable.zipFolderPrefix); + while (zipFolder.exists()) { + try { FileUtils.deleteDirectory(zipFolder); + } catch (Exception e) { + try { + System.gc(); + FileUtils.deleteDirectory(zipFolder); + } catch (Exception ex) { + context.send(BasicConfig.MODULE_MESSAGE, new ExceptionMessage(bundle.getString("excZip"), ex)); + } } - } catch (Exception e) { - context.send(BasicConfig.MODULE_MESSAGE, new ExceptionMessage(bundle.getString("excZip"), e)); + count++; + zipFolder = new File(internal + GetInputRunnable.zipFolderPrefix + count); } } private void removeDownloadFolder(String internal) { try { + // Delete zip File zipFolder = new File(internal + "download"); if (zipFolder.exists() && zipFolder.isDirectory()) { FileUtils.deleteDirectory(zipFolder); } } catch (Exception e) { - context.send(BasicConfig.MODULE_MESSAGE, new ExceptionMessage(bundle.getString("excDownload"), e)); + // Sleep 1 sec and retry + try { + Thread.sleep(1000); + File zipFolder = new File(internal + "download"); + if (zipFolder.exists() && zipFolder.isDirectory()) { + FileUtils.deleteDirectory(zipFolder); + } + } catch (Exception ex) { + context.send(BasicConfig.MODULE_MESSAGE, new ExceptionMessage(bundle.getString("excDownload"), ex)); + } } } diff --git a/src/main/java/dpfmanager/shell/modules/threading/messages/GlobalStatusMessage.java b/src/main/java/dpfmanager/shell/modules/threading/messages/GlobalStatusMessage.java index d52dc908..91d33819 100644 --- a/src/main/java/dpfmanager/shell/modules/threading/messages/GlobalStatusMessage.java +++ b/src/main/java/dpfmanager/shell/modules/threading/messages/GlobalStatusMessage.java @@ -23,6 +23,8 @@ import dpfmanager.shell.core.messages.DpfMessage; import dpfmanager.shell.modules.threading.runnable.DpfRunnable; +import java.util.Map; + /** * Created by Adria Llorens on 08/04/2016. */ @@ -43,6 +45,7 @@ public enum Type { private String internal; private String input; private DpfRunnable run; + private Map zipsPaths; public GlobalStatusMessage(Type t, Long u, DpfRunnable r, String i) { // New @@ -52,7 +55,7 @@ public GlobalStatusMessage(Type t, Long u, DpfRunnable r, String i) { input = i; } - public GlobalStatusMessage(Type t, long u, int n, Configuration c, String i, String ri) { + public GlobalStatusMessage(Type t, long u, int n, Configuration c, String i, String ri, Map z) { // Init type = t; uuid = u; @@ -60,6 +63,7 @@ public GlobalStatusMessage(Type t, long u, int n, Configuration c, String i, Str config = c; internal = i; input = ri; + zipsPaths = z; } public GlobalStatusMessage(Type t, long u) { @@ -124,4 +128,7 @@ public DpfRunnable getRunnable() { return run; } + public Map getZipsPaths() { + return zipsPaths; + } } diff --git a/src/main/java/dpfmanager/shell/modules/threading/messages/RunnableMessage.java b/src/main/java/dpfmanager/shell/modules/threading/messages/RunnableMessage.java index cb8cf866..cde86db1 100644 --- a/src/main/java/dpfmanager/shell/modules/threading/messages/RunnableMessage.java +++ b/src/main/java/dpfmanager/shell/modules/threading/messages/RunnableMessage.java @@ -28,11 +28,19 @@ public class RunnableMessage extends DpfMessage { private Long uuid; + private String pool; private DpfRunnable runnable; public RunnableMessage(Long u, DpfRunnable r) { uuid = u; runnable = r; + pool = "default"; + } + + public RunnableMessage(Long u, DpfRunnable r, String p) { + uuid = u; + runnable = r; + pool = p; } public DpfRunnable getRunnable() { @@ -42,4 +50,8 @@ public DpfRunnable getRunnable() { public Long getUuid() { return uuid; } + + public String getPool() { + return pool; + } } diff --git a/src/main/java/dpfmanager/shell/modules/threading/messages/ThreadsMessage.java b/src/main/java/dpfmanager/shell/modules/threading/messages/ThreadsMessage.java index e02f2ab3..6fb73388 100644 --- a/src/main/java/dpfmanager/shell/modules/threading/messages/ThreadsMessage.java +++ b/src/main/java/dpfmanager/shell/modules/threading/messages/ThreadsMessage.java @@ -31,12 +31,14 @@ public enum Type { private Type type; private Long uuid; + private String pool; private boolean request; - public ThreadsMessage(Type t, Long u, boolean r) { + public ThreadsMessage(Type t, Long u, boolean r, String p) { type = t; uuid = u; request = r; + pool = p; } public boolean isPause() { @@ -58,4 +60,8 @@ public boolean isRequest() { public Long getUuid() { return uuid; } + + public String getPool() { + return pool; + } } diff --git a/src/main/java/dpfmanager/shell/modules/threading/runnable/DpfRunnable.java b/src/main/java/dpfmanager/shell/modules/threading/runnable/DpfRunnable.java index 11f4bb6f..df285619 100644 --- a/src/main/java/dpfmanager/shell/modules/threading/runnable/DpfRunnable.java +++ b/src/main/java/dpfmanager/shell/modules/threading/runnable/DpfRunnable.java @@ -78,7 +78,7 @@ public void run() { finish = true; } catch (OutOfMemoryError err){ // Cancel the check and informs out of memory - context.send(BasicConfig.MODULE_THREADING, new ThreadsMessage(ThreadsMessage.Type.CANCEL, getUuid(), true)); + context.send(BasicConfig.MODULE_THREADING, new ThreadsMessage(ThreadsMessage.Type.CANCEL, getUuid(), true, "default")); context.send(BasicConfig.MODULE_MESSAGE, new ExceptionMessage(bundle.getString("checkCancelled"), err)); } } diff --git a/src/main/resources/bundles/language.properties b/src/main/resources/bundles/language.properties index 1ba4d79f..efe01b81 100644 --- a/src/main/resources/bundles/language.properties +++ b/src/main/resources/bundles/language.properties @@ -190,13 +190,14 @@ reloadReports=Reload reports showStadistics=Generate statistics colDate=Date colTime=Time -colN=#Files +colN=# Files colFile=Input colErrors=Errors colWarnings=Warnings colPassed=Passed colScore=Score colFormats=Formats +colActions=Actions colDelete= errors=%1 errors warnings=%1 warnings @@ -211,7 +212,7 @@ alertSelectDate=Please specify a date. errorDeleteReports=Error deleting reports. successDeleteReports=Reports deleted correctly. incorrectReport=Incorrect report folder found -loading=Loading... +loading=Calculating... # @@ -686,4 +687,52 @@ showDefault=Show default values # # Show module # -loadingReports=Generating individual reports. This may take a long. \ No newline at end of file +loadingReports=Generating report/s. This may take a long. + + +# +# Global view +# +globalTitle=RESULTS +individualTitle=Individual reports +colSingleFile=Name +colSinglePath=Path +colIsosChecked=# ISOs +colResult=Result +colNErrors=# Errors +colNWarnings=# Warnings +colWithWarnings=Passed with warnings +oneIso=%1 ISO +multipleIso=%1 ISOs +showGenerate=Generate Reports +showTransform=Make Full Reports +generateReports=Generate +transformReports=Start Full Check +labelTransform=Which files you want to make the full report? +labelTable=Reports +labelReport=Results +labelSingle=Format +deleteConfirmationGlobal=Do you really want to delete this report? +deleteInfoGlobal=This will delete all individual reports too. +rowDate=Date: +rowFiles=Files: +rowScore=Score: +rowDuration=Duration: +passedWithWarnings=%1 passed with warnings +errorCheck=File check with errors +passedCheck=File check passed +optionErrors=Files with errors +optionCorrect=Correct files +filesNotFound=The next files where not found: +filesEmpty=No files found matching your options. +makeFullReport=Start full check +colType=Type +typeQuick=Quick +typeFull=Full +labelIsOld=Some functionalities and information are disabled because this report is in old format. +downloadReport=Save report +generateReport=Generate report +showReport=Show report +errorSavingReport=Error saving the report +filesAreZip=The file you requested were inside a zip. It will make the full report of the zip file. + diff --git a/src/main/resources/fxml/fragments/individual.fxml b/src/main/resources/fxml/fragments/individual.fxml new file mode 100644 index 00000000..9bcb150e --- /dev/null +++ b/src/main/resources/fxml/fragments/individual.fxml @@ -0,0 +1,116 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/resources/fxml/fragments/nav.fxml b/src/main/resources/fxml/fragments/nav.fxml new file mode 100644 index 00000000..e75fb09b --- /dev/null +++ b/src/main/resources/fxml/fragments/nav.fxml @@ -0,0 +1,55 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/resources/fxml/fragments/report.fxml b/src/main/resources/fxml/fragments/report.fxml index 59b7c972..a76f3a9e 100644 --- a/src/main/resources/fxml/fragments/report.fxml +++ b/src/main/resources/fxml/fragments/report.fxml @@ -1,11 +1,11 @@ - - + + - + @@ -13,39 +13,64 @@ + + + - + - - - - + + + + + - - - + + + + + + + diff --git a/src/main/resources/fxml/global.fxml b/src/main/resources/fxml/global.fxml new file mode 100644 index 00000000..b1e44248 --- /dev/null +++ b/src/main/resources/fxml/global.fxml @@ -0,0 +1,497 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/resources/fxml/show.fxml b/src/main/resources/fxml/show.fxml index 3003de80..fc37a4be 100644 --- a/src/main/resources/fxml/show.fxml +++ b/src/main/resources/fxml/show.fxml @@ -5,6 +5,9 @@ + + + @@ -12,7 +15,7 @@ - +