List of usage examples for org.apache.pdfbox.io IOUtils closeQuietly
public static void closeQuietly(Closeable closeable)
From source file:org.apache.padaf.xmpbox.parser.XMLPropertiesDescriptionManager.java
License:Apache License
/** * Load Properties Description from XML Stream * //from ww w.j av a 2s . c o m * @param is * Stream where read data * @throws BuildPDFAExtensionSchemaDescriptionException * When problems to get or treat data in XML description file */ public void loadListFromXML(InputStream is) throws BuildPDFAExtensionSchemaDescriptionException { try { Object o = xstream.fromXML(is); if (o instanceof List<?>) { if (((List<?>) o).get(0) != null) { if (((List<?>) o).get(0) instanceof PropertyDescription) { propDescs = (List<PropertyDescription>) o; } else { throw new BuildPDFAExtensionSchemaDescriptionException( "Failed to get correct properties descriptions from specified XML stream"); } } else { throw new BuildPDFAExtensionSchemaDescriptionException( "Failed to find a properties description into the specified XML stream"); } } } catch (Exception e) { throw new BuildPDFAExtensionSchemaDescriptionException( "Failed to get correct properties descriptions from specified XML stream", e.getCause()); } finally { IOUtils.closeQuietly(is); } }
From source file:org.apache.padaf.xmpbox.parser.XMLPropertiesDescriptionManagerTest.java
License:Apache License
@Test public void testPropDesc() throws Exception { List<String> propNames = new ArrayList<String>(); propNames.add("propName1"); propNames.add("propName2"); List<String> descProps = new ArrayList<String>(); descProps.add("descProp1"); descProps.add("descProp2"); XMLPropertiesDescriptionManager xmlParser = new XMLPropertiesDescriptionManager(); xmlParser.addPropertyDescription(propNames.get(0), descProps.get(0)); xmlParser.addPropertyDescription(propNames.get(1), descProps.get(1)); ByteArrayOutputStream bos = new ByteArrayOutputStream(); xmlParser.toXML(bos);// ww w .j a v a 2 s . c om IOUtils.closeQuietly(bos); XMLPropertiesDescriptionManager propRetrieve = new XMLPropertiesDescriptionManager(); InputStream is = new ByteArrayInputStream(bos.toByteArray()); propRetrieve.loadListFromXML(is); List<PropertyDescription> propList = propRetrieve.getPropertiesDescriptionList(); Assert.assertEquals(propNames.size(), propList.size()); for (int i = 0; i < propList.size(); i++) { Assert.assertTrue(propNames.contains(propList.get(i).getPropertyName())); Assert.assertTrue(descProps.contains(propList.get(i).getDescription())); } }
From source file:org.apache.padaf.xmpbox.parser.XMLValueTypeDescriptionManager.java
License:Apache License
/** * Load Value Types Descriptions from XML Stream * /*from ww w . jav a2 s . co m*/ * @param is * Stream where read data * @throws BuildPDFAExtensionSchemaDescriptionException * When problems to get or treat data in XML description file */ public void loadListFromXML(InputStream is) throws BuildPDFAExtensionSchemaDescriptionException { try { Object o = xstream.fromXML(is); if (o instanceof List<?>) { if (((List<?>) o).get(0) != null) { if (((List<?>) o).get(0) instanceof ValueTypeDescription) { vTypes = (List<ValueTypeDescription>) o; } else { throw new BuildPDFAExtensionSchemaDescriptionException( "Failed to get correct valuetypes descriptions from specified XML stream"); } } else { throw new BuildPDFAExtensionSchemaDescriptionException( "Failed to find a valuetype description into the specified XML stream"); } } } catch (Exception e) { throw new BuildPDFAExtensionSchemaDescriptionException( "Failed to get correct valuetypes descriptions from specified XML stream", e.getCause()); } finally { IOUtils.closeQuietly(is); } }
From source file:org.apache.padaf.xmpbox.parser.XMLValueTypeDescriptionManagerTest.java
License:Apache License
@Test public void testPropDesc() throws Exception { List<String> types = new ArrayList<String>(); types.add("type1"); types.add("type2"); List<String> uris = new ArrayList<String>(); uris.add("nsURI1"); uris.add("nsURI2"); List<String> prefixs = new ArrayList<String>(); prefixs.add("pref1"); prefixs.add("pref2"); List<String> descProps = new ArrayList<String>(); descProps.add("descProp1"); descProps.add("descProp2"); XMLValueTypeDescriptionManager xmlParser = new XMLValueTypeDescriptionManager(); xmlParser.addValueTypeDescription(types.get(0), uris.get(0), prefixs.get(0), descProps.get(0)); xmlParser.addValueTypeDescription(types.get(1), uris.get(1), prefixs.get(1), descProps.get(1)); ByteArrayOutputStream bos = new ByteArrayOutputStream(); xmlParser.toXML(bos);//from w w w. ja v a 2 s . c o m IOUtils.closeQuietly(bos); XMLValueTypeDescriptionManager propRetrieve = new XMLValueTypeDescriptionManager(); InputStream is = new ByteArrayInputStream(bos.toByteArray()); propRetrieve.loadListFromXML(is); List<ValueTypeDescription> vtList = propRetrieve.getValueTypesDescriptionList(); Assert.assertEquals(types.size(), vtList.size()); for (int i = 0; i < vtList.size(); i++) { Assert.assertTrue(types.contains(vtList.get(i).getType())); Assert.assertTrue(uris.contains(vtList.get(i).getNamespaceURI())); Assert.assertTrue(prefixs.contains(vtList.get(i).getPrefix())); Assert.assertTrue(descProps.contains(vtList.get(i).getDescription())); Assert.assertNull(vtList.get(i).getFields()); } }
From source file:org.apache.padaf.xmpbox.parser.XMLValueTypeDescriptionManagerTest.java
License:Apache License
@Test public void testPropDescWithField() throws Exception { String type = "type1"; String uri = "nsURI1"; String prefix = "pref1"; String descProp = "descProp1"; List<String> fieldNames = new ArrayList<String>(); fieldNames.add("fieldName1"); fieldNames.add("fieldName2"); List<String> fieldValueTypes = new ArrayList<String>(); fieldValueTypes.add("fieldVT1"); fieldValueTypes.add("fieldVT2"); List<String> fieldDescription = new ArrayList<String>(); fieldDescription.add("FieldDesc1"); fieldDescription.add("FieldDesc2"); List<FieldDescription> fieldList = new ArrayList<FieldDescription>(); fieldList.add(new FieldDescription(fieldNames.get(0), fieldValueTypes.get(0), fieldDescription.get(0))); fieldList.add(new FieldDescription(fieldNames.get(1), fieldValueTypes.get(1), fieldDescription.get(1))); XMLValueTypeDescriptionManager xmlParser = new XMLValueTypeDescriptionManager(); xmlParser.addValueTypeDescription(type, uri, prefix, descProp, fieldList); ByteArrayOutputStream bos = new ByteArrayOutputStream(); xmlParser.toXML(bos);/*ww w .ja va 2 s . co m*/ IOUtils.closeQuietly(bos); XMLValueTypeDescriptionManager propRetrieve = new XMLValueTypeDescriptionManager(); InputStream is = new ByteArrayInputStream(bos.toByteArray()); propRetrieve.loadListFromXML(is); List<ValueTypeDescription> vtList = propRetrieve.getValueTypesDescriptionList(); Assert.assertEquals(1, vtList.size()); ValueTypeDescription vt = vtList.get(0); Assert.assertEquals(type, vt.getType()); Assert.assertEquals(uri, vt.getNamespaceURI()); Assert.assertEquals(prefix, vt.getPrefix()); Assert.assertEquals(descProp, vt.getDescription()); List<FieldDescription> fieldsFound = vt.getFields(); Assert.assertNotNull(fieldsFound); for (int i = 0; i < fieldsFound.size(); i++) { Assert.assertTrue(fieldNames.contains(fieldsFound.get(i).getName())); Assert.assertTrue(fieldValueTypes.contains(fieldsFound.get(i).getValueType())); Assert.assertTrue(fieldDescription.contains(fieldsFound.get(i).getDescription())); } }
From source file:org.apache.padaf.xmpbox.parser.XMPDocumentBuilder.java
License:Apache License
/** * Parsing method. Return a XMPMetadata object with all elements read * //www .ja v a2 s. c o m * @param xmp * serialized XMP * @return Metadata with all information read * @throws XmpParsingException * When element expected not found * @throws XmpSchemaException * When instancing schema object failed or in PDF/A Extension * case, if its namespace miss * @throws XmpUnknownValueTypeException * When ValueType found not correspond to basic type and not has * been declared in current schema * @throws XmpExpectedRdfAboutAttribute * When rdf:Description not contains rdf:about attribute * @throws XmpXpacketEndException * When xpacket end Processing Instruction is missing or is * incorrect * @throws BadFieldValueException * When treat a Schema associed to a schema Description in PDF/A * Extension schema */ public XMPMetadata parse(byte[] xmp) throws XmpParsingException, XmpSchemaException, XmpUnknownValueTypeException, XmpExpectedRdfAboutAttribute, XmpXpacketEndException, BadFieldValueException { if (!(this instanceof XMPDocumentPreprocessor)) { for (XMPDocumentPreprocessor processor : preprocessors) { NSMapping additionalNSMapping = processor.process(xmp); this.nsMap.importNSMapping(additionalNSMapping); } } ByteArrayInputStream is = new ByteArrayInputStream(xmp); try { XMLInputFactory factory = XMLInputFactory.newInstance(); reader.set(factory.createXMLStreamReader(is)); // expect xpacket processing instruction expectNext(XMLStreamReader.PROCESSING_INSTRUCTION, "Did not find initial xpacket processing instruction"); XMPMetadata metadata = parseInitialXpacket(reader.get().getPIData()); // expect x:xmpmeta expectNextTag(XMLStreamReader.START_ELEMENT, "Did not find initial x:xmpmeta"); expectName("adobe:ns:meta/", "xmpmeta"); // expect rdf:RDF expectNextTag(XMLStreamReader.START_ELEMENT, "Did not find initial rdf:RDF"); expectName("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "RDF"); nsMap.resetComplexBasicTypesDeclarationInEntireXMPLevel(); // add all namespaces which could declare nsURI of a basicValueType // all others declarations are ignored int nsCount = reader.get().getNamespaceCount(); for (int i = 0; i < nsCount; i++) { if (nsMap.isComplexBasicTypes(reader.get().getNamespaceURI(i))) { nsMap.setComplexBasicTypesDeclarationForLevelXMP(reader.get().getNamespaceURI(i), reader.get().getNamespacePrefix(i)); } } // now work on each rdf:Description int type = reader.get().nextTag(); while (type == XMLStreamReader.START_ELEMENT) { parseDescription(metadata); type = reader.get().nextTag(); } // all description are finished // expect end of rdf:RDF expectType(XMLStreamReader.END_ELEMENT, "Expected end of descriptions"); expectName("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "RDF"); // expect ending xmpmeta expectNextTag(XMLStreamReader.END_ELEMENT, "Did not find initial x:xmpmeta"); expectName("adobe:ns:meta/", "xmpmeta"); // expect final processing instruction expectNext(XMLStreamReader.PROCESSING_INSTRUCTION, "Did not find final xpacket processing instruction"); // treats xpacket end if (!reader.get().getPITarget().equals("xpacket")) { throw new XmpXpacketEndException("Excepted PI xpacket"); } String xpackData = reader.get().getPIData(); // end attribute must be present and placed in first // xmp spec says Other unrecognized attributes can follow, but // should be ignored if (xpackData.startsWith("end=")) { // check value (5 for end='X') if (xpackData.charAt(5) != 'r' && xpackData.charAt(5) != 'w') { throw new XmpXpacketEndException("Excepted xpacket 'end' attribute with value 'r' or 'w' "); } } else { // should find end='r/w' throw new XmpXpacketEndException( "Excepted xpacket 'end' attribute (must be present and placed in first)"); } metadata.setEndXPacket(xpackData); // return constructed object return metadata; } catch (XMLStreamException e) { throw new XmpParsingException("An error has occured when processing the underlying XMP source", e); } finally { reader.remove(); IOUtils.closeQuietly(is); } }
From source file:org.apache.padaf.xmpbox.parser.XMPDocumentBuilder.java
License:Apache License
private byte[] getStreamAsByteArray(InputStream input) throws XmpParsingException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try {//from w w w . java 2 s.co m IOUtils.copy(input, bos); } catch (IOException e) { throw new XmpParsingException("An error has occured when processing the underlying XMP source", e); } finally { IOUtils.closeQuietly(bos); IOUtils.closeQuietly(input); } return bos.toByteArray(); }
From source file:org.apache.padaf.xmpbox.SaveMetadataHelper.java
License:Apache License
/** * Serialize metadata into the byte array returned * // ww w.j av a 2 s. co m * @param metadata * Metadata concerned by the serialization processing * @param intoXPacket * True to put XPacket Processing Information * @return ByteArray which contains serialized metadata * @throws TransformException * When couldn't parse data to XML/RDF */ public static byte[] serialize(XMPMetadata metadata, boolean intoXPacket) throws TransformException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); serialize(metadata, intoXPacket, bos); IOUtils.closeQuietly(bos); return bos.toByteArray(); }
From source file:org.apache.padaf.xmpbox.SaveMetadataHelper.java
License:Apache License
/** * Serialize a schema into a Byte Array/*from w w w .j a v a2s . c o m*/ * * @param schema * Schema concerned by the serialization processing * @return a ByteArray which contains serialized schema * @throws TransformException * When couldn't parse data to XML/RDF */ public static byte[] serialize(XMPSchema schema) throws TransformException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); serialize(schema, bos); IOUtils.closeQuietly(bos); return bos.toByteArray(); }
From source file:org.olat.commons.servlets.RSSServlet.java
License:Apache License
/** * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) *///from w w w . j a v a 2 s . c o m protected void doGet(HttpServletRequest request, HttpServletResponse response) { SyndFeed feed = null; Writer writer = null; try { String pathInfo = request.getPathInfo(); if ((pathInfo == null) || (pathInfo.equals(""))) { return; // error } // pathInfo is like /personal/username/tokenid.rss if (pathInfo.indexOf(RSSUtil.RSS_PREFIX_PERSONAL) == 0) { feed = getPersonalFeed(pathInfo); if (feed == null) { DispatcherModule.sendNotFound(pathInfo, response); return; } } else { DispatcherModule.sendNotFound(pathInfo, response); return; } // OLAT-5400 and OLAT-5243 related: sending back the reply can take arbitrary long, // considering slow end-user connections for example - or a sudden death of the connection // on the client-side which remains unnoticed (network partitioning) DBFactory.getInstance().intermediateCommit(); response.setBufferSize(outputBufferSize); String encoding = feed.getEncoding(); if (encoding == null) { encoding = DEFAULT_ENCODING; if (log.isDebug()) { log.debug("Feed encoding::" + encoding); } log.warn("No encoding provided by feed::" + feed.getClass().getCanonicalName() + " Using utf-8 as default."); } response.setCharacterEncoding(encoding); response.setContentType("application/rss+xml"); Date pubDate = feed.getPublishedDate(); if (pubDate != null) { response.setDateHeader("Last-Modified", pubDate.getTime()); } // TODO:GW Do we need this? // response.setContentLength(feed.get); writer = response.getWriter(); SyndFeedOutput output = new SyndFeedOutput(); output.output(feed, writer); } catch (FeedException e) { // throw olat exception for nice logging log.warn("Error when generating RSS stream for path::" + request.getPathInfo(), e); DispatcherModule.sendNotFound("none", response); } catch (Exception e) { log.warn("Unknown Exception in rssservlet", e); DispatcherModule.sendNotFound("none", response); } catch (Error e) { log.warn("Unknown Error in rssservlet", e); DispatcherModule.sendNotFound("none", response); } finally { IOUtils.closeQuietly(writer); DBFactory.getInstance(false).commitAndCloseSession(); } }