use of org.apache.poi.openxml4j.exceptions.InvalidFormatException in project goci by EBISPOT.
the class AssociationFileUploadService method processAndValidateAssociationFile.
/**
* Process uploaded file and return a list of errors
*
* @param file XLSX file supplied by user
*/
public ValidationSummary processAndValidateAssociationFile(File file, String validationLevel) throws FileNotFoundException, SheetProcessingException {
ValidationSummary validationSummary = new ValidationSummary();
Collection<RowValidationSummary> rowValidationSummaries = new ArrayList<>();
Collection<AssociationSummary> associationSummaries = new ArrayList<>();
Collection<AssociationUploadRow> fileRows = new ArrayList<>();
if (file.exists()) {
// Create sheet
XSSFSheet sheet = null;
try {
// Create a sheet for reading
sheet = sheetCreationService.createSheet(file.getAbsolutePath());
// Process file, depending on validation level, into a generic row object
UploadSheetProcessor uploadSheetProcessor = uploadSheetProcessorBuilder.buildProcessor(validationLevel);
fileRows = uploadSheetProcessor.readSheetRows(sheet);
} catch (InvalidFormatException | InvalidOperationException | IOException e) {
getLog().error("File: " + file.getName() + " cannot be processed", e);
file.delete();
throw new SheetProcessingException("File: " + file.getName() + " cannot be processed", e);
}
} else {
getLog().error("File: " + file.getName() + " cannot be found");
throw new FileNotFoundException("File does not exist");
}
String eRelease = ensemblRestTemplateService.getRelease();
// Error check each row
if (!fileRows.isEmpty()) {
// Check for missing values and syntax errors that would prevent code creating an association
for (AssociationUploadRow row : fileRows) {
getLog().info("Syntax checking row: " + row.getRowNumber() + " of file, " + file.getAbsolutePath());
RowValidationSummary rowValidationSummary = createRowValidationSummary(row, eRelease);
// Only store summary if there is an error
if (!rowValidationSummary.getErrors().isEmpty()) {
rowValidationSummaries.add(rowValidationSummary);
}
}
if (rowValidationSummaries.isEmpty()) {
//Proceed to carry out full checks of values
fileRows.forEach(row -> {
associationSummaries.add(createAssociationSummary(row, validationLevel, eRelease));
});
}
} else {
getLog().error("Parsing file failed");
}
validationSummary.setAssociationSummaries(associationSummaries);
validationSummary.setRowValidationSummaries(rowValidationSummaries);
return validationSummary;
}
use of org.apache.poi.openxml4j.exceptions.InvalidFormatException in project poi by apache.
the class XWPFDocument method initHyperlinks.
private void initHyperlinks() {
// TODO: make me optional/separated in private function
try {
Iterator<PackageRelationship> relIter = getPackagePart().getRelationshipsByType(XWPFRelation.HYPERLINK.getRelation()).iterator();
while (relIter.hasNext()) {
PackageRelationship rel = relIter.next();
hyperlinks.add(new XWPFHyperlink(rel.getId(), rel.getTargetURI().toString()));
}
} catch (InvalidFormatException e) {
throw new POIXMLException(e);
}
}
use of org.apache.poi.openxml4j.exceptions.InvalidFormatException in project poi by apache.
the class SignatureInfo method writeDocument.
/**
* Write XML signature into the OPC package
*
* @param document the xml signature document
* @throws MarshalException
*/
protected void writeDocument(Document document) throws MarshalException {
XmlOptions xo = new XmlOptions();
Map<String, String> namespaceMap = new HashMap<String, String>();
for (Map.Entry<String, String> entry : signatureConfig.getNamespacePrefixes().entrySet()) {
namespaceMap.put(entry.getValue(), entry.getKey());
}
xo.setSaveSuggestedPrefixes(namespaceMap);
xo.setUseDefaultNamespace();
LOG.log(POILogger.DEBUG, "output signed Office OpenXML document");
/*
* Copy the original OOXML content to the signed OOXML package. During
* copying some files need to changed.
*/
OPCPackage pkg = signatureConfig.getOpcPackage();
PackagePartName sigPartName, sigsPartName;
try {
// <Override PartName="/_xmlsignatures/sig1.xml" ContentType="application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml"/>
sigPartName = PackagingURIHelper.createPartName("/_xmlsignatures/sig1.xml");
// <Default Extension="sigs" ContentType="application/vnd.openxmlformats-package.digital-signature-origin"/>
sigsPartName = PackagingURIHelper.createPartName("/_xmlsignatures/origin.sigs");
} catch (InvalidFormatException e) {
throw new MarshalException(e);
}
PackagePart sigPart = pkg.getPart(sigPartName);
if (sigPart == null) {
sigPart = pkg.createPart(sigPartName, ContentTypes.DIGITAL_SIGNATURE_XML_SIGNATURE_PART);
}
try {
OutputStream os = sigPart.getOutputStream();
SignatureDocument sigDoc = SignatureDocument.Factory.parse(document, DEFAULT_XML_OPTIONS);
sigDoc.save(os, xo);
os.close();
} catch (Exception e) {
throw new MarshalException("Unable to write signature document", e);
}
PackagePart sigsPart = pkg.getPart(sigsPartName);
if (sigsPart == null) {
// touch empty marker file
sigsPart = pkg.createPart(sigsPartName, ContentTypes.DIGITAL_SIGNATURE_ORIGIN_PART);
}
PackageRelationshipCollection relCol = pkg.getRelationshipsByType(PackageRelationshipTypes.DIGITAL_SIGNATURE_ORIGIN);
for (PackageRelationship pr : relCol) {
pkg.removeRelationship(pr.getId());
}
pkg.addRelationship(sigsPartName, TargetMode.INTERNAL, PackageRelationshipTypes.DIGITAL_SIGNATURE_ORIGIN);
sigsPart.addRelationship(sigPartName, TargetMode.INTERNAL, PackageRelationshipTypes.DIGITAL_SIGNATURE);
}
use of org.apache.poi.openxml4j.exceptions.InvalidFormatException in project poi by apache.
the class OOXMLSignatureFacet method addManifestReferences.
@SuppressWarnings("resource")
protected void addManifestReferences(List<Reference> manifestReferences) throws XMLSignatureException {
OPCPackage ooxml = signatureConfig.getOpcPackage();
List<PackagePart> relsEntryNames = ooxml.getPartsByContentType(ContentTypes.RELATIONSHIPS_PART);
Set<String> digestedPartNames = new HashSet<String>();
for (PackagePart pp : relsEntryNames) {
String baseUri = pp.getPartName().getName().replaceFirst("(.*)/_rels/.*", "$1");
PackageRelationshipCollection prc;
try {
prc = new PackageRelationshipCollection(ooxml);
prc.parseRelationshipsPart(pp);
} catch (InvalidFormatException e) {
throw new XMLSignatureException("Invalid relationship descriptor: " + pp.getPartName().getName(), e);
}
RelationshipTransformParameterSpec parameterSpec = new RelationshipTransformParameterSpec();
for (PackageRelationship relationship : prc) {
String relationshipType = relationship.getRelationshipType();
/*
* ECMA-376 Part 2 - 3rd edition
* 13.2.4.16 Manifest Element
* "The producer shall not create a Manifest element that references any data outside of the package."
*/
if (TargetMode.EXTERNAL == relationship.getTargetMode()) {
continue;
}
if (!isSignedRelationship(relationshipType))
continue;
parameterSpec.addRelationshipReference(relationship.getId());
// TODO: find a better way ...
String partName = relationship.getTargetURI().toString();
if (!partName.startsWith(baseUri)) {
partName = baseUri + partName;
}
try {
partName = new URI(partName).normalize().getPath().replace('\\', '/');
LOG.log(POILogger.DEBUG, "part name: " + partName);
} catch (URISyntaxException e) {
throw new XMLSignatureException(e);
}
String contentType;
try {
PackagePartName relName = PackagingURIHelper.createPartName(partName);
PackagePart pp2 = ooxml.getPart(relName);
contentType = pp2.getContentType();
} catch (InvalidFormatException e) {
throw new XMLSignatureException(e);
}
if (relationshipType.endsWith("customXml") && !(contentType.equals("inkml+xml") || contentType.equals("text/xml"))) {
LOG.log(POILogger.DEBUG, "skipping customXml with content type: " + contentType);
continue;
}
if (!digestedPartNames.contains(partName)) {
// We only digest a part once.
String uri = partName + "?ContentType=" + contentType;
Reference reference = newReference(uri, null, null, null, null);
manifestReferences.add(reference);
digestedPartNames.add(partName);
}
}
if (parameterSpec.hasSourceIds()) {
List<Transform> transforms = new ArrayList<Transform>();
transforms.add(newTransform(RelationshipTransformService.TRANSFORM_URI, parameterSpec));
transforms.add(newTransform(CanonicalizationMethod.INCLUSIVE));
String uri = pp.getPartName().getName() + "?ContentType=application/vnd.openxmlformats-package.relationships+xml";
Reference reference = newReference(uri, transforms, null, null, null);
manifestReferences.add(reference);
}
}
}
use of org.apache.poi.openxml4j.exceptions.InvalidFormatException in project poi by apache.
the class TestWorkbookFactory method testCreateGeneric.
/**
* Creates the appropriate kind of Workbook, but
* checking the mime magic at the start of the
* InputStream, then creating what's required.
*/
@Test
public void testCreateGeneric() throws Exception {
Workbook wb;
// InputStream -> either
wb = WorkbookFactory.create(HSSFTestDataSamples.openSampleFileStream(xls));
assertNotNull(wb);
assertTrue(wb instanceof HSSFWorkbook);
assertCloseDoesNotModifyFile(xls, wb);
wb = WorkbookFactory.create(HSSFTestDataSamples.openSampleFileStream(xlsx));
assertNotNull(wb);
assertTrue(wb instanceof XSSFWorkbook);
assertCloseDoesNotModifyFile(xlsx, wb);
// File -> either
wb = WorkbookFactory.create(HSSFTestDataSamples.getSampleFile(xls));
assertNotNull(wb);
assertTrue(wb instanceof HSSFWorkbook);
assertCloseDoesNotModifyFile(xls, wb);
wb = WorkbookFactory.create(HSSFTestDataSamples.getSampleFile(xlsx));
assertNotNull(wb);
assertTrue(wb instanceof XSSFWorkbook);
assertCloseDoesNotModifyFile(xlsx, wb);
// Invalid type -> exception
final byte[] before = HSSFTestDataSamples.getTestDataFileContent(txt);
try {
InputStream stream = HSSFTestDataSamples.openSampleFileStream(txt);
try {
wb = WorkbookFactory.create(stream);
} finally {
stream.close();
}
fail();
} catch (InvalidFormatException e) {
// Good
}
final byte[] after = HSSFTestDataSamples.getTestDataFileContent(txt);
assertArrayEquals("Invalid type file was modified after trying to open the file as a spreadsheet", before, after);
}
Aggregations