proj_name
stringclasses
131 values
relative_path
stringlengths
30
228
class_name
stringlengths
1
68
func_name
stringlengths
1
48
masked_class
stringlengths
78
9.82k
func_body
stringlengths
46
9.61k
len_input
int64
29
2.01k
len_output
int64
14
1.94k
total
int64
55
2.05k
relevant_context
stringlengths
0
38.4k
apache_pdfbox
pdfbox/fontbox/src/main/java/org/apache/fontbox/util/BoundingBox.java
BoundingBox
contains
class BoundingBox { private float lowerLeftX; private float lowerLeftY; private float upperRightX; private float upperRightY; /** * Default constructor. */ public BoundingBox() { } /** * Constructor. * * @param minX lower left x value * @param minY lower left y value * @param maxX upper right x value * @param maxY upper right y value */ public BoundingBox(float minX, float minY, float maxX, float maxY) { lowerLeftX = minX; lowerLeftY = minY; upperRightX = maxX; upperRightY = maxY; } /** * Constructor. * * @param numbers list of four numbers */ public BoundingBox(List<Number> numbers) { lowerLeftX = numbers.get(0).floatValue(); lowerLeftY = numbers.get(1).floatValue(); upperRightX = numbers.get(2).floatValue(); upperRightY = numbers.get(3).floatValue(); } /** * Getter for property lowerLeftX. * * @return Value of property lowerLeftX. */ public float getLowerLeftX() { return lowerLeftX; } /** * Setter for property lowerLeftX. * * @param lowerLeftXValue New value of property lowerLeftX. */ public void setLowerLeftX(float lowerLeftXValue) { this.lowerLeftX = lowerLeftXValue; } /** * Getter for property lowerLeftY. * * @return Value of property lowerLeftY. */ public float getLowerLeftY() { return lowerLeftY; } /** * Setter for property lowerLeftY. * * @param lowerLeftYValue New value of property lowerLeftY. */ public void setLowerLeftY(float lowerLeftYValue) { this.lowerLeftY = lowerLeftYValue; } /** * Getter for property upperRightX. * * @return Value of property upperRightX. */ public float getUpperRightX() { return upperRightX; } /** * Setter for property upperRightX. * * @param upperRightXValue New value of property upperRightX. */ public void setUpperRightX(float upperRightXValue) { this.upperRightX = upperRightXValue; } /** * Getter for property upperRightY. * * @return Value of property upperRightY. */ public float getUpperRightY() { return upperRightY; } /** * Setter for property upperRightY. * * @param upperRightYValue New value of property upperRightY. */ public void setUpperRightY(float upperRightYValue) { this.upperRightY = upperRightYValue; } /** * This will get the width of this rectangle as calculated by * upperRightX - lowerLeftX. * * @return The width of this rectangle. */ public float getWidth() { return getUpperRightX() - getLowerLeftX(); } /** * This will get the height of this rectangle as calculated by * upperRightY - lowerLeftY. * * @return The height of this rectangle. */ public float getHeight() { return getUpperRightY() - getLowerLeftY(); } /** * Checks if a point is inside this rectangle. * * @param x The x coordinate. * @param y The y coordinate. * * @return true If the point is on the edge or inside the rectangle bounds. */ public boolean contains( float x, float y ) {<FILL_FUNCTION_BODY>} /** * This will return a string representation of this rectangle. * * @return This object as a string. */ @Override public String toString() { return "[" + getLowerLeftX() + "," + getLowerLeftY() + "," + getUpperRightX() + "," + getUpperRightY() +"]"; } }
return x >= lowerLeftX && x <= upperRightX && y >= lowerLeftY && y <= upperRightY;
1,156
32
1,188
<no_super_class>
apache_pdfbox
pdfbox/fontbox/src/main/java/org/apache/fontbox/util/autodetect/FontFileFinder.java
FontFileFinder
checkFontfile
class FontFileFinder { private static final Logger LOG = LogManager.getLogger(FontFileFinder.class); private FontDirFinder fontDirFinder = null; /** * Default constructor. */ public FontFileFinder() { } private FontDirFinder determineDirFinder() { final String osName = System.getProperty("os.name"); if (osName.startsWith("Windows")) { return new WindowsFontDirFinder(); } else if (osName.startsWith("Mac")) { return new MacFontDirFinder(); } else if (osName.startsWith("OS/400")) { return new OS400FontDirFinder(); } else { return new UnixFontDirFinder(); } } /** * Automagically finds a list of font files on local system. * * @return List&lt;URI&gt; of font files */ public List<URI> find() { if (fontDirFinder == null) { fontDirFinder = determineDirFinder(); } List<File> fontDirs = fontDirFinder.find(); List<URI> results = new ArrayList<>(); fontDirs.forEach(dir -> walk(dir, results)); return results; } /** * Searches a given directory for font files. * * @param dir directory to search * @return list&lt;URI&gt; of font files */ public List<URI> find(String dir) { List<URI> results = new ArrayList<>(); File directory = new File(dir); if (directory.isDirectory()) { walk(directory, results); } return results; } /** * walk down the directory tree and search for font files. * * @param directory the directory to start at * @param results names of all found font files */ private void walk(File directory, List<URI> results) { // search for font files recursively in the given directory if (!directory.isDirectory()) { return; } File[] filelist = directory.listFiles(); if (filelist == null) { return; } for (File file : filelist) { if (file.isDirectory()) { // skip hidden directories if (file.isHidden()) { LOG.debug("skip hidden directory {}", file); continue; } walk(file, results); } else { LOG.debug("checkFontfile check {}", file); if (checkFontfile(file)) { LOG.debug("checkFontfile found {}", file); results.add(file.toURI()); } } } } /** * Check if the given name belongs to a font file. * * @param file the given file * @return true if the given filename has a typical font file ending */ private boolean checkFontfile(File file) {<FILL_FUNCTION_BODY>} }
String name = file.getName().toLowerCase(Locale.US); return (name.endsWith(".ttf") || name.endsWith(".otf") || name.endsWith(".pfb") || name.endsWith(".ttc")) // PDFBOX-3377 exclude weird files in AIX && !name.startsWith("fonts.");
832
90
922
<no_super_class>
apache_pdfbox
pdfbox/fontbox/src/main/java/org/apache/fontbox/util/autodetect/MacFontDirFinder.java
MacFontDirFinder
getSearchableDirectories
class MacFontDirFinder extends NativeFontDirFinder { /** * Some guesses at possible unix font directory locations. * * @return a array of possible font directory locations */ @Override protected String[] getSearchableDirectories() {<FILL_FUNCTION_BODY>} }
return new String[] { System.getProperty("user.home") + "/Library/Fonts/", // user "/Library/Fonts/", // local "/System/Library/Fonts/", // system "/Network/Library/Fonts/" // network };
84
68
152
<methods>public non-sealed void <init>() ,public List<java.io.File> find() <variables>private static final Logger LOG
apache_pdfbox
pdfbox/fontbox/src/main/java/org/apache/fontbox/util/autodetect/NativeFontDirFinder.java
NativeFontDirFinder
find
class NativeFontDirFinder implements FontDirFinder { private static final Logger LOG = LogManager.getLogger(NativeFontDirFinder.class); /** * Generic method used by Mac and Unix font finders. * * @return list of natively existing font directories {@inheritDoc} */ @Override public List<File> find() {<FILL_FUNCTION_BODY>} /** * Returns an array of directories to search for fonts in. * * @return an array of directories */ protected abstract String[] getSearchableDirectories(); }
List<File> fontDirList = new java.util.ArrayList<>(); String[] searchableDirectories = getSearchableDirectories(); if (searchableDirectories != null) { for (String searchableDirectorie : searchableDirectories) { File fontDir = new File(searchableDirectorie); try { if (fontDir.exists() && fontDir.canRead()) { fontDirList.add(fontDir); } } catch (SecurityException e) { LOG.debug("Couldn't get native font directories - ignoring", e); // should continue if this fails } } } return fontDirList;
158
182
340
<no_super_class>
apache_pdfbox
pdfbox/fontbox/src/main/java/org/apache/fontbox/util/autodetect/OS400FontDirFinder.java
OS400FontDirFinder
getSearchableDirectories
class OS400FontDirFinder extends NativeFontDirFinder { @Override protected String[] getSearchableDirectories() {<FILL_FUNCTION_BODY>} }
return new String[] { System.getProperty("user.home") + "/.fonts", // user "/QIBM/ProdData/OS400/Fonts" };
50
48
98
<methods>public non-sealed void <init>() ,public List<java.io.File> find() <variables>private static final Logger LOG
apache_pdfbox
pdfbox/fontbox/src/main/java/org/apache/fontbox/util/autodetect/UnixFontDirFinder.java
UnixFontDirFinder
getSearchableDirectories
class UnixFontDirFinder extends NativeFontDirFinder { /** * Some guesses at possible unix font directory locations. * * @return an array of possible font locations */ @Override protected String[] getSearchableDirectories() {<FILL_FUNCTION_BODY>} }
return new String[] { System.getProperty("user.home") + "/.fonts", // user "/usr/local/fonts", // local "/usr/local/share/fonts", // local shared "/usr/share/fonts", // system "/usr/X11R6/lib/X11/fonts", // X "/usr/share/X11/fonts" // CentOS };
84
102
186
<methods>public non-sealed void <init>() ,public List<java.io.File> find() <variables>private static final Logger LOG
apache_pdfbox
pdfbox/fontbox/src/main/java/org/apache/fontbox/util/autodetect/WindowsFontDirFinder.java
WindowsFontDirFinder
find
class WindowsFontDirFinder implements FontDirFinder { private static final Logger LOG = LogManager.getLogger(WindowsFontDirFinder.class); /** * Attempts to read windir environment variable on windows (disclaimer: This is a bit dirty but seems to work * nicely). */ private String getWinDir(String osName) throws IOException { Process process; Runtime runtime = Runtime.getRuntime(); String cmd; if (osName.startsWith("Windows 9")) { cmd = "command.com"; } else { cmd = "cmd.exe"; } String[] cmdArray = { cmd, "/c", "echo", "%windir%" }; process = runtime.exec(cmdArray); try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader( process.getInputStream(), StandardCharsets.ISO_8859_1))) { return bufferedReader.readLine(); } } /** * {@inheritDoc} * * @return a list of detected font files */ @Override public List<File> find() {<FILL_FUNCTION_BODY>} }
List<File> fontDirList = new java.util.ArrayList<>(); String windir = null; try { windir = System.getProperty("env.windir"); } catch (SecurityException e) { LOG.debug("Couldn't get Windows font directories - ignoring", e); // should continue if this fails } String osName = System.getProperty("os.name"); if (windir == null) { try { windir = getWinDir(osName); } catch (IOException | SecurityException e) { LOG.debug("Couldn't get Windows font directories - ignoring", e); // should continue if this fails } } File osFontsDir; File psFontsDir; if (windir != null && windir.length() > 2) { // remove any trailing '/' if (windir.endsWith("/")) { windir = windir.substring(0, windir.length() - 1); } osFontsDir = new File(windir + File.separator + "FONTS"); if (osFontsDir.exists() && osFontsDir.canRead()) { fontDirList.add(osFontsDir); } psFontsDir = new File(windir.substring(0, 2) + File.separator + "PSFONTS"); if (psFontsDir.exists() && psFontsDir.canRead()) { fontDirList.add(psFontsDir); } } else { String windowsDirName = osName.endsWith("NT") ? "WINNT" : "WINDOWS"; // look for true type font folder for (char driveLetter = 'C'; driveLetter <= 'E'; driveLetter++) { osFontsDir = new File(driveLetter + ":" + File.separator + windowsDirName + File.separator + "FONTS"); try { if (osFontsDir.exists() && osFontsDir.canRead()) { fontDirList.add(osFontsDir); break; } } catch (SecurityException e) { LOG.debug("Couldn't get Windows font directories - ignoring", e); // should continue if this fails } } // look for type 1 font folder for (char driveLetter = 'C'; driveLetter <= 'E'; driveLetter++) { psFontsDir = new File(driveLetter + ":" + File.separator + "PSFONTS"); try { if (psFontsDir.exists() && psFontsDir.canRead()) { fontDirList.add(psFontsDir); break; } } catch (SecurityException e) { LOG.debug("Couldn't get Windows font directories - ignoring", e); // should continue if this fails } } } try { String localAppData = System.getenv("LOCALAPPDATA"); if (localAppData != null && !localAppData.isEmpty()) { File localFontDir = new File(localAppData + File.separator + "Microsoft" + File.separator + "Windows" + File.separator + "Fonts"); if (localFontDir.exists() && localFontDir.canRead()) { fontDirList.add(localFontDir); } } } catch (SecurityException e) { LOG.debug("Couldn't get LOCALAPPDATA directory - ignoring", e); // should continue if this fails } return fontDirList;
314
963
1,277
<no_super_class>
apache_pdfbox
pdfbox/io/src/main/java/org/apache/pdfbox/io/RandomAccessInputStream.java
RandomAccessInputStream
read
class RandomAccessInputStream extends InputStream { private static final Logger LOG = LogManager.getLogger(RandomAccessInputStream.class); private final RandomAccessRead input; private long position; /** * Creates a new RandomAccessInputStream, with a position of zero. The InputStream will maintain * its own position independent of the RandomAccessRead. * * @param randomAccessRead The RandomAccessRead to read from. */ public RandomAccessInputStream(RandomAccessRead randomAccessRead) { input = randomAccessRead; position = 0; } void restorePosition() throws IOException { input.seek(position); } @Override public int available() throws IOException { return (int) Math.max(0, Math.min(input.length() - position, Integer.MAX_VALUE)); } @Override public int read() throws IOException { restorePosition(); if (input.isEOF()) { return -1; } int b = input.read(); if (b != -1) { position += 1; } else { // should never happen due to prior isEOF() check // unless there is an unsynchronized concurrent access LOG.error("read() returns -1, assumed position: {}, actual position: {}", position, input.getPosition()); } return b; } @Override public int read(byte[] b, int off, int len) throws IOException {<FILL_FUNCTION_BODY>} @Override public long skip(long n) throws IOException { if (n <= 0) { return 0; } restorePosition(); input.seek(position + n); position += n; return n; } }
restorePosition(); if (input.isEOF()) { return -1; } int n = input.read(b, off, len); if (n != -1) { position += n; } else { // should never happen due to prior isEOF() check // unless there is an unsynchronized concurrent access LOG.error("read() returns -1, assumed position: {}, actual position: {}", position, input.getPosition()); } return n;
470
138
608
<methods>public void <init>() ,public int available() throws java.io.IOException,public void close() throws java.io.IOException,public synchronized void mark(int) ,public boolean markSupported() ,public static java.io.InputStream nullInputStream() ,public abstract int read() throws java.io.IOException,public int read(byte[]) throws java.io.IOException,public int read(byte[], int, int) throws java.io.IOException,public byte[] readAllBytes() throws java.io.IOException,public byte[] readNBytes(int) throws java.io.IOException,public int readNBytes(byte[], int, int) throws java.io.IOException,public synchronized void reset() throws java.io.IOException,public long skip(long) throws java.io.IOException,public void skipNBytes(long) throws java.io.IOException,public long transferTo(java.io.OutputStream) throws java.io.IOException<variables>private static final int DEFAULT_BUFFER_SIZE,private static final int MAX_BUFFER_SIZE,private static final int MAX_SKIP_BUFFER_SIZE
apache_pdfbox
pdfbox/io/src/main/java/org/apache/pdfbox/io/RandomAccessReadBufferedFile.java
RandomAccessReadBufferedFile
seek
class RandomAccessReadBufferedFile implements RandomAccessRead { private static final int PAGE_SIZE_SHIFT = 12; private static final int PAGE_SIZE = 1 << PAGE_SIZE_SHIFT; private static final long PAGE_OFFSET_MASK = -1L << PAGE_SIZE_SHIFT; private static final int MAX_CACHED_PAGES = 1000; // map holding all copies of the current buffered file private final ConcurrentMap<Long, RandomAccessReadBufferedFile> rafCopies = new ConcurrentHashMap<>(); private ByteBuffer lastRemovedCachePage = null; /** Create a LRU page cache. */ private final Map<Long, ByteBuffer> pageCache = new LinkedHashMap<>(MAX_CACHED_PAGES, 0.75f, true) { private static final long serialVersionUID = -6302488539257741101L; @Override protected boolean removeEldestEntry(Map.Entry<Long, ByteBuffer> eldest) { final boolean doRemove = size() > MAX_CACHED_PAGES; if (doRemove) { lastRemovedCachePage = eldest.getValue(); lastRemovedCachePage.clear(); } return doRemove; } }; private long curPageOffset = -1; private ByteBuffer curPage; private int offsetWithinPage = 0; private final FileChannel fileChannel; private final Path path; private final long fileLength; private long fileOffset = 0; private boolean isClosed; /** * Create a random access buffered file instance for the file with the given name. * * @param filename the filename of the file to be read. * @throws IOException if something went wrong while accessing the given file. */ public RandomAccessReadBufferedFile( String filename ) throws IOException { this(new File(filename)); } /** * Create a random access buffered file instance for the given file. * * @param file the file to be read. * @throws IOException if something went wrong while accessing the given file. */ public RandomAccessReadBufferedFile( File file ) throws IOException { this(file.toPath()); } /** * Create a random access buffered file instance using the given path. * * @param path path of the file to be read. * @throws IOException if something went wrong while accessing the given file. */ public RandomAccessReadBufferedFile(Path path) throws IOException { this.path = path; fileChannel = FileChannel.open(path, StandardOpenOption.READ); fileLength = fileChannel.size(); seek(0); } @Override public long getPosition() throws IOException { checkClosed(); return fileOffset; } /** * Seeks to new position. If new position is outside of current page the new page is either * taken from cache or read from file and added to cache. * * @param position the position to seek to. * @throws java.io.IOException if something went wrong. */ @Override public void seek( final long position ) throws IOException {<FILL_FUNCTION_BODY>} /** * Reads a page with data from current file position. If we have a * previously removed page from cache the buffer of this page is reused. * Otherwise a new byte buffer is created. */ private ByteBuffer readPage() throws IOException { ByteBuffer page; if ( lastRemovedCachePage != null ) { page = lastRemovedCachePage; lastRemovedCachePage = null; } else { page = ByteBuffer.allocate(PAGE_SIZE); } int readBytes = 0; while (readBytes < PAGE_SIZE) { int curBytesRead = fileChannel.read(page); if (curBytesRead < 0) { // EOF break; } readBytes += curBytesRead; } return page; } @Override public int read() throws IOException { checkClosed(); if ( fileOffset >= fileLength ) { return -1; } if (offsetWithinPage == PAGE_SIZE) { seek( fileOffset ); } fileOffset++; return curPage.get(offsetWithinPage++) & 0xff; } @Override public int read( byte[] b, int off, int len ) throws IOException { checkClosed(); if ( fileOffset >= fileLength ) { return -1; } if (offsetWithinPage == PAGE_SIZE) { seek( fileOffset ); } int commonLen = Math.min(PAGE_SIZE - offsetWithinPage, len); if ((fileLength - fileOffset) < PAGE_SIZE) { commonLen = Math.min( commonLen, (int) ( fileLength - fileOffset ) ); } curPage.position(offsetWithinPage); curPage.get(b, off, commonLen); offsetWithinPage += commonLen; fileOffset += commonLen; return commonLen; } @Override public long length() throws IOException { return fileLength; } @Override public void close() throws IOException { rafCopies.values().forEach(IOUtils::closeQuietly); rafCopies.clear(); fileChannel.close(); pageCache.clear(); isClosed = true; } @Override public boolean isClosed() { return isClosed; } /** * Ensure that the RandomAccessBuffer is not closed * @throws IOException If RandomAccessBuffer already closed */ private void checkClosed() throws IOException { if (isClosed) { throw new IOException(getClass().getName() + " already closed"); } } @Override public boolean isEOF() throws IOException { return peek() == -1; } @Override public RandomAccessReadView createView(long startPosition, long streamLength) throws IOException { checkClosed(); Long currentThreadID = Thread.currentThread().getId(); RandomAccessReadBufferedFile randomAccessReadBufferedFile = rafCopies.get(currentThreadID); if (randomAccessReadBufferedFile == null || randomAccessReadBufferedFile.isClosed()) { randomAccessReadBufferedFile = new RandomAccessReadBufferedFile(path); rafCopies.put(currentThreadID, randomAccessReadBufferedFile); } return new RandomAccessReadView(randomAccessReadBufferedFile, startPosition, streamLength); } }
checkClosed(); if (position < 0) { throw new IOException("Invalid position " + position); } final long newPageOffset = position & PAGE_OFFSET_MASK; if ( newPageOffset != curPageOffset ) { ByteBuffer newPage = pageCache.get(newPageOffset); if ( newPage == null ) { fileChannel.position(newPageOffset); newPage = readPage(); pageCache.put( newPageOffset, newPage ); } curPageOffset = newPageOffset; curPage = newPage; } fileOffset = Math.min(position, fileLength); offsetWithinPage = (int) (fileOffset - curPageOffset);
1,792
188
1,980
<no_super_class>
apache_pdfbox
pdfbox/io/src/main/java/org/apache/pdfbox/io/RandomAccessReadMemoryMappedFile.java
RandomAccessReadMemoryMappedFile
seek
class RandomAccessReadMemoryMappedFile implements RandomAccessRead { // mapped byte buffer private ByteBuffer mappedByteBuffer; // size of the whole file private final long size; // file channel of the file to be read private final FileChannel fileChannel; // function to unmap the byte buffer private final Consumer<? super ByteBuffer> unmapper; /** * Create a random access memory mapped file instance for the file with the given name. * * @param filename the filename of the file to be read * * @throws IOException If there is an IO error opening the file. */ public RandomAccessReadMemoryMappedFile(String filename) throws IOException { this(new File(filename)); } /** * Create a random access memory mapped file instance for the given file. * * @param file the file to be read * * @throws IOException If there is an IO error opening the file. */ public RandomAccessReadMemoryMappedFile(File file) throws IOException { this(file.toPath()); } /** * Create a random access memory mapped file instance using the given path. * * @param path path of the file to be read. * * @throws IOException If there is an IO error opening the file. */ public RandomAccessReadMemoryMappedFile(Path path) throws IOException { fileChannel = FileChannel.open(path, EnumSet.of(StandardOpenOption.READ)); size = fileChannel.size(); // TODO only ints are allowed -> implement paging if (size > Integer.MAX_VALUE) { throw new IOException(getClass().getName() + " doesn't yet support files bigger than " + Integer.MAX_VALUE); } // map the whole file to memory mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, size); unmapper = IOUtils::unmap; } private RandomAccessReadMemoryMappedFile(RandomAccessReadMemoryMappedFile parent) { mappedByteBuffer = parent.mappedByteBuffer.duplicate(); size = parent.size; mappedByteBuffer.rewind(); // unmap doesn't work on duplicate, see Unsafe#invokeCleaner unmapper = null; fileChannel = null; } /** * {@inheritDoc} */ @Override public void close() throws IOException { if (fileChannel != null) { fileChannel.close(); } if (mappedByteBuffer != null) { Optional.ofNullable(unmapper).ifPresent(u -> u.accept(mappedByteBuffer)); mappedByteBuffer = null; } } /** * {@inheritDoc} */ @Override public void seek(long position) throws IOException {<FILL_FUNCTION_BODY>} /** * {@inheritDoc} */ @Override public long getPosition() throws IOException { checkClosed(); return mappedByteBuffer.position(); } /** * {@inheritDoc} */ @Override public int read() throws IOException { if (isEOF()) { return -1; } return mappedByteBuffer.get() & 0xff; } /** * {@inheritDoc} */ @Override public int read(byte[] b, int offset, int length) throws IOException { if (isEOF()) { return -1; } int remainingBytes = (int)size - mappedByteBuffer.position(); remainingBytes = Math.min(remainingBytes, length); mappedByteBuffer.get(b, offset, remainingBytes); return remainingBytes; } /** * {@inheritDoc} */ @Override public long length() throws IOException { checkClosed(); return size; } /** * Ensure that the RandomAccessReadMemoryMappedFile is not closed * * @throws IOException If RandomAccessBuffer already closed */ private void checkClosed() throws IOException { if (isClosed()) { throw new IOException(getClass().getSimpleName() + " already closed"); } } /** * {@inheritDoc} */ @Override public boolean isClosed() { return mappedByteBuffer == null; } /** * {@inheritDoc} */ @Override public boolean isEOF() throws IOException { checkClosed(); return mappedByteBuffer.position() >= size; } @Override public RandomAccessReadView createView(long startPosition, long streamLength) { return new RandomAccessReadView(new RandomAccessReadMemoryMappedFile(this), startPosition, streamLength, true); } }
checkClosed(); if (position < 0) { throw new IOException("Invalid position "+position); } // it is allowed to jump beyond the end of the file // jump to the end of the reader mappedByteBuffer.position((int) Math.min(position, size));
1,267
77
1,344
<no_super_class>
apache_pdfbox
pdfbox/io/src/main/java/org/apache/pdfbox/io/RandomAccessReadView.java
RandomAccessReadView
seek
class RandomAccessReadView implements RandomAccessRead { // the underlying random access read private RandomAccessRead randomAccessRead; // the start position within the underlying source private final long startPosition; // stream length private final long streamLength; // close input private final boolean closeInput; // current position within the view private long currentPosition = 0; /** * Constructor. * * @param randomAccessRead the underlying random access read * @param startPosition start position within the underlying random access read * @param streamLength stream length */ public RandomAccessReadView(RandomAccessRead randomAccessRead, long startPosition, long streamLength) { this(randomAccessRead, startPosition, streamLength, false); } /** * Constructor. * * @param randomAccessRead the underlying random access read * @param startPosition start position within the underlying random access read * @param streamLength stream length * @param closeInput close the underlying random access read when closing the view if set to true */ public RandomAccessReadView(RandomAccessRead randomAccessRead, long startPosition, long streamLength, boolean closeInput) { this.randomAccessRead = randomAccessRead; this.startPosition = startPosition; this.streamLength = streamLength; this.closeInput = closeInput; } /** * {@inheritDoc} */ @Override public long getPosition() throws IOException { checkClosed(); return currentPosition; } /** * {@inheritDoc} */ @Override public void seek(final long newOffset) throws IOException {<FILL_FUNCTION_BODY>} /** * {@inheritDoc} */ @Override public int read() throws IOException { if (isEOF()) { return -1; } restorePosition(); int readValue = randomAccessRead.read(); if (readValue > -1) { currentPosition++; } return readValue; } /** * {@inheritDoc} */ @Override public int read(byte[] b, int off, int len) throws IOException { if (isEOF()) { return -1; } restorePosition(); int readBytes = randomAccessRead.read(b, off, Math.min(len, available())); currentPosition += readBytes; return readBytes; } /** * {@inheritDoc} */ @Override public long length() throws IOException { checkClosed(); return streamLength; } /** * {@inheritDoc} */ @Override public void close() throws IOException { if (closeInput && randomAccessRead != null) { randomAccessRead.close(); } randomAccessRead = null; } /** * {@inheritDoc} */ @Override public boolean isClosed() { return randomAccessRead == null || randomAccessRead.isClosed(); } /** * {@inheritDoc} */ @Override public void rewind(int bytes) throws IOException { checkClosed(); restorePosition(); randomAccessRead.rewind(bytes); currentPosition -= bytes; } /** * {@inheritDoc} */ @Override public boolean isEOF() throws IOException { checkClosed(); return currentPosition >= streamLength; } /** * Restore the current position within the underlying random access read. * * @throws IOException */ private void restorePosition() throws IOException { randomAccessRead.seek(startPosition + currentPosition); } /** * Ensure that that the view isn't closed. * * @throws IOException If RandomAccessReadView already closed */ private void checkClosed() throws IOException { if (isClosed()) { // consider that the rab is closed if there is no current buffer throw new IOException("RandomAccessReadView already closed"); } } @Override public RandomAccessReadView createView(long startPosition, long streamLength) throws IOException { throw new IOException(getClass().getName() + ".createView isn't supported."); } }
checkClosed(); if (newOffset < 0) { throw new IOException("Invalid position " + newOffset); } randomAccessRead.seek(startPosition + Math.min(newOffset, streamLength)); currentPosition = newOffset;
1,124
66
1,190
<no_super_class>
apache_pdfbox
pdfbox/io/src/main/java/org/apache/pdfbox/io/RandomAccessReadWriteBuffer.java
RandomAccessReadWriteBuffer
write
class RandomAccessReadWriteBuffer extends RandomAccessReadBuffer implements RandomAccess { /** * Default constructor. */ public RandomAccessReadWriteBuffer() { super(); } /** * Default constructor. */ public RandomAccessReadWriteBuffer(int definedChunkSize) { super(definedChunkSize); } /** * {@inheritDoc} */ @Override public void clear() throws IOException { checkClosed(); resetBuffers(); } /** * {@inheritDoc} */ @Override public void write(int b) throws IOException {<FILL_FUNCTION_BODY>} /** * {@inheritDoc} */ @Override public void write(byte[] b) throws IOException { write(b, 0, b.length); } /** * {@inheritDoc} */ @Override public void write(byte[] b, int off, int len) throws IOException { checkClosed(); int remain = len; int bOff = off; while (remain > 0) { int bytesToWrite = Math.min(remain, chunkSize - currentBufferPointer); if (bytesToWrite <= 0) { expandBuffer(); bytesToWrite = Math.min(remain, chunkSize - currentBufferPointer); } if (bytesToWrite > 0) { currentBuffer.put(b, bOff, bytesToWrite); currentBufferPointer += bytesToWrite; pointer += bytesToWrite; } bOff += bytesToWrite; remain -= bytesToWrite; } if (pointer > size) { size = pointer; } } }
checkClosed(); if (chunkSize - currentBufferPointer <= 0) { expandBuffer(); } currentBuffer.put((byte) b); currentBufferPointer++; pointer++; if (pointer > size) { size = pointer; }
461
78
539
<methods>public void <init>(byte[]) ,public void <init>(java.nio.ByteBuffer) ,public void <init>(java.io.InputStream) throws java.io.IOException,public void close() throws java.io.IOException,public static org.apache.pdfbox.io.RandomAccessReadBuffer createBufferFromStream(java.io.InputStream) throws java.io.IOException,public org.apache.pdfbox.io.RandomAccessReadView createView(long, long) throws java.io.IOException,public long getPosition() throws java.io.IOException,public boolean isClosed() ,public boolean isEOF() throws java.io.IOException,public long length() throws java.io.IOException,public int read() throws java.io.IOException,public int read(byte[], int, int) throws java.io.IOException,public void seek(long) throws java.io.IOException<variables>public static final int DEFAULT_CHUNK_SIZE_4KB,private final non-sealed List<java.nio.ByteBuffer> bufferList,private int bufferListIndex,private int bufferListMaxIndex,protected int chunkSize,protected java.nio.ByteBuffer currentBuffer,protected int currentBufferPointer,protected long pointer,private final ConcurrentMap<java.lang.Long,org.apache.pdfbox.io.RandomAccessReadBuffer> rarbCopies,protected long size
apache_pdfbox
pdfbox/io/src/main/java/org/apache/pdfbox/io/SequenceRandomAccessRead.java
SequenceRandomAccessRead
read
class SequenceRandomAccessRead implements RandomAccessRead { private final List<RandomAccessRead> readerList; private final long[] startPositions; private final long[] endPositions; private final int numberOfReader; private int currentIndex = 0; private long currentPosition = 0; private long totalLength = 0; private boolean isClosed = false; private RandomAccessRead currentRandomAccessRead = null; public SequenceRandomAccessRead(List<RandomAccessRead> randomAccessReadList) { if (randomAccessReadList == null) { throw new IllegalArgumentException("Missing input parameter"); } if (randomAccessReadList.isEmpty()) { throw new IllegalArgumentException("Empty list"); } readerList = randomAccessReadList.stream() // .filter(r -> { try { return r.length() > 0; } catch (IOException e) { throw new IllegalArgumentException("Problematic list", e); } }).collect(Collectors.toList()); currentRandomAccessRead = readerList.get(currentIndex); numberOfReader = readerList.size(); startPositions = new long[numberOfReader]; endPositions = new long[numberOfReader]; for(int i=0;i<numberOfReader;i++) { try { startPositions[i] = totalLength; totalLength += readerList.get(i).length(); endPositions[i] = totalLength - 1; } catch (IOException e) { throw new IllegalArgumentException("Problematic list", e); } } } @Override public void close() throws IOException { for (RandomAccessRead randomAccessRead : readerList) { randomAccessRead.close(); } readerList.clear(); currentRandomAccessRead = null; isClosed = true; } private RandomAccessRead getCurrentReader() throws IOException { if (currentRandomAccessRead.isEOF() && currentIndex < numberOfReader - 1) { currentIndex++; currentRandomAccessRead = readerList.get(currentIndex); currentRandomAccessRead.seek(0); } return currentRandomAccessRead; } @Override public int read() throws IOException { checkClosed(); RandomAccessRead randomAccessRead = getCurrentReader(); int value = randomAccessRead.read(); if (value > -1) { currentPosition++; } return value; } @Override public int read(byte[] b, int offset, int length) throws IOException {<FILL_FUNCTION_BODY>} @Override public long getPosition() throws IOException { checkClosed(); return currentPosition; } @Override public void seek(long position) throws IOException { checkClosed(); if (position < 0) { throw new IOException("Invalid position " + position); } // it is allowed to jump beyond the end of the file // jump to the end of the reader if (position >= totalLength) { currentIndex = numberOfReader - 1; currentPosition = totalLength; } else { // search forward/backwards if the new position is after/before the current position int increment = position < currentPosition ? -1 : 1; for (int i = currentIndex; i < numberOfReader && i >= 0; i += increment) { if (position >= startPositions[i] && position <= endPositions[i]) { currentIndex = i; break; } } currentPosition = position; } currentRandomAccessRead = readerList.get(currentIndex); currentRandomAccessRead.seek(currentPosition - startPositions[currentIndex]); } @Override public long length() throws IOException { checkClosed(); return totalLength; } @Override public boolean isClosed() { return isClosed; } /** * Ensure that the SequenceRandomAccessRead is not closed * * @throws IOException If RandomAccessBuffer already closed */ private void checkClosed() throws IOException { if (isClosed) { // consider that the rab is closed if there is no current buffer throw new IOException("RandomAccessBuffer already closed"); } } @Override public boolean isEOF() throws IOException { checkClosed(); return currentPosition >= totalLength; } @Override public RandomAccessReadView createView(long startPosition, long streamLength) throws IOException { throw new UnsupportedOperationException(getClass().getName() + ".createView isn't supported."); } }
checkClosed(); int maxAvailBytes = Math.min(available(), length); if (maxAvailBytes == 0) { return -1; } RandomAccessRead randomAccessRead = getCurrentReader(); int bytesRead = randomAccessRead.read(b, offset, maxAvailBytes); while (bytesRead > -1 && bytesRead < maxAvailBytes) { randomAccessRead = getCurrentReader(); bytesRead += randomAccessRead.read(b, offset + bytesRead, maxAvailBytes - bytesRead); } currentPosition += bytesRead; return bytesRead;
1,238
156
1,394
<no_super_class>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/contentstream/operator/DrawObject.java
DrawObject
process
class DrawObject extends OperatorProcessor { private static final Logger LOG = LogManager.getLogger(DrawObject.class); public DrawObject(PDFStreamEngine context) { super(context); } @Override public void process(Operator operator, List<COSBase> arguments) throws IOException {<FILL_FUNCTION_BODY>} @Override public String getName() { return OperatorName.DRAW_OBJECT; } }
if (arguments.isEmpty()) { throw new MissingOperandException(operator, arguments); } COSBase base0 = arguments.get(0); if (!(base0 instanceof COSName)) { return; } COSName name = (COSName) base0; PDFStreamEngine context = getContext(); if (context.getResources().isImageXObject(name)) { // we're done here, don't decode images when doing text extraction return; } PDXObject xobject = context.getResources().getXObject(name); if (xobject instanceof PDFormXObject) { try { context.increaseLevel(); if (context.getLevel() > 50) { LOG.error("recursion is too deep, skipping form XObject"); return; } if (xobject instanceof PDTransparencyGroup) { context.showTransparencyGroup((PDTransparencyGroup) xobject); } else { context.showForm((PDFormXObject) xobject); } } finally { context.decreaseLevel(); } }
127
317
444
<methods>public boolean checkArrayTypesClass(List<org.apache.pdfbox.cos.COSBase>, Class<?>) ,public abstract java.lang.String getName() ,public abstract void process(org.apache.pdfbox.contentstream.operator.Operator, List<org.apache.pdfbox.cos.COSBase>) throws java.io.IOException<variables>private final non-sealed org.apache.pdfbox.contentstream.PDFStreamEngine context
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/contentstream/operator/Operator.java
Operator
getOperator
class Operator { private final String theOperator; private byte[] imageData; private COSDictionary imageParameters; /** map for singleton operator objects; use {@link ConcurrentHashMap} for better scalability with multiple threads */ private static final ConcurrentMap<String,Operator> operators = new ConcurrentHashMap<>(); /** * Constructor. * * @param aOperator The operator that this object will represent. * @throws IllegalArgumentException if the operator starts with "/". */ private Operator(String aOperator) { theOperator = aOperator; if( aOperator.startsWith( "/" ) ) { throw new IllegalArgumentException( "Operators are not allowed to start with / '" + aOperator + "'" ); } } /** * This is used to create/cache operators in the system. * * @param operator The operator for the system. * * @return The operator that matches the operator keyword. */ public static Operator getOperator( String operator ) {<FILL_FUNCTION_BODY>} /** * This will get the name of the operator. * * @return The string representation of the operation. */ public String getName() { return theOperator; } /** * This will print a string rep of this class. * * @return A string rep of this class. */ @Override public String toString() { return "PDFOperator{" + theOperator + "}"; } /** * This is the special case for the ID operator where there are just random * bytes inlined the stream. * * @return Value of property imageData. */ public byte[] getImageData() { return this.imageData; } /** * This will set the image data, this is only used for the ID operator. * * @param imageDataArray New value of property imageData. */ public void setImageData(byte[] imageDataArray) { imageData = imageDataArray; } /** * This will get the image parameters, this is only valid for BI operators. * * @return The image parameters. */ public COSDictionary getImageParameters() { return imageParameters; } /** * This will set the image parameters, this is only valid for BI operators. * * @param params The image parameters. */ public void setImageParameters( COSDictionary params) { imageParameters = params; } }
Operator operation; if (operator.equals(OperatorName.BEGIN_INLINE_IMAGE_DATA) || OperatorName.BEGIN_INLINE_IMAGE.equals(operator)) { //we can't cache the ID operators. operation = new Operator( operator ); } else { operation = operators.get( operator ); if( operation == null ) { // another thread may has already added an operator of this kind // make sure that we get the same operator operation = operators.putIfAbsent( operator, new Operator( operator ) ); if ( operation == null ) { operation = operators.get( operator ); } } } return operation;
664
185
849
<no_super_class>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/contentstream/operator/color/SetColor.java
SetColor
process
class SetColor extends OperatorProcessor { protected SetColor(PDFStreamEngine context) { super(context); } @Override public void process(Operator operator, List<COSBase> arguments) throws IOException {<FILL_FUNCTION_BODY>} /** * Returns either the stroking or non-stroking color value. * @return The stroking or non-stroking color value. */ protected abstract PDColor getColor(); /** * Sets either the stroking or non-stroking color value. * @param color The stroking or non-stroking color value. */ protected abstract void setColor(PDColor color); /** * Returns either the stroking or non-stroking color space. * @return The stroking or non-stroking color space. */ protected abstract PDColorSpace getColorSpace(); }
PDColorSpace colorSpace = getColorSpace(); if (!(colorSpace instanceof PDPattern)) { if (arguments.size() < colorSpace.getNumberOfComponents()) { throw new MissingOperandException(operator, arguments); } if (!checkArrayTypesClass(arguments, COSNumber.class)) { return; } } COSArray array = new COSArray(arguments); setColor(new PDColor(array, colorSpace));
260
143
403
<methods>public boolean checkArrayTypesClass(List<org.apache.pdfbox.cos.COSBase>, Class<?>) ,public abstract java.lang.String getName() ,public abstract void process(org.apache.pdfbox.contentstream.operator.Operator, List<org.apache.pdfbox.cos.COSBase>) throws java.io.IOException<variables>private final non-sealed org.apache.pdfbox.contentstream.PDFStreamEngine context
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/contentstream/operator/color/SetNonStrokingColorSpace.java
SetNonStrokingColorSpace
process
class SetNonStrokingColorSpace extends OperatorProcessor { public SetNonStrokingColorSpace(PDFStreamEngine context) { super(context); } @Override public void process(Operator operator, List<COSBase> arguments) throws IOException {<FILL_FUNCTION_BODY>} @Override public String getName() { return OperatorName.NON_STROKING_COLORSPACE; } }
if (arguments.isEmpty()) { return; } COSBase base = arguments.get(0); if (!(base instanceof COSName)) { return; } PDFStreamEngine context = getContext(); PDColorSpace cs = context.getResources().getColorSpace((COSName) base); context.getGraphicsState().setNonStrokingColorSpace(cs); context.getGraphicsState().setNonStrokingColor(cs.getInitialColor());
121
128
249
<methods>public boolean checkArrayTypesClass(List<org.apache.pdfbox.cos.COSBase>, Class<?>) ,public abstract java.lang.String getName() ,public abstract void process(org.apache.pdfbox.contentstream.operator.Operator, List<org.apache.pdfbox.cos.COSBase>) throws java.io.IOException<variables>private final non-sealed org.apache.pdfbox.contentstream.PDFStreamEngine context
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/contentstream/operator/color/SetNonStrokingDeviceCMYKColor.java
SetNonStrokingDeviceCMYKColor
process
class SetNonStrokingDeviceCMYKColor extends SetNonStrokingColor { public SetNonStrokingDeviceCMYKColor(PDFStreamEngine context) { super(context); } @Override public void process(Operator operator, List<COSBase> arguments) throws IOException {<FILL_FUNCTION_BODY>} @Override public String getName() { return OperatorName.NON_STROKING_CMYK; } }
PDFStreamEngine context = getContext(); PDColorSpace cs = context.getResources().getColorSpace(COSName.DEVICECMYK); context.getGraphicsState().setNonStrokingColorSpace(cs); super.process(operator, arguments);
130
69
199
<methods>public void <init>(org.apache.pdfbox.contentstream.PDFStreamEngine) ,public java.lang.String getName() <variables>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/contentstream/operator/color/SetNonStrokingDeviceGrayColor.java
SetNonStrokingDeviceGrayColor
process
class SetNonStrokingDeviceGrayColor extends SetNonStrokingColor { public SetNonStrokingDeviceGrayColor(PDFStreamEngine context) { super(context); } @Override public void process(Operator operator, List<COSBase> arguments) throws IOException {<FILL_FUNCTION_BODY>} @Override public String getName() { return OperatorName.NON_STROKING_GRAY; } }
PDFStreamEngine context = getContext(); PDColorSpace cs = context.getResources().getColorSpace(COSName.DEVICEGRAY); context.getGraphicsState().setNonStrokingColorSpace(cs); super.process(operator, arguments);
127
68
195
<methods>public void <init>(org.apache.pdfbox.contentstream.PDFStreamEngine) ,public java.lang.String getName() <variables>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/contentstream/operator/color/SetNonStrokingDeviceRGBColor.java
SetNonStrokingDeviceRGBColor
process
class SetNonStrokingDeviceRGBColor extends SetNonStrokingColor { public SetNonStrokingDeviceRGBColor(PDFStreamEngine context) { super(context); } @Override public void process(Operator operator, List<COSBase> arguments) throws IOException {<FILL_FUNCTION_BODY>} @Override public String getName() { return OperatorName.NON_STROKING_RGB; } }
PDFStreamEngine context = getContext(); PDColorSpace cs = context.getResources().getColorSpace(COSName.DEVICERGB); context.getGraphicsState().setNonStrokingColorSpace(cs); super.process(operator, arguments);
127
69
196
<methods>public void <init>(org.apache.pdfbox.contentstream.PDFStreamEngine) ,public java.lang.String getName() <variables>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/contentstream/operator/color/SetStrokingColorSpace.java
SetStrokingColorSpace
process
class SetStrokingColorSpace extends OperatorProcessor { public SetStrokingColorSpace(PDFStreamEngine context) { super(context); } @Override public void process(Operator operator, List<COSBase> arguments) throws IOException {<FILL_FUNCTION_BODY>} @Override public String getName() { return OperatorName.STROKING_COLORSPACE; } }
if (arguments.isEmpty()) { return; } COSBase base = arguments.get(0); if (!(base instanceof COSName)) { return; } PDFStreamEngine context = getContext(); PDColorSpace cs = context.getResources().getColorSpace((COSName) base); context.getGraphicsState().setStrokingColorSpace(cs); context.getGraphicsState().setStrokingColor(cs.getInitialColor());
116
126
242
<methods>public boolean checkArrayTypesClass(List<org.apache.pdfbox.cos.COSBase>, Class<?>) ,public abstract java.lang.String getName() ,public abstract void process(org.apache.pdfbox.contentstream.operator.Operator, List<org.apache.pdfbox.cos.COSBase>) throws java.io.IOException<variables>private final non-sealed org.apache.pdfbox.contentstream.PDFStreamEngine context
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/contentstream/operator/color/SetStrokingDeviceCMYKColor.java
SetStrokingDeviceCMYKColor
process
class SetStrokingDeviceCMYKColor extends SetStrokingColor { public SetStrokingDeviceCMYKColor(PDFStreamEngine context) { super(context); } @Override public void process(Operator operator, List<COSBase> arguments) throws IOException {<FILL_FUNCTION_BODY>} @Override public String getName() { return OperatorName.STROKING_COLOR_CMYK; } }
PDFStreamEngine context = getContext(); PDColorSpace cs = context.getResources().getColorSpace(COSName.DEVICECMYK); context.getGraphicsState().setStrokingColorSpace(cs); super.process(operator, arguments);
126
68
194
<methods>public void <init>(org.apache.pdfbox.contentstream.PDFStreamEngine) ,public java.lang.String getName() <variables>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/contentstream/operator/color/SetStrokingDeviceGrayColor.java
SetStrokingDeviceGrayColor
process
class SetStrokingDeviceGrayColor extends SetStrokingColor { public SetStrokingDeviceGrayColor(PDFStreamEngine context) { super(context); } @Override public void process(Operator operator, List<COSBase> arguments) throws IOException {<FILL_FUNCTION_BODY>} @Override public String getName() { return OperatorName.STROKING_COLOR_GRAY; } }
PDFStreamEngine context = getContext(); PDColorSpace cs = context.getResources().getColorSpace(COSName.DEVICEGRAY); context.getGraphicsState().setStrokingColorSpace(cs); super.process(operator, arguments);
123
67
190
<methods>public void <init>(org.apache.pdfbox.contentstream.PDFStreamEngine) ,public java.lang.String getName() <variables>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/contentstream/operator/color/SetStrokingDeviceRGBColor.java
SetStrokingDeviceRGBColor
process
class SetStrokingDeviceRGBColor extends SetStrokingColor { public SetStrokingDeviceRGBColor(PDFStreamEngine context) { super(context); } /** * RG Set the stroking colour space to DeviceRGB and set the colour to * use for stroking operations. * * @param operator The operator that is being executed. * @param arguments List * @throws IOException If the color space cannot be read. */ @Override public void process(Operator operator, List<COSBase> arguments) throws IOException {<FILL_FUNCTION_BODY>} @Override public String getName() { return OperatorName.STROKING_COLOR_RGB; } }
PDFStreamEngine context = getContext(); PDColorSpace cs = context.getResources().getColorSpace(COSName.DEVICERGB); context.getGraphicsState().setStrokingColorSpace(cs); super.process(operator, arguments);
195
68
263
<methods>public void <init>(org.apache.pdfbox.contentstream.PDFStreamEngine) ,public java.lang.String getName() <variables>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/contentstream/operator/graphics/AppendRectangleToPath.java
AppendRectangleToPath
process
class AppendRectangleToPath extends GraphicsOperatorProcessor { public AppendRectangleToPath(PDFGraphicsStreamEngine context) { super(context); } @Override public void process(Operator operator, List<COSBase> operands) throws IOException {<FILL_FUNCTION_BODY>} @Override public String getName() { return OperatorName.APPEND_RECT; } }
if (operands.size() < 4) { throw new MissingOperandException(operator, operands); } if (!checkArrayTypesClass(operands, COSNumber.class)) { return; } COSNumber x = (COSNumber) operands.get(0); COSNumber y = (COSNumber) operands.get(1); COSNumber w = (COSNumber) operands.get(2); COSNumber h = (COSNumber) operands.get(3); float x1 = x.floatValue(); float y1 = y.floatValue(); // create a pair of coordinates for the transformation float x2 = w.floatValue() + x1; float y2 = h.floatValue() + y1; PDFGraphicsStreamEngine context = getGraphicsContext(); Point2D p0 = context.transformedPoint(x1, y1); Point2D p1 = context.transformedPoint(x2, y1); Point2D p2 = context.transformedPoint(x2, y2); Point2D p3 = context.transformedPoint(x1, y2); context.appendRectangle(p0, p1, p2, p3);
115
319
434
<no_super_class>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/contentstream/operator/graphics/BeginInlineImage.java
BeginInlineImage
process
class BeginInlineImage extends GraphicsOperatorProcessor { public BeginInlineImage(PDFGraphicsStreamEngine context) { super(context); } @Override public void process(Operator operator, List<COSBase> operands) throws IOException {<FILL_FUNCTION_BODY>} @Override public String getName() { return OperatorName.BEGIN_INLINE_IMAGE; } }
if (operator.getImageData() == null || operator.getImageData().length == 0) { return; } PDFGraphicsStreamEngine context = getGraphicsContext(); PDImage image = new PDInlineImage(operator.getImageParameters(), operator.getImageData(), context.getResources()); context.drawImage(image);
113
92
205
<no_super_class>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/contentstream/operator/graphics/ClosePath.java
ClosePath
process
class ClosePath extends GraphicsOperatorProcessor { private static final Logger LOG = LogManager.getLogger(ClosePath.class); public ClosePath(PDFGraphicsStreamEngine context) { super(context); } @Override public void process(Operator operator, List<COSBase> operands) throws IOException {<FILL_FUNCTION_BODY>} @Override public String getName() { return OperatorName.CLOSE_PATH; } }
if (getGraphicsContext().getCurrentPoint() == null) { LOG.warn("ClosePath without initial MoveTo"); return; } getGraphicsContext().closePath();
129
50
179
<no_super_class>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/contentstream/operator/graphics/CurveTo.java
CurveTo
process
class CurveTo extends GraphicsOperatorProcessor { private static final Logger LOG = LogManager.getLogger(CurveTo.class); public CurveTo(PDFGraphicsStreamEngine context) { super(context); } @Override public void process(Operator operator, List<COSBase> operands) throws IOException {<FILL_FUNCTION_BODY>} @Override public String getName() { return OperatorName.CURVE_TO; } }
if (operands.size() < 6) { throw new MissingOperandException(operator, operands); } if (!checkArrayTypesClass(operands, COSNumber.class)) { return; } COSNumber x1 = (COSNumber)operands.get(0); COSNumber y1 = (COSNumber)operands.get(1); COSNumber x2 = (COSNumber)operands.get(2); COSNumber y2 = (COSNumber)operands.get(3); COSNumber x3 = (COSNumber)operands.get(4); COSNumber y3 = (COSNumber)operands.get(5); PDFGraphicsStreamEngine context = getGraphicsContext(); Point2D.Float point1 = context.transformedPoint(x1.floatValue(), y1.floatValue()); Point2D.Float point2 = context.transformedPoint(x2.floatValue(), y2.floatValue()); Point2D.Float point3 = context.transformedPoint(x3.floatValue(), y3.floatValue()); if (context.getCurrentPoint() == null) { LOG.warn("curveTo ({},{}) without initial MoveTo", point3.x, point3.y); context.moveTo(point3.x, point3.y); } else { context.curveTo(point1.x, point1.y, point2.x, point2.y, point3.x, point3.y); }
131
398
529
<no_super_class>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/contentstream/operator/graphics/CurveToReplicateFinalPoint.java
CurveToReplicateFinalPoint
process
class CurveToReplicateFinalPoint extends GraphicsOperatorProcessor { public CurveToReplicateFinalPoint(PDFGraphicsStreamEngine context) { super(context); } @Override public void process(Operator operator, List<COSBase> operands) throws IOException {<FILL_FUNCTION_BODY>} @Override public String getName() { return OperatorName.CURVE_TO_REPLICATE_FINAL_POINT; } }
if (operands.size() < 4) { throw new MissingOperandException(operator, operands); } if (!checkArrayTypesClass(operands, COSNumber.class)) { return; } COSNumber x1 = (COSNumber)operands.get(0); COSNumber y1 = (COSNumber)operands.get(1); COSNumber x3 = (COSNumber)operands.get(2); COSNumber y3 = (COSNumber)operands.get(3); PDFGraphicsStreamEngine context = getGraphicsContext(); Point2D.Float point1 = context.transformedPoint(x1.floatValue(), y1.floatValue()); Point2D.Float point3 = context.transformedPoint(x3.floatValue(), y3.floatValue()); context.curveTo(point1.x, point1.y, point3.x, point3.y, point3.x, point3.y);
130
256
386
<no_super_class>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/contentstream/operator/graphics/CurveToReplicateInitialPoint.java
CurveToReplicateInitialPoint
process
class CurveToReplicateInitialPoint extends GraphicsOperatorProcessor { private static final Logger LOG = LogManager.getLogger(CurveToReplicateInitialPoint.class); public CurveToReplicateInitialPoint(PDFGraphicsStreamEngine context) { super(context); } @Override public void process(Operator operator, List<COSBase> operands) throws IOException {<FILL_FUNCTION_BODY>} @Override public String getName() { return OperatorName.CURVE_TO_REPLICATE_INITIAL_POINT; } }
if (operands.size() < 4) { throw new MissingOperandException(operator, operands); } if (!checkArrayTypesClass(operands, COSNumber.class)) { return; } COSNumber x2 = (COSNumber)operands.get(0); COSNumber y2 = (COSNumber)operands.get(1); COSNumber x3 = (COSNumber)operands.get(2); COSNumber y3 = (COSNumber)operands.get(3); PDFGraphicsStreamEngine context = getGraphicsContext(); Point2D currentPoint = context.getCurrentPoint(); Point2D.Float point2 = context.transformedPoint(x2.floatValue(), y2.floatValue()); Point2D.Float point3 = context.transformedPoint(x3.floatValue(), y3.floatValue()); if (currentPoint == null) { LOG.warn("curveTo ({},{}) without initial MoveTo", point3.x, point3.y); context.moveTo(point3.x, point3.y); } else { context.curveTo((float) currentPoint.getX(), (float) currentPoint.getY(), point2.x, point2.y, point3.x, point3.y); }
158
348
506
<no_super_class>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/contentstream/operator/graphics/DrawObject.java
DrawObject
process
class DrawObject extends GraphicsOperatorProcessor { private static final Logger LOG = LogManager.getLogger(DrawObject.class); public DrawObject(PDFGraphicsStreamEngine context) { super(context); } @Override public void process(Operator operator, List<COSBase> operands) throws IOException {<FILL_FUNCTION_BODY>} @Override public String getName() { return OperatorName.DRAW_OBJECT; } }
if (operands.isEmpty()) { throw new MissingOperandException(operator, operands); } COSBase base0 = operands.get(0); if (!(base0 instanceof COSName)) { return; } COSName objectName = (COSName) base0; PDFGraphicsStreamEngine context = getGraphicsContext(); PDXObject xobject = context.getResources().getXObject(objectName); if (xobject == null) { throw new MissingResourceException("Missing XObject: " + objectName.getName()); } else if (xobject instanceof PDImageXObject) { PDImageXObject image = (PDImageXObject)xobject; context.drawImage(image); } else if (xobject instanceof PDFormXObject) { try { context.increaseLevel(); if (context.getLevel() > 50) { LOG.error("recursion is too deep, skipping form XObject"); return; } if (xobject instanceof PDTransparencyGroup) { context.showTransparencyGroup((PDTransparencyGroup) xobject); } else { context.showForm((PDFormXObject) xobject); } } finally { context.decreaseLevel(); } }
129
359
488
<no_super_class>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/contentstream/operator/graphics/LineTo.java
LineTo
process
class LineTo extends GraphicsOperatorProcessor { private static final Logger LOG = LogManager.getLogger(LineTo.class); public LineTo(PDFGraphicsStreamEngine context) { super(context); } @Override public void process(Operator operator, List<COSBase> operands) throws IOException {<FILL_FUNCTION_BODY>} @Override public String getName() { return OperatorName.LINE_TO; } }
if (operands.size() < 2) { throw new MissingOperandException(operator, operands); } COSBase base0 = operands.get(0); if (!(base0 instanceof COSNumber)) { return; } COSBase base1 = operands.get(1); if (!(base1 instanceof COSNumber)) { return; } // append straight line segment from the current point to the point COSNumber x = (COSNumber) base0; COSNumber y = (COSNumber) base1; PDFGraphicsStreamEngine context = getGraphicsContext(); Point2D.Float pos = context.transformedPoint(x.floatValue(), y.floatValue()); if (context.getCurrentPoint() == null) { LOG.warn("LineTo ({},{}) without initial MoveTo", pos.x, pos.y); context.moveTo(pos.x, pos.y); } else { context.lineTo(pos.x, pos.y); }
127
277
404
<no_super_class>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/contentstream/operator/graphics/MoveTo.java
MoveTo
process
class MoveTo extends GraphicsOperatorProcessor { public MoveTo(PDFGraphicsStreamEngine context) { super(context); } @Override public void process(Operator operator, List<COSBase> operands) throws IOException {<FILL_FUNCTION_BODY>} @Override public String getName() { return OperatorName.MOVE_TO; } }
if (operands.size() < 2) { throw new MissingOperandException(operator, operands); } COSBase base0 = operands.get(0); if (!(base0 instanceof COSNumber)) { return; } COSBase base1 = operands.get(1); if (!(base1 instanceof COSNumber)) { return; } COSNumber x = (COSNumber) base0; COSNumber y = (COSNumber) base1; PDFGraphicsStreamEngine context = getGraphicsContext(); Point2D.Float pos = context.transformedPoint(x.floatValue(), y.floatValue()); context.moveTo(pos.x, pos.y);
106
192
298
<no_super_class>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/contentstream/operator/graphics/ShadingFill.java
ShadingFill
process
class ShadingFill extends GraphicsOperatorProcessor { public ShadingFill(PDFGraphicsStreamEngine context) { super(context); } @Override public void process(Operator operator, List<COSBase> operands) throws IOException {<FILL_FUNCTION_BODY>} @Override public String getName() { return OperatorName.SHADING_FILL; } }
if (operands.isEmpty()) { throw new MissingOperandException(operator, operands); } COSBase base = operands.get(0); if (!(base instanceof COSName)) { throw new MissingOperandException(operator, operands); } getGraphicsContext().shadingFill((COSName) base);
110
95
205
<no_super_class>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/contentstream/operator/markedcontent/BeginMarkedContentSequence.java
BeginMarkedContentSequence
process
class BeginMarkedContentSequence extends OperatorProcessor { public BeginMarkedContentSequence(PDFStreamEngine context) { super(context); } @Override public void process(Operator operator, List<COSBase> arguments) throws IOException {<FILL_FUNCTION_BODY>} @Override public String getName() { return OperatorName.BEGIN_MARKED_CONTENT; } }
COSName tag = null; for (COSBase argument : arguments) { if (argument instanceof COSName) { tag = (COSName) argument; } } getContext().beginMarkedContentSequence(tag, null);
130
81
211
<methods>public boolean checkArrayTypesClass(List<org.apache.pdfbox.cos.COSBase>, Class<?>) ,public abstract java.lang.String getName() ,public abstract void process(org.apache.pdfbox.contentstream.operator.Operator, List<org.apache.pdfbox.cos.COSBase>) throws java.io.IOException<variables>private final non-sealed org.apache.pdfbox.contentstream.PDFStreamEngine context
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/contentstream/operator/markedcontent/BeginMarkedContentSequenceWithProperties.java
BeginMarkedContentSequenceWithProperties
process
class BeginMarkedContentSequenceWithProperties extends OperatorProcessor { public BeginMarkedContentSequenceWithProperties(PDFStreamEngine context) { super(context); } @Override public void process(Operator operator, List<COSBase> arguments) throws IOException {<FILL_FUNCTION_BODY>} @Override public String getName() { return OperatorName.BEGIN_MARKED_CONTENT_SEQ; } }
COSName tag = null; COSDictionary properties = null; for (COSBase argument : arguments) { if (argument instanceof COSName) { tag = (COSName) argument; } else if (argument instanceof COSDictionary) { properties = (COSDictionary) argument; } } getContext().beginMarkedContentSequence(tag, properties);
137
123
260
<methods>public boolean checkArrayTypesClass(List<org.apache.pdfbox.cos.COSBase>, Class<?>) ,public abstract java.lang.String getName() ,public abstract void process(org.apache.pdfbox.contentstream.operator.Operator, List<org.apache.pdfbox.cos.COSBase>) throws java.io.IOException<variables>private final non-sealed org.apache.pdfbox.contentstream.PDFStreamEngine context
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/contentstream/operator/markedcontent/DrawObject.java
DrawObject
process
class DrawObject extends OperatorProcessor { private static final Logger LOG = LogManager.getLogger(DrawObject.class); public DrawObject(PDFStreamEngine context) { super(context); } @Override public void process(Operator operator, List<COSBase> arguments) throws IOException {<FILL_FUNCTION_BODY>} @Override public String getName() { return OperatorName.DRAW_OBJECT; } }
if (arguments.isEmpty()) { throw new MissingOperandException(operator, arguments); } COSBase base0 = arguments.get(0); if (!(base0 instanceof COSName)) { return; } COSName name = (COSName) base0; PDFStreamEngine context = getContext(); PDXObject xobject = context.getResources().getXObject(name); ((PDFMarkedContentExtractor) context).xobject(xobject); if (xobject instanceof PDFormXObject) { try { context.increaseLevel(); if (context.getLevel() > 50) { LOG.error("recursion is too deep, skipping form XObject"); return; } if (xobject instanceof PDTransparencyGroup) { context.showTransparencyGroup((PDTransparencyGroup) xobject); } else { context.showForm((PDFormXObject) xobject); } } finally { context.decreaseLevel(); } }
127
287
414
<methods>public boolean checkArrayTypesClass(List<org.apache.pdfbox.cos.COSBase>, Class<?>) ,public abstract java.lang.String getName() ,public abstract void process(org.apache.pdfbox.contentstream.operator.Operator, List<org.apache.pdfbox.cos.COSBase>) throws java.io.IOException<variables>private final non-sealed org.apache.pdfbox.contentstream.PDFStreamEngine context
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/contentstream/operator/state/Concatenate.java
Concatenate
process
class Concatenate extends OperatorProcessor { public Concatenate(PDFStreamEngine context) { super(context); } @Override public void process(Operator operator, List<COSBase> arguments) throws IOException {<FILL_FUNCTION_BODY>} @Override public String getName() { return OperatorName.CONCAT; } }
if (arguments.size() < 6) { throw new MissingOperandException(operator, arguments); } if (!checkArrayTypesClass(arguments, COSNumber.class)) { return; } // concatenate matrix to current transformation matrix COSNumber a = (COSNumber) arguments.get(0); COSNumber b = (COSNumber) arguments.get(1); COSNumber c = (COSNumber) arguments.get(2); COSNumber d = (COSNumber) arguments.get(3); COSNumber e = (COSNumber) arguments.get(4); COSNumber f = (COSNumber) arguments.get(5); Matrix matrix = new Matrix(a.floatValue(), b.floatValue(), c.floatValue(), d.floatValue(), e.floatValue(), f.floatValue()); getContext().getGraphicsState().getCurrentTransformationMatrix().concatenate(matrix);
106
244
350
<methods>public boolean checkArrayTypesClass(List<org.apache.pdfbox.cos.COSBase>, Class<?>) ,public abstract java.lang.String getName() ,public abstract void process(org.apache.pdfbox.contentstream.operator.Operator, List<org.apache.pdfbox.cos.COSBase>) throws java.io.IOException<variables>private final non-sealed org.apache.pdfbox.contentstream.PDFStreamEngine context
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/contentstream/operator/state/Restore.java
Restore
process
class Restore extends OperatorProcessor { public Restore(PDFStreamEngine context) { super(context); } @Override public void process(Operator operator, List<COSBase> arguments) throws IOException {<FILL_FUNCTION_BODY>} @Override public String getName() { return OperatorName.RESTORE; } }
PDFStreamEngine context = getContext(); if (context.getGraphicsStackSize() > 1) { context.restoreGraphicsState(); } else { // this shouldn't happen but it does, see PDFBOX-161 throw new EmptyGraphicsStackException(); }
104
81
185
<methods>public boolean checkArrayTypesClass(List<org.apache.pdfbox.cos.COSBase>, Class<?>) ,public abstract java.lang.String getName() ,public abstract void process(org.apache.pdfbox.contentstream.operator.Operator, List<org.apache.pdfbox.cos.COSBase>) throws java.io.IOException<variables>private final non-sealed org.apache.pdfbox.contentstream.PDFStreamEngine context
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/contentstream/operator/state/SetFlatness.java
SetFlatness
process
class SetFlatness extends OperatorProcessor { public SetFlatness(PDFStreamEngine context) { super(context); } @Override public void process(Operator operator, List<COSBase> operands) throws IOException {<FILL_FUNCTION_BODY>} @Override public String getName() { return OperatorName.SET_FLATNESS; } }
if (operands.isEmpty()) { throw new MissingOperandException(operator, operands); } if (!checkArrayTypesClass(operands, COSNumber.class)) { return; } COSNumber value = (COSNumber) operands.get(0); getContext().getGraphicsState().setFlatness(value.floatValue());
111
99
210
<methods>public boolean checkArrayTypesClass(List<org.apache.pdfbox.cos.COSBase>, Class<?>) ,public abstract java.lang.String getName() ,public abstract void process(org.apache.pdfbox.contentstream.operator.Operator, List<org.apache.pdfbox.cos.COSBase>) throws java.io.IOException<variables>private final non-sealed org.apache.pdfbox.contentstream.PDFStreamEngine context
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/contentstream/operator/state/SetGraphicsStateParameters.java
SetGraphicsStateParameters
process
class SetGraphicsStateParameters extends OperatorProcessor { private static final Logger LOG = LogManager.getLogger(SetGraphicsStateParameters.class); public SetGraphicsStateParameters(PDFStreamEngine context) { super(context); } @Override public void process(Operator operator, List<COSBase> arguments) throws IOException {<FILL_FUNCTION_BODY>} @Override public String getName() { return OperatorName.SET_GRAPHICS_STATE_PARAMS; } }
if (arguments.isEmpty()) { throw new MissingOperandException(operator, arguments); } COSBase base0 = arguments.get(0); if (!(base0 instanceof COSName)) { return; } // set parameters from graphics state parameter dictionary COSName graphicsName = (COSName) base0; PDFStreamEngine context = getContext(); PDExtendedGraphicsState gs = context.getResources().getExtGState(graphicsName); if (gs == null) { LOG.error("name for 'gs' operator not found in resources: /{}", graphicsName.getName()); return; } gs.copyIntoGraphicsState( context.getGraphicsState() );
138
190
328
<methods>public boolean checkArrayTypesClass(List<org.apache.pdfbox.cos.COSBase>, Class<?>) ,public abstract java.lang.String getName() ,public abstract void process(org.apache.pdfbox.contentstream.operator.Operator, List<org.apache.pdfbox.cos.COSBase>) throws java.io.IOException<variables>private final non-sealed org.apache.pdfbox.contentstream.PDFStreamEngine context
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/contentstream/operator/state/SetLineCapStyle.java
SetLineCapStyle
process
class SetLineCapStyle extends OperatorProcessor { public SetLineCapStyle(PDFStreamEngine context) { super(context); } @Override public void process(Operator operator, List<COSBase> arguments) throws IOException {<FILL_FUNCTION_BODY>} @Override public String getName() { return OperatorName.SET_LINE_CAPSTYLE; } }
if (arguments.isEmpty()) { throw new MissingOperandException(operator, arguments); } int lineCapStyle = ((COSNumber)arguments.get( 0 )).intValue(); getContext().getGraphicsState().setLineCap(lineCapStyle);
112
71
183
<methods>public boolean checkArrayTypesClass(List<org.apache.pdfbox.cos.COSBase>, Class<?>) ,public abstract java.lang.String getName() ,public abstract void process(org.apache.pdfbox.contentstream.operator.Operator, List<org.apache.pdfbox.cos.COSBase>) throws java.io.IOException<variables>private final non-sealed org.apache.pdfbox.contentstream.PDFStreamEngine context
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/contentstream/operator/state/SetLineDashPattern.java
SetLineDashPattern
process
class SetLineDashPattern extends OperatorProcessor { private static final Logger LOG = LogManager.getLogger(SetLineDashPattern.class); public SetLineDashPattern(PDFStreamEngine context) { super(context); } @Override public void process(Operator operator, List<COSBase> arguments) throws MissingOperandException {<FILL_FUNCTION_BODY>} @Override public String getName() { return OperatorName.SET_LINE_DASHPATTERN; } }
if (arguments.size() < 2) { throw new MissingOperandException(operator, arguments); } COSBase base0 = arguments.get(0); if (!(base0 instanceof COSArray)) { return; } COSBase base1 = arguments.get(1); if (!(base1 instanceof COSNumber)) { return; } COSArray dashArray = (COSArray) base0; int dashPhase = ((COSNumber) base1).intValue(); for (COSBase base : dashArray) { if (base instanceof COSNumber) { COSNumber num = (COSNumber) base; if (Float.compare(num.floatValue(), 0) != 0) { break; } } else { LOG.warn("dash array has non number element {}, ignored", base); dashArray = new COSArray(); break; } } getContext().setLineDashPattern(dashArray, dashPhase);
144
278
422
<methods>public boolean checkArrayTypesClass(List<org.apache.pdfbox.cos.COSBase>, Class<?>) ,public abstract java.lang.String getName() ,public abstract void process(org.apache.pdfbox.contentstream.operator.Operator, List<org.apache.pdfbox.cos.COSBase>) throws java.io.IOException<variables>private final non-sealed org.apache.pdfbox.contentstream.PDFStreamEngine context
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/contentstream/operator/state/SetLineJoinStyle.java
SetLineJoinStyle
process
class SetLineJoinStyle extends OperatorProcessor { public SetLineJoinStyle(PDFStreamEngine context) { super(context); } @Override public void process(Operator operator, List<COSBase> arguments) throws IOException {<FILL_FUNCTION_BODY>} @Override public String getName() { return OperatorName.SET_LINE_JOINSTYLE; } }
if (arguments.isEmpty()) { throw new MissingOperandException(operator, arguments); } int lineJoinStyle = ((COSNumber)arguments.get( 0 )).intValue(); getContext().getGraphicsState().setLineJoin(lineJoinStyle);
112
71
183
<methods>public boolean checkArrayTypesClass(List<org.apache.pdfbox.cos.COSBase>, Class<?>) ,public abstract java.lang.String getName() ,public abstract void process(org.apache.pdfbox.contentstream.operator.Operator, List<org.apache.pdfbox.cos.COSBase>) throws java.io.IOException<variables>private final non-sealed org.apache.pdfbox.contentstream.PDFStreamEngine context
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/contentstream/operator/state/SetLineMiterLimit.java
SetLineMiterLimit
process
class SetLineMiterLimit extends OperatorProcessor { public SetLineMiterLimit(PDFStreamEngine context) { super(context); } @Override public void process(Operator operator, List<COSBase> arguments) throws IOException {<FILL_FUNCTION_BODY>} @Override public String getName() { return OperatorName.SET_LINE_MITERLIMIT; } }
if (arguments.isEmpty()) { throw new MissingOperandException(operator, arguments); } COSNumber miterLimit = (COSNumber)arguments.get( 0 ); getContext().getGraphicsState().setMiterLimit(miterLimit.floatValue());
115
73
188
<methods>public boolean checkArrayTypesClass(List<org.apache.pdfbox.cos.COSBase>, Class<?>) ,public abstract java.lang.String getName() ,public abstract void process(org.apache.pdfbox.contentstream.operator.Operator, List<org.apache.pdfbox.cos.COSBase>) throws java.io.IOException<variables>private final non-sealed org.apache.pdfbox.contentstream.PDFStreamEngine context
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/contentstream/operator/state/SetLineWidth.java
SetLineWidth
process
class SetLineWidth extends OperatorProcessor { public SetLineWidth(PDFStreamEngine context) { super(context); } @Override public void process(Operator operator, List<COSBase> arguments) throws IOException {<FILL_FUNCTION_BODY>} @Override public String getName() { return OperatorName.SET_LINE_WIDTH; } }
if (arguments.isEmpty()) { throw new MissingOperandException(operator, arguments); } COSNumber width = (COSNumber) arguments.get(0); getContext().getGraphicsState().setLineWidth(width.floatValue());
108
67
175
<methods>public boolean checkArrayTypesClass(List<org.apache.pdfbox.cos.COSBase>, Class<?>) ,public abstract java.lang.String getName() ,public abstract void process(org.apache.pdfbox.contentstream.operator.Operator, List<org.apache.pdfbox.cos.COSBase>) throws java.io.IOException<variables>private final non-sealed org.apache.pdfbox.contentstream.PDFStreamEngine context
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/contentstream/operator/state/SetMatrix.java
SetMatrix
process
class SetMatrix extends OperatorProcessor { public SetMatrix(PDFStreamEngine context) { super(context); } @Override public void process(Operator operator, List<COSBase> arguments) throws MissingOperandException {<FILL_FUNCTION_BODY>} @Override public String getName() { return OperatorName.SET_MATRIX; } }
if (arguments.size() < 6) { throw new MissingOperandException(operator, arguments); } if (!checkArrayTypesClass(arguments, COSNumber.class)) { return; } COSNumber a = (COSNumber)arguments.get( 0 ); COSNumber b = (COSNumber)arguments.get( 1 ); COSNumber c = (COSNumber)arguments.get( 2 ); COSNumber d = (COSNumber)arguments.get( 3 ); COSNumber e = (COSNumber)arguments.get( 4 ); COSNumber f = (COSNumber)arguments.get( 5 ); Matrix matrix = new Matrix(a.floatValue(), b.floatValue(), c.floatValue(), d.floatValue(), e.floatValue(), f.floatValue()); PDFStreamEngine context = getContext(); context.setTextMatrix(matrix); context.setTextLineMatrix(matrix.clone());
110
248
358
<methods>public boolean checkArrayTypesClass(List<org.apache.pdfbox.cos.COSBase>, Class<?>) ,public abstract java.lang.String getName() ,public abstract void process(org.apache.pdfbox.contentstream.operator.Operator, List<org.apache.pdfbox.cos.COSBase>) throws java.io.IOException<variables>private final non-sealed org.apache.pdfbox.contentstream.PDFStreamEngine context
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/contentstream/operator/state/SetRenderingIntent.java
SetRenderingIntent
process
class SetRenderingIntent extends OperatorProcessor { public SetRenderingIntent(PDFStreamEngine context) { super(context); } @Override public void process(Operator operator, List<COSBase> operands) throws IOException {<FILL_FUNCTION_BODY>} @Override public String getName() { return OperatorName.SET_RENDERINGINTENT; } }
if (operands.isEmpty()) { throw new MissingOperandException(operator, operands); } COSBase base = operands.get(0); if (!(base instanceof COSName)) { return; } getContext().getGraphicsState() // .setRenderingIntent(RenderingIntent.fromString(((COSName) base).getName()));
113
102
215
<methods>public boolean checkArrayTypesClass(List<org.apache.pdfbox.cos.COSBase>, Class<?>) ,public abstract java.lang.String getName() ,public abstract void process(org.apache.pdfbox.contentstream.operator.Operator, List<org.apache.pdfbox.cos.COSBase>) throws java.io.IOException<variables>private final non-sealed org.apache.pdfbox.contentstream.PDFStreamEngine context
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/contentstream/operator/text/BeginText.java
BeginText
process
class BeginText extends OperatorProcessor { public BeginText(PDFStreamEngine context) { super(context); } @Override public void process(Operator operator, List<COSBase> arguments) throws IOException {<FILL_FUNCTION_BODY>} @Override public String getName() { return OperatorName.BEGIN_TEXT; } }
PDFStreamEngine context = getContext(); context.setTextMatrix( new Matrix()); context.setTextLineMatrix( new Matrix() ); context.beginText();
103
42
145
<methods>public boolean checkArrayTypesClass(List<org.apache.pdfbox.cos.COSBase>, Class<?>) ,public abstract java.lang.String getName() ,public abstract void process(org.apache.pdfbox.contentstream.operator.Operator, List<org.apache.pdfbox.cos.COSBase>) throws java.io.IOException<variables>private final non-sealed org.apache.pdfbox.contentstream.PDFStreamEngine context
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/contentstream/operator/text/MoveText.java
MoveText
process
class MoveText extends OperatorProcessor { private static final Logger LOG = LogManager.getLogger(MoveText.class); public MoveText(PDFStreamEngine context) { super(context); } @Override public void process(Operator operator, List<COSBase> arguments) throws MissingOperandException {<FILL_FUNCTION_BODY>} @Override public String getName() { return OperatorName.MOVE_TEXT; } }
if (arguments.size() < 2) { throw new MissingOperandException(operator, arguments); } PDFStreamEngine context = getContext(); Matrix textLineMatrix = context.getTextLineMatrix(); if (textLineMatrix == null) { LOG.warn("TextLineMatrix is null, {} operator will be ignored", getName()); return; } COSBase base0 = arguments.get(0); COSBase base1 = arguments.get(1); if (!(base0 instanceof COSNumber)) { return; } if (!(base1 instanceof COSNumber)) { return; } COSNumber x = (COSNumber) base0; COSNumber y = (COSNumber) base1; Matrix matrix = new Matrix(1, 0, 0, 1, x.floatValue(), y.floatValue()); textLineMatrix.concatenate(matrix); context.setTextMatrix(textLineMatrix.clone());
129
258
387
<methods>public boolean checkArrayTypesClass(List<org.apache.pdfbox.cos.COSBase>, Class<?>) ,public abstract java.lang.String getName() ,public abstract void process(org.apache.pdfbox.contentstream.operator.Operator, List<org.apache.pdfbox.cos.COSBase>) throws java.io.IOException<variables>private final non-sealed org.apache.pdfbox.contentstream.PDFStreamEngine context
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/contentstream/operator/text/MoveTextSetLeading.java
MoveTextSetLeading
process
class MoveTextSetLeading extends OperatorProcessor { public MoveTextSetLeading(PDFStreamEngine context) { super(context); } @Override public void process(Operator operator, List<COSBase> arguments) throws IOException {<FILL_FUNCTION_BODY>} @Override public String getName() { return OperatorName.MOVE_TEXT_SET_LEADING; } }
if (arguments.size() < 2) { throw new MissingOperandException(operator, arguments); } //move text position and set leading COSBase base1 = arguments.get(1); if (!(base1 instanceof COSNumber)) { return; } COSNumber y = (COSNumber) base1; List<COSBase> args = new ArrayList<>(); args.add(new COSFloat(-y.floatValue())); PDFStreamEngine context = getContext(); context.processOperator(OperatorName.SET_TEXT_LEADING, args); context.processOperator(OperatorName.MOVE_TEXT, arguments);
116
175
291
<methods>public boolean checkArrayTypesClass(List<org.apache.pdfbox.cos.COSBase>, Class<?>) ,public abstract java.lang.String getName() ,public abstract void process(org.apache.pdfbox.contentstream.operator.Operator, List<org.apache.pdfbox.cos.COSBase>) throws java.io.IOException<variables>private final non-sealed org.apache.pdfbox.contentstream.PDFStreamEngine context
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/contentstream/operator/text/NextLine.java
NextLine
process
class NextLine extends OperatorProcessor { public NextLine(PDFStreamEngine context) { super(context); } @Override public void process(Operator operator, List<COSBase> arguments) throws IOException {<FILL_FUNCTION_BODY>} @Override public String getName() { return OperatorName.NEXT_LINE; } }
//move to start of next text line List<COSBase> args = new ArrayList<>(2); args.add(COSFloat.ZERO); PDFStreamEngine context = getContext(); // this must be -leading instead of just leading as written in the // specification (p.369) the acrobat reader seems to implement it the same way args.add(new COSFloat(-context.getGraphicsState().getTextState().getLeading())); // use Td instead of repeating code context.processOperator(OperatorName.MOVE_TEXT, args);
104
143
247
<methods>public boolean checkArrayTypesClass(List<org.apache.pdfbox.cos.COSBase>, Class<?>) ,public abstract java.lang.String getName() ,public abstract void process(org.apache.pdfbox.contentstream.operator.Operator, List<org.apache.pdfbox.cos.COSBase>) throws java.io.IOException<variables>private final non-sealed org.apache.pdfbox.contentstream.PDFStreamEngine context
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/contentstream/operator/text/SetCharSpacing.java
SetCharSpacing
process
class SetCharSpacing extends OperatorProcessor { public SetCharSpacing(PDFStreamEngine context) { super(context); } @Override public void process(Operator operator, List<COSBase> arguments) throws IOException {<FILL_FUNCTION_BODY>} @Override public String getName() { return OperatorName.SET_CHAR_SPACING; } }
if (arguments.isEmpty()) { throw new MissingOperandException(operator, arguments); } // there are some documents which are incorrectly structured, and have // a wrong number of arguments to this, so we will assume the last argument // in the list Object charSpacing = arguments.get(arguments.size()-1); if (charSpacing instanceof COSNumber) { COSNumber characterSpacing = (COSNumber)charSpacing; getContext().getGraphicsState().getTextState() .setCharacterSpacing(characterSpacing.floatValue()); }
111
151
262
<methods>public boolean checkArrayTypesClass(List<org.apache.pdfbox.cos.COSBase>, Class<?>) ,public abstract java.lang.String getName() ,public abstract void process(org.apache.pdfbox.contentstream.operator.Operator, List<org.apache.pdfbox.cos.COSBase>) throws java.io.IOException<variables>private final non-sealed org.apache.pdfbox.contentstream.PDFStreamEngine context
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/contentstream/operator/text/SetFontAndSize.java
SetFontAndSize
process
class SetFontAndSize extends OperatorProcessor { private static final Logger LOG = LogManager.getLogger(SetFontAndSize.class); public SetFontAndSize(PDFStreamEngine context) { super(context); } @Override public void process(Operator operator, List<COSBase> arguments) throws IOException {<FILL_FUNCTION_BODY>} @Override public String getName() { return OperatorName.SET_FONT_AND_SIZE; } }
if (arguments.size() < 2) { throw new MissingOperandException(operator, arguments); } COSBase base0 = arguments.get(0); COSBase base1 = arguments.get(1); if (!(base0 instanceof COSName)) { return; } if (!(base1 instanceof COSNumber)) { return; } COSName fontName = (COSName) base0; float fontSize = ((COSNumber) base1).floatValue(); PDFStreamEngine context = getContext(); context.getGraphicsState().getTextState().setFontSize(fontSize); PDFont font = context.getResources().getFont(fontName); if (font == null) { LOG.warn("font '{}' not found in resources", fontName.getName()); } context.getGraphicsState().getTextState().setFont(font);
134
235
369
<methods>public boolean checkArrayTypesClass(List<org.apache.pdfbox.cos.COSBase>, Class<?>) ,public abstract java.lang.String getName() ,public abstract void process(org.apache.pdfbox.contentstream.operator.Operator, List<org.apache.pdfbox.cos.COSBase>) throws java.io.IOException<variables>private final non-sealed org.apache.pdfbox.contentstream.PDFStreamEngine context
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/contentstream/operator/text/SetTextHorizontalScaling.java
SetTextHorizontalScaling
process
class SetTextHorizontalScaling extends OperatorProcessor { public SetTextHorizontalScaling(PDFStreamEngine context) { super(context); } @Override public void process(Operator operator, List<COSBase> arguments) throws IOException {<FILL_FUNCTION_BODY>} @Override public String getName() { return OperatorName.SET_TEXT_HORIZONTAL_SCALING; } }
if (arguments.isEmpty()) { throw new MissingOperandException(operator, arguments); } COSBase base = arguments.get(0); if (!(base instanceof COSNumber)) { return; } COSNumber scaling = (COSNumber) base; getContext().getGraphicsState().getTextState().setHorizontalScaling(scaling.floatValue());
121
105
226
<methods>public boolean checkArrayTypesClass(List<org.apache.pdfbox.cos.COSBase>, Class<?>) ,public abstract java.lang.String getName() ,public abstract void process(org.apache.pdfbox.contentstream.operator.Operator, List<org.apache.pdfbox.cos.COSBase>) throws java.io.IOException<variables>private final non-sealed org.apache.pdfbox.contentstream.PDFStreamEngine context
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/contentstream/operator/text/SetTextLeading.java
SetTextLeading
process
class SetTextLeading extends OperatorProcessor { public SetTextLeading(PDFStreamEngine context) { super(context); } @Override public void process(Operator operator, List<COSBase> arguments) throws IOException {<FILL_FUNCTION_BODY>} @Override public String getName() { return OperatorName.SET_TEXT_LEADING; } }
if (arguments.isEmpty()) { throw new MissingOperandException(operator, arguments); } COSBase base = arguments.get(0); if (!(base instanceof COSNumber)) { return; } COSNumber leading = (COSNumber) base; getContext().getGraphicsState().getTextState().setLeading(leading.floatValue());
111
100
211
<methods>public boolean checkArrayTypesClass(List<org.apache.pdfbox.cos.COSBase>, Class<?>) ,public abstract java.lang.String getName() ,public abstract void process(org.apache.pdfbox.contentstream.operator.Operator, List<org.apache.pdfbox.cos.COSBase>) throws java.io.IOException<variables>private final non-sealed org.apache.pdfbox.contentstream.PDFStreamEngine context
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/contentstream/operator/text/SetTextRenderingMode.java
SetTextRenderingMode
process
class SetTextRenderingMode extends OperatorProcessor { public SetTextRenderingMode(PDFStreamEngine context) { super(context); } @Override public void process(Operator operator, List<COSBase> arguments) throws IOException {<FILL_FUNCTION_BODY>} @Override public String getName() { return OperatorName.SET_TEXT_RENDERINGMODE; } }
if (arguments.isEmpty()) { throw new MissingOperandException(operator, arguments); } COSBase base0 = arguments.get(0); if (!(base0 instanceof COSNumber)) { return; } COSNumber mode = (COSNumber) base0; int val = mode.intValue(); if (val < 0 || val >= RenderingMode.values().length) { return; } RenderingMode renderingMode = RenderingMode.fromInt(val); getContext().getGraphicsState().getTextState().setRenderingMode(renderingMode);
115
161
276
<methods>public boolean checkArrayTypesClass(List<org.apache.pdfbox.cos.COSBase>, Class<?>) ,public abstract java.lang.String getName() ,public abstract void process(org.apache.pdfbox.contentstream.operator.Operator, List<org.apache.pdfbox.cos.COSBase>) throws java.io.IOException<variables>private final non-sealed org.apache.pdfbox.contentstream.PDFStreamEngine context
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/contentstream/operator/text/SetTextRise.java
SetTextRise
process
class SetTextRise extends OperatorProcessor { public SetTextRise(PDFStreamEngine context) { super(context); } @Override public void process(Operator operator, List<COSBase> arguments) throws IOException {<FILL_FUNCTION_BODY>} @Override public String getName() { return OperatorName.SET_TEXT_RISE; } }
if (arguments.isEmpty()) { return; } COSBase base = arguments.get(0); if (!(base instanceof COSNumber)) { return; } COSNumber rise = (COSNumber) base; getContext().getGraphicsState().getTextState().setRise(rise.floatValue());
110
90
200
<methods>public boolean checkArrayTypesClass(List<org.apache.pdfbox.cos.COSBase>, Class<?>) ,public abstract java.lang.String getName() ,public abstract void process(org.apache.pdfbox.contentstream.operator.Operator, List<org.apache.pdfbox.cos.COSBase>) throws java.io.IOException<variables>private final non-sealed org.apache.pdfbox.contentstream.PDFStreamEngine context
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/contentstream/operator/text/SetWordSpacing.java
SetWordSpacing
process
class SetWordSpacing extends OperatorProcessor { public SetWordSpacing(PDFStreamEngine context) { super(context); } @Override public void process(Operator operator, List<COSBase> arguments) {<FILL_FUNCTION_BODY>} @Override public String getName() { return OperatorName.SET_WORD_SPACING; } }
if (arguments.isEmpty()) { return; } COSBase base = arguments.get(0); if (!(base instanceof COSNumber)) { return; } COSNumber wordSpacing = (COSNumber) base; getContext().getGraphicsState().getTextState().setWordSpacing(wordSpacing.floatValue());
109
95
204
<methods>public boolean checkArrayTypesClass(List<org.apache.pdfbox.cos.COSBase>, Class<?>) ,public abstract java.lang.String getName() ,public abstract void process(org.apache.pdfbox.contentstream.operator.Operator, List<org.apache.pdfbox.cos.COSBase>) throws java.io.IOException<variables>private final non-sealed org.apache.pdfbox.contentstream.PDFStreamEngine context
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/contentstream/operator/text/ShowText.java
ShowText
process
class ShowText extends OperatorProcessor { public ShowText(PDFStreamEngine context) { super(context); } @Override public void process(Operator operator, List<COSBase> arguments) throws IOException {<FILL_FUNCTION_BODY>} @Override public String getName() { return OperatorName.SHOW_TEXT; } }
if (arguments.isEmpty()) { // ignore ( )Tj return; } COSBase base = arguments.get(0); if (!(base instanceof COSString)) { // ignore return; } PDFStreamEngine context = getContext(); if (context.getTextMatrix() == null) { // ignore: outside of BT...ET return; } COSString string = (COSString) base; context.showTextString(string.getBytes());
104
136
240
<methods>public boolean checkArrayTypesClass(List<org.apache.pdfbox.cos.COSBase>, Class<?>) ,public abstract java.lang.String getName() ,public abstract void process(org.apache.pdfbox.contentstream.operator.Operator, List<org.apache.pdfbox.cos.COSBase>) throws java.io.IOException<variables>private final non-sealed org.apache.pdfbox.contentstream.PDFStreamEngine context
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/contentstream/operator/text/ShowTextAdjusted.java
ShowTextAdjusted
process
class ShowTextAdjusted extends OperatorProcessor { public ShowTextAdjusted(PDFStreamEngine context) { super(context); } @Override public void process(Operator operator, List<COSBase> arguments) throws IOException {<FILL_FUNCTION_BODY>} @Override public String getName() { return OperatorName.SHOW_TEXT_ADJUSTED; } }
if (arguments.isEmpty()) { return; } COSBase base = arguments.get(0); if (!(base instanceof COSArray)) { return; } PDFStreamEngine context = getContext(); if (context.getTextMatrix() == null) { // ignore: outside of BT...ET return; } COSArray array = (COSArray) base; context.showTextStrings(array);
115
122
237
<methods>public boolean checkArrayTypesClass(List<org.apache.pdfbox.cos.COSBase>, Class<?>) ,public abstract java.lang.String getName() ,public abstract void process(org.apache.pdfbox.contentstream.operator.Operator, List<org.apache.pdfbox.cos.COSBase>) throws java.io.IOException<variables>private final non-sealed org.apache.pdfbox.contentstream.PDFStreamEngine context
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/contentstream/operator/text/ShowTextLineAndSpace.java
ShowTextLineAndSpace
process
class ShowTextLineAndSpace extends OperatorProcessor { public ShowTextLineAndSpace(PDFStreamEngine context) { super(context); } @Override public void process(Operator operator, List<COSBase> arguments) throws IOException {<FILL_FUNCTION_BODY>} @Override public String getName() { return OperatorName.SHOW_TEXT_LINE_AND_SPACE; } }
if (arguments.size() < 3) { throw new MissingOperandException(operator, arguments); } PDFStreamEngine context = getContext(); context.processOperator(OperatorName.SET_WORD_SPACING, arguments.subList(0, 1)); context.processOperator(OperatorName.SET_CHAR_SPACING, arguments.subList(1, 2)); context.processOperator(OperatorName.SHOW_TEXT_LINE, arguments.subList(2, 3));
117
127
244
<methods>public boolean checkArrayTypesClass(List<org.apache.pdfbox.cos.COSBase>, Class<?>) ,public abstract java.lang.String getName() ,public abstract void process(org.apache.pdfbox.contentstream.operator.Operator, List<org.apache.pdfbox.cos.COSBase>) throws java.io.IOException<variables>private final non-sealed org.apache.pdfbox.contentstream.PDFStreamEngine context
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/cos/COSBoolean.java
COSBoolean
hashCode
class COSBoolean extends COSBase { /** * The true boolean token. */ private static final byte[] TRUE_BYTES = { 116, 114, 117, 101 }; // "true".getBytes("ISO-8859-1") /** * The false boolean token. */ private static final byte[] FALSE_BYTES = { 102, 97, 108, 115, 101 }; // "false".getBytes("ISO-8859-1") /** * The PDF true value. */ public static final COSBoolean TRUE = new COSBoolean( true ); /** * The PDF false value. */ public static final COSBoolean FALSE = new COSBoolean( false ); private final boolean value; /** * Constructor. * * @param aValue The boolean value. */ private COSBoolean(boolean aValue) { value = aValue; } /** * This will get the value that this object wraps. * * @return The boolean value of this object. */ public boolean getValue() { return value; } /** * This will get the value that this object wraps. * * @return The boolean value of this object. */ public Boolean getValueAsObject() { return value ? Boolean.TRUE : Boolean.FALSE; } /** * This will get the boolean value. * * @param value Parameter telling which boolean value to get. * * @return The single boolean instance that matches the parameter. */ public static COSBoolean getBoolean( boolean value ) { return value ? TRUE : FALSE; } /** * This will get the boolean value. * * @param value Parameter telling which boolean value to get. * * @return The single boolean instance that matches the parameter. */ public static COSBoolean getBoolean( Boolean value ) { return getBoolean( value.booleanValue() ); } /** * visitor pattern double dispatch method. * * @param visitor The object to notify when visiting this object. * @throws IOException If an error occurs while visiting this object. */ @Override public void accept(ICOSVisitor visitor) throws IOException { visitor.visitFromBoolean(this); } /** * Return a string representation of this object. * * @return The string value of this object. */ @Override public String toString() { return String.valueOf( value ); } /** * {@inheritDoc} */ @Override public int hashCode() {<FILL_FUNCTION_BODY>} /** * {@inheritDoc} */ public boolean equals(Object obj) { return this == obj; // this is correct because there are only two COSBoolean objects. } /** * This will write this object out to a PDF stream. * * @param output The stream to write this object out to. * * @throws IOException If an error occurs while writing out this object. */ public void writePDF( OutputStream output ) throws IOException { if( value ) { output.write( TRUE_BYTES ); } else { output.write( FALSE_BYTES ); } } }
//taken from java.lang.Boolean return value ? 1231 : 1237;
904
30
934
<methods>public void <init>() ,public abstract void accept(org.apache.pdfbox.cos.ICOSVisitor) throws java.io.IOException,public org.apache.pdfbox.cos.COSBase getCOSObject() ,public org.apache.pdfbox.cos.COSObjectKey getKey() ,public boolean isDirect() ,public void setDirect(boolean) ,public void setKey(org.apache.pdfbox.cos.COSObjectKey) <variables>private boolean direct,private org.apache.pdfbox.cos.COSObjectKey key
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/cos/COSFloat.java
COSFloat
formatString
class COSFloat extends COSNumber { private final float value; private String valueAsString; public static final COSFloat ZERO = new COSFloat(0f, "0.0"); public static final COSFloat ONE = new COSFloat(1f, "1.0"); /** * Constructor. * * @param aFloat The primitive float object that this object wraps. */ public COSFloat( float aFloat ) { value = aFloat; } /** * An internal constructor to avoid formatting for the predefined constants. * * @param aFloat * @param valueString */ private COSFloat(float aFloat, String valueString) { value = aFloat; valueAsString = valueString; } /** * Constructor. * * @param aFloat The primitive float object that this object wraps. * * @throws IOException If aFloat is not a float. */ public COSFloat( String aFloat ) throws IOException { float parsedValue; String stringValue = null; try { float f = Float.parseFloat(aFloat); parsedValue = coerce(f); stringValue = f == parsedValue ? aFloat : null; } catch( NumberFormatException e ) { if (aFloat.startsWith("--")) { // PDFBOX-4289 has --16.33 aFloat = aFloat.substring(1); } else if (aFloat.matches("^0\\.0*-\\d+")) { // PDFBOX-2990 has 0.00000-33917698 // PDFBOX-3369 has 0.00-35095424 // PDFBOX-3500 has 0.-262 aFloat = "-" + aFloat.replaceFirst("-", ""); } else { throw new IOException("Error expected floating point number actual='" + aFloat + "'", e); } try { parsedValue = coerce(Float.parseFloat(aFloat)); } catch (NumberFormatException e2) { throw new IOException("Error expected floating point number actual='" + aFloat + "'", e2); } } value = parsedValue; valueAsString = stringValue; } /** * Check and coerce the value field to be between MIN_NORMAL and MAX_VALUE. * * @param floatValue the value to be checked * @return the coerced value */ private float coerce(float floatValue) { if (floatValue == Float.POSITIVE_INFINITY) { return Float.MAX_VALUE; } if (floatValue == Float.NEGATIVE_INFINITY) { return -Float.MAX_VALUE; } if (Math.abs(floatValue) < Float.MIN_NORMAL) { // values smaller than the smallest possible float value are converted to 0 // see PDF spec, chapter 2 of Appendix C Implementation Limits return 0f; } return floatValue; } /** * The value of the float object that this one wraps. * * @return The value of this object. */ @Override public float floatValue() { return value; } /** * This will get the long value of this object. * * @return The long value of this object, */ @Override public long longValue() { return (long) value; } /** * This will get the integer value of this object. * * @return The int value of this object, */ @Override public int intValue() { return (int) value; } /** * {@inheritDoc} */ @Override public boolean equals( Object o ) { return o instanceof COSFloat && Float.floatToIntBits(((COSFloat)o).value) == Float.floatToIntBits(value); } /** * {@inheritDoc} */ @Override public int hashCode() { return Float.hashCode(value); } /** * {@inheritDoc} */ @Override public String toString() { return "COSFloat{" + formatString() + "}"; } /** * Builds, if needed, and returns the string representation of the current value. * @return current value as string. */ private String formatString() {<FILL_FUNCTION_BODY>} /** * Visitor pattern double dispatch method. * * @param visitor The object to notify when visiting this object. * @throws IOException If an error occurs while visiting this object. */ @Override public void accept(ICOSVisitor visitor) throws IOException { visitor.visitFromFloat(this); } /** * This will output this string as a PDF object. * * @param output The stream to write to. * @throws IOException If there is an error writing to the stream. */ public void writePDF( OutputStream output ) throws IOException { output.write(formatString().getBytes(StandardCharsets.ISO_8859_1)); } }
if (valueAsString == null) { String s = String.valueOf(value); boolean simpleFormat = s.indexOf('E') < 0; valueAsString = simpleFormat ? s : new BigDecimal(s).stripTrailingZeros().toPlainString(); } return valueAsString;
1,437
84
1,521
<methods>public non-sealed void <init>() ,public abstract float floatValue() ,public static org.apache.pdfbox.cos.COSNumber get(java.lang.String) throws java.io.IOException,public abstract int intValue() ,public abstract long longValue() <variables>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/cos/COSInputStream.java
COSInputStream
create
class COSInputStream extends FilterInputStream { /** * Creates a new COSInputStream from an encoded input stream. * * @param filters Filters to be applied. * @param parameters Filter parameters. * @param in Encoded input stream. * @return Decoded stream. * @throws IOException If the stream could not be read. */ static COSInputStream create(List<Filter> filters, COSDictionary parameters, InputStream in) throws IOException { return create(filters, parameters, in, DecodeOptions.DEFAULT); } /** * Creates a new COSInputStream from an encoded input stream. * * @param filters Filters to be applied. * @param parameters Filter parameters. * @param in Encoded input stream. * @param options decode options for the encoded stream * @return Decoded stream. * @throws IOException If the stream could not be read. */ static COSInputStream create(List<Filter> filters, COSDictionary parameters, InputStream in, DecodeOptions options) throws IOException {<FILL_FUNCTION_BODY>} private final List<DecodeResult> decodeResults; /** * Constructor. * * @param input decoded stream * @param decodeResults results of decoding */ private COSInputStream(InputStream input, List<DecodeResult> decodeResults) { super(input); this.decodeResults = decodeResults; } /** * Returns the result of the last filter, for use by repair mechanisms. * * @return the result of the last filter */ public DecodeResult getDecodeResult() { if (decodeResults.isEmpty()) { return DecodeResult.createDefault(); } else { return decodeResults.get(decodeResults.size() - 1); } } }
if (filters.isEmpty()) { return new COSInputStream(in, Collections.emptyList()); } List<DecodeResult> results = new ArrayList<>(filters.size()); RandomAccessRead decoded = Filter.decode(in, filters, parameters, options, results); return new COSInputStream(new RandomAccessInputStream(decoded), results);
489
93
582
<methods>public int available() throws java.io.IOException,public void close() throws java.io.IOException,public synchronized void mark(int) ,public boolean markSupported() ,public int read() throws java.io.IOException,public int read(byte[]) throws java.io.IOException,public int read(byte[], int, int) throws java.io.IOException,public synchronized void reset() throws java.io.IOException,public long skip(long) throws java.io.IOException<variables>protected volatile java.io.InputStream in
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/cos/COSInteger.java
COSInteger
get
class COSInteger extends COSNumber { /** * The lowest integer to be kept in the {@link #STATIC} array. */ private static final int LOW = -100; /** * The highest integer to be kept in the {@link #STATIC} array. */ private static final int HIGH = 256; /** * Static instances of all COSIntegers in the range from {@link #LOW} * to {@link #HIGH}. */ private static final COSInteger[] STATIC = new COSInteger[HIGH - LOW + 1]; /** * Constant for the number zero. * @since Apache PDFBox 1.1.0 */ public static final COSInteger ZERO = get(0); /** * Constant for the number one. * @since Apache PDFBox 1.1.0 */ public static final COSInteger ONE = get(1); /** * Constant for the number two. * @since Apache PDFBox 1.1.0 */ public static final COSInteger TWO = get(2); /** * Constant for the number three. * @since Apache PDFBox 1.1.0 */ public static final COSInteger THREE = get(3); /** * Constant for an out of range value which is bigger than Log.MAX_VALUE. */ protected static final COSInteger OUT_OF_RANGE_MAX = getInvalid(true); /** * Constant for an out of range value which is smaller than Log.MIN_VALUE. */ protected static final COSInteger OUT_OF_RANGE_MIN = getInvalid(false); /** * Returns a COSInteger instance with the given value. * * @param val integer value * @return COSInteger instance */ public static COSInteger get(long val) {<FILL_FUNCTION_BODY>} private static COSInteger getInvalid(boolean maxValue) { return maxValue ? new COSInteger(Long.MAX_VALUE, false) : new COSInteger(Long.MIN_VALUE, false); } private final long value; private final boolean isValid; /** * constructor. * * @param val The integer value of this object. * @param valid indicates if the value is valid. */ private COSInteger(long val, boolean valid) { value = val; isValid = valid; } /** * {@inheritDoc} */ @Override public boolean equals(Object o) { return o instanceof COSInteger && ((COSInteger)o).intValue() == intValue(); } /** * {@inheritDoc} */ @Override public int hashCode() { //taken from java.lang.Long return (int)(value ^ (value >> 32)); } /** * {@inheritDoc} */ @Override public String toString() { return "COSInt{" + value + "}"; } /** * polymorphic access to value as float. * * @return The float value of this object. */ @Override public float floatValue() { return value; } /** * Polymorphic access to value as int * This will get the integer value of this object. * * @return The int value of this object, */ @Override public int intValue() { return (int)value; } /** * Polymorphic access to value as int * This will get the integer value of this object. * * @return The int value of this object, */ @Override public long longValue() { return value; } /** * Indicates whether this instance represents a valid value. * * @return true if the value is valid */ public boolean isValid() { return isValid; } /** * visitor pattern double dispatch method. * * @param visitor The object to notify when visiting this object. * @throws IOException If an error occurs while visiting this object. */ @Override public void accept(ICOSVisitor visitor) throws IOException { visitor.visitFromInt(this); } /** * This will output this string as a PDF object. * * @param output The stream to write to. * @throws IOException If there is an error writing to the stream. */ public void writePDF( OutputStream output ) throws IOException { output.write(String.valueOf(value).getBytes(StandardCharsets.ISO_8859_1)); } }
if (LOW <= val && val <= HIGH) { int index = (int) val - LOW; // no synchronization needed if (STATIC[index] == null) { STATIC[index] = new COSInteger(val, true); } return STATIC[index]; } return new COSInteger(val, true);
1,245
97
1,342
<methods>public non-sealed void <init>() ,public abstract float floatValue() ,public static org.apache.pdfbox.cos.COSNumber get(java.lang.String) throws java.io.IOException,public abstract int intValue() ,public abstract long longValue() <variables>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/cos/COSNumber.java
COSNumber
get
class COSNumber extends COSBase { /** * This will get the float value of this number. * * @return The float value of this object. */ public abstract float floatValue(); /** * This will get the integer value of this number. * * @return The integer value of this number. */ public abstract int intValue(); /** * This will get the long value of this number. * * @return The long value of this number. */ public abstract long longValue(); /** * This factory method will get the appropriate number object. * * @param number The string representation of the number. * * @return A number object, either float or int. * * @throws IOException If the string is not a number. */ public static COSNumber get( String number ) throws IOException {<FILL_FUNCTION_BODY>} private static boolean isFloat( String number ) { int length = number.length(); for (int i = 0; i < length; i++) { char digit = number.charAt(i); if (digit == '.' || digit == 'e') { return true; } } return false; } }
if (number.length() == 1) { char digit = number.charAt(0); if ('0' <= digit && digit <= '9') { return COSInteger.get((long) digit - '0'); } if (digit == '-' || digit == '.') { // See https://issues.apache.org/jira/browse/PDFBOX-592 return COSInteger.ZERO; } throw new IOException("Not a number: " + number); } if (isFloat(number)) { return new COSFloat(number); } try { return COSInteger.get(Long.parseLong(number)); } catch (NumberFormatException e) { // check if the given string could be a number at all String numberString = number.startsWith("+") || number.startsWith("-") ? number.substring(1) : number; if (!numberString.matches("[0-9]*")) { throw new IOException("Not a number: " + number); } // return a limited COSInteger value which is marked as invalid return number.startsWith("-") ? COSInteger.OUT_OF_RANGE_MIN : COSInteger.OUT_OF_RANGE_MAX; }
332
349
681
<methods>public void <init>() ,public abstract void accept(org.apache.pdfbox.cos.ICOSVisitor) throws java.io.IOException,public org.apache.pdfbox.cos.COSBase getCOSObject() ,public org.apache.pdfbox.cos.COSObjectKey getKey() ,public boolean isDirect() ,public void setDirect(boolean) ,public void setKey(org.apache.pdfbox.cos.COSObjectKey) <variables>private boolean direct,private org.apache.pdfbox.cos.COSObjectKey key
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/cos/COSObject.java
COSObject
getObject
class COSObject extends COSBase implements COSUpdateInfo { private COSBase baseObject; private ICOSParser parser; private boolean isDereferenced = false; private final COSUpdateState updateState; private static final Logger LOG = LogManager.getLogger(COSObject.class); /** * Constructor. * * @param object The object that this encapsulates. * */ public COSObject(COSBase object) { updateState = new COSUpdateState(this); baseObject = object; isDereferenced = true; } /** * Constructor. * * @param object The object that this encapsulates. * @param objectKey The COSObjectKey of the encapsulated object */ public COSObject(COSBase object, COSObjectKey objectKey) { this(objectKey, null); baseObject = object; isDereferenced = true; } /** * Constructor. * * @param object The object that this encapsulates. * @param parser The parser to be used to load the object on demand * */ public COSObject(COSBase object, ICOSParser parser) { updateState = new COSUpdateState(this); baseObject = object; isDereferenced = object != null; this.parser = parser; } /** * Constructor. * * @param key The object number of the encapsulated object. * @param parser The parser to be used to load the object on demand * */ public COSObject(COSObjectKey key, ICOSParser parser) { updateState = new COSUpdateState(this); this.parser = parser; setKey(key); } /** * Indicates if the referenced object is present or not. * * @return true if the indirect object is dereferenced */ public boolean isObjectNull() { return baseObject == null; } /** * This will get the object that this object encapsulates. * * @return The encapsulated object. */ public COSBase getObject() {<FILL_FUNCTION_BODY>} /** * Sets the referenced object to COSNull and removes the initially assigned parser. */ public final void setToNull() { if(baseObject != null) { getUpdateState().update(); } baseObject = COSNull.NULL; parser = null; } /** * {@inheritDoc} */ @Override public String toString() { return "COSObject{" + getKey() + "}"; } /** * visitor pattern double dispatch method. * * @param visitor The object to notify when visiting this object. * @throws IOException If an error occurs while visiting this object. */ @Override public void accept( ICOSVisitor visitor ) throws IOException { COSBase object = getObject(); if (object != null) { object.accept(visitor); } else { COSNull.NULL.accept(visitor); } } /** * Returns {@code true}, if the hereby referenced {@link COSBase} has already been parsed and loaded. * * @return {@code true}, if the hereby referenced {@link COSBase} has already been parsed and loaded. */ public boolean isDereferenced() { return isDereferenced; } /** * Returns the current {@link COSUpdateState} of this {@link COSObject}. * * @return The current {@link COSUpdateState} of this {@link COSObject}. * @see COSUpdateState */ @Override public COSUpdateState getUpdateState() { return updateState; } }
if (!isDereferenced && parser != null) { try { // mark as dereferenced to avoid endless recursions isDereferenced = true; baseObject = parser.dereferenceCOSObject(this); getUpdateState().dereferenceChild(baseObject); } catch (IOException e) { LOG.error("Can't dereference {}", this, e); } finally { parser = null; } } return baseObject;
1,039
136
1,175
<methods>public void <init>() ,public abstract void accept(org.apache.pdfbox.cos.ICOSVisitor) throws java.io.IOException,public org.apache.pdfbox.cos.COSBase getCOSObject() ,public org.apache.pdfbox.cos.COSObjectKey getKey() ,public boolean isDirect() ,public void setDirect(boolean) ,public void setKey(org.apache.pdfbox.cos.COSObjectKey) <variables>private boolean direct,private org.apache.pdfbox.cos.COSObjectKey key
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/cos/COSObjectKey.java
COSObjectKey
toString
class COSObjectKey implements Comparable<COSObjectKey> { private static final int NUMBER_OFFSET = Short.SIZE; private static final long GENERATION_MASK = (long) Math.pow(2, NUMBER_OFFSET) - 1; // combined number and generation // The lowest 16 bits hold the generation 0-65535 // The rest is used for the number (even though 34 bit are sufficient for 10 digits) private final long numberAndGeneration; // index within a compressed object stream if applicable otherwise -1 private final int streamIndex; /** * Constructor. * * @param num The object number. * @param gen The object generation number. */ public COSObjectKey(long num, int gen) { this(num, gen, -1); } /** * Constructor. * * @param num The object number. * @param gen The object generation number. * @param index The index within a compressed object stream */ public COSObjectKey(long num, int gen, int index) { if (num < 0) { throw new IllegalArgumentException("Object number must not be a negative value"); } if (gen < 0) { throw new IllegalArgumentException("Generation number must not be a negative value"); } numberAndGeneration = computeInternalHash(num, gen); this.streamIndex = index; } /** * Calculate the internal hash value for the given object number and generation number. * * @param num the object number * @param gen the generation number * @return the internal hash for the given values */ public static final long computeInternalHash(long num, int gen) { return num << NUMBER_OFFSET | (gen & GENERATION_MASK); } /** * Return the internal hash value which is based on the number and the generation. * * @return the internal hash value */ public long getInternalHash() { return numberAndGeneration; } /** * {@inheritDoc} */ @Override public boolean equals(Object obj) { COSObjectKey objToBeCompared = obj instanceof COSObjectKey ? (COSObjectKey)obj : null; return objToBeCompared != null && objToBeCompared.numberAndGeneration == numberAndGeneration; } /** * This will get the object generation number. * * @return The object generation number. */ public int getGeneration() { return (int) (numberAndGeneration & GENERATION_MASK); } /** * This will get the object number. * * @return The object number. */ public long getNumber() { return numberAndGeneration >>> NUMBER_OFFSET; } /** * The index within a compressed object stream. * * @return the index within a compressed object stream if applicable otherwise -1 */ public int getStreamIndex() { return streamIndex; } /** * {@inheritDoc} */ @Override public int hashCode() { return Long.hashCode(numberAndGeneration); } @Override public String toString() {<FILL_FUNCTION_BODY>} @Override public int compareTo(COSObjectKey other) { return Long.compare(numberAndGeneration, other.numberAndGeneration); } }
return getNumber() + " " + getGeneration() + " R";
936
21
957
<no_super_class>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/cos/COSOutputStream.java
COSOutputStream
close
class COSOutputStream extends FilterOutputStream { private final List<Filter> filters; private final COSDictionary parameters; private final RandomAccessStreamCache streamCache; private RandomAccess buffer; /** * Creates a new COSOutputStream writes to an encoded COS stream. * * @param filters Filters to apply. * @param parameters Filter parameters. * @param output Encoded stream. * @param streamCache Stream cache to use. * * @throws IOException If there was an error creating a temporary buffer */ COSOutputStream(List<Filter> filters, COSDictionary parameters, OutputStream output, RandomAccessStreamCache streamCache) throws IOException { super(output); this.filters = filters; this.parameters = parameters; this.streamCache = streamCache; buffer = filters.isEmpty() ? null : streamCache.createBuffer(); } @Override public void write(byte[] b) throws IOException { write(b, 0, b.length); } @Override public void write(byte[] b, int off, int len) throws IOException { if (buffer != null) { buffer.write(b, off, len); } else { super.write(b, off, len); } } @Override public void write(int b) throws IOException { if (buffer != null) { buffer.write(b); } else { super.write(b); } } @Override public void flush() throws IOException { if (buffer == null) { super.flush(); } } @Override public void close() throws IOException {<FILL_FUNCTION_BODY>} }
try { if (buffer != null) { try { // apply filters in reverse order for (int i = filters.size() - 1; i >= 0; i--) { try (InputStream unfilteredIn = new RandomAccessInputStream(buffer)) { if (i == 0) { /* * The last filter to run can encode directly to the enclosed output * stream. */ filters.get(i).encode(unfilteredIn, out, parameters, i); } else { RandomAccess filteredBuffer = streamCache.createBuffer(); try (OutputStream filteredOut = new RandomAccessOutputStream(filteredBuffer)) { filters.get(i).encode(unfilteredIn, filteredOut, parameters, i); } finally { buffer.close(); buffer = filteredBuffer; } } } } } finally { buffer.close(); buffer = null; } } } finally { super.close(); }
469
282
751
<methods>public void <init>(java.io.OutputStream) ,public void close() throws java.io.IOException,public void flush() throws java.io.IOException,public void write(int) throws java.io.IOException,public void write(byte[]) throws java.io.IOException,public void write(byte[], int, int) throws java.io.IOException<variables>private final java.lang.Object closeLock,private volatile boolean closed,protected java.io.OutputStream out
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/cos/COSString.java
COSString
getString
class COSString extends COSBase { private static final Logger LOG = LogManager.getLogger(COSString.class); private byte[] bytes; private boolean forceHexForm; // legacy behaviour for old PDFParser public static final boolean FORCE_PARSING = Boolean.getBoolean("org.apache.pdfbox.forceParsing"); /** * Creates a new PDF string from a byte array. This method can be used to read a string from * an existing PDF file, or to create a new byte string. * * @param bytes The raw bytes of the PDF text string or byte string. */ public COSString(byte[] bytes) { setValue(bytes); } /** * Creates a new <i>text string</i> from a Java String. * * @param text The string value of the object. */ public COSString(String text) { // check whether the string uses only characters available in PDFDocEncoding boolean isOnlyPDFDocEncoding = true; for (char c : text.toCharArray()) { if (!PDFDocEncoding.containsChar(c)) { isOnlyPDFDocEncoding = false; break; } } if (isOnlyPDFDocEncoding) { // PDFDocEncoded string bytes = PDFDocEncoding.getBytes(text); } else { // UTF-16BE encoded string with a leading byte order marker byte[] data = text.getBytes(StandardCharsets.UTF_16BE); bytes = new byte[data.length + 2]; bytes[0] = (byte) 0xFE; bytes[1] = (byte) 0xFF; System.arraycopy(data, 0, bytes, 2, data.length); } } /** * This will create a COS string from a string of hex characters. * * @param hex A hex string. * @return A cos string with the hex characters converted to their actual bytes. * @throws IOException If there is an error with the hex string. */ public static COSString parseHex(String hex) throws IOException { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); StringBuilder hexBuffer = new StringBuilder(hex.trim()); // if odd number then the last hex digit is assumed to be 0 if (hexBuffer.length() % 2 != 0) { hexBuffer.append('0'); } int length = hexBuffer.length(); for (int i = 0; i < length; i += 2) { try { bytes.write(Integer.parseInt(hexBuffer.substring(i, i + 2), 16)); } catch (NumberFormatException e) { if (FORCE_PARSING) { LOG.warn("Encountered a malformed hex string"); bytes.write('?'); // todo: what does Acrobat do? Any example PDFs? } else { throw new IOException("Invalid hex string: " + hex, e); } } } return new COSString(bytes.toByteArray()); } /** * Sets the raw value of this string. * * @param value The raw bytes of the PDF text string or byte string. * * @deprecated to be removed in a future release. */ @Deprecated public void setValue(byte[] value) { bytes = value.clone(); } /** * Sets whether to force the string is to be written in hex form. * This is needed when signing PDF files. * * @param value True to force hex. */ public void setForceHexForm(boolean value) { this.forceHexForm = value; } /** * Returns true if the string is to be written in hex form. * * @return true if the COSString is written in hex form */ public boolean getForceHexForm() { return forceHexForm; } /** * Returns the content of this string as a PDF <i>text string</i>. * * @return the PDF string representation of the COSString */ public String getString() {<FILL_FUNCTION_BODY>} /** * Returns the content of this string as a PDF <i>ASCII string</i>. * * @return the ASCII string representation of the COSString */ public String getASCII() { // ASCII string return new String(bytes, StandardCharsets.US_ASCII); } /** * Returns the raw bytes of the string using a new byte array. Best used with a PDF <i>byte string</i>. * * @return a clone of the underlying byte[] representation of the COSString */ public byte[] getBytes() { return bytes.clone(); } /** * This will take this string and create a hex representation of the bytes that make the string. * * @return A hex string representing the bytes in this string. */ public String toHexString() { return Hex.getString(bytes); } /** * Visitor pattern double dispatch method. * * @param visitor The object to notify when visiting this object. * @throws IOException If an error occurs while visiting this object. */ @Override public void accept(ICOSVisitor visitor) throws IOException { visitor.visitFromString(this); } @Override public boolean equals(Object obj) { if (obj instanceof COSString) { COSString strObj = (COSString) obj; return getString().equals(strObj.getString()) && forceHexForm == strObj.forceHexForm; } return false; } @Override public int hashCode() { int result = Arrays.hashCode(bytes); return result + (forceHexForm ? 17 : 0); } @Override public String toString() { return "COSString{" + getString() + "}"; } }
// text string - BOM indicates Unicode if (bytes.length >= 2) { if ((bytes[0] & 0xff) == 0xFE && (bytes[1] & 0xff) == 0xFF) { // UTF-16BE return new String(bytes, 2, bytes.length - 2, StandardCharsets.UTF_16BE); } else if ((bytes[0] & 0xff) == 0xFF && (bytes[1] & 0xff) == 0xFE) { // UTF-16LE - not in the PDF spec! return new String(bytes, 2, bytes.length - 2, StandardCharsets.UTF_16LE); } } // otherwise use PDFDocEncoding return PDFDocEncoding.toString(bytes);
1,615
214
1,829
<methods>public void <init>() ,public abstract void accept(org.apache.pdfbox.cos.ICOSVisitor) throws java.io.IOException,public org.apache.pdfbox.cos.COSBase getCOSObject() ,public org.apache.pdfbox.cos.COSObjectKey getKey() ,public boolean isDirect() ,public void setDirect(boolean) ,public void setKey(org.apache.pdfbox.cos.COSObjectKey) <variables>private boolean direct,private org.apache.pdfbox.cos.COSObjectKey key
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/cos/PDFDocEncoding.java
PDFDocEncoding
toString
class PDFDocEncoding { private static final char REPLACEMENT_CHARACTER = '\uFFFD'; private static final int[] CODE_TO_UNI; private static final Map<Character, Integer> UNI_TO_CODE; static { CODE_TO_UNI = new int[256]; UNI_TO_CODE = new HashMap<>(256); // initialize with basically ISO-8859-1 for (int i = 0; i < 256; i++) { // skip entries not in Unicode column if (i > 0x17 && i < 0x20) { continue; } if (i > 0x7E && i < 0xA1) { continue; } if (i == 0xAD) { continue; } set(i, (char)i); } // then do all deviations (based on the table in ISO 32000-1:2008) // block 1 set(0x18, '\u02D8'); // BREVE set(0x19, '\u02C7'); // CARON set(0x1A, '\u02C6'); // MODIFIER LETTER CIRCUMFLEX ACCENT set(0x1B, '\u02D9'); // DOT ABOVE set(0x1C, '\u02DD'); // DOUBLE ACUTE ACCENT set(0x1D, '\u02DB'); // OGONEK set(0x1E, '\u02DA'); // RING ABOVE set(0x1F, '\u02DC'); // SMALL TILDE // block 2 set(0x7F, REPLACEMENT_CHARACTER); // undefined set(0x80, '\u2022'); // BULLET set(0x81, '\u2020'); // DAGGER set(0x82, '\u2021'); // DOUBLE DAGGER set(0x83, '\u2026'); // HORIZONTAL ELLIPSIS set(0x84, '\u2014'); // EM DASH set(0x85, '\u2013'); // EN DASH set(0x86, '\u0192'); // LATIN SMALL LETTER SCRIPT F set(0x87, '\u2044'); // FRACTION SLASH (solidus) set(0x88, '\u2039'); // SINGLE LEFT-POINTING ANGLE QUOTATION MARK set(0x89, '\u203A'); // SINGLE RIGHT-POINTING ANGLE QUOTATION MARK set(0x8A, '\u2212'); // MINUS SIGN set(0x8B, '\u2030'); // PER MILLE SIGN set(0x8C, '\u201E'); // DOUBLE LOW-9 QUOTATION MARK (quotedblbase) set(0x8D, '\u201C'); // LEFT DOUBLE QUOTATION MARK (quotedblleft) set(0x8E, '\u201D'); // RIGHT DOUBLE QUOTATION MARK (quotedblright) set(0x8F, '\u2018'); // LEFT SINGLE QUOTATION MARK (quoteleft) set(0x90, '\u2019'); // RIGHT SINGLE QUOTATION MARK (quoteright) set(0x91, '\u201A'); // SINGLE LOW-9 QUOTATION MARK (quotesinglbase) set(0x92, '\u2122'); // TRADE MARK SIGN set(0x93, '\uFB01'); // LATIN SMALL LIGATURE FI set(0x94, '\uFB02'); // LATIN SMALL LIGATURE FL set(0x95, '\u0141'); // LATIN CAPITAL LETTER L WITH STROKE set(0x96, '\u0152'); // LATIN CAPITAL LIGATURE OE set(0x97, '\u0160'); // LATIN CAPITAL LETTER S WITH CARON set(0x98, '\u0178'); // LATIN CAPITAL LETTER Y WITH DIAERESIS set(0x99, '\u017D'); // LATIN CAPITAL LETTER Z WITH CARON set(0x9A, '\u0131'); // LATIN SMALL LETTER DOTLESS I set(0x9B, '\u0142'); // LATIN SMALL LETTER L WITH STROKE set(0x9C, '\u0153'); // LATIN SMALL LIGATURE OE set(0x9D, '\u0161'); // LATIN SMALL LETTER S WITH CARON set(0x9E, '\u017E'); // LATIN SMALL LETTER Z WITH CARON set(0x9F, REPLACEMENT_CHARACTER); // undefined set(0xA0, '\u20AC'); // EURO SIGN // end of deviations } private PDFDocEncoding() { } private static void set(int code, char unicode) { CODE_TO_UNI[code] = unicode; UNI_TO_CODE.put(unicode, code); } /** * Returns the string representation of the given PDFDocEncoded bytes. */ public static String toString(byte[] bytes) {<FILL_FUNCTION_BODY>} /** * Returns the given string encoded with PDFDocEncoding. */ public static byte[] getBytes(String text) { ByteArrayOutputStream out = new ByteArrayOutputStream(text.length()); for (char c : text.toCharArray()) { out.write(UNI_TO_CODE.getOrDefault(c, 0)); } return out.toByteArray(); } /** * Returns true if the given character is available in PDFDocEncoding. * * @param character UTF-16 character */ public static boolean containsChar(char character) { return UNI_TO_CODE.containsKey(character); } }
StringBuilder sb = new StringBuilder(bytes.length); for (byte b : bytes) { if ((b & 0xff) >= CODE_TO_UNI.length) { sb.append('?'); } else { sb.append((char)CODE_TO_UNI[b & 0xff]); } } return sb.toString();
1,675
106
1,781
<no_super_class>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/filter/ASCII85Filter.java
ASCII85Filter
encode
class ASCII85Filter extends Filter { @Override public DecodeResult decode(InputStream encoded, OutputStream decoded, COSDictionary parameters, int index) throws IOException { try (ASCII85InputStream is = new ASCII85InputStream(encoded)) { is.transferTo(decoded); } decoded.flush(); return new DecodeResult(parameters); } @Override protected void encode(InputStream input, OutputStream encoded, COSDictionary parameters) throws IOException {<FILL_FUNCTION_BODY>} }
try (ASCII85OutputStream os = new ASCII85OutputStream(encoded)) { input.transferTo(os); } encoded.flush();
150
47
197
<methods>public abstract org.apache.pdfbox.filter.DecodeResult decode(java.io.InputStream, java.io.OutputStream, org.apache.pdfbox.cos.COSDictionary, int) throws java.io.IOException,public org.apache.pdfbox.filter.DecodeResult decode(java.io.InputStream, java.io.OutputStream, org.apache.pdfbox.cos.COSDictionary, int, org.apache.pdfbox.filter.DecodeOptions) throws java.io.IOException,public static org.apache.pdfbox.io.RandomAccessRead decode(java.io.InputStream, List<org.apache.pdfbox.filter.Filter>, org.apache.pdfbox.cos.COSDictionary, org.apache.pdfbox.filter.DecodeOptions, List<org.apache.pdfbox.filter.DecodeResult>) throws java.io.IOException,public final void encode(java.io.InputStream, java.io.OutputStream, org.apache.pdfbox.cos.COSDictionary, int) throws java.io.IOException,public static final javax.imageio.ImageReader findImageReader(java.lang.String, java.lang.String) throws org.apache.pdfbox.filter.MissingImageReaderException,public static int getCompressionLevel() <variables>private static final Logger LOG,public static final java.lang.String SYSPROP_DEFLATELEVEL
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/filter/ASCII85InputStream.java
ASCII85InputStream
read
class ASCII85InputStream extends FilterInputStream { private int index; private int n; private boolean eof; private byte[] ascii; private byte[] b; private static final char TERMINATOR = '~'; private static final char OFFSET = '!'; private static final char NEWLINE = '\n'; private static final char RETURN = '\r'; private static final char SPACE = ' '; private static final char PADDING_U = 'u'; private static final char Z = 'z'; /** * Constructor. * * @param is The input stream to actually read from. */ ASCII85InputStream(InputStream is) { super(is); index = 0; n = 0; eof = false; ascii = new byte[5]; b = new byte[4]; } /** * This will read the next byte from the stream. * * @return The next byte read from the stream. * * @throws IOException If there is an error reading from the wrapped stream. */ @Override public int read() throws IOException {<FILL_FUNCTION_BODY>} /** * This will read a chunk of data. * * @param data The buffer to write data to. * @param offset The offset into the data stream. * @param len The number of byte to attempt to read. * * @return The number of bytes actually read. * * @throws IOException If there is an error reading data from the underlying stream. */ @Override public int read(byte[] data, int offset, int len) throws IOException { if (eof && index >= n) { return -1; } for (int i = 0; i < len; i++) { if (index < n) { data[i + offset] = b[index++]; } else { int t = read(); if (t == -1) { return i; } data[i + offset] = (byte) t; } } return len; } /** * This will close the underlying stream and release any resources. * * @throws IOException If there is an error closing the underlying stream. */ @Override public void close() throws IOException { ascii = null; eof = true; b = null; super.close(); } /** * non supported interface methods. * * @return False always. */ @Override public boolean markSupported() { return false; } /** * Unsupported. * * @param nValue ignored. * * @return Always zero. */ @Override public long skip(long nValue) { return 0; } /** * Unsupported. * * @return Always zero. */ @Override public int available() { return 0; } /** * Unsupported. * * @param readlimit ignored. */ @Override public synchronized void mark(int readlimit) { } /** * Unsupported. * * @throws IOException telling that this is an unsupported action. */ @Override public synchronized void reset() throws IOException { throw new IOException("Reset is not supported"); } }
if (index >= n) { if (eof) { return -1; } index = 0; int k; byte z; do { int zz = (byte) in.read(); if (zz == -1) { eof = true; return -1; } z = (byte) zz; } while (z == NEWLINE || z == RETURN || z == SPACE); if (z == TERMINATOR) { eof = true; ascii = b = null; n = 0; return -1; } else if (z == Z) { b[0] = b[1] = b[2] = b[3] = 0; n = 4; } else { ascii[0] = z; // may be EOF here.... for (k = 1; k < 5; ++k) { do { int zz = (byte) in.read(); if (zz == -1) { eof = true; return -1; } z = (byte) zz; } while (z == NEWLINE || z == RETURN || z == SPACE); ascii[k] = z; if (z == TERMINATOR) { // don't include ~ as padding byte ascii[k] = (byte) PADDING_U; break; } } n = k - 1; if (n == 0) { eof = true; ascii = null; b = null; return -1; } if (k < 5) { for (++k; k < 5; ++k) { // use 'u' for padding ascii[k] = (byte) PADDING_U; } eof = true; } // decode stream long t = 0; for (k = 0; k < 5; ++k) { z = (byte) (ascii[k] - OFFSET); if (z < 0 || z > 93) { n = 0; eof = true; ascii = null; b = null; throw new IOException("Invalid data in Ascii85 stream"); } t = (t * 85L) + z; } for (k = 3; k >= 0; --k) { b[k] = (byte) (t & 0xFFL); t >>>= 8; } } } return b[index++] & 0xFF;
920
718
1,638
<methods>public int available() throws java.io.IOException,public void close() throws java.io.IOException,public synchronized void mark(int) ,public boolean markSupported() ,public int read() throws java.io.IOException,public int read(byte[]) throws java.io.IOException,public int read(byte[], int, int) throws java.io.IOException,public synchronized void reset() throws java.io.IOException,public long skip(long) throws java.io.IOException<variables>protected volatile java.io.InputStream in
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/filter/ASCII85OutputStream.java
ASCII85OutputStream
setTerminator
class ASCII85OutputStream extends FilterOutputStream { private int lineBreak; private int count; private byte[] indata; private byte[] outdata; /** * Function produces five ASCII printing characters from * four bytes of binary data. */ private int maxline; private boolean flushed; private char terminator; private static final char OFFSET = '!'; private static final char NEWLINE = '\n'; private static final char Z = 'z'; /** * Constructor. * * @param out The output stream to write to. */ ASCII85OutputStream(OutputStream out) { super(out); lineBreak = 36 * 2; maxline = 36 * 2; count = 0; indata = new byte[4]; outdata = new byte[5]; flushed = true; terminator = '~'; } /** * This will set the terminating character. * * @param term The terminating character. */ public void setTerminator(char term) {<FILL_FUNCTION_BODY>} /** * This will get the terminating character. * * @return The terminating character. */ public char getTerminator() { return terminator; } /** * This will set the line length that will be used. * * @param l The length of the line to use. */ public void setLineLength(int l) { if (lineBreak > l) { lineBreak = l; } maxline = l; } /** * This will get the length of the line. * * @return The line length attribute. */ public int getLineLength() { return maxline; } /** * This will transform the next four ascii bytes. */ private void transformASCII85() { long word = ((((indata[0] << 8) | (indata[1] & 0xFF)) << 16) | ((indata[2] & 0xFF) << 8) | (indata[3] & 0xFF)) & 0xFFFFFFFFL; if (word == 0) { outdata[0] = (byte) Z; outdata[1] = 0; return; } long x; x = word / (85L * 85L * 85L * 85L); outdata[0] = (byte) (x + OFFSET); word -= x * 85L * 85L * 85L * 85L; x = word / (85L * 85L * 85L); outdata[1] = (byte) (x + OFFSET); word -= x * 85L * 85L * 85L; x = word / (85L * 85L); outdata[2] = (byte) (x + OFFSET); word -= x * 85L * 85L; x = word / 85L; outdata[3] = (byte) (x + OFFSET); outdata[4] = (byte) ((word % 85L) + OFFSET); } /** * This will write a single byte. * * @param b The byte to write. * * @throws IOException If there is an error writing to the stream. */ @Override public void write(int b) throws IOException { flushed = false; indata[count++] = (byte) b; if (count < 4) { return; } transformASCII85(); for (int i = 0; i < 5; i++) { if (outdata[i] == 0) { break; } out.write(outdata[i]); if (--lineBreak == 0) { out.write(NEWLINE); lineBreak = maxline; } } count = 0; } /** * This will flush the data to the stream. * * @throws IOException If there is an error writing the data to the stream. */ @Override public void flush() throws IOException { if (flushed) { return; } if (count > 0) { for (int i = count; i < 4; i++) { indata[i] = 0; } transformASCII85(); if (outdata[0] == Z) { for (int i = 0; i < 5; i++) // expand 'z', { outdata[i] = (byte) OFFSET; } } for (int i = 0; i < count + 1; i++) { out.write(outdata[i]); if (--lineBreak == 0) { out.write(NEWLINE); lineBreak = maxline; } } } if (--lineBreak == 0) { out.write(NEWLINE); } out.write(terminator); out.write('>'); out.write(NEWLINE); count = 0; lineBreak = maxline; flushed = true; super.flush(); } /** * This will close the stream. * * @throws IOException If there is an error closing the wrapped stream. */ @Override public void close() throws IOException { try { flush(); super.close(); } finally { indata = outdata = null; } } }
if (term < 118 || term > 126 || term == Z) { throw new IllegalArgumentException("Terminator must be 118-126 excluding z"); } terminator = term;
1,519
60
1,579
<methods>public void <init>(java.io.OutputStream) ,public void close() throws java.io.IOException,public void flush() throws java.io.IOException,public void write(int) throws java.io.IOException,public void write(byte[]) throws java.io.IOException,public void write(byte[], int, int) throws java.io.IOException<variables>private final java.lang.Object closeLock,private volatile boolean closed,protected java.io.OutputStream out
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/filter/ASCIIHexFilter.java
ASCIIHexFilter
isWhitespace
class ASCIIHexFilter extends Filter { private static final Logger LOG = LogManager.getLogger(ASCIIHexFilter.class); private static final int[] REVERSE_HEX = { /* 0 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 10 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 20 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 30 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 40 */ -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, /* 50 */ 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, /* 60 */ -1, -1, -1, -1, -1, 10, 11, 12, 13, 14, /* 70 */ 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 80 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 90 */ -1, -1, -1, -1, -1, -1, -1, 10, 11, 12, /* 100 */ 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, /* 110 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 120 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 130 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 140 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 150 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 160 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 170 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 180 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 190 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 200 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 210 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 220 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 230 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 240 */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 250 */ -1, -1, -1, -1, -1, -1 }; @Override public DecodeResult decode(InputStream encoded, OutputStream decoded, COSDictionary parameters, int index) throws IOException { int value, firstByte, secondByte; while ((firstByte = encoded.read()) != -1) { // always after first char while (isWhitespace(firstByte)) { firstByte = encoded.read(); } if (firstByte == -1 || isEOD(firstByte)) { break; } if (REVERSE_HEX[firstByte] == -1) { LOG.error("Invalid hex, int: {} char: {}", firstByte, (char) firstByte); } value = REVERSE_HEX[firstByte] * 16; secondByte = encoded.read(); if (secondByte == -1 || isEOD(secondByte)) { // second value behaves like 0 in case of EOD decoded.write(value); break; } if (REVERSE_HEX[secondByte] == -1) { LOG.error("Invalid hex, int: {} char: {}", secondByte, (char) secondByte); } value += REVERSE_HEX[secondByte]; decoded.write(value); } decoded.flush(); return new DecodeResult(parameters); } // whitespace // 0 0x00 Null (NUL) // 9 0x09 Tab (HT) // 10 0x0A Line feed (LF) // 12 0x0C Form feed (FF) // 13 0x0D Carriage return (CR) // 32 0x20 Space (SP) private static boolean isWhitespace(int c) {<FILL_FUNCTION_BODY>} private static boolean isEOD(int c) { return c == '>'; } @Override public void encode(InputStream input, OutputStream encoded, COSDictionary parameters) throws IOException { int byteRead; while ((byteRead = input.read()) != -1) { Hex.writeHexByte((byte)byteRead, encoded); } encoded.flush(); } }
switch (c) { case 0: case 9: case 10: case 12: case 13: case 32: return true; default: return false; }
1,656
69
1,725
<methods>public abstract org.apache.pdfbox.filter.DecodeResult decode(java.io.InputStream, java.io.OutputStream, org.apache.pdfbox.cos.COSDictionary, int) throws java.io.IOException,public org.apache.pdfbox.filter.DecodeResult decode(java.io.InputStream, java.io.OutputStream, org.apache.pdfbox.cos.COSDictionary, int, org.apache.pdfbox.filter.DecodeOptions) throws java.io.IOException,public static org.apache.pdfbox.io.RandomAccessRead decode(java.io.InputStream, List<org.apache.pdfbox.filter.Filter>, org.apache.pdfbox.cos.COSDictionary, org.apache.pdfbox.filter.DecodeOptions, List<org.apache.pdfbox.filter.DecodeResult>) throws java.io.IOException,public final void encode(java.io.InputStream, java.io.OutputStream, org.apache.pdfbox.cos.COSDictionary, int) throws java.io.IOException,public static final javax.imageio.ImageReader findImageReader(java.lang.String, java.lang.String) throws org.apache.pdfbox.filter.MissingImageReaderException,public static int getCompressionLevel() <variables>private static final Logger LOG,public static final java.lang.String SYSPROP_DEFLATELEVEL
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/filter/CCITTFaxDecoderStream.java
Tree
fill
class Tree { final Node root = new Node(); void fill(final int depth, final int path, final int value) throws IOException { Node current = root; for (int i = 0; i < depth; i++) { int bitPos = depth - 1 - i; boolean isSet = ((path >> bitPos) & 1) == 1; Node next = current.walk(isSet); if (next == null) { next = new Node(); if (i == depth - 1) { next.value = value; next.isLeaf = true; } if (path == 0) { next.canBeFill = true; } current.set(isSet, next); } else { if (next.isLeaf) { throw new IOException("node is leaf, no other following"); } } current = next; } } void fill(final int depth, final int path, final Node node) throws IOException {<FILL_FUNCTION_BODY>} }
Node current = root; for (int i = 0; i < depth; i++) { int bitPos = depth - 1 - i; boolean isSet = ((path >> bitPos) & 1) == 1; Node next = current.walk(isSet); if (next == null) { if (i == depth - 1) { next = node; } else { next = new Node(); } if (path == 0) { next.canBeFill = true; } current.set(isSet, next); } else { if (next.isLeaf) { throw new IOException("node is leaf, no other following"); } } current = next; }
276
200
476
<methods>public int available() throws java.io.IOException,public void close() throws java.io.IOException,public synchronized void mark(int) ,public boolean markSupported() ,public int read() throws java.io.IOException,public int read(byte[]) throws java.io.IOException,public int read(byte[], int, int) throws java.io.IOException,public synchronized void reset() throws java.io.IOException,public long skip(long) throws java.io.IOException<variables>protected volatile java.io.InputStream in
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/filter/CCITTFaxFilter.java
CCITTFaxFilter
decode
class CCITTFaxFilter extends Filter { @Override public DecodeResult decode(InputStream encoded, OutputStream decoded, COSDictionary parameters, int index) throws IOException {<FILL_FUNCTION_BODY>} void readFromDecoderStream(CCITTFaxDecoderStream decoderStream, byte[] result) throws IOException { int pos = 0; int read; while ((read = decoderStream.read(result, pos, result.length - pos)) > -1) { pos += read; if (pos >= result.length) { break; } } } private void invertBitmap(byte[] bufferData) { for (int i = 0, c = bufferData.length; i < c; i++) { bufferData[i] = (byte) (~bufferData[i] & 0xFF); } } @Override protected void encode(InputStream input, OutputStream encoded, COSDictionary parameters) throws IOException { int cols = parameters.getInt(COSName.COLUMNS); int rows = parameters.getInt(COSName.ROWS); CCITTFaxEncoderStream ccittFaxEncoderStream = new CCITTFaxEncoderStream(encoded, cols, rows, TIFFExtension.FILL_LEFT_TO_RIGHT); input.transferTo(ccittFaxEncoderStream); } }
// get decode parameters COSDictionary decodeParms = getDecodeParams(parameters, index); // parse dimensions int cols = decodeParms.getInt(COSName.COLUMNS, 1728); int rows = decodeParms.getInt(COSName.ROWS, 0); int height = parameters.getInt(COSName.HEIGHT, COSName.H, 0); if (rows > 0 && height > 0) { // PDFBOX-771, PDFBOX-3727: rows in DecodeParms sometimes contains an incorrect value rows = height; } else { // at least one of the values has to have a valid value rows = Math.max(rows, height); } // decompress data int k = decodeParms.getInt(COSName.K, 0); boolean encodedByteAlign = decodeParms.getBoolean(COSName.ENCODED_BYTE_ALIGN, false); int arraySize = (cols + 7) / 8 * rows; // TODO possible options?? byte[] decompressed = new byte[arraySize]; CCITTFaxDecoderStream s; int type; long tiffOptions = 0; if (k == 0) { type = TIFFExtension.COMPRESSION_CCITT_T4; // Group 3 1D byte[] streamData = new byte[20]; int bytesRead = encoded.read(streamData); if (bytesRead == -1) { throw new IOException("EOF while reading CCITT header"); } PushbackInputStream pushbackInputStream = new PushbackInputStream(encoded, streamData.length); pushbackInputStream.unread(streamData, 0, bytesRead); encoded = pushbackInputStream; if (streamData[0] != 0 || (streamData[1] >> 4 != 1 && streamData[1] != 1)) { // leading EOL (0b000000000001) not found, search further and try RLE if not // found type = TIFFExtension.COMPRESSION_CCITT_MODIFIED_HUFFMAN_RLE; short b = (short) (((streamData[0] << 8) + (streamData[1] & 0xff)) >> 4); for (int i = 12; i < bytesRead * 8; i++) { b = (short) ((b << 1) + ((streamData[(i / 8)] >> (7 - (i % 8))) & 0x01)); if ((b & 0xFFF) == 1) { type = TIFFExtension.COMPRESSION_CCITT_T4; break; } } } } else if (k > 0) { // Group 3 2D type = TIFFExtension.COMPRESSION_CCITT_T4; tiffOptions = TIFFExtension.GROUP3OPT_2DENCODING; } else { // Group 4 type = TIFFExtension.COMPRESSION_CCITT_T6; } s = new CCITTFaxDecoderStream(encoded, cols, type, tiffOptions, encodedByteAlign); readFromDecoderStream(s, decompressed); // invert bitmap boolean blackIsOne = decodeParms.getBoolean(COSName.BLACK_IS_1, false); if (!blackIsOne) { // Inverting the bitmap // Note the previous approach with starting from an IndexColorModel didn't work // reliably. In some cases the image wouldn't be painted for some reason. // So a safe but slower approach was taken. invertBitmap(decompressed); } decoded.write(decompressed); return new DecodeResult(parameters);
376
1,012
1,388
<methods>public abstract org.apache.pdfbox.filter.DecodeResult decode(java.io.InputStream, java.io.OutputStream, org.apache.pdfbox.cos.COSDictionary, int) throws java.io.IOException,public org.apache.pdfbox.filter.DecodeResult decode(java.io.InputStream, java.io.OutputStream, org.apache.pdfbox.cos.COSDictionary, int, org.apache.pdfbox.filter.DecodeOptions) throws java.io.IOException,public static org.apache.pdfbox.io.RandomAccessRead decode(java.io.InputStream, List<org.apache.pdfbox.filter.Filter>, org.apache.pdfbox.cos.COSDictionary, org.apache.pdfbox.filter.DecodeOptions, List<org.apache.pdfbox.filter.DecodeResult>) throws java.io.IOException,public final void encode(java.io.InputStream, java.io.OutputStream, org.apache.pdfbox.cos.COSDictionary, int) throws java.io.IOException,public static final javax.imageio.ImageReader findImageReader(java.lang.String, java.lang.String) throws org.apache.pdfbox.filter.MissingImageReaderException,public static int getCompressionLevel() <variables>private static final Logger LOG,public static final java.lang.String SYSPROP_DEFLATELEVEL
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/filter/CryptFilter.java
CryptFilter
encode
class CryptFilter extends Filter { @Override public DecodeResult decode(InputStream encoded, OutputStream decoded, COSDictionary parameters, int index) throws IOException { COSName encryptionName = parameters.getCOSName(COSName.NAME); if(encryptionName == null || encryptionName.equals(COSName.IDENTITY)) { // currently the only supported implementation is the Identity crypt filter Filter identityFilter = new IdentityFilter(); identityFilter.decode(encoded, decoded, parameters, index); return new DecodeResult(parameters); } throw new IOException("Unsupported crypt filter " + encryptionName.getName()); } @Override protected void encode(InputStream input, OutputStream encoded, COSDictionary parameters) throws IOException {<FILL_FUNCTION_BODY>} }
COSName encryptionName = parameters.getCOSName(COSName.NAME); if(encryptionName == null || encryptionName.equals(COSName.IDENTITY)) { // currently the only supported implementation is the Identity crypt filter Filter identityFilter = new IdentityFilter(); identityFilter.encode(input, encoded, parameters); } else { throw new IOException("Unsupported crypt filter " + encryptionName.getName()); }
211
116
327
<methods>public abstract org.apache.pdfbox.filter.DecodeResult decode(java.io.InputStream, java.io.OutputStream, org.apache.pdfbox.cos.COSDictionary, int) throws java.io.IOException,public org.apache.pdfbox.filter.DecodeResult decode(java.io.InputStream, java.io.OutputStream, org.apache.pdfbox.cos.COSDictionary, int, org.apache.pdfbox.filter.DecodeOptions) throws java.io.IOException,public static org.apache.pdfbox.io.RandomAccessRead decode(java.io.InputStream, List<org.apache.pdfbox.filter.Filter>, org.apache.pdfbox.cos.COSDictionary, org.apache.pdfbox.filter.DecodeOptions, List<org.apache.pdfbox.filter.DecodeResult>) throws java.io.IOException,public final void encode(java.io.InputStream, java.io.OutputStream, org.apache.pdfbox.cos.COSDictionary, int) throws java.io.IOException,public static final javax.imageio.ImageReader findImageReader(java.lang.String, java.lang.String) throws org.apache.pdfbox.filter.MissingImageReaderException,public static int getCompressionLevel() <variables>private static final Logger LOG,public static final java.lang.String SYSPROP_DEFLATELEVEL
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/filter/FilterFactory.java
FilterFactory
getFilter
class FilterFactory { /** * Singleton instance. */ public static final FilterFactory INSTANCE = new FilterFactory(); private final Map<COSName, Filter> filters = new HashMap<>(); private FilterFactory() { Filter flate = new FlateFilter(); Filter dct = new DCTFilter(); Filter ccittFax = new CCITTFaxFilter(); Filter lzw = new LZWFilter(); Filter asciiHex = new ASCIIHexFilter(); Filter ascii85 = new ASCII85Filter(); Filter runLength = new RunLengthDecodeFilter(); Filter crypt = new CryptFilter(); Filter jpx = new JPXFilter(); Filter jbig2 = new JBIG2Filter(); filters.put(COSName.FLATE_DECODE, flate); filters.put(COSName.FLATE_DECODE_ABBREVIATION, flate); filters.put(COSName.DCT_DECODE, dct); filters.put(COSName.DCT_DECODE_ABBREVIATION, dct); filters.put(COSName.CCITTFAX_DECODE, ccittFax); filters.put(COSName.CCITTFAX_DECODE_ABBREVIATION, ccittFax); filters.put(COSName.LZW_DECODE, lzw); filters.put(COSName.LZW_DECODE_ABBREVIATION, lzw); filters.put(COSName.ASCII_HEX_DECODE, asciiHex); filters.put(COSName.ASCII_HEX_DECODE_ABBREVIATION, asciiHex); filters.put(COSName.ASCII85_DECODE, ascii85); filters.put(COSName.ASCII85_DECODE_ABBREVIATION, ascii85); filters.put(COSName.RUN_LENGTH_DECODE, runLength); filters.put(COSName.RUN_LENGTH_DECODE_ABBREVIATION, runLength); filters.put(COSName.CRYPT, crypt); filters.put(COSName.JPX_DECODE, jpx); filters.put(COSName.JBIG2_DECODE, jbig2); } /** * Returns a filter instance given its name as a string. * @param filterName the name of the filter to retrieve * @return the filter that matches the name * @throws IOException if the filter name was invalid */ public Filter getFilter(String filterName) throws IOException { return getFilter(COSName.getPDFName(filterName)); } /** * Returns a filter instance given its COSName. * @param filterName the name of the filter to retrieve * @return the filter that matches the name * @throws IOException if the filter name was invalid */ public Filter getFilter(COSName filterName) throws IOException {<FILL_FUNCTION_BODY>} // returns all available filters, for testing Collection<Filter> getAllFilters() { return filters.values(); } }
Filter filter = filters.get(filterName); if (filter == null) { throw new IOException("Invalid filter: " + filterName); } return filter;
827
48
875
<no_super_class>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/filter/FlateFilter.java
FlateFilter
decompress
class FlateFilter extends Filter { private static final Logger LOG = LogManager.getLogger(FlateFilter.class); @Override public DecodeResult decode(InputStream encoded, OutputStream decoded, COSDictionary parameters, int index) throws IOException { final COSDictionary decodeParams = getDecodeParams(parameters, index); try { decompress(encoded, Predictor.wrapPredictor(decoded, decodeParams)); } catch (DataFormatException e) { // if the stream is corrupt a DataFormatException may occur LOG.error("FlateFilter: stop reading corrupt stream due to a DataFormatException"); // re-throw the exception throw new IOException(e); } return new DecodeResult(parameters); } // Use Inflater instead of InflateInputStream to avoid an EOFException due to a probably // missing Z_STREAM_END, see PDFBOX-1232 for details private void decompress(InputStream in, OutputStream out) throws IOException, DataFormatException {<FILL_FUNCTION_BODY>} @Override protected void encode(InputStream input, OutputStream encoded, COSDictionary parameters) throws IOException { int compressionLevel = getCompressionLevel(); Deflater deflater = new Deflater(compressionLevel); try (DeflaterOutputStream out = new DeflaterOutputStream(encoded,deflater)) { input.transferTo(out); } encoded.flush(); deflater.end(); } }
byte[] buf = new byte[2048]; // skip zlib header in.read(); in.read(); int read = in.read(buf); if (read > 0) { // use nowrap mode to bypass zlib-header and checksum to avoid a DataFormatException Inflater inflater = new Inflater(true); inflater.setInput(buf,0,read); byte[] res = new byte[1024]; boolean dataWritten = false; try { while (true) { int resRead = 0; try { resRead = inflater.inflate(res); } catch(DataFormatException exception) { if (dataWritten) { // some data could be read -> don't throw an exception LOG.warn("FlateFilter: premature end of stream due to a DataFormatException"); break; } else { // nothing could be read -> re-throw exception throw exception; } } if (resRead != 0) { out.write(res,0,resRead); dataWritten = true; continue; } if (inflater.finished() || inflater.needsDictionary() || in.available() == 0) { break; } read = in.read(buf); inflater.setInput(buf,0,read); } } finally { inflater.end(); } } out.flush();
394
422
816
<methods>public abstract org.apache.pdfbox.filter.DecodeResult decode(java.io.InputStream, java.io.OutputStream, org.apache.pdfbox.cos.COSDictionary, int) throws java.io.IOException,public org.apache.pdfbox.filter.DecodeResult decode(java.io.InputStream, java.io.OutputStream, org.apache.pdfbox.cos.COSDictionary, int, org.apache.pdfbox.filter.DecodeOptions) throws java.io.IOException,public static org.apache.pdfbox.io.RandomAccessRead decode(java.io.InputStream, List<org.apache.pdfbox.filter.Filter>, org.apache.pdfbox.cos.COSDictionary, org.apache.pdfbox.filter.DecodeOptions, List<org.apache.pdfbox.filter.DecodeResult>) throws java.io.IOException,public final void encode(java.io.InputStream, java.io.OutputStream, org.apache.pdfbox.cos.COSDictionary, int) throws java.io.IOException,public static final javax.imageio.ImageReader findImageReader(java.lang.String, java.lang.String) throws org.apache.pdfbox.filter.MissingImageReaderException,public static int getCompressionLevel() <variables>private static final Logger LOG,public static final java.lang.String SYSPROP_DEFLATELEVEL
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/filter/JBIG2Filter.java
JBIG2Filter
decode
class JBIG2Filter extends Filter { private static final Logger LOG = LogManager.getLogger(JBIG2Filter.class); private static boolean levigoLogged = false; private static synchronized void logLevigoDonated() { if (!levigoLogged) { LOG.info("The Levigo JBIG2 plugin has been donated to the Apache Foundation"); LOG.info("and an improved version is available for download at " + "https://pdfbox.apache.org/download.cgi"); levigoLogged = true; } } @Override public DecodeResult decode(InputStream encoded, OutputStream decoded, COSDictionary parameters, int index, DecodeOptions options) throws IOException {<FILL_FUNCTION_BODY>} @Override public DecodeResult decode(InputStream encoded, OutputStream decoded, COSDictionary parameters, int index) throws IOException { return decode(encoded, decoded, parameters, index, DecodeOptions.DEFAULT); } @Override protected void encode(InputStream input, OutputStream encoded, COSDictionary parameters) throws IOException { throw new UnsupportedOperationException("JBIG2 encoding not implemented"); } }
ImageReader reader = findImageReader("JBIG2", "jbig2-imageio is not installed"); if (reader.getClass().getName().contains("levigo")) { logLevigoDonated(); } int bits = parameters.getInt(COSName.BITS_PER_COMPONENT, 1); COSDictionary params = getDecodeParams(parameters, index); ImageReadParam irp = reader.getDefaultReadParam(); irp.setSourceSubsampling(options.getSubsamplingX(), options.getSubsamplingY(), options.getSubsamplingOffsetX(), options.getSubsamplingOffsetY()); irp.setSourceRegion(options.getSourceRegion()); options.setFilterSubsampled(true); InputStream source = encoded; if (params != null) { COSStream globals = params.getCOSStream(COSName.JBIG2_GLOBALS); if (globals != null) { source = new SequenceInputStream(globals.createInputStream(), encoded); } } try (ImageInputStream iis = ImageIO.createImageInputStream(source)) { reader.setInput(iis); BufferedImage image; try { image = reader.read(0, irp); } catch (Exception e) { // wrap and rethrow any exceptions throw new IOException("Could not read JBIG2 image", e); } // I am assuming since JBIG2 is always black and white // depending on your renderer this might or might be needed if (image.getColorModel().getPixelSize() != bits) { if (bits != 1) { LOG.warn("Attempting to handle a JBIG2 with more than 1-bit depth"); } BufferedImage packedImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_BYTE_BINARY); Graphics graphics = packedImage.getGraphics(); graphics.drawImage(image, 0, 0, null); graphics.dispose(); image = packedImage; } DataBuffer dBuf = image.getData().getDataBuffer(); if (dBuf.getDataType() == DataBuffer.TYPE_BYTE) { decoded.write(((DataBufferByte) dBuf).getData()); } else { throw new IOException("Unexpected image buffer type"); } } finally { reader.dispose(); } return new DecodeResult(parameters);
317
669
986
<methods>public abstract org.apache.pdfbox.filter.DecodeResult decode(java.io.InputStream, java.io.OutputStream, org.apache.pdfbox.cos.COSDictionary, int) throws java.io.IOException,public org.apache.pdfbox.filter.DecodeResult decode(java.io.InputStream, java.io.OutputStream, org.apache.pdfbox.cos.COSDictionary, int, org.apache.pdfbox.filter.DecodeOptions) throws java.io.IOException,public static org.apache.pdfbox.io.RandomAccessRead decode(java.io.InputStream, List<org.apache.pdfbox.filter.Filter>, org.apache.pdfbox.cos.COSDictionary, org.apache.pdfbox.filter.DecodeOptions, List<org.apache.pdfbox.filter.DecodeResult>) throws java.io.IOException,public final void encode(java.io.InputStream, java.io.OutputStream, org.apache.pdfbox.cos.COSDictionary, int) throws java.io.IOException,public static final javax.imageio.ImageReader findImageReader(java.lang.String, java.lang.String) throws org.apache.pdfbox.filter.MissingImageReaderException,public static int getCompressionLevel() <variables>private static final Logger LOG,public static final java.lang.String SYSPROP_DEFLATELEVEL
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/filter/JPXFilter.java
JPXFilter
readJPX
class JPXFilter extends Filter { private static final Logger LOG = LogManager.getLogger(JPXFilter.class); /** * {@inheritDoc} */ @Override public DecodeResult decode(InputStream encoded, OutputStream decoded, COSDictionary parameters, int index, DecodeOptions options) throws IOException { DecodeResult result = new DecodeResult(new COSDictionary()); result.getParameters().addAll(parameters); BufferedImage image = readJPX(encoded, options, result); Raster raster = image.getRaster(); switch (raster.getDataBuffer().getDataType()) { case DataBuffer.TYPE_BYTE: DataBufferByte byteBuffer = (DataBufferByte) raster.getDataBuffer(); decoded.write(byteBuffer.getData()); return result; case DataBuffer.TYPE_USHORT: DataBufferUShort wordBuffer = (DataBufferUShort) raster.getDataBuffer(); for (short w : wordBuffer.getData()) { decoded.write(w >> 8); decoded.write(w); } return result; case DataBuffer.TYPE_INT: // not yet used (as of October 2018) but works as fallback // if we decide to convert to BufferedImage.TYPE_INT_RGB int[] ar = new int[raster.getNumBands()]; for (int y = 0; y < image.getHeight(); ++y) { for (int x = 0; x < image.getWidth(); ++x) { raster.getPixel(x, y, ar); for (int i = 0; i < ar.length; ++i) { decoded.write(ar[i]); } } } return result; default: throw new IOException("Data type " + raster.getDataBuffer().getDataType() + " not implemented"); } } @Override public DecodeResult decode(InputStream encoded, OutputStream decoded, COSDictionary parameters, int index) throws IOException { return decode(encoded, decoded, parameters, index, DecodeOptions.DEFAULT); } // try to read using JAI Image I/O private BufferedImage readJPX(InputStream input, DecodeOptions options, DecodeResult result) throws IOException {<FILL_FUNCTION_BODY>} /** * {@inheritDoc} */ @Override protected void encode(InputStream input, OutputStream encoded, COSDictionary parameters) throws IOException { throw new UnsupportedOperationException("JPX encoding not implemented"); } }
ImageReader reader = findImageReader("JPEG2000", "Java Advanced Imaging (JAI) Image I/O Tools are not installed"); // PDFBOX-4121: ImageIO.createImageInputStream() is much slower try (ImageInputStream iis = new MemoryCacheImageInputStream(input)) { reader.setInput(iis, true, true); ImageReadParam irp = reader.getDefaultReadParam(); irp.setSourceRegion(options.getSourceRegion()); irp.setSourceSubsampling(options.getSubsamplingX(), options.getSubsamplingY(), options.getSubsamplingOffsetX(), options.getSubsamplingOffsetY()); options.setFilterSubsampled(true); BufferedImage image; try { image = reader.read(0, irp); } catch (Exception e) { // wrap and rethrow any exceptions throw new IOException("Could not read JPEG 2000 (JPX) image", e); } COSDictionary parameters = result.getParameters(); // "If the image stream uses the JPXDecode filter, this entry is optional // and shall be ignored if present" // // note that indexed color spaces make the BPC logic tricky, see PDFBOX-2204 int bpc = image.getColorModel().getPixelSize() / image.getRaster().getNumBands(); parameters.setInt(COSName.BITS_PER_COMPONENT, bpc); // "Decode shall be ignored, except in the case where the image is treated as a mask" if (!parameters.getBoolean(COSName.IMAGE_MASK, false)) { parameters.setItem(COSName.DECODE, null); } // override dimensions, see PDFBOX-1735 parameters.setInt(COSName.WIDTH, reader.getWidth(0)); parameters.setInt(COSName.HEIGHT, reader.getHeight(0)); // extract embedded color space if (!parameters.containsKey(COSName.COLORSPACE)) { if (image.getSampleModel() instanceof MultiPixelPackedSampleModel && image.getColorModel().getPixelSize() == 1 && image.getRaster().getNumBands() == 1 && image.getColorModel() instanceof IndexColorModel) { // PDFBOX-4326: // force CS_GRAY colorspace because colorspace in IndexColorModel // has 3 colors despite that there is only 1 color per pixel // in raster result.setColorSpace(new PDJPXColorSpace(ColorSpace.getInstance(ColorSpace.CS_GRAY))); } else if (image.getTransparency() == Transparency.TRANSLUCENT && parameters.getInt(COSName.SMASK_IN_DATA) > 0) { LOG.warn("JPEG2000 SMaskInData is not supported, returning opaque image"); BufferedImage bim = new BufferedImage( image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB); Graphics2D g2d = (Graphics2D) bim.getGraphics(); g2d.drawImage(image, 0, 0, null); g2d.dispose(); image = bim; result.setColorSpace(new PDJPXColorSpace(image.getColorModel().getColorSpace())); } else { result.setColorSpace(new PDJPXColorSpace(image.getColorModel().getColorSpace())); } } return image; } finally { reader.dispose(); }
683
949
1,632
<methods>public abstract org.apache.pdfbox.filter.DecodeResult decode(java.io.InputStream, java.io.OutputStream, org.apache.pdfbox.cos.COSDictionary, int) throws java.io.IOException,public org.apache.pdfbox.filter.DecodeResult decode(java.io.InputStream, java.io.OutputStream, org.apache.pdfbox.cos.COSDictionary, int, org.apache.pdfbox.filter.DecodeOptions) throws java.io.IOException,public static org.apache.pdfbox.io.RandomAccessRead decode(java.io.InputStream, List<org.apache.pdfbox.filter.Filter>, org.apache.pdfbox.cos.COSDictionary, org.apache.pdfbox.filter.DecodeOptions, List<org.apache.pdfbox.filter.DecodeResult>) throws java.io.IOException,public final void encode(java.io.InputStream, java.io.OutputStream, org.apache.pdfbox.cos.COSDictionary, int) throws java.io.IOException,public static final javax.imageio.ImageReader findImageReader(java.lang.String, java.lang.String) throws org.apache.pdfbox.filter.MissingImageReaderException,public static int getCompressionLevel() <variables>private static final Logger LOG,public static final java.lang.String SYSPROP_DEFLATELEVEL
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/filter/RunLengthDecodeFilter.java
RunLengthDecodeFilter
encode
class RunLengthDecodeFilter extends Filter { private static final int RUN_LENGTH_EOD = 128; @Override public DecodeResult decode(InputStream encoded, OutputStream decoded, COSDictionary parameters, int index) throws IOException { int dupAmount; byte[] buffer = new byte[128]; while ((dupAmount = encoded.read()) != -1 && dupAmount != RUN_LENGTH_EOD) { if (dupAmount <= 127) { int amountToCopy = dupAmount + 1; int compressedRead; while (amountToCopy > 0) { compressedRead = encoded.read(buffer, 0, amountToCopy); // EOF reached? if (compressedRead == -1) { break; } decoded.write(buffer, 0, compressedRead); amountToCopy -= compressedRead; } } else { int dupByte = encoded.read(); // EOF reached? if (dupByte == -1) { break; } for (int i = 0; i < 257 - dupAmount; i++) { decoded.write(dupByte); } } } return new DecodeResult(parameters); } @Override protected void encode(InputStream input, OutputStream encoded, COSDictionary parameters) throws IOException {<FILL_FUNCTION_BODY>} }
// Not used in PDFBox except for testing the decoder. int lastVal = -1; int byt; int count = 0; boolean equality = false; // buffer for "unequal" runs, size between 2 and 128 byte[] buf = new byte[128]; while ((byt = input.read()) != -1) { if (lastVal == -1) { // first time lastVal = byt; count = 1; } else { if (count == 128) { if (equality) { // max length of equals encoded.write(129); // = 257 - 128 encoded.write(lastVal); } else { // max length of unequals encoded.write(127); encoded.write(buf, 0, 128); } equality = false; lastVal = byt; count = 1; } else if (count == 1) { if (byt == lastVal) { equality = true; } else { buf[0] = (byte) lastVal; buf[1] = (byte) byt; lastVal = byt; } count = 2; } else { // 1 < count < 128 if (byt == lastVal) { if (equality) { ++count; } else { // write all we got except the last encoded.write(count - 2); encoded.write(buf, 0, count - 1); count = 2; equality = true; } } else { if (equality) { // equality ends here encoded.write(257 - count); encoded.write(lastVal); equality = false; count = 1; } else { buf[count] = (byte) byt; ++count; } lastVal = byt; } } } } if (count > 0) { if (count == 1) { encoded.write(0); encoded.write(lastVal); } else if (equality) { encoded.write(257 - count); encoded.write(lastVal); } else { encoded.write(count - 1); encoded.write(buf, 0, count); } } encoded.write(RUN_LENGTH_EOD);
392
697
1,089
<methods>public abstract org.apache.pdfbox.filter.DecodeResult decode(java.io.InputStream, java.io.OutputStream, org.apache.pdfbox.cos.COSDictionary, int) throws java.io.IOException,public org.apache.pdfbox.filter.DecodeResult decode(java.io.InputStream, java.io.OutputStream, org.apache.pdfbox.cos.COSDictionary, int, org.apache.pdfbox.filter.DecodeOptions) throws java.io.IOException,public static org.apache.pdfbox.io.RandomAccessRead decode(java.io.InputStream, List<org.apache.pdfbox.filter.Filter>, org.apache.pdfbox.cos.COSDictionary, org.apache.pdfbox.filter.DecodeOptions, List<org.apache.pdfbox.filter.DecodeResult>) throws java.io.IOException,public final void encode(java.io.InputStream, java.io.OutputStream, org.apache.pdfbox.cos.COSDictionary, int) throws java.io.IOException,public static final javax.imageio.ImageReader findImageReader(java.lang.String, java.lang.String) throws org.apache.pdfbox.filter.MissingImageReaderException,public static int getCompressionLevel() <variables>private static final Logger LOG,public static final java.lang.String SYSPROP_DEFLATELEVEL
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/multipdf/PDFCloneUtility.java
PDFCloneUtility
hasSelfReference
class PDFCloneUtility { private static final Logger LOG = LogManager.getLogger(PDFCloneUtility.class); private final PDDocument destination; private final Map<COSBase, COSBase> clonedVersion = new HashMap<>(); private final Set<COSBase> clonedValues = new HashSet<>(); // It might be useful to use IdentityHashMap like in PDFBOX-4477 for speed, // but we need a really huge file to test this. A test with the file from PDFBOX-4477 // did not show a noticeable speed difference. /** * Creates a new instance for the given target document. * * @param dest the destination PDF document that will receive the clones */ protected PDFCloneUtility(PDDocument dest) { this.destination = dest; } /** * Returns the destination PDF document this cloner instance is set up for. * * @return the destination PDF document */ PDDocument getDestination() { return this.destination; } /** * Deep-clones the given object for inclusion into a different PDF document identified by the destination parameter. * * Expert use only, don’t use it if you don’t know exactly what you are doing. * * @param base the initial object as the root of the deep-clone operation * @return the cloned instance of the base object * @throws IOException if an I/O error occurs */ @SuppressWarnings("unchecked") public <TCOSBase extends COSBase> TCOSBase cloneForNewDocument(TCOSBase base) throws IOException { if (base == null) { return null; } COSBase retval = clonedVersion.get(base); if (retval != null) { // we are done, it has already been converted. return (TCOSBase) retval; } if (clonedValues.contains(base)) { // Don't clone a clone return base; } retval = cloneCOSBaseForNewDocument(base); clonedVersion.put(base, retval); clonedValues.add(retval); return (TCOSBase) retval; } private COSBase cloneCOSBaseForNewDocument(COSBase base) throws IOException { if (base instanceof COSObject) { return cloneForNewDocument(((COSObject) base).getObject()); } if (base instanceof COSArray) { return cloneCOSArray((COSArray) base); } if (base instanceof COSStream) { return cloneCOSStream((COSStream) base); } if (base instanceof COSDictionary) { return cloneCOSDictionary((COSDictionary) base); } return base; } private COSArray cloneCOSArray(COSArray array) throws IOException { COSArray newArray = new COSArray(); for (int i = 0; i < array.size(); i++) { COSBase value = array.get(i); if (hasSelfReference(array, value)) { newArray.add(newArray); } else { newArray.add(cloneForNewDocument(value)); } } return newArray; } private COSStream cloneCOSStream(COSStream stream) throws IOException { COSStream newStream = destination.getDocument().createCOSStream(); try (OutputStream output = newStream.createRawOutputStream(); InputStream input = stream.createRawInputStream()) { input.transferTo(output); } clonedVersion.put(stream, newStream); for (Map.Entry<COSName, COSBase> entry : stream.entrySet()) { COSBase value = entry.getValue(); if (hasSelfReference(stream, value)) { newStream.setItem(entry.getKey(), newStream); } else { newStream.setItem(entry.getKey(), cloneForNewDocument(value)); } } return newStream; } private COSDictionary cloneCOSDictionary(COSDictionary dictionary) throws IOException { COSDictionary newDictionary = new COSDictionary(); clonedVersion.put(dictionary, newDictionary); for (Map.Entry<COSName, COSBase> entry : dictionary.entrySet()) { COSBase value = entry.getValue(); if (hasSelfReference(dictionary, value)) { newDictionary.setItem(entry.getKey(), newDictionary); } else { newDictionary.setItem(entry.getKey(), cloneForNewDocument(value)); } } return newDictionary; } /** * Merges two objects of the same type by deep-cloning its members. <br> * Base and target must be instances of the same class. * * @param base the base object to be cloned * @param target the merge target * @throws IOException if an I/O error occurs */ void cloneMerge(final COSObjectable base, COSObjectable target) throws IOException { if (base == null || base == target) { return; } cloneMergeCOSBase(base.getCOSObject(), target.getCOSObject()); } private void cloneMergeCOSBase(final COSBase source, final COSBase target) throws IOException { COSBase sourceBase = source instanceof COSObject ? ((COSObject) source).getObject() : source; COSBase targetBase = target instanceof COSObject ? ((COSObject) target).getObject() : target; if (sourceBase instanceof COSArray && targetBase instanceof COSArray) { COSArray array = (COSArray) sourceBase; for (int i = 0; i < array.size(); i++) { ((COSArray) targetBase).add(cloneForNewDocument(array.get(i))); } } else if (sourceBase instanceof COSDictionary && targetBase instanceof COSDictionary) { COSDictionary sourceDict = (COSDictionary) sourceBase; COSDictionary targetDict = (COSDictionary) targetBase; for (Map.Entry<COSName, COSBase> entry : sourceDict.entrySet()) { COSName key = entry.getKey(); COSBase value = entry.getValue(); if (targetDict.getItem(key) != null) { cloneMerge(value, targetDict.getItem(key)); } else { targetDict.setItem(key, cloneForNewDocument(value)); } } } } /** * Check whether an element (of an array or a dictionary) points to its parent. * * @param parent COSArray or COSDictionary * @param value an element */ private boolean hasSelfReference(COSBase parent, COSBase value) {<FILL_FUNCTION_BODY>} }
if (value instanceof COSObject) { COSBase actual = ((COSObject) value).getObject(); if (actual == parent) { COSObject cosObj = ((COSObject) value); LOG.warn("{} object has a reference to itself: {}", parent.getClass().getSimpleName(), cosObj.getKey()); return true; } } return false;
1,849
108
1,957
<no_super_class>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/multipdf/PageExtractor.java
PageExtractor
extract
class PageExtractor { private final PDDocument sourceDocument; // first page to extract is page 1 (by default) private int startPage = 1; private int endPage; /** * Creates a new instance of PageExtractor * @param sourceDocument The document to split. */ public PageExtractor(PDDocument sourceDocument) { this.sourceDocument = sourceDocument; endPage = sourceDocument.getNumberOfPages(); } /** * Creates a new instance of PageExtractor * @param sourceDocument The document to split. * @param startPage The first page you want extracted (1-based, inclusive) * @param endPage The last page you want extracted (1-based, inclusive) */ public PageExtractor(PDDocument sourceDocument, int startPage, int endPage) { this.sourceDocument = sourceDocument; this.startPage = startPage; this.endPage = endPage; } /** * This will take a document and extract the desired pages into a new * document. Both startPage and endPage are included in the extracted * document. If the endPage is greater than the number of pages in the * source document, it will go to the end of the document. If startPage is * less than 1, it'll start with page 1. If startPage is greater than * endPage or greater than the number of pages in the source document, a * blank document will be returned. * * @return The extracted document * @throws IOException If there is an IOError */ public PDDocument extract() throws IOException {<FILL_FUNCTION_BODY>} /** * Gets the first page number to be extracted. * @return the first page number which should be extracted */ public int getStartPage() { return startPage; } /** * Sets the first page number to be extracted. * @param startPage the first page number which should be extracted */ public void setStartPage(int startPage) { this.startPage = startPage; } /** * Gets the last page number (inclusive) to be extracted. * @return the last page number which should be extracted */ public int getEndPage() { return endPage; } /** * Sets the last page number to be extracted. * @param endPage the last page number which should be extracted */ public void setEndPage(int endPage) { this.endPage = endPage; } }
if (endPage - startPage + 1 <= 0) { return new PDDocument(); } Splitter splitter = new Splitter(); splitter.setStartPage(Math.max(startPage, 1)); splitter.setEndPage(Math.min(endPage, sourceDocument.getNumberOfPages())); splitter.setSplitAtPage(getEndPage() - getStartPage() + 1); List<PDDocument> splitted = splitter.split(sourceDocument); return splitted.get(0);
677
138
815
<no_super_class>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdfparser/EndstreamFilterStream.java
EndstreamFilterStream
filter
class EndstreamFilterStream { private boolean hasCR = false; private boolean hasLF = false; private int pos = 0; private boolean mustFilter = true; private long length = 0; /** * Write CR and/or LF that were kept, then writes len bytes from the * specified byte array starting at offset off to this output stream, * except trailing CR, CR LF, or LF. No filtering will be done for the * entire stream if the beginning is assumed to be ASCII. * @param b byte array. * @param off offset. * @param len length of segment to write. */ public void filter(byte[] b, int off, int len) {<FILL_FUNCTION_BODY>} /** * write out a single CR if one was kept. Don't write kept CR LF or LF, * and then call the base method to flush. * */ public long calculateLength() { // if there is only a CR and no LF, write it if (hasCR && !hasLF) { length++; ++pos; } hasCR = false; hasLF = false; return length; } }
if (pos == 0 && len > 10) { // PDFBOX-2120 Don't filter if ASCII, i.e. keep a final CR LF or LF mustFilter = false; for (int i = 0; i < 10; ++i) { // Heuristic approach, taken from PDFStreamParser, PDFBOX-1164 if ((b[i] < 0x09) || ((b[i] > 0x0a) && (b[i] < 0x20) && (b[i] != 0x0d))) { // control character or > 0x7f -> we have binary data mustFilter = true; break; } } } if (mustFilter) { // first write what we kept last time if (hasCR) { // previous buffer ended with CR hasCR = false; if (!hasLF && len == 1 && b[off] == '\n') { // actual buffer contains only LF so it will be the last one // => we're done // reset hasCR done too to avoid CR getting written in the flush return; } length++; } if (hasLF) { length++; hasLF = false; } // don't write CR, LF, or CR LF if at the end of the buffer if (len > 0) { if (b[off + len - 1] == '\r') { hasCR = true; --len; } else if (b[off + len - 1] == '\n') { hasLF = true; --len; if (len > 0 && b[off + len - 1] == '\r') { hasCR = true; --len; } } } } length += len; pos += len;
322
504
826
<no_super_class>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdfparser/FDFParser.java
FDFParser
parse
class FDFParser extends COSParser { /** * Constructs parser for given file using memory buffer. * * @param source the source of the pdf to be parsed * * @throws IOException If something went wrong. */ public FDFParser(RandomAccessRead source) throws IOException { super(source); } /** * The initial parse will first parse only the trailer, the xrefstart and all xref tables to have a pointer (offset) * to all the pdf's objects. It can handle linearized pdfs, which will have an xref at the end pointing to an xref * at the beginning of the file. Last the root object is parsed. * * @throws IOException If something went wrong. */ private void initialParse() throws IOException { COSDictionary trailer = retrieveTrailer(); COSDictionary root = trailer.getCOSDictionary(COSName.ROOT); if (root == null) { throw new IOException("Missing root object specification in trailer."); } initialParseDone = true; } /** * This will parse the stream and populate the FDFDocument object. * * @return the parsed FDFDocument * @throws IOException If there is an error reading from the stream or corrupt data is found. */ public FDFDocument parse() throws IOException {<FILL_FUNCTION_BODY>} }
// set to false if all is processed boolean exceptionOccurred = true; try { if (!parseFDFHeader()) { throw new IOException( "Error: Header doesn't contain versioninfo" ); } initialParse(); exceptionOccurred = false; return new FDFDocument(document); } finally { if (exceptionOccurred && document != null) { IOUtils.closeQuietly(document); document = null; } }
359
138
497
<methods>public void <init>(org.apache.pdfbox.io.RandomAccessRead) throws java.io.IOException,public void <init>(org.apache.pdfbox.io.RandomAccessRead, java.lang.String, java.io.InputStream, java.lang.String) throws java.io.IOException,public void <init>(org.apache.pdfbox.io.RandomAccessRead, java.lang.String, java.io.InputStream, java.lang.String, org.apache.pdfbox.io.RandomAccessStreamCache.StreamCacheCreateFunction) throws java.io.IOException,public org.apache.pdfbox.io.RandomAccessReadView createRandomAccessReadView(long, long) throws java.io.IOException,public org.apache.pdfbox.cos.COSBase dereferenceCOSObject(org.apache.pdfbox.cos.COSObject) throws java.io.IOException,public boolean isLenient() ,public void setEOFLookupRange(int) <variables>private static final int DEFAULT_TRAIL_BYTECOUNT,private static final byte[] ENDOBJ,private static final byte[] ENDSTREAM,private static final char[] EOF_MARKER,private static final java.lang.String FDF_DEFAULT_VERSION,private static final java.lang.String FDF_HEADER,private static final Logger LOG,protected static final long MINIMUM_SEARCH_OFFSET,private static final char[] OBJ_MARKER,private static final java.lang.String PDF_DEFAULT_VERSION,private static final java.lang.String PDF_HEADER,private static final char[] STARTXREF,private static final int STRMBUFLEN,public static final java.lang.String SYSPROP_EOFLOOKUPRANGE,private org.apache.pdfbox.pdmodel.encryption.AccessPermission accessPermission,private org.apache.pdfbox.pdfparser.BruteForceParser bruteForceParser,private final Map<java.lang.Long,Map<org.apache.pdfbox.cos.COSObjectKey,org.apache.pdfbox.cos.COSBase>> decompressedObjects,private org.apache.pdfbox.pdmodel.encryption.PDEncryption encryption,private final non-sealed long fileLen,protected boolean initialParseDone,private boolean isLenient,private java.lang.String keyAlias,private java.io.InputStream keyStoreInputStream,private java.lang.String password,private int readTrailBytes,private SecurityHandler<org.apache.pdfbox.pdmodel.encryption.ProtectionPolicy> securityHandler,private final byte[] strmBuf,private boolean trailerWasRebuild,private final Map<org.apache.pdfbox.cos.COSObjectKey,java.lang.Long> xrefTable
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdfparser/PDFObjectStreamParser.java
PDFObjectStreamParser
privateReadObjectNumbers
class PDFObjectStreamParser extends BaseParser { private final int numberOfObjects; private final int firstObject; /** * Constructor. * * @param stream The stream to parse. * @param document The document for the current parsing. * @throws IOException If there is an error initializing the stream. */ public PDFObjectStreamParser(COSStream stream, COSDocument document) throws IOException { super(stream.createView()); this.document = document; // get mandatory number of objects numberOfObjects = stream.getInt(COSName.N); if (numberOfObjects == -1) { throw new IOException("/N entry missing in object stream"); } if (numberOfObjects < 0) { throw new IOException("Illegal /N entry in object stream: " + numberOfObjects); } // get mandatory stream offset of the first object firstObject = stream.getInt(COSName.FIRST); if (firstObject == -1) { throw new IOException("/First entry missing in object stream"); } if (firstObject < 0) { throw new IOException("Illegal /First entry in object stream: " + firstObject); } } /** * Search for/parse the object with the given object number. The stream is closed after parsing the object with the * given number. * * @param objectNumber the number of the object to b e parsed * @return the parsed object or null if the object with the given number can't be found * @throws IOException if there is an error while parsing the stream */ public COSBase parseObject(long objectNumber) throws IOException { COSBase streamObject = null; try { Integer objectOffset = privateReadObjectNumbers().get(objectNumber); if (objectOffset != null) { // jump to the offset of the first object long currentPosition = source.getPosition(); if (firstObject > 0 && currentPosition < firstObject) { source.skip(firstObject - (int) currentPosition); } // jump to the offset of the object to be parsed source.skip(objectOffset); streamObject = parseDirObject(); if (streamObject != null) { streamObject.setDirect(false); } } } finally { source.close(); document = null; } return streamObject; } /** * Parse all compressed objects. The stream is closed after parsing. * * @return a map containing all parsed objects using the object number as key * @throws IOException if there is an error while parsing the stream */ public Map<COSObjectKey, COSBase> parseAllObjects() throws IOException { Map<COSObjectKey, COSBase> allObjects = new HashMap<>(); try { Map<Integer, Long> objectNumbers = privateReadObjectOffsets(); // count the number of object numbers eliminating double entries long numberOfObjNumbers = objectNumbers.values().stream().distinct().count(); // the usage of the index should be restricted to cases where more than one // object use the same object number. // there are malformed pdfs in the wild which would lead to false results if // pdfbox always relies on the index if available. In most cases the object number // is sufficient to choose the correct object boolean indexNeeded = objectNumbers.size() > numberOfObjNumbers; long currentPosition = source.getPosition(); if (firstObject > 0 && currentPosition < firstObject) { source.skip(firstObject - (int) currentPosition); } int index = 0; for (Entry<Integer, Long> entry : objectNumbers.entrySet()) { COSObjectKey objectKey = getObjectKey(entry.getValue(), 0); // skip object if the index doesn't match if (indexNeeded && objectKey.getStreamIndex() > -1 && objectKey.getStreamIndex() != index) { index++; continue; } int finalPosition = firstObject + entry.getKey(); currentPosition = source.getPosition(); if (finalPosition > 0 && currentPosition < finalPosition) { // jump to the offset of the object to be parsed source.skip(finalPosition - (int) currentPosition); } COSBase streamObject = parseDirObject(); if (streamObject != null) { streamObject.setDirect(false); } allObjects.put(objectKey, streamObject); index++; } } finally { source.close(); document = null; } return allObjects; } private Map<Long, Integer> privateReadObjectNumbers() throws IOException {<FILL_FUNCTION_BODY>} private Map<Integer, Long> privateReadObjectOffsets() throws IOException { // according to the pdf spec the offsets shall be sorted ascending // but we can't rely on that, so that we have to sort the offsets // as the sequential parsers relies on it, see PDFBOX-4927 Map<Integer, Long> objectOffsets = new TreeMap<>(); long firstObjectPosition = source.getPosition() + firstObject - 1; for (int i = 0; i < numberOfObjects; i++) { // don't read beyond the part of the stream reserved for the object numbers if (source.getPosition() >= firstObjectPosition) { break; } long objectNumber = readObjectNumber(); int offset = (int) readLong(); objectOffsets.put(offset, objectNumber); } return objectOffsets; } /** * Read all object numbers from the compressed object stream. The stream is closed after reading the object numbers. * * @return a map off all object numbers and the corresponding offset within the object stream. * @throws IOException if there is an error while parsing the stream */ public Map<Long, Integer> readObjectNumbers() throws IOException { Map<Long, Integer> objectNumbers = null; try { objectNumbers = privateReadObjectNumbers(); } finally { source.close(); document = null; } return objectNumbers; } }
// don't initialize map using numberOfObjects as there might by less object numbers than expected Map<Long, Integer> objectNumbers = new HashMap<>(); long firstObjectPosition = source.getPosition() + firstObject - 1; for (int i = 0; i < numberOfObjects; i++) { // don't read beyond the part of the stream reserved for the object numbers if (source.getPosition() >= firstObjectPosition) { break; } long objectNumber = readObjectNumber(); int offset = (int) readLong(); objectNumbers.put(objectNumber, offset); } return objectNumbers;
1,620
167
1,787
<methods><variables>protected static final int A,private static final non-sealed java.nio.charset.Charset ALTERNATIVE_CHARSET,private static final byte ASCII_CR,private static final byte ASCII_FF,private static final byte ASCII_LF,private static final byte ASCII_NINE,private static final byte ASCII_NULL,private static final byte ASCII_SPACE,private static final byte ASCII_TAB,private static final byte ASCII_ZERO,protected static final int B,protected static final int D,public static final java.lang.String DEF,protected static final int E,protected static final java.lang.String ENDOBJ_STRING,protected static final java.lang.String ENDSTREAM_STRING,private static final char[] FALSE,private static final long GENERATION_NUMBER_THRESHOLD,protected static final int J,private static final Logger LOG,protected static final int M,private static final int MAX_LENGTH_LONG,protected static final int N,private static final char[] NULL,protected static final int O,private static final long OBJECT_NUMBER_THRESHOLD,protected static final int R,protected static final int S,protected static final java.lang.String STREAM_STRING,protected static final int T,private static final char[] TRUE,protected org.apache.pdfbox.cos.COSDocument document,private final Map<java.lang.Long,org.apache.pdfbox.cos.COSObjectKey> keyCache,protected final non-sealed org.apache.pdfbox.io.RandomAccessRead source,private final java.nio.charset.CharsetDecoder utf8Decoder
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdfparser/PDFParser.java
PDFParser
initialParse
class PDFParser extends COSParser { private static final Logger LOG = LogManager.getLogger(PDFParser.class); /** * Constructor. * Unrestricted main memory will be used for buffering PDF streams. * * @param source source representing the pdf. * @throws IOException If something went wrong. */ public PDFParser(RandomAccessRead source) throws IOException { this(source, ""); } /** * Constructor. * Unrestricted main memory will be used for buffering PDF streams. * * @param source input representing the pdf. * @param decryptionPassword password to be used for decryption. * @throws IOException If something went wrong. */ public PDFParser(RandomAccessRead source, String decryptionPassword) throws IOException { this(source, decryptionPassword, null, null); } /** * Constructor. * Unrestricted main memory will be used for buffering PDF streams. * * @param source input representing the pdf. * @param decryptionPassword password to be used for decryption. * @param keyStore key store to be used for decryption when using public key security * @param alias alias to be used for decryption when using public key security * * @throws IOException If something went wrong. */ public PDFParser(RandomAccessRead source, String decryptionPassword, InputStream keyStore, String alias) throws IOException { this(source, decryptionPassword, keyStore, alias, null); } /** * Constructor. * * @param source input representing the pdf. * @param decryptionPassword password to be used for decryption. * @param keyStore key store to be used for decryption when using public key security * @param alias alias to be used for decryption when using public key security * @param streamCacheCreateFunction a function to create an instance of the stream cache * * @throws IOException If something went wrong. */ public PDFParser(RandomAccessRead source, String decryptionPassword, InputStream keyStore, String alias, StreamCacheCreateFunction streamCacheCreateFunction) throws IOException { super(source, decryptionPassword, keyStore, alias, streamCacheCreateFunction); } /** * The initial parse will first parse only the trailer, the xrefstart and all xref tables to have a pointer (offset) * to all the pdf's objects. It can handle linearized pdfs, which will have an xref at the end pointing to an xref * at the beginning of the file. Last the root object is parsed. * * @throws InvalidPasswordException If the password is incorrect. * @throws IOException If something went wrong. */ protected void initialParse() throws IOException {<FILL_FUNCTION_BODY>} /** * This will parse the stream and populate the PDDocument object. This will close the keystore stream when it is * done parsing. Lenient mode is active by default. * * @return the populated PDDocument * * @throws InvalidPasswordException If the password is incorrect. * @throws IOException If there is an error reading from the stream or corrupt data is found. */ public PDDocument parse() throws IOException { return parse(true); } /** * This will parse the stream and populate the PDDocument object. This will close the keystore stream when it is * done parsing. * * @param lenient activate leniency if set to true * @return the populated PDDocument * * @throws InvalidPasswordException If the password is incorrect. * @throws IOException If there is an error reading from the stream or corrupt data is found. */ public PDDocument parse(boolean lenient) throws IOException { setLenient(lenient); // set to false if all is processed boolean exceptionOccurred = true; try { // PDFBOX-1922 read the version header and rewind if (!parsePDFHeader() && !parseFDFHeader()) { if (lenient) { LOG.warn("Error: Header doesn't contain versioninfo"); } else { throw new IOException("Error: Header doesn't contain versioninfo"); } } if (!initialParseDone) { initialParse(); } exceptionOccurred = false; PDDocument pdDocument = createDocument(); pdDocument.setEncryptionDictionary(getEncryption()); return pdDocument; } finally { if (exceptionOccurred && document != null) { IOUtils.closeQuietly(document); document = null; } } } /** * Create the resulting document. Maybe overwritten if the parser uses another class as document. * * @return the resulting document * @throws IOException if the method is called before parsing the document */ protected PDDocument createDocument() throws IOException { return new PDDocument(document, source, getAccessPermission()); } /** * Parses a PDF. Unrestricted main memory will be used for buffering PDF streams. * * @param file file to be loaded * * @return loaded document * * @throws InvalidPasswordException If the file required a non-empty password. * @throws IOException in case of a file reading or parsing error * * @deprecated use {@link Loader#loadPDF(File)} instead */ @Deprecated public static PDDocument load(File file) throws IOException { return Loader.loadPDF(file); } /** * Parses a PDF. Unrestricted main memory will be used for buffering PDF streams. * * @param file file to be loaded * @param password password to be used for decryption * * @return loaded document * * @throws InvalidPasswordException If the password is incorrect. * @throws IOException in case of a file reading or parsing error * * @deprecated use {@link Loader#loadPDF(File, String)} instead */ @Deprecated public static PDDocument load(File file, String password) throws IOException { return Loader.loadPDF(file, password); } }
COSDictionary trailer = retrieveTrailer(); COSDictionary root = trailer.getCOSDictionary(COSName.ROOT); if (root == null) { throw new IOException("Missing root object specification in trailer."); } // in some pdfs the type value "Catalog" is missing in the root object if (isLenient() && !root.containsKey(COSName.TYPE)) { root.setItem(COSName.TYPE, COSName.CATALOG); } // check pages dictionaries checkPages(root); document.setDecrypted(); initialParseDone = true;
1,605
163
1,768
<methods>public void <init>(org.apache.pdfbox.io.RandomAccessRead) throws java.io.IOException,public void <init>(org.apache.pdfbox.io.RandomAccessRead, java.lang.String, java.io.InputStream, java.lang.String) throws java.io.IOException,public void <init>(org.apache.pdfbox.io.RandomAccessRead, java.lang.String, java.io.InputStream, java.lang.String, org.apache.pdfbox.io.RandomAccessStreamCache.StreamCacheCreateFunction) throws java.io.IOException,public org.apache.pdfbox.io.RandomAccessReadView createRandomAccessReadView(long, long) throws java.io.IOException,public org.apache.pdfbox.cos.COSBase dereferenceCOSObject(org.apache.pdfbox.cos.COSObject) throws java.io.IOException,public boolean isLenient() ,public void setEOFLookupRange(int) <variables>private static final int DEFAULT_TRAIL_BYTECOUNT,private static final byte[] ENDOBJ,private static final byte[] ENDSTREAM,private static final char[] EOF_MARKER,private static final java.lang.String FDF_DEFAULT_VERSION,private static final java.lang.String FDF_HEADER,private static final Logger LOG,protected static final long MINIMUM_SEARCH_OFFSET,private static final char[] OBJ_MARKER,private static final java.lang.String PDF_DEFAULT_VERSION,private static final java.lang.String PDF_HEADER,private static final char[] STARTXREF,private static final int STRMBUFLEN,public static final java.lang.String SYSPROP_EOFLOOKUPRANGE,private org.apache.pdfbox.pdmodel.encryption.AccessPermission accessPermission,private org.apache.pdfbox.pdfparser.BruteForceParser bruteForceParser,private final Map<java.lang.Long,Map<org.apache.pdfbox.cos.COSObjectKey,org.apache.pdfbox.cos.COSBase>> decompressedObjects,private org.apache.pdfbox.pdmodel.encryption.PDEncryption encryption,private final non-sealed long fileLen,protected boolean initialParseDone,private boolean isLenient,private java.lang.String keyAlias,private java.io.InputStream keyStoreInputStream,private java.lang.String password,private int readTrailBytes,private SecurityHandler<org.apache.pdfbox.pdmodel.encryption.ProtectionPolicy> securityHandler,private final byte[] strmBuf,private boolean trailerWasRebuild,private final Map<org.apache.pdfbox.cos.COSObjectKey,java.lang.Long> xrefTable
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdfparser/PDFXRefStream.java
PDFXRefStream
getIndexEntry
class PDFXRefStream { private final List<XReferenceEntry> streamData = new ArrayList<>(); private final Set<Long> objectNumbers = new TreeSet<>(); private final COSStream stream; private long size = -1; /** * Create a fresh XRef stream like for a fresh file or an incremental update. * * @param cosDocument the COSDocmernt to be used to create a new COSStream */ public PDFXRefStream(COSDocument cosDocument) { stream = cosDocument.createCOSStream(); } /** * Returns the stream of the XRef. * @return the XRef stream * @throws IOException if something went wrong */ public COSStream getStream() throws IOException { stream.setItem(COSName.TYPE, COSName.XREF); if (size == -1) { throw new IllegalArgumentException("size is not set in xrefstream"); } stream.setLong(COSName.SIZE, size); List<Long> indexEntry = getIndexEntry(); COSArray indexAsArray = new COSArray(); for ( Long i : indexEntry ) { indexAsArray.add(COSInteger.get(i)); } stream.setItem(COSName.INDEX, indexAsArray); int[] wEntry = getWEntry(); COSArray wAsArray = new COSArray(); for (int j : wEntry) { wAsArray.add(COSInteger.get(j)); } stream.setItem(COSName.W, wAsArray); try (OutputStream outputStream = this.stream.createOutputStream(COSName.FLATE_DECODE)) { writeStreamData(outputStream, wEntry); outputStream.flush(); } Set<COSName> keySet = this.stream.keySet(); for ( COSName cosName : keySet ) { // "Other cross-reference stream entries not listed in Table 17 may be indirect; in fact, // some (such as Root in Table 15) shall be indirect." if (COSName.ROOT.equals(cosName) || COSName.INFO.equals(cosName) || COSName.PREV.equals(cosName)) { continue; } // this one too, because it has already been written in COSWriter.doWriteBody() if (COSName.ENCRYPT.equals(cosName)) { continue; } COSBase dictionaryObject = this.stream.getDictionaryObject(cosName); dictionaryObject.setDirect(true); } return this.stream; } /** * Copy all Trailer Information to this file. * * @param trailerDict dictionary to be added as trailer info */ public void addTrailerInfo(COSDictionary trailerDict) { trailerDict.forEach((key, value) -> { if (COSName.INFO.equals(key) || COSName.ROOT.equals(key) || COSName.ENCRYPT.equals(key) || COSName.ID.equals(key) || COSName.PREV.equals(key)) { stream.setItem(key, value); } }); } /** * Add an new entry to the XRef stream. * * @param entry new entry to be added */ public void addEntry(XReferenceEntry entry) { if (objectNumbers.contains(entry.getReferencedKey().getNumber())) { return; } objectNumbers.add(entry.getReferencedKey().getNumber()); streamData.add(entry); } /** * determines the minimal length required for all the lengths. * * @return the length information */ private int[] getWEntry() { long[] wMax = new long[3]; for (XReferenceEntry entry : streamData) { wMax[0] = Math.max(wMax[0], entry.getFirstColumnValue()); wMax[1] = Math.max(wMax[1], entry.getSecondColumnValue()); wMax[2] = Math.max(wMax[2], entry.getThirdColumnValue()); } // find the max bytes needed to display that column int[] w = new int[3]; for ( int i = 0; i < w.length; i++ ) { while (wMax[i] > 0) { w[i]++; wMax[i] >>= 8; } } return w; } /** * Set the size of the XRef stream. * * @param streamSize size to bet set as stream size */ public void setSize(long streamSize) { this.size = streamSize; } private List<Long> getIndexEntry() {<FILL_FUNCTION_BODY>} private void writeNumber(OutputStream os, long number, int bytes) throws IOException { byte[] buffer = new byte[bytes]; for ( int i = 0; i < bytes; i++ ) { buffer[i] = (byte)(number & 0xff); number >>= 8; } for ( int i = 0; i < bytes; i++ ) { os.write(buffer[bytes-i-1]); } } private void writeStreamData(OutputStream os, int[] w) throws IOException { Collections.sort(streamData); FreeXReference nullEntry = FreeXReference.NULL_ENTRY; writeNumber(os, nullEntry.getFirstColumnValue(), w[0]); writeNumber(os, nullEntry.getSecondColumnValue(), w[1]); writeNumber(os, nullEntry.getThirdColumnValue(), w[2]); // iterate over all streamData and write it in the required format for (XReferenceEntry entry : streamData) { writeNumber(os, entry.getFirstColumnValue(), w[0]); writeNumber(os, entry.getSecondColumnValue(), w[1]); writeNumber(os, entry.getThirdColumnValue(), w[2]); } } }
LinkedList<Long> linkedList = new LinkedList<>(); Long first = null; Long length = null; Set<Long> objNumbers = new TreeSet<>(); // add object number 0 to the set objNumbers.add(0L); objNumbers.addAll(objectNumbers); for ( Long objNumber : objNumbers ) { if (first == null) { first = objNumber; length = 1L; } if (first + length == objNumber) { length += 1; } if (first + length < objNumber) { linkedList.add(first); linkedList.add(length); first = objNumber; length = 1L; } } linkedList.add(first); linkedList.add(length); return linkedList;
1,618
225
1,843
<no_super_class>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdfparser/PDFXrefStreamParser.java
PDFXrefStreamParser
parse
class PDFXrefStreamParser { private final int[] w = new int[3]; private ObjectNumbers objectNumbers = null; private final RandomAccessRead source; /** * Constructor. * * @param stream The stream to parse. * * @throws IOException If there is an error initializing the stream. */ public PDFXrefStreamParser(COSStream stream) throws IOException { source = stream.createView(); try { initParserValues(stream); } catch (IOException exception) { close(); throw exception; } } private void initParserValues(COSStream stream) throws IOException { COSArray wArray = stream.getCOSArray(COSName.W); if (wArray == null) { throw new IOException("/W array is missing in Xref stream"); } if (wArray.size() != 3) { throw new IOException( "Wrong number of values for /W array in XRef: " + Arrays.toString(w)); } for (int i = 0; i < 3; i++) { w[i] = wArray.getInt(i, 0); } if (w[0] < 0 || w[1] < 0 || w[2] < 0) { throw new IOException("Incorrect /W array in XRef: " + Arrays.toString(w)); } COSArray indexArray = stream.getCOSArray(COSName.INDEX); if (indexArray == null) { // If /Index doesn't exist, we will use the default values. indexArray = new COSArray(); indexArray.add(COSInteger.ZERO); indexArray.add(COSInteger.get(stream.getInt(COSName.SIZE, 0))); } if (indexArray.isEmpty() || indexArray.size() % 2 == 1) { throw new IOException( "Wrong number of values for /Index array in XRef: " + Arrays.toString(w)); } // create an Iterator for all object numbers using the index array objectNumbers = new ObjectNumbers(indexArray); } private void close() throws IOException { if (source != null) { source.close(); } objectNumbers = null; } /** * Parses through the unfiltered stream and populates the xrefTable HashMap. * * @param resolver resolver to read the xref/trailer information * @throws IOException If there is an error while parsing the stream. */ public void parse(XrefTrailerResolver resolver) throws IOException {<FILL_FUNCTION_BODY>} private void readNextValue(byte[] value) throws IOException { int remainingBytes = value.length; int amountRead; while ((amountRead = source.read(value, value.length - remainingBytes, remainingBytes)) > 0) { remainingBytes -= amountRead; } } private long parseValue(byte[] data, int start, int length) { long value = 0; for (int i = 0; i < length; i++) { value += ((long) data[i + start] & 0x00ff) << ((length - i - 1) * 8); } return value; } private static class ObjectNumbers implements Iterator<Long> { private final long[] start; private final long[] end; private int currentRange = 0; private long currentEnd = 0; private long currentNumber = 0; private ObjectNumbers(COSArray indexArray) throws IOException { start = new long[indexArray.size() / 2]; end = new long[start.length]; int counter = 0; Iterator<COSBase> indexIter = indexArray.iterator(); while (indexIter.hasNext()) { COSBase base = indexIter.next(); if (!(base instanceof COSInteger)) { throw new IOException("Xref stream must have integer in /Index array"); } long startValue = ((COSInteger) base).longValue(); if (!indexIter.hasNext()) { break; } base = indexIter.next(); if (!(base instanceof COSInteger)) { throw new IOException("Xref stream must have integer in /Index array"); } long sizeValue = ((COSInteger) base).longValue(); start[counter] = startValue; end[counter] = startValue + sizeValue; counter++; } currentNumber = start[0]; currentEnd = end[0]; } @Override public boolean hasNext() { if (start.length == 1) { return currentNumber < currentEnd; } return currentRange < start.length - 1 || currentNumber < currentEnd; } @Override public Long next() { if (currentNumber < currentEnd) { return currentNumber++; } if (currentRange >= start.length - 1) { throw new NoSuchElementException(); } currentNumber = start[++currentRange]; currentEnd = end[currentRange]; return currentNumber++; } } }
byte[] currLine = new byte[w[0] + w[1] + w[2]]; while (!source.isEOF() && objectNumbers.hasNext()) { readNextValue(currLine); // get the current objID long objID = objectNumbers.next(); // default value is 1 if w[0] == 0, otherwise parse first field int type = w[0] == 0 ? 1 : (int) parseValue(currLine, 0, w[0]); // Skip free objects (type 0) and invalid types if (type == 0) { continue; } // second field holds the offset (type 1) or the object stream number (type 2) long offset = parseValue(currLine, w[0], w[1]); // third filed may hold the generation number (type1) or the index within a object stream (type2) int thirdValue = (int) parseValue(currLine, w[0] + w[1], w[2]); if (type == 1) { // third field holds the generation number for type 1 entries resolver.setXRef(new COSObjectKey(objID, thirdValue), offset); } else { // For XRef aware parsers we have to know which objects contain object streams. We will store this // information in normal xref mapping table but add object stream number with minus sign in order to // distinguish from file offsets resolver.setXRef(new COSObjectKey(objID, 0, thirdValue), -offset); } } close();
1,386
409
1,795
<no_super_class>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdfparser/xref/AbstractXReference.java
AbstractXReference
compareTo
class AbstractXReference implements XReferenceEntry { private final XReferenceType type; /** * Creates a crossreference stream entry of the given {@link XReferenceType}. * * @param type The {@link XReferenceType} of the crossreference stream entry. */ protected AbstractXReference(XReferenceType type) { this.type = type; } /** * Returns the {@link XReferenceType} of this crossreference stream entry. * * @return The {@link XReferenceType} of this crossreference stream entry. */ @Override public XReferenceType getType() { return type; } /** * Returns the value for the first column of the crossreference stream entry. (The numeric representation of this * entry's (The numeric representation of this entry's {@link XReferenceType}.) * * @return The value for the first column of the crossreference stream entry. */ @Override public long getFirstColumnValue() { return getType().getNumericValue(); } /** * Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer * as this object is less than, equal to, or greater than the specified object. * * @param xReferenceEntry the object to be compared. * @return a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than * the specified object. */ @Override public int compareTo(XReferenceEntry xReferenceEntry) {<FILL_FUNCTION_BODY>} }
if (getReferencedKey() == null) { return -1; } else if (xReferenceEntry == null || xReferenceEntry.getReferencedKey() == null) { return 1; } return getReferencedKey().compareTo(xReferenceEntry.getReferencedKey());
411
87
498
<no_super_class>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdfparser/xref/FreeXReference.java
FreeXReference
toString
class FreeXReference extends AbstractXReference { public static final FreeXReference NULL_ENTRY = // new FreeXReference(new COSObjectKey(0, 65535), 0); private final COSObjectKey key; private final long nextFreeObject; /** * Sets the given {@link COSObjectKey} as a free reference in a PDF's crossreference stream ({@link PDFXRefStream}). * * @param key The key, that shall be set as the free reference of the document. * @param nextFreeObject The object number of the next free object. */ public FreeXReference(COSObjectKey key, long nextFreeObject) { super(XReferenceType.FREE); this.key = key; this.nextFreeObject = nextFreeObject; } /** * Returns the {@link COSObjectKey} of the object, that is described by this crossreference stream entry. * * @return The {@link COSObjectKey} of the object, that is described by this crossreference stream entry. */ @Override public COSObjectKey getReferencedKey() { return key; } /** * Returns the value for the second column of the crossreference stream entry. (This is the object number of the set * next free {@link COSObjectKey} - for entries of this type.) * * @return The value for the second column of the crossreference stream entry. */ @Override public long getSecondColumnValue() { return nextFreeObject; } /** * Returns the value for the third column of the crossreference stream entry. (This is the generation number of the * set next free {@link COSObjectKey} - for entries of this type.) * * @return The value for the third column of the crossreference stream entry. */ @Override public long getThirdColumnValue() { return getReferencedKey().getGeneration(); } /** * Returns a string representation of this crossreference stream entry. * * @return A string representation of this crossreference stream entry. */ @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "FreeReference{" + "key=" + key + ", nextFreeObject=" + nextFreeObject + ", type=" + getType().getNumericValue() + " }";
570
48
618
<methods>public int compareTo(org.apache.pdfbox.pdfparser.xref.XReferenceEntry) ,public long getFirstColumnValue() ,public org.apache.pdfbox.pdfparser.xref.XReferenceType getType() <variables>private final non-sealed org.apache.pdfbox.pdfparser.xref.XReferenceType type
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdfparser/xref/NormalXReference.java
NormalXReference
toString
class NormalXReference extends AbstractXReference { private final long byteOffset; private final COSObjectKey key; private final COSBase object; private final boolean objectStream; /** * Prepares a normal reference for the given {@link COSObject} in a PDF's crossreference stream * ({@link PDFXRefStream}). * * @param byteOffset The byte offset of the {@link COSObject} in the PDF file. * @param key The {@link COSObjectKey}, that is represented by this entry. * @param object The {@link COSObject}, that is represented by this entry. */ public NormalXReference(long byteOffset, COSObjectKey key, COSBase object) { super(XReferenceType.NORMAL); this.byteOffset = byteOffset; this.key = key; this.object = object; COSBase base = object instanceof COSObject ? ((COSObject) object).getObject() : object; if (base instanceof COSStream) { objectStream = COSName.OBJ_STM.equals(((COSStream) base).getCOSName(COSName.TYPE)); } else { objectStream = false; } } /** * Returns the byte offset of the {@link COSObject} in the PDF file. * * @return The byte offset of the {@link COSObject} in the PDF file. */ public long getByteOffset() { return byteOffset; } /** * Returns the {@link COSObjectKey} of the object, that is described by this crossreference stream entry. * * @return The {@link COSObjectKey} of the object, that is described by this crossreference stream entry. */ @Override public COSObjectKey getReferencedKey() { return key; } /** * Returns the {@link COSObject}, that is described by this crossreference stream entry. * * @return The {@link COSObject}, that is described by this crossreference stream entry. */ public COSBase getObject() { return object; } /** * Returns true, if the referenced object is an object stream. * * @return True, if the referenced object is an object stream. */ public boolean isObjectStream() { return objectStream; } /** * Returns the value for the second column of the crossreference stream entry. (This is byte offset of the * {@link COSObject} in the PDF file - for entries of this type.) * * @return The value for the second column of the crossreference stream entry. */ @Override public long getSecondColumnValue() { return getByteOffset(); } /** * Returns the value for the third column of the crossreference stream entry. (This is the generation number of the * set {@link COSObjectKey} - for entries of this type.) * * @return The value for the third column of the crossreference stream entry. */ @Override public long getThirdColumnValue() { return getReferencedKey().getGeneration(); } /** * Returns a string representation of this crossreference stream entry. * * @return A string representation of this crossreference stream entry. */ @Override public String toString() {<FILL_FUNCTION_BODY>} }
return (isObjectStream() ? "ObjectStreamParent{" : "NormalReference{") + " key=" + key + ", type=" + getType().getNumericValue() + ", byteOffset=" + byteOffset + " }";
881
59
940
<methods>public int compareTo(org.apache.pdfbox.pdfparser.xref.XReferenceEntry) ,public long getFirstColumnValue() ,public org.apache.pdfbox.pdfparser.xref.XReferenceType getType() <variables>private final non-sealed org.apache.pdfbox.pdfparser.xref.XReferenceType type
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdfparser/xref/ObjectStreamXReference.java
ObjectStreamXReference
toString
class ObjectStreamXReference extends AbstractXReference { private final int objectStreamIndex; private final COSObjectKey key; private final COSBase object; private final COSObjectKey parentKey; /** * Prepares a object stream entry reference for the given {@link COSObject} in a PDF's crossreference stream * ({@link PDFXRefStream}). * * @param objectStreamIndex The index of the {@link COSObject} in the containing object stream. * @param key The {@link COSObjectKey}, that is represented by this entry. * @param object The {@link COSObject}, that is represented by this entry. * @param parentKey The {@link COSObjectKey} of the object stream, that is containing the object. */ public ObjectStreamXReference(int objectStreamIndex, COSObjectKey key, COSBase object, COSObjectKey parentKey) { super(XReferenceType.OBJECT_STREAM_ENTRY); this.objectStreamIndex = objectStreamIndex; this.key = key; this.object = object; this.parentKey = parentKey; } /** * Returns the index of the {@link COSObject} in it's containing object stream. * * @return The index of the {@link COSObject} in it's containing object stream. */ public int getObjectStreamIndex() { return objectStreamIndex; } /** * Returns the {@link COSObjectKey} of the object, that is described by this crossreference stream entry. * * @return The {@link COSObjectKey} of the object, that is described by this crossreference stream entry. */ @Override public COSObjectKey getReferencedKey() { return key; } /** * Returns the {@link COSObject}, that is described by this crossreference stream entry. * * @return The {@link COSObject}, that is described by this crossreference stream entry. */ public COSBase getObject() { return object; } /** * Returns the {@link COSObjectKey} of the object stream, that is containing the object. * * @return The {@link COSObjectKey} of the object stream, that is containing the object. */ public COSObjectKey getParentKey() { return parentKey; } /** * Returns the value for the second column of the crossreference stream entry. (This is object number from the * {@link COSObjectKey} of the object stream, that is containing the object represented by this entry - for entries * of this type..) * * @return The value for the second column of the crossreference stream entry. */ @Override public long getSecondColumnValue() { return getParentKey().getNumber(); } /** * Returns the value for the third column of the crossreference stream entry. (This is index of the * {@link COSObject} in the containing object stream - for entries of this type.) * * @return The value for the third column of the crossreference stream entry. */ @Override public long getThirdColumnValue() { return getObjectStreamIndex(); } /** * Returns a string representation of this crossreference stream entry. * * @return A string representation of this crossreference stream entry. */ @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "ObjectStreamEntry{" + " key=" + key + ", type=" + getType().getNumericValue() + ", objectStreamIndex=" + objectStreamIndex + ", parent=" + parentKey + " }";
891
57
948
<methods>public int compareTo(org.apache.pdfbox.pdfparser.xref.XReferenceEntry) ,public long getFirstColumnValue() ,public org.apache.pdfbox.pdfparser.xref.XReferenceType getType() <variables>private final non-sealed org.apache.pdfbox.pdfparser.xref.XReferenceType type
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdfwriter/ContentStreamWriter.java
ContentStreamWriter
writeTokens
class ContentStreamWriter { private final OutputStream output; /** * space character. */ public static final byte[] SPACE = { 32 }; /** * standard line separator */ public static final byte[] EOL = { 0x0A }; /** * This will create a new content stream writer. * * @param out The stream to write the data to. */ public ContentStreamWriter( OutputStream out ) { output = out; } /** * Writes a single operand token. * * @param base The operand to write to the stream. * @throws IOException If there is an error writing to the stream. */ public void writeToken(COSBase base) throws IOException { writeObject(base); } /** * Writes a single operator token. * * @param op The operator to write to the stream. * @throws IOException If there is an error writing to the stream. */ public void writeToken(Operator op) throws IOException { writeObject(op); } /** * Writes a series of tokens followed by a new line. * * @param tokens The tokens to write to the stream. * @throws IOException If there is an error writing to the stream. */ public void writeTokens(Object... tokens) throws IOException {<FILL_FUNCTION_BODY>} /** * This will write out the list of tokens to the stream. * * @param tokens The tokens to write to the stream. * @throws IOException If there is an error writing to the stream. */ public void writeTokens( List<?> tokens ) throws IOException { for (Object token : tokens) { writeObject(token); } } private void writeObject(Object o) throws IOException { if (o instanceof COSBase) { writeObject((COSBase) o); } else if (o instanceof Operator) { writeObject((Operator) o); } else { throw new IOException("Error:Unknown type in content stream:" + o); } } private void writeObject(Operator op) throws IOException { if (op.getName().equals(OperatorName.BEGIN_INLINE_IMAGE)) { output.write(OperatorName.BEGIN_INLINE_IMAGE.getBytes(StandardCharsets.ISO_8859_1)); output.write(EOL); COSDictionary dic = op.getImageParameters(); for (COSName key : dic.keySet()) { COSBase value = dic.getDictionaryObject(key); key.writePDF(output); output.write(SPACE); writeObject(value); output.write(EOL); } output.write(OperatorName.BEGIN_INLINE_IMAGE_DATA.getBytes(StandardCharsets.ISO_8859_1)); output.write(EOL); output.write(op.getImageData()); output.write(EOL); output.write(OperatorName.END_INLINE_IMAGE.getBytes(StandardCharsets.ISO_8859_1)); output.write(EOL); } else { output.write(op.getName().getBytes(StandardCharsets.ISO_8859_1)); output.write(EOL); } } private void writeObject( COSBase o ) throws IOException { if( o instanceof COSString ) { COSWriter.writeString((COSString)o, output); output.write( SPACE ); } else if( o instanceof COSFloat ) { ((COSFloat)o).writePDF( output ); output.write( SPACE ); } else if( o instanceof COSInteger ) { ((COSInteger)o).writePDF( output ); output.write( SPACE ); } else if( o instanceof COSBoolean ) { ((COSBoolean)o).writePDF( output ); output.write( SPACE ); } else if( o instanceof COSName ) { ((COSName)o).writePDF( output ); output.write( SPACE ); } else if( o instanceof COSArray ) { COSArray array = (COSArray)o; output.write(COSWriter.ARRAY_OPEN); for( int i=0; i<array.size(); i++ ) { writeObject(array.get(i)); } output.write(COSWriter.ARRAY_CLOSE); output.write(SPACE); } else if( o instanceof COSDictionary ) { COSDictionary obj = (COSDictionary)o; output.write( COSWriter.DICT_OPEN ); for (Map.Entry<COSName, COSBase> entry : obj.entrySet()) { if (entry.getValue() != null) { writeObject(entry.getKey()); writeObject(entry.getValue()); } } output.write( COSWriter.DICT_CLOSE ); output.write( SPACE ); } else if (o instanceof COSNull) { output.write("null".getBytes(StandardCharsets.US_ASCII)); output.write(SPACE); } else { throw new IOException( "Error:Unknown type in content stream:" + o ); } } }
for (Object token : tokens) { writeObject(token); } output.write("\n".getBytes(StandardCharsets.US_ASCII));
1,435
46
1,481
<no_super_class>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdfwriter/compress/COSObjectPool.java
COSObjectPool
put
class COSObjectPool { private final Map<COSObjectKey, COSBase> keyPool = new HashMap<>(); private final Map<COSBase, COSObjectKey> objectPool = new HashMap<>(); private long highestXRefObjectNumber = 0; /** * Creates a map of {@link COSBase} instances to {@link COSObjectKey}s, allowing bidirectional lookups. This * constructor can be used for pre - initialized structures to start the assignment of new object numbers starting * from the hereby given offset. * * @param highestXRefObjectNumber The highest known object number. */ public COSObjectPool(long highestXRefObjectNumber) { this.highestXRefObjectNumber = Math.max(this.highestXRefObjectNumber, highestXRefObjectNumber); } /** * Update the key and object maps. * * @param key The key, that shall be added. * @param object The object, that shall be added. * @return The actual key, the object has been added for. */ public COSObjectKey put(COSObjectKey key, COSBase object) {<FILL_FUNCTION_BODY>} /** * Returns the {@link COSObjectKey} for a given registered {@link COSBase}. Returns null if such an object is not * registered. * * @param object The {@link COSBase} a {@link COSObjectKey} shall be determined for. * @return key The {@link COSObjectKey}, that matches the registered {@link COSBase}, or null if such an object is * not registered. */ public COSObjectKey getKey(COSBase object) { COSObjectKey key = null; if (object instanceof COSObject) { key = objectPool.get(((COSObject) object).getObject()); } if (key == null) { return objectPool.get(object); } return key; } /** * Returns true, if a {@link COSBase} is registered for the given {@link COSObjectKey}. * * @param key The {@link COSObjectKey} that shall be checked for a registered {@link COSBase}. * @return True, if a {@link COSBase} is registered for the given {@link COSObjectKey}. */ public boolean contains(COSObjectKey key) { return keyPool.containsKey(key); } /** * Returns the {@link COSBase}, that is registered for the given {@link COSObjectKey}, or null if no object is * registered for that key. * * @param key The {@link COSObjectKey} a registered {@link COSBase} shall be found for. * @return The {@link COSBase}, that is registered for the given {@link COSObjectKey}, or null if no object is * registered for that key. */ public COSBase getObject(COSObjectKey key) { return keyPool.get(key); } /** * Returns true, if the given {@link COSBase} is a registered object of this pool. * * @param object The {@link COSBase} that shall be checked. * @return True, if such a {@link COSBase} is registered in this pool. */ public boolean contains(COSBase object) { return (object instanceof COSObject && objectPool.containsKey(((COSObject) object).getObject())) || objectPool.containsKey(object); } /** * Returns the highest known object number (see: {@link COSObjectKey} for further information), that is currently * registered in this pool. * * @return The highest known object number (see: {@link COSObjectKey} for further information), that is currently * registered in this pool. */ public long getHighestXRefObjectNumber() { return highestXRefObjectNumber; } }
// to avoid to mixup indirect COSInteger objects holding the same value we have to check // if the given key is the same than the key which is stored for the "same" base object wihtin the object pool // the same is always true for COSFloat, COSBoolean and COSName and under certain circumstances for the remainig // types as well if (object == null || (contains(object) && getKey(object).equals(key))) { return null; } COSObjectKey actualKey = key; if (actualKey == null || contains(actualKey)) { highestXRefObjectNumber++; actualKey = new COSObjectKey(highestXRefObjectNumber, 0); object.setKey(actualKey); } else { highestXRefObjectNumber = Math.max(key.getNumber(), highestXRefObjectNumber); } keyPool.put(actualKey, object); objectPool.put(object, actualKey); return actualKey;
1,014
254
1,268
<no_super_class>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/DefaultResourceCache.java
DefaultResourceCache
getFont
class DefaultResourceCache implements ResourceCache { private final Map<COSObject, SoftReference<PDFont>> fonts = new HashMap<>(); private final Map<COSObject, SoftReference<PDColorSpace>> colorSpaces = new HashMap<>(); private final Map<COSObject, SoftReference<PDXObject>> xobjects = new HashMap<>(); private final Map<COSObject, SoftReference<PDExtendedGraphicsState>> extGStates = new HashMap<>(); private final Map<COSObject, SoftReference<PDShading>> shadings = new HashMap<>(); private final Map<COSObject, SoftReference<PDAbstractPattern>> patterns = new HashMap<>(); private final Map<COSObject, SoftReference<PDPropertyList>> properties = new HashMap<>(); @Override public PDFont getFont(COSObject indirect) {<FILL_FUNCTION_BODY>} @Override public void put(COSObject indirect, PDFont font) { fonts.put(indirect, new SoftReference<>(font)); } @Override public PDColorSpace getColorSpace(COSObject indirect) { SoftReference<PDColorSpace> colorSpace = colorSpaces.get(indirect); if (colorSpace != null) { return colorSpace.get(); } return null; } @Override public void put(COSObject indirect, PDColorSpace colorSpace) { colorSpaces.put(indirect, new SoftReference<>(colorSpace)); } @Override public PDExtendedGraphicsState getExtGState(COSObject indirect) { SoftReference<PDExtendedGraphicsState> extGState = extGStates.get(indirect); if (extGState != null) { return extGState.get(); } return null; } @Override public void put(COSObject indirect, PDExtendedGraphicsState extGState) { extGStates.put(indirect, new SoftReference<>(extGState)); } @Override public PDShading getShading(COSObject indirect) { SoftReference<PDShading> shading = shadings.get(indirect); if (shading != null) { return shading.get(); } return null; } @Override public void put(COSObject indirect, PDShading shading) { shadings.put(indirect, new SoftReference<>(shading)); } @Override public PDAbstractPattern getPattern(COSObject indirect) { SoftReference<PDAbstractPattern> pattern = patterns.get(indirect); if (pattern != null) { return pattern.get(); } return null; } @Override public void put(COSObject indirect, PDAbstractPattern pattern) { patterns.put(indirect, new SoftReference<>(pattern)); } @Override public PDPropertyList getProperties(COSObject indirect) { SoftReference<PDPropertyList> propertyList = properties.get(indirect); if (propertyList != null) { return propertyList.get(); } return null; } @Override public void put(COSObject indirect, PDPropertyList propertyList) { properties.put(indirect, new SoftReference<>(propertyList)); } @Override public PDXObject getXObject(COSObject indirect) { SoftReference<PDXObject> xobject = xobjects.get(indirect); if (xobject != null) { return xobject.get(); } return null; } @Override public void put(COSObject indirect, PDXObject xobject) { xobjects.put(indirect, new SoftReference<>(xobject)); } }
SoftReference<PDFont> font = fonts.get(indirect); if (font != null) { return font.get(); } return null;
1,035
47
1,082
<no_super_class>
apache_pdfbox
pdfbox/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/PDDestinationNameTreeNode.java
PDDestinationNameTreeNode
convertCOSToPD
class PDDestinationNameTreeNode extends PDNameTreeNode<PDPageDestination> { /** * Constructor. */ public PDDestinationNameTreeNode() { super(); } /** * Constructor. * * @param dic The COS dictionary. */ public PDDestinationNameTreeNode( COSDictionary dic ) { super(dic); } @Override protected PDPageDestination convertCOSToPD( COSBase base ) throws IOException {<FILL_FUNCTION_BODY>} @Override protected PDNameTreeNode<PDPageDestination> createChildNode( COSDictionary dic ) { return new PDDestinationNameTreeNode(dic); } }
COSBase destination = base; if( base instanceof COSDictionary ) { //the destination is sometimes stored in the D dictionary //entry instead of being directly an array, so just dereference //it for now destination = ((COSDictionary)base).getDictionaryObject( COSName.D ); } return (PDPageDestination)PDDestination.create( destination );
202
100
302
<methods>public org.apache.pdfbox.cos.COSDictionary getCOSObject() ,public List<PDNameTreeNode<org.apache.pdfbox.pdmodel.interactive.documentnavigation.destination.PDPageDestination>> getKids() ,public java.lang.String getLowerLimit() ,public Map<java.lang.String,org.apache.pdfbox.pdmodel.interactive.documentnavigation.destination.PDPageDestination> getNames() throws java.io.IOException,public PDNameTreeNode<org.apache.pdfbox.pdmodel.interactive.documentnavigation.destination.PDPageDestination> getParent() ,public java.lang.String getUpperLimit() ,public org.apache.pdfbox.pdmodel.interactive.documentnavigation.destination.PDPageDestination getValue(java.lang.String) throws java.io.IOException,public boolean isRootNode() ,public void setKids(List<? extends PDNameTreeNode<org.apache.pdfbox.pdmodel.interactive.documentnavigation.destination.PDPageDestination>>) ,public void setNames(Map<java.lang.String,org.apache.pdfbox.pdmodel.interactive.documentnavigation.destination.PDPageDestination>) ,public void setParent(PDNameTreeNode<org.apache.pdfbox.pdmodel.interactive.documentnavigation.destination.PDPageDestination>) <variables>private static final Logger LOG,private final non-sealed org.apache.pdfbox.cos.COSDictionary node,private PDNameTreeNode<org.apache.pdfbox.pdmodel.interactive.documentnavigation.destination.PDPageDestination> parent