Beispiel 7.30. LazyLoading von Dokumenten auf dem Classpath
Dieses Beispiel zeigt exemplarisch, wie LazyStreamPageSegments verwendet
werden können, um Dokumenteninhalte zu laden.
Hier wird ein Document erzeugt, dass aus beliebig vielen einseitigen
physikalischen Dokumenten besteht, die jeweils durch ein
LazyStreamPageSegment repräsentiert werden.
/**
* Creates a document containing one LazyStreamPageSegment per page based on the resources given as
* parameters.
*
* @param resources the names of the resources to be added to the document.
* @return a {@link Document} where each page consists of a {@link LazyStreamPageSegment}
*/
public static Document createLazyDocument(String... resources) {
// set the initial size for the pageSegment. This value will be updated once the actual contents are
// rendered.
int height = (int) Unit.Inch.convertTo(Unit.JadiceDocumentUnit, 1);
int width = (int) Unit.Inch.convertTo(Unit.JadiceDocumentUnit, 1);
Dimension defaultDimension = new Dimension(width, height);
BasicDocument lazyDocument = new BasicDocument();
// Create and add one page per resource to the document
for (String s : resources) {
Page page = new BasicPage();
// create the LazyStreamPageSegment which will load the contents when needed
LazyStreamPageSegment pageSegment = new LazyStreamPageSegment(page, new SimpleResourceLazyPageSegmentProvider(s));
// set the initial
pageSegment.setInitialSize(defaultDimension);
// add the lazy pageSegment to the default layer of the page
page.add(DocumentLayer.DEFAULT, pageSegment);
// finally add the page to the document
lazyDocument.getPages().add(page);
}
return lazyDocument;
}
/**
* A simple {@link com.levigo.jadice.document.lazy.LazyStreamPageSegment.StreamDataProvider}
* implementation which holds the name of a resource.
*/
private static class SimpleResourceLazyPageSegmentProvider extends LazyStreamPageSegment.StreamDataProvider {
private final String resourceName;
/**
* Creates a new {@link SimpleResourceLazyPageSegmentProvider} which returns a stream to the
* resource with the given name if requested.
*
* @param resourceName
*/
public SimpleResourceLazyPageSegmentProvider(String resourceName) {
this.resourceName = resourceName;
}
@Override
public Provider<InputStream, IOException> getStream() {
return () -> getClass().getResourceAsStream(resourceName);
}
}
