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/pdfbox/src/main/java/org/apache/pdfbox/util/filetypedetector/FileTypeDetector.java
FileTypeDetector
detectFileType
class FileTypeDetector { private static final ByteTrie<FileType> root; static { root = new ByteTrie<>(); root.setDefaultValue(FileType.UNKNOWN); // https://en.wikipedia.org/wiki/List_of_file_signatures root.addPath(FileType.JPEG, new byte[]{(byte)0xff, (byte)0xd8}); root.addPath(FileType.TIFF, "II".getBytes(StandardCharsets.ISO_8859_1), new byte[]{0x2a, 0x00}); root.addPath(FileType.TIFF, "MM".getBytes(StandardCharsets.ISO_8859_1), new byte[]{0x00, 0x2a}); root.addPath(FileType.PSD, "8BPS".getBytes(StandardCharsets.ISO_8859_1)); root.addPath(FileType.PNG, new byte[]{(byte)0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52}); // TODO technically there are other very rare magic numbers for OS/2 BMP files... root.addPath(FileType.BMP, "BM".getBytes(StandardCharsets.ISO_8859_1)); root.addPath(FileType.GIF, "GIF87a".getBytes(StandardCharsets.ISO_8859_1)); root.addPath(FileType.GIF, "GIF89a".getBytes(StandardCharsets.ISO_8859_1)); root.addPath(FileType.ICO, new byte[]{0x00, 0x00, 0x01, 0x00}); // multiple PCX versions, explicitly listed root.addPath(FileType.PCX, new byte[]{0x0A, 0x00, 0x01}); root.addPath(FileType.PCX, new byte[]{0x0A, 0x02, 0x01}); root.addPath(FileType.PCX, new byte[]{0x0A, 0x03, 0x01}); root.addPath(FileType.PCX, new byte[]{0x0A, 0x05, 0x01}); root.addPath(FileType.RIFF, "RIFF".getBytes(StandardCharsets.ISO_8859_1)); // https://github.com/drewnoakes/metadata-extractor/issues/217 // root.addPath(FileType.ARW, "II".getBytes(StandardCharsets.ISO_8859_1), new byte[]{0x2a, 0x00, 0x08, 0x00}) root.addPath(FileType.CRW, "II".getBytes(StandardCharsets.ISO_8859_1), new byte[]{0x1a, 0x00, 0x00, 0x00}, "HEAPCCDR".getBytes(StandardCharsets.ISO_8859_1)); root.addPath(FileType.CR2, "II".getBytes(StandardCharsets.ISO_8859_1), new byte[]{0x2a, 0x00, 0x10, 0x00, 0x00, 0x00, 0x43, 0x52}); root.addPath(FileType.NEF, "MM".getBytes(StandardCharsets.ISO_8859_1), new byte[]{0x00, 0x2a, 0x00, 0x00, 0x00, (byte)0x80, 0x00}); root.addPath(FileType.ORF, "IIRO".getBytes(StandardCharsets.ISO_8859_1), new byte[]{(byte)0x08, 0x00}); root.addPath(FileType.ORF, "IIRS".getBytes(StandardCharsets.ISO_8859_1), new byte[]{(byte)0x08, 0x00}); root.addPath(FileType.RAF, "FUJIFILMCCD-RAW".getBytes(StandardCharsets.ISO_8859_1)); root.addPath(FileType.RW2, "II".getBytes(StandardCharsets.ISO_8859_1), new byte[]{0x55, 0x00}); } private FileTypeDetector() { } /** * Examines the a file's first bytes and estimates the file's type. * <p> * Requires a {@link BufferedInputStream} in order to mark and reset the stream to the position * at which it was provided to this method once completed. * <p> * Requires the stream to contain at least eight bytes. * * @param inputStream a buffered input stream of the file to examine. * @return the file type. * @throws IOException if an IO error occurred or the input stream ended unexpectedly. */ public static FileType detectFileType(final BufferedInputStream inputStream) throws IOException {<FILL_FUNCTION_BODY>} public static FileType detectFileType(final byte[] fileBytes) { return root.find(fileBytes); } }
if (!inputStream.markSupported()) { throw new IOException("Stream must support mark/reset"); } int maxByteCount = root.getMaxDepth(); inputStream.mark(maxByteCount); byte[] bytes = new byte[maxByteCount]; int bytesRead = inputStream.read(bytes); if (bytesRead == -1) { throw new IOException("Stream ended before file's magic number could be determined."); } inputStream.reset(); //noinspection ConstantConditions return root.find(bytes);
1,431
148
1,579
<no_super_class>
apache_pdfbox
pdfbox/tools/src/main/java/org/apache/pdfbox/tools/DecompressObjectstreams.java
DecompressObjectstreams
main
class DecompressObjectstreams implements Callable<Integer> { // Expected for CLI app to write to System.out/System.err @SuppressWarnings("squid:S106") private final PrintStream SYSERR; @Option(names = {"-h", "--help"}, usageHelp = true, description = "display this help message") boolean usageHelpRequested; @Option(names = {"-i", "--input"}, description = "the PDF file to decompress", required = true) private File infile; @Option(names = {"-o", "--output"}, description = "the decompressed PDF file. If omitted the original file is overwritten.") private File outfile; /** * Constructor. */ public DecompressObjectstreams() { SYSERR = System.err; } /** * This is the entry point for the application. * * @param args The command-line arguments. */ public static void main(String[] args) {<FILL_FUNCTION_BODY>} public Integer call() { try (PDDocument doc = Loader.loadPDF(infile)) { // overwrite inputfile if no outputfile was specified if (outfile == null) { outfile = infile; } doc.save(outfile, CompressParameters.NO_COMPRESSION); } catch (IOException ioe) { SYSERR.println("Error processing file [" + ioe.getClass().getSimpleName() + "]: " + ioe.getMessage()); return 4; } return 0; } }
// suppress the Dock icon on OS X System.setProperty("apple.awt.UIElement", "true"); int exitCode = new CommandLine(new DecompressObjectstreams()).execute(args); System.exit(exitCode);
430
63
493
<no_super_class>
apache_pdfbox
pdfbox/tools/src/main/java/org/apache/pdfbox/tools/Decrypt.java
Decrypt
call
class Decrypt implements Callable<Integer> { // Expected for CLI app to write to System.out/System.err @SuppressWarnings("squid:S106") private final PrintStream SYSERR; @Option(names = "-alias", description = "the alias to the certificate in the keystore.") private String alias; @Option(names = "-keyStore", description = "the path to the keystore that holds the certificate to decrypt the document. " + "This is only required if the document is encrypted with a certificate, otherwise only the password is required.") private String keyStore; @Option(names = "-password", arity="0..1", interactive = true, description = "the password for the PDF or certificate in keystore.") private String password; @Option(names = {"-i", "--input"}, description = "the PDF file to decrypt", required = true) private File infile; @Option(names = {"-o", "--output"}, description = "the decrypted PDF file. If omitted the original file is overwritten.") private File outfile; /** * Constructor. */ public Decrypt() { SYSERR = System.err; } /** * This is the entry point for the application. * * @param args The command-line arguments. * */ public static void main(String[] args) { // suppress the Dock icon on OS X System.setProperty("apple.awt.UIElement", "true"); int exitCode = new CommandLine(new Decrypt()).execute(args); System.exit(exitCode); } public Integer call() {<FILL_FUNCTION_BODY>} }
try (InputStream keyStoreStream = keyStore == null ? null : new FileInputStream(keyStore); PDDocument document = Loader.loadPDF(infile, password, keyStoreStream, alias)) { // overwrite inputfile if no outputfile was specified if (outfile == null) { outfile = infile; } if (document.isEncrypted()) { AccessPermission ap = document.getCurrentAccessPermission(); if(ap.isOwnerPermission()) { document.setAllSecurityToBeRemoved(true); document.save( outfile ); } else { SYSERR.println( "Error: You are only allowed to decrypt a document with the owner password."); return 1; } } else { SYSERR.println( "Error: Document is not encrypted."); return 1; } } catch (IOException ioe) { SYSERR.println( "Error decrypting document [" + ioe.getClass().getSimpleName() + "]: " + ioe.getMessage()); return 4; } return 0;
447
294
741
<no_super_class>
apache_pdfbox
pdfbox/tools/src/main/java/org/apache/pdfbox/tools/Encrypt.java
Encrypt
call
class Encrypt implements Callable<Integer> { // Expected for CLI app to write to System.out/System.err @SuppressWarnings("squid:S106") private final PrintStream SYSERR; @Option(names = "-O", description = "set the owner password (ignored if certFile is set)", arity = "0..1", interactive = true) private String ownerPassword; @Option(names = "-U", description = "set the user password (ignored if certFile is set)", arity = "0..1", interactive = true) private String userPassword; @Option(names = "-certFile", paramLabel="certFile", description = "Path to X.509 certificate (repeat both if needed)") private List<File> certFileList = new ArrayList<>(); @Option(names = "-canAssemble", description = "set the assemble permission (default: ${DEFAULT-VALUE})") private boolean canAssembleDocument = true; @Option(names = "-canExtractContent", description = "set the extraction permission (default: ${DEFAULT-VALUE})") private boolean canExtractContent = true; @Option(names = "-canExtractForAccessibility", description = "set the extraction permission (default: ${DEFAULT-VALUE})") private boolean canExtractForAccessibility = true; @Option(names = "-canFillInForm", description = "set the form fill in permission (default: ${DEFAULT-VALUE})") private boolean canFillInForm = true; @Option(names = "-canModify", description = "set the modify permission (default: ${DEFAULT-VALUE})") private boolean canModify = true; @Option(names = "-canModifyAnnotations", description = "set the modify annots permission (default: ${DEFAULT-VALUE})") private boolean canModifyAnnotations = true; @Option(names = "-canPrint", description = "set the print permission (default: ${DEFAULT-VALUE})") private boolean canPrint = true; @Option(names = "-canPrintFaithful", description = "set the print faithful permission (default: ${DEFAULT-VALUE})") private boolean canPrintFaithful = true; @Option(names = "-keyLength", description = "Key length in bits (valid values: 40, 128 or 256) (default: ${DEFAULT-VALUE})") private int keyLength = 256; @Option(names = {"-i", "--input"}, description = "the PDF file to encrypt", required = true) private File infile; @Option(names = {"-o", "--output"}, description = "the encrypted PDF file. If omitted the original file is overwritten.") private File outfile; /** * Constructor. */ public Encrypt() { SYSERR = System.err; } /** * This is the entry point for the application. * * @param args The command-line arguments. */ public static void main( String[] args ) { // suppress the Dock icon on OS X System.setProperty("apple.awt.UIElement", "true"); int exitCode = new CommandLine(new Encrypt()).execute(args); System.exit(exitCode); } public Integer call() {<FILL_FUNCTION_BODY>} }
AccessPermission ap = new AccessPermission(); ap.setCanAssembleDocument(canAssembleDocument); ap.setCanExtractContent(canExtractContent); ap.setCanExtractForAccessibility(canExtractForAccessibility); ap.setCanFillInForm(canFillInForm); ap.setCanModify(canModify); ap.setCanModifyAnnotations(canModifyAnnotations); ap.setCanPrint(canPrint); ap.setCanPrintFaithful(canPrintFaithful); if (outfile == null) { outfile = infile; } try (PDDocument document = Loader.loadPDF(infile)) { if( !document.isEncrypted() ) { if (!document.getSignatureDictionaries().isEmpty()) { SYSERR.println( "Warning: Document contains signatures which will be invalidated by encryption." ); } if (!certFileList.isEmpty()) { PublicKeyProtectionPolicy ppp = new PublicKeyProtectionPolicy(); PublicKeyRecipient recip = new PublicKeyRecipient(); recip.setPermission(ap); CertificateFactory cf = CertificateFactory.getInstance("X.509"); for (File certFile : certFileList) { try (InputStream inStream = new FileInputStream(certFile)) { X509Certificate certificate = (X509Certificate) cf.generateCertificate(inStream); recip.setX509(certificate); } ppp.addRecipient(recip); } ppp.setEncryptionKeyLength(keyLength); document.protect(ppp); } else { StandardProtectionPolicy spp = new StandardProtectionPolicy(ownerPassword, userPassword, ap); spp.setEncryptionKeyLength(keyLength); document.protect(spp); } document.save( outfile ); } else { SYSERR.println( "Error: Document is already encrypted." ); } } catch (IOException | CertificateException ex) { SYSERR.println( "Error encrypting PDF [" + ex.getClass().getSimpleName() + "]: " + ex.getMessage()); return 4; } return 0;
848
602
1,450
<no_super_class>
apache_pdfbox
pdfbox/tools/src/main/java/org/apache/pdfbox/tools/ExportFDF.java
ExportFDF
call
class ExportFDF implements Callable<Integer> { // Expected for CLI app to write to System.out/System.err @SuppressWarnings("squid:S106") private final PrintStream SYSERR; @Option(names = {"-i", "--input"}, description = "the PDF file to export", required = true) private File infile; @Option(names = {"-o", "--output"}, description = "the FDF data file", required = true) private File outfile; /** * Constructor. */ public ExportFDF() { SYSERR = System.err; } /** * This is the entry point for the application. * * @param args The command-line arguments. * */ public static void main(String[] args) { // suppress the Dock icon on OS X System.setProperty("apple.awt.UIElement", "true"); int exitCode = new CommandLine(new ExportFDF()).execute(args); System.exit(exitCode); } public Integer call() {<FILL_FUNCTION_BODY>} }
try (PDDocument pdf = Loader.loadPDF(infile)) { PDAcroForm form = pdf.getDocumentCatalog().getAcroForm(); if( form == null ) { SYSERR.println( "Error: This PDF does not contain a form." ); return 1; } else { if (outfile == null) { String outPath = FilenameUtils.removeExtension(infile.getAbsolutePath()) + ".fdf"; outfile = new File(outPath); } try (FDFDocument fdf = form.exportFDF()) { fdf.save( outfile ); } } } catch (IOException ioe) { SYSERR.println( "Error exporting FDF data [" + ioe.getClass().getSimpleName() + "]: " + ioe.getMessage()); return 4; } return 0;
306
244
550
<no_super_class>
apache_pdfbox
pdfbox/tools/src/main/java/org/apache/pdfbox/tools/ExportXFDF.java
ExportXFDF
call
class ExportXFDF implements Callable<Integer> { // Expected for CLI app to write to System.out/System.err @SuppressWarnings("squid:S106") private final PrintStream SYSERR; @Option(names = {"-i", "--input"}, description = "the PDF file to export", required = true) private File infile; @Option(names = {"-o", "--output"}, description = "the XFDF data file", required = true) private File outfile; /** * Constructor. */ public ExportXFDF() { SYSERR = System.err; } /** * This is the entry point for the application. * * @param args The command-line arguments. * */ public static void main(String[] args) { // suppress the Dock icon on OS X System.setProperty("apple.awt.UIElement", "true"); int exitCode = new CommandLine(new ExportXFDF()).execute(args); System.exit(exitCode); } public Integer call() {<FILL_FUNCTION_BODY>} }
try (PDDocument pdf = Loader.loadPDF(infile)) { PDAcroForm form = pdf.getDocumentCatalog().getAcroForm(); if( form == null ) { SYSERR.println( "Error: This PDF does not contain a form." ); } else { if (outfile == null) { String outPath = FilenameUtils.removeExtension(infile.getAbsolutePath()) + ".xfdf"; outfile = new File(outPath); } try (FDFDocument fdf = form.exportFDF()) { fdf.saveXFDF(outfile); } } } catch (IOException ioe) { SYSERR.println( "Error exporting XFDF data [" + ioe.getClass().getSimpleName() + "]: " + ioe.getMessage()); return 4; } return 0;
310
244
554
<no_super_class>
apache_pdfbox
pdfbox/tools/src/main/java/org/apache/pdfbox/tools/ExtractXMP.java
ExtractXMP
call
class ExtractXMP implements Callable<Integer> { // Expected for CLI app to write to System.out/System.err @SuppressWarnings("squid:S106") private final PrintStream SYSOUT; @SuppressWarnings("squid:S106") private final PrintStream SYSERR; @CommandLine.Option(names = "-page", description = "extract the XMP information from a specific page (1 based)") private int page = 0; @CommandLine.Option(names = "-password", description = "the password for the PDF or certificate in keystore.", arity = "0..1", interactive = true) private String password = ""; @CommandLine.Option(names = "-console", description = "Send text to console instead of file") private boolean toConsole = false; @CommandLine.Option(names = {"-i", "--input"}, description = "the PDF file", required = true) private File infile; @CommandLine.Option(names = {"-o", "--output"}, description = "the exported text file") private File outfile; /** * Constructor. */ public ExtractXMP() { SYSOUT = System.out; SYSERR = System.err; } /** * Infamous main method. * * @param args Command line arguments, should be one and a reference to a file. */ public static void main(String[] args) { // suppress the Dock icon on OS X System.setProperty("apple.awt.UIElement", "true"); int exitCode = new CommandLine(new ExtractXMP()).execute(args); System.exit(exitCode); } /** * Starts the xmp extraction. */ @Override public Integer call() {<FILL_FUNCTION_BODY>} }
if (outfile == null) { String outPath = FilenameUtils.removeExtension(infile.getAbsolutePath()) + ".xml"; outfile = new File(outPath); } try (PDDocument document = Loader.loadPDF(infile, password)) { PDDocumentCatalog catalog = document.getDocumentCatalog(); PDMetadata meta; if (page == 0) { meta = catalog.getMetadata(); } else { if (page > document.getNumberOfPages()) { SYSERR.println("Page " + page + " doesn't exist"); return 1; } meta = document.getPage(page - 1).getMetadata(); } if (meta == null) { SYSERR.println("No XMP metadata available"); return 1; } try (PrintStream ps = toConsole ? SYSOUT : new PrintStream(outfile)) { ps.write(meta.toByteArray()); } } catch (IOException ioe) { SYSERR.println( "Error extracting text for document [" + ioe.getClass().getSimpleName() + "]: " + ioe.getMessage()); return 4; } return 0;
487
336
823
<no_super_class>
apache_pdfbox
pdfbox/tools/src/main/java/org/apache/pdfbox/tools/ImageToPDF.java
ImageToPDF
createRectangle
class ImageToPDF implements Callable<Integer> { private PDRectangle mediaBox = PDRectangle.LETTER; // Expected for CLI app to write to System.out/System.err @SuppressWarnings("squid:S106") private final PrintStream SYSERR; @Option(names = "-autoOrientation", description = "set orientation depending of image proportion") private boolean autoOrientation = false; @Option(names = "-landscape", description = "set orientation to landscape") private boolean landscape = false; @Option(names = "-pageSize", description = "the page size to use: Letter, Legal, A0, A1, A2, A3, A4, A5, A6 (default: ${DEFAULT-VALUE})") private String pageSize = "Letter"; @Option(names = "-resize", description = "resize to page size") private boolean resize = false; @Option(names = {"-i", "--input"}, description = "the image files to convert", paramLabel="image-file", required = true) private File[] infiles; @Option(names = {"-o", "--output"}, description = "the generated PDF file", required = true) private File outfile; /** * Constructor. */ public ImageToPDF() { SYSERR = System.err; } public static void main(String[] args) { // suppress the Dock icon on OS X System.setProperty("apple.awt.UIElement", "true"); int exitCode = new CommandLine(new ImageToPDF()).execute(args); System.exit(exitCode); } public Integer call() { setMediaBox(createRectangle(pageSize)); try (PDDocument doc = new PDDocument()) { for (File imageFile : infiles) { PDImageXObject pdImage = PDImageXObject.createFromFile(imageFile.getAbsolutePath(), doc); PDRectangle actualMediaBox = mediaBox; if ((autoOrientation && pdImage.getWidth() > pdImage.getHeight()) || landscape) { actualMediaBox = new PDRectangle(mediaBox.getHeight(), mediaBox.getWidth()); } PDPage page = new PDPage(actualMediaBox); doc.addPage(page); try (PDPageContentStream contents = new PDPageContentStream(doc, page)) { if (resize) { contents.drawImage(pdImage, 0, 0, actualMediaBox.getWidth(), actualMediaBox.getHeight()); } else { contents.drawImage(pdImage, 0, 0, pdImage.getWidth(), pdImage.getHeight()); } } } doc.save(outfile); } catch (IOException ioe) { SYSERR.println( "Error converting image to PDF [" + ioe.getClass().getSimpleName() + "]: " + ioe.getMessage()); return 4; } return 0; } private static PDRectangle createRectangle(String paperSize) {<FILL_FUNCTION_BODY>} /** * Sets page size of produced PDF. * * @return returns the page size (media box) */ public PDRectangle getMediaBox() { return mediaBox; } /** * Sets page size of produced PDF. * * @param mediaBox the media box of the PDF document. */ public void setMediaBox(PDRectangle mediaBox) { this.mediaBox = mediaBox; } /** * Tells the paper orientation. * * @return true for landscape orientation */ public boolean isLandscape() { return landscape; } /** * Sets paper orientation. * * @param landscape use landscape orientation. */ public void setLandscape(boolean landscape) { this.landscape = landscape; } /** * Gets whether page orientation (portrait / landscape) should be decided automatically for each * page depending on image proportion. * * @return true if auto, false if not. */ public boolean isAutoOrientation() { return autoOrientation; } /** * Sets whether page orientation (portrait / landscape) should be decided automatically for each * page depending on image proportion. * * @param autoOrientation true if auto, false if not. */ public void setAutoOrientation(boolean autoOrientation) { this.autoOrientation = autoOrientation; } }
if ("letter".equalsIgnoreCase(paperSize)) { return PDRectangle.LETTER; } else if ("legal".equalsIgnoreCase(paperSize)) { return PDRectangle.LEGAL; } else if ("A0".equalsIgnoreCase(paperSize)) { return PDRectangle.A0; } else if ("A1".equalsIgnoreCase(paperSize)) { return PDRectangle.A1; } else if ("A2".equalsIgnoreCase(paperSize)) { return PDRectangle.A2; } else if ("A3".equalsIgnoreCase(paperSize)) { return PDRectangle.A3; } else if ("A4".equalsIgnoreCase(paperSize)) { return PDRectangle.A4; } else if ("A5".equalsIgnoreCase(paperSize)) { return PDRectangle.A5; } else if ("A6".equalsIgnoreCase(paperSize)) { return PDRectangle.A6; } else { // return default if wron size was specified return PDRectangle.LETTER; }
1,208
320
1,528
<no_super_class>
apache_pdfbox
pdfbox/tools/src/main/java/org/apache/pdfbox/tools/ImportFDF.java
ImportFDF
call
class ImportFDF implements Callable<Integer> { // Expected for CLI app to write to System.out/System.err @SuppressWarnings("squid:S106") private final PrintStream SYSERR; @Option(names = {"-i", "--input"}, description = "the PDF file to import to", required = true) private File infile; @Option(names = {"-o", "--output"}, description = "the PDF file to save to. If omitted the original file will be used") private File outfile; @Option(names = {"--data"}, description = "the FDF data file to import from", required = true) private File fdffile; /** * This will takes the values from the fdf document and import them into the * PDF document. * * @param pdfDocument The document to put the fdf data into. * @param fdfDocument The FDF document to get the data from. * * @throws IOException If there is an error setting the data in the field. */ public void importFDF( PDDocument pdfDocument, FDFDocument fdfDocument ) throws IOException { PDDocumentCatalog docCatalog = pdfDocument.getDocumentCatalog(); PDAcroForm acroForm = docCatalog.getAcroForm(); if (acroForm == null) { return; } acroForm.setCacheFields( true ); acroForm.importFDF( fdfDocument ); //TODO this can be removed when we create appearance streams acroForm.setNeedAppearances(true); } /** * Constructor. */ public ImportFDF() { SYSERR = System.err; } /** * This will import an fdf document and write out another pdf. <br> * see usage() for commandline * * @param args command line arguments */ public static void main(String[] args) { // suppress the Dock icon on OS X System.setProperty("apple.awt.UIElement", "true"); int exitCode = new CommandLine(new ImportFDF()).execute(args); System.exit(exitCode); } public Integer call() {<FILL_FUNCTION_BODY>} }
ImportFDF importer = new ImportFDF(); try (PDDocument pdf = Loader.loadPDF(infile); FDFDocument fdf = Loader.loadFDF(fdffile)) { importer.importFDF( pdf, fdf ); if (outfile == null) { outfile = infile; } pdf.save(outfile); } catch (IOException ioe) { SYSERR.println( "Error importing FDF data [" + ioe.getClass().getSimpleName() + "]: " + ioe.getMessage()); return 4; } return 0;
591
171
762
<no_super_class>
apache_pdfbox
pdfbox/tools/src/main/java/org/apache/pdfbox/tools/ImportXFDF.java
ImportXFDF
call
class ImportXFDF implements Callable<Integer> { // Expected for CLI app to write to System.out/System.err @SuppressWarnings("squid:S106") private final PrintStream SYSERR; @Option(names = {"-i", "--input"}, description = "the PDF file to import to", required = true) private File infile; @Option(names = {"-o", "--output"}, description = "the PDF file to save to. If omitted the original file will be used") private File outfile; @Option(names = {"--data"}, description = "the XFDF data file to import from", required = true) private File xfdffile; /** * This will takes the values from the fdf document and import them into the * PDF document. * * @param pdfDocument The document to put the fdf data into. * @param fdfDocument The FDF document to get the data from. * * @throws IOException If there is an error setting the data in the field. */ public void importFDF( PDDocument pdfDocument, FDFDocument fdfDocument ) throws IOException { PDDocumentCatalog docCatalog = pdfDocument.getDocumentCatalog(); PDAcroForm acroForm = docCatalog.getAcroForm(); acroForm.setCacheFields( true ); acroForm.importFDF( fdfDocument ); } /** * Constructor. */ public ImportXFDF() { SYSERR = System.err; } /** * This will import an fdf document and write out another pdf. <br> * see usage() for commandline * * @param args command line arguments */ public static void main(String[] args) { // suppress the Dock icon on OS X System.setProperty("apple.awt.UIElement", "true"); int exitCode = new CommandLine(new ImportXFDF()).execute(args); System.exit(exitCode); } public Integer call() {<FILL_FUNCTION_BODY>} }
ImportXFDF importer = new ImportXFDF(); try (PDDocument pdf = Loader.loadPDF(infile); FDFDocument fdf = Loader.loadXFDF(xfdffile)) { importer.importFDF( pdf, fdf ); if (outfile == null) { outfile = infile; } pdf.save(outfile); } catch (IOException ioe) { SYSERR.println( "Error importing XFDF data [" + ioe.getClass().getSimpleName() + "]: " + ioe.getMessage()); return 4; } return 0;
544
175
719
<no_super_class>
apache_pdfbox
pdfbox/tools/src/main/java/org/apache/pdfbox/tools/OverlayPDF.java
OverlayPDF
call
class OverlayPDF implements Callable<Integer> { // Expected for CLI app to write to System.out/System.err @SuppressWarnings("squid:S106") private final PrintStream SYSERR; @Option(names = "-odd", description = "overlay file used for odd pages") private File oddPageOverlay; @Option(names = "-even", description = "overlay file used for even pages") private File evenPageOverlay; @Option(names = "-first", description = "overlay file used for the first page") private File firstPageOverlay; @Option(names = "-last", description = "overlay file used for the last page") private File lastPageOverlay; @Option(names = "-useAllPages", description = "overlay file used for overlay, all pages are used by simply repeating them") private File useAllPages; @Option(names = "-page", description = "overlay file used for the given page number, may occur more than once") Map<Integer, String> specificPageOverlayFile = new HashMap<>(); @Option(names = {"-default"}, description = "the default overlay file") private File defaultOverlay; @Option(names = "-position", description = "where to put the overlay file: foreground or background (default: ${DEFAULT-VALUE})") private Position position = Position.BACKGROUND; @Option(names = {"-i", "--input"}, description = "the PDF input file", required = true) private File infile; @Option(names = {"-o", "--output"}, description = "the PDF output file", required = true) private File outfile; /** * Constructor. */ public OverlayPDF() { SYSERR = System.err; } /** * This will overlay a document and write out the results. * * @param args command line arguments */ public static void main(final String[] args) { // suppress the Dock icon on OS X System.setProperty("apple.awt.UIElement", "true"); int exitCode = new CommandLine(new OverlayPDF()).execute(args); System.exit(exitCode); } @Override public Integer call() {<FILL_FUNCTION_BODY>} }
int retcode = 0; Overlay overlayer = new Overlay(); overlayer.setOverlayPosition(position); if (firstPageOverlay != null) { overlayer.setFirstPageOverlayFile(firstPageOverlay.getAbsolutePath()); } if (lastPageOverlay != null) { overlayer.setLastPageOverlayFile(lastPageOverlay.getAbsolutePath()); } if (oddPageOverlay != null) { overlayer.setOddPageOverlayFile(oddPageOverlay.getAbsolutePath()); } if (evenPageOverlay != null) { overlayer.setEvenPageOverlayFile(evenPageOverlay.getAbsolutePath()); } if (useAllPages != null) { overlayer.setAllPagesOverlayFile(useAllPages.getAbsolutePath()); } if (defaultOverlay != null) { overlayer.setDefaultOverlayFile(defaultOverlay.getAbsolutePath()); } if (infile != null) { overlayer.setInputFile(infile.getAbsolutePath()); } try (PDDocument result = overlayer.overlay(specificPageOverlayFile)) { result.save(outfile); } catch (IOException ioe) { SYSERR.println( "Error adding overlay(s) to PDF [" + ioe.getClass().getSimpleName() + "]: " + ioe.getMessage()); return 4; } finally { // close the input files AFTER saving the resulting file as some // streams are shared among the input and the output files try { overlayer.close(); } catch (IOException ioe) { SYSERR.println( "Error adding overlay(s) to PDF [" + ioe.getClass().getSimpleName() + "]: " + ioe.getMessage()); retcode = 4; } } return retcode;
599
531
1,130
<no_super_class>
apache_pdfbox
pdfbox/tools/src/main/java/org/apache/pdfbox/tools/PDFBox.java
PDFBox
main
class PDFBox implements Runnable { @Spec CommandLine.Model.CommandSpec spec; /** * Main method. * * @param args command line arguments */ public static void main(String[] args) {<FILL_FUNCTION_BODY>} @Override public void run() { throw new ParameterException(spec.commandLine(), "Error: Subcommand required"); } }
// suppress the Dock icon on OS X System.setProperty("apple.awt.UIElement", "true"); CommandLine commandLine = new CommandLine(new PDFBox()).setSubcommandsCaseInsensitive(true); if (!GraphicsEnvironment.isHeadless()) { commandLine.addSubcommand("debug", PDFDebugger.class); } commandLine.addSubcommand("decrypt", Decrypt.class); commandLine.addSubcommand("encrypt", Encrypt.class); commandLine.addSubcommand("decode", WriteDecodedDoc.class); commandLine.addSubcommand("export:images", ExtractImages.class); commandLine.addSubcommand("export:xmp", ExtractXMP.class); commandLine.addSubcommand("export:text", ExtractText.class); commandLine.addSubcommand("export:fdf", ExportFDF.class); commandLine.addSubcommand("export:xfdf", ExportXFDF.class); commandLine.addSubcommand("import:fdf", ImportFDF.class); commandLine.addSubcommand("import:xfdf", ImportXFDF.class); commandLine.addSubcommand("overlay", OverlayPDF.class); commandLine.addSubcommand("print", PrintPDF.class); commandLine.addSubcommand("render", PDFToImage.class); commandLine.addSubcommand("merge", PDFMerger.class); commandLine.addSubcommand("split", PDFSplit.class); commandLine.addSubcommand("fromimage", ImageToPDF.class); commandLine.addSubcommand("fromtext", TextToPDF.class); commandLine.addSubcommand("version", Version.class); commandLine.addSubcommand("help", CommandLine.HelpCommand.class); commandLine.execute(args);
114
452
566
<no_super_class>
apache_pdfbox
pdfbox/tools/src/main/java/org/apache/pdfbox/tools/PDFMerger.java
PDFMerger
main
class PDFMerger implements Callable<Integer> { // Expected for CLI app to write to System.out/System.err @SuppressWarnings("squid:S106") private final PrintStream SYSERR; @Option(names = {"-i", "--input"}, description = "the PDF files to merge.", paramLabel = "<infile>", required = true) private File[] infiles; @Option(names = {"-o", "--output"}, description = "the merged PDF file.", required = true) private File outfile; /** * Constructor. */ public PDFMerger() { SYSERR = System.err; } /** * Infamous main method. * * @param args Command line arguments, should be at least 3. */ public static void main( String[] args ) {<FILL_FUNCTION_BODY>} public Integer call() { PDFMergerUtility merger = new PDFMergerUtility(); try { for (File infile : infiles) { merger.addSource(infile); } merger.setDestinationFileName(outfile.getAbsolutePath()); merger.mergeDocuments(IOUtils.createMemoryOnlyStreamCache()); } catch (IOException ioe) { SYSERR.println( "Error merging documents [" + ioe.getClass().getSimpleName() + "]: " + ioe.getMessage()); return 4; } return 0; } }
// suppress the Dock icon on OS X System.setProperty("apple.awt.UIElement", "true"); int exitCode = new CommandLine(new PDFMerger()).execute(args); System.exit(exitCode);
410
61
471
<no_super_class>
apache_pdfbox
pdfbox/tools/src/main/java/org/apache/pdfbox/tools/PDFSplit.java
PDFSplit
call
class PDFSplit implements Callable<Integer> { // Expected for CLI app to write to System.out/System.err @SuppressWarnings("squid:S106") private final PrintStream SYSERR; @Option(names = "-password", description = "the password to decrypt the document.", arity = "0..1", interactive = true) private String password; @Option(names = "-split", description = "split after this many pages (default 1, if startPage and endPage are unset).") private int split = -1; @Option(names = "-startPage", description = "start page.") private int startPage = -1; @Option(names = "-endPage", description = "end page.") private int endPage = -1; @Option(names = "-outputPrefix", description = "the filename prefix for split files.") private String outputPrefix; @Option(names = {"-i", "--input"}, description = "the PDF file to split", required = true) private File infile; /** * Constructor. */ public PDFSplit() { SYSERR = System.err; } /** * Infamous main method. * * @param args Command line arguments, should be one and a reference to a file. */ public static void main( String[] args ) { // suppress the Dock icon on OS X System.setProperty("apple.awt.UIElement", "true"); int exitCode = new CommandLine(new PDFSplit()).execute(args); System.exit(exitCode); } public Integer call() {<FILL_FUNCTION_BODY>} }
Splitter splitter = new Splitter(); if (outputPrefix == null) { outputPrefix = FilenameUtils.removeExtension(infile.getAbsolutePath()); } List<PDDocument> documents = null; try (PDDocument document = Loader.loadPDF(infile, password)) { boolean startEndPageSet = false; if (startPage != -1) { splitter.setStartPage(startPage); startEndPageSet = true; if (split == -1) { int numberOfPages = document.getNumberOfPages(); splitter.setSplitAtPage(numberOfPages); } } if (endPage != -1) { splitter.setEndPage(endPage); startEndPageSet = true; if (split == -1) { splitter.setSplitAtPage(endPage); } } if (split != -1) { splitter.setSplitAtPage(split); } else { if (!startEndPageSet) { splitter.setSplitAtPage(1); } } documents = splitter.split( document ); for( int i=0; i<documents.size(); i++ ) { try (PDDocument doc = documents.get(i)) { doc.save(outputPrefix + "-" + (i + 1) + ".pdf"); } } } catch (IOException ioe) { SYSERR.println( "Error splitting document [" + ioe.getClass().getSimpleName() + "]: " + ioe.getMessage()); return 4; } finally { if (documents != null) { documents.forEach(IOUtils::closeQuietly); } } return 0;
438
493
931
<no_super_class>
apache_pdfbox
pdfbox/tools/src/main/java/org/apache/pdfbox/tools/PDFText2HTML.java
FontState
closeUntil
class FontState { private final List<String> stateList = new ArrayList<>(); private final Set<String> stateSet = new HashSet<>(); /** * Pushes new {@link TextPosition TextPositions} into the font state. The state is only * preserved correctly for each letter if the number of letters in <code>text</code> matches * the number of {@link TextPosition} objects. Otherwise, it's done once for the complete * array (just by looking at its first entry). * * @return A string that contains the text including tag changes caused by its font state. */ public String push(String text, List<TextPosition> textPositions) { StringBuilder buffer = new StringBuilder(); if (text.length() == textPositions.size()) { // There is a 1:1 mapping, and we can use the TextPositions directly for (int i = 0; i < text.length(); i++) { push(buffer, text.charAt(i), textPositions.get(i)); } } else if (!text.isEmpty()) { // The normalized text does not match the number of TextPositions, so we'll just // have a look at its first entry. // TODO change PDFTextStripper.normalize() such that it maintains the 1:1 relation if (textPositions.isEmpty()) { return text; } push(buffer, text.charAt(0), textPositions.get(0)); buffer.append(escape(text.substring(1))); } return buffer.toString(); } /** * Closes all open states. * @return A string that contains the closing tags of all currently open states. */ public String clear() { StringBuilder buffer = new StringBuilder(); closeUntil(buffer, null); stateList.clear(); stateSet.clear(); return buffer.toString(); } protected String push(StringBuilder buffer, char character, TextPosition textPosition) { boolean bold = false; boolean italics = false; PDFontDescriptor descriptor = textPosition.getFont().getFontDescriptor(); if (descriptor != null) { bold = isBold(descriptor); italics = isItalic(descriptor); } buffer.append(bold ? open("b") : close("b")); buffer.append(italics ? open("i") : close("i")); appendEscaped(buffer, character); return buffer.toString(); } private String open(String tag) { if (stateSet.contains(tag)) { return ""; } stateList.add(tag); stateSet.add(tag); return openTag(tag); } private String close(String tag) { if (!stateSet.contains(tag)) { return ""; } // Close all tags until (but including) the one we should close StringBuilder tagsBuilder = new StringBuilder(); int index = closeUntil(tagsBuilder, tag); // Remove from state stateList.remove(index); stateSet.remove(tag); // Now open the states that were closed but should remain open again for (; index < stateList.size(); index++) { tagsBuilder.append(openTag(stateList.get(index))); } return tagsBuilder.toString(); } private int closeUntil(StringBuilder tagsBuilder, String endTag) {<FILL_FUNCTION_BODY>} private String openTag(String tag) { return "<" + tag + ">"; } private String closeTag(String tag) { return "</" + tag + ">"; } private boolean isBold(PDFontDescriptor descriptor) { if (descriptor.isForceBold()) { return true; } return descriptor.getFontName().contains("Bold"); } private boolean isItalic(PDFontDescriptor descriptor) { if (descriptor.isItalic()) { return true; } return descriptor.getFontName().contains("Italic"); } }
for (int i = stateList.size(); i-- > 0;) { String tag = stateList.get(i); tagsBuilder.append(closeTag(tag)); if (endTag != null && tag.equals(endTag)) { return i; } } return -1;
1,082
84
1,166
<methods>public void <init>() ,public boolean getAddMoreFormatting() ,public java.lang.String getArticleEnd() ,public java.lang.String getArticleStart() ,public float getAverageCharTolerance() ,public float getDropThreshold() ,public org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem getEndBookmark() ,public int getEndPage() ,public float getIndentThreshold() ,public java.lang.String getLineSeparator() ,public java.lang.String getPageEnd() ,public java.lang.String getPageStart() ,public java.lang.String getParagraphEnd() ,public java.lang.String getParagraphStart() ,public boolean getSeparateByBeads() ,public boolean getSortByPosition() ,public float getSpacingTolerance() ,public org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem getStartBookmark() ,public int getStartPage() ,public boolean getSuppressDuplicateOverlappingText() ,public java.lang.String getText(org.apache.pdfbox.pdmodel.PDDocument) throws java.io.IOException,public java.lang.String getWordSeparator() ,public void processPage(org.apache.pdfbox.pdmodel.PDPage) throws java.io.IOException,public void setAddMoreFormatting(boolean) ,public void setArticleEnd(java.lang.String) ,public void setArticleStart(java.lang.String) ,public void setAverageCharTolerance(float) ,public void setDropThreshold(float) ,public void setEndBookmark(org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem) ,public void setEndPage(int) ,public void setIndentThreshold(float) ,public void setLineSeparator(java.lang.String) ,public void setPageEnd(java.lang.String) ,public void setPageStart(java.lang.String) ,public void setParagraphEnd(java.lang.String) ,public void setParagraphStart(java.lang.String) ,public void setShouldSeparateByBeads(boolean) ,public void setSortByPosition(boolean) ,public void setSpacingTolerance(float) ,public void setStartBookmark(org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem) ,public void setStartPage(int) ,public void setSuppressDuplicateOverlappingText(boolean) ,public void setWordSeparator(java.lang.String) ,public void writeText(org.apache.pdfbox.pdmodel.PDDocument, java.io.Writer) throws java.io.IOException<variables>private static final float END_OF_LAST_TEXT_X_RESET_VALUE,private static final float EXPECTED_START_OF_NEXT_WORD_X_RESET_VALUE,private static final float LAST_WORD_SPACING_RESET_VALUE,protected static final java.lang.String LINE_SEPARATOR,private static final java.lang.String[] LIST_ITEM_EXPRESSIONS,private static final Logger LOG,private static final float MAX_HEIGHT_FOR_LINE_RESET_VALUE,private static final float MAX_Y_FOR_LINE_RESET_VALUE,private static final float MIN_Y_TOP_FOR_LINE_RESET_VALUE,private static final Map<java.lang.Character,java.lang.Character> MIRRORING_CHAR_MAP,private boolean addMoreFormatting,private java.lang.String articleEnd,private java.lang.String articleStart,private float averageCharTolerance,private List<org.apache.pdfbox.pdmodel.common.PDRectangle> beadRectangles,private final Map<java.lang.String,TreeMap<java.lang.Float,TreeSet<java.lang.Float>>> characterListMapping,protected ArrayList<List<org.apache.pdfbox.text.TextPosition>> charactersByArticle,private int currentPageNo,private static float defaultDropThreshold,private static float defaultIndentThreshold,protected org.apache.pdfbox.pdmodel.PDDocument document,private float dropThreshold,private org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem endBookmark,private int endBookmarkPageNumber,private int endPage,private boolean inParagraph,private float indentThreshold,private java.lang.String lineSeparator,private List<java.util.regex.Pattern> listOfPatterns,protected java.io.Writer output,private java.lang.String pageEnd,private java.lang.String pageStart,private java.lang.String paragraphEnd,private java.lang.String paragraphStart,private boolean shouldSeparateByBeads,private boolean sortByPosition,private float spacingTolerance,private org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem startBookmark,private int startBookmarkPageNumber,private int startPage,private boolean suppressDuplicateOverlappingText,private java.lang.String wordSeparator
apache_pdfbox
pdfbox/tools/src/main/java/org/apache/pdfbox/tools/PDFText2Markdown.java
FontState
isItalic
class FontState { private final List<String> stateList = new ArrayList<>(); private final Set<String> stateSet = new HashSet<>(); /** * Pushes new {@link TextPosition TextPositions} into the font state. The state is only * preserved correctly for each letter if the number of letters in <code>text</code> matches * the number of {@link TextPosition} objects. Otherwise, it's done once for the complete * array (just by looking at its first entry). * * @return A string that contains the text including tag changes caused by its font state. */ public String push(String text, List<TextPosition> textPositions) { StringBuilder buffer = new StringBuilder(); if (text.length() == textPositions.size()) { // There is a 1:1 mapping, and we can use the TextPositions directly for (int i = 0; i < text.length(); i++) { push(buffer, text.charAt(i), textPositions.get(i)); } } else if (!text.isEmpty()) { // The normalized text does not match the number of TextPositions, so we'll just // have a look at its first entry. // TODO change PDFTextStripper.normalize() such that it maintains the 1:1 relation if (textPositions.isEmpty()) { return text; } push(buffer, text.charAt(0), textPositions.get(0)); buffer.append(escape(text.substring(1))); } return buffer.toString(); } /** * Closes all open Markdown formatting. * * @return A string that contains the closing tags of all currently open Markdown * formatting. */ public String clear() { StringBuilder buffer = new StringBuilder(); closeUntil(buffer, null); stateList.clear(); stateSet.clear(); return buffer.toString(); } protected String push(StringBuilder buffer, char character, TextPosition textPosition) { boolean bold = false; boolean italics = false; PDFontDescriptor descriptor = textPosition.getFont().getFontDescriptor(); if (descriptor != null) { bold = isBold(descriptor); italics = isItalic(descriptor); } buffer.append(bold ? open("**") : close("**")); buffer.append(italics ? open("*") : close("*")); appendEscaped(buffer, character); return buffer.toString(); } private String open(String tag) { if (stateSet.contains(tag)) { return ""; } stateList.add(tag); stateSet.add(tag); return openTag(tag); } private String close(String tag) { if (!stateSet.contains(tag)) { return ""; } // Close all tags until (but including) the one we should close StringBuilder tagsBuilder = new StringBuilder(); int index = closeUntil(tagsBuilder, tag); // Remove from state stateList.remove(index); stateSet.remove(tag); // Now open the states that were closed but should remain open again for (; index < stateList.size(); index++) { tagsBuilder.append(openTag(stateList.get(index))); } return tagsBuilder.toString(); } private int closeUntil(StringBuilder tagsBuilder, String endTag) { for (int i = stateList.size(); i-- > 0;) { String tag = stateList.get(i); tagsBuilder.append(closeTag(tag)); if (endTag != null && tag.equals(endTag)) { return i; } } return -1; } private String openTag(String tag) { return tag; } private String closeTag(String tag) { return tag; } private boolean isBold(PDFontDescriptor descriptor) { if (descriptor.isForceBold()) { return true; } return descriptor.getFontName().toLowerCase().contains("bold"); } private boolean isItalic(PDFontDescriptor descriptor) {<FILL_FUNCTION_BODY>} }
if (descriptor.isItalic()) { return true; } String fontName = descriptor.getFontName().toLowerCase(); return fontName.contains("italic") || fontName.contains("oblique");
1,126
63
1,189
<methods>public void <init>() ,public boolean getAddMoreFormatting() ,public java.lang.String getArticleEnd() ,public java.lang.String getArticleStart() ,public float getAverageCharTolerance() ,public float getDropThreshold() ,public org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem getEndBookmark() ,public int getEndPage() ,public float getIndentThreshold() ,public java.lang.String getLineSeparator() ,public java.lang.String getPageEnd() ,public java.lang.String getPageStart() ,public java.lang.String getParagraphEnd() ,public java.lang.String getParagraphStart() ,public boolean getSeparateByBeads() ,public boolean getSortByPosition() ,public float getSpacingTolerance() ,public org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem getStartBookmark() ,public int getStartPage() ,public boolean getSuppressDuplicateOverlappingText() ,public java.lang.String getText(org.apache.pdfbox.pdmodel.PDDocument) throws java.io.IOException,public java.lang.String getWordSeparator() ,public void processPage(org.apache.pdfbox.pdmodel.PDPage) throws java.io.IOException,public void setAddMoreFormatting(boolean) ,public void setArticleEnd(java.lang.String) ,public void setArticleStart(java.lang.String) ,public void setAverageCharTolerance(float) ,public void setDropThreshold(float) ,public void setEndBookmark(org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem) ,public void setEndPage(int) ,public void setIndentThreshold(float) ,public void setLineSeparator(java.lang.String) ,public void setPageEnd(java.lang.String) ,public void setPageStart(java.lang.String) ,public void setParagraphEnd(java.lang.String) ,public void setParagraphStart(java.lang.String) ,public void setShouldSeparateByBeads(boolean) ,public void setSortByPosition(boolean) ,public void setSpacingTolerance(float) ,public void setStartBookmark(org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem) ,public void setStartPage(int) ,public void setSuppressDuplicateOverlappingText(boolean) ,public void setWordSeparator(java.lang.String) ,public void writeText(org.apache.pdfbox.pdmodel.PDDocument, java.io.Writer) throws java.io.IOException<variables>private static final float END_OF_LAST_TEXT_X_RESET_VALUE,private static final float EXPECTED_START_OF_NEXT_WORD_X_RESET_VALUE,private static final float LAST_WORD_SPACING_RESET_VALUE,protected static final java.lang.String LINE_SEPARATOR,private static final java.lang.String[] LIST_ITEM_EXPRESSIONS,private static final Logger LOG,private static final float MAX_HEIGHT_FOR_LINE_RESET_VALUE,private static final float MAX_Y_FOR_LINE_RESET_VALUE,private static final float MIN_Y_TOP_FOR_LINE_RESET_VALUE,private static final Map<java.lang.Character,java.lang.Character> MIRRORING_CHAR_MAP,private boolean addMoreFormatting,private java.lang.String articleEnd,private java.lang.String articleStart,private float averageCharTolerance,private List<org.apache.pdfbox.pdmodel.common.PDRectangle> beadRectangles,private final Map<java.lang.String,TreeMap<java.lang.Float,TreeSet<java.lang.Float>>> characterListMapping,protected ArrayList<List<org.apache.pdfbox.text.TextPosition>> charactersByArticle,private int currentPageNo,private static float defaultDropThreshold,private static float defaultIndentThreshold,protected org.apache.pdfbox.pdmodel.PDDocument document,private float dropThreshold,private org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem endBookmark,private int endBookmarkPageNumber,private int endPage,private boolean inParagraph,private float indentThreshold,private java.lang.String lineSeparator,private List<java.util.regex.Pattern> listOfPatterns,protected java.io.Writer output,private java.lang.String pageEnd,private java.lang.String pageStart,private java.lang.String paragraphEnd,private java.lang.String paragraphStart,private boolean shouldSeparateByBeads,private boolean sortByPosition,private float spacingTolerance,private org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem startBookmark,private int startBookmarkPageNumber,private int startPage,private boolean suppressDuplicateOverlappingText,private java.lang.String wordSeparator
apache_pdfbox
pdfbox/tools/src/main/java/org/apache/pdfbox/tools/PDFToImage.java
PDFToImage
call
class PDFToImage implements Callable<Integer> { // Expected for CLI app to write to System.out/System.err @SuppressWarnings("squid:S106") private final PrintStream SYSERR; @Option(names = "-password", description = "the password to decrypt the document", arity = "0..1", interactive = true) private String password; @Option(names = {"-format"}, description = "the image file format (default: ${DEFAULT-VALUE})") private String imageFormat = "jpg"; @Option(names = {"-prefix", "-outputPrefix"}, description = "the filename prefix for image files") private String outputPrefix; @Option(names = "-page", description = "the only page to extract (1-based)") private int page = -1; @Option(names = "-startPage", description = "the first page to start extraction (1-based)") private int startPage = 1; @Option(names = "-endPage", description = "the last page to extract (inclusive)") private int endPage = Integer.MAX_VALUE; @Option(names = "-color", description = "the color depth (valid: ${COMPLETION-CANDIDATES}) (default: ${DEFAULT-VALUE})") private ImageType imageType = ImageType.RGB; @Option(names = {"-dpi", "-resolution"}, description = "the DPI of the output image, default: screen resolution or 96 if unknown") private int dpi; @Option(names = "-quality", description = "the quality to be used when compressing the image (0 <= quality <= 1) " + "(default: 0 for PNG and 1 for the other formats)") private float quality = -1; @Option(names = "-cropbox", arity="4", description = "the page area to export") private int[] cropbox; @Option(names = "-time", description = "print timing information to stdout") private boolean showTime; @Option(names = "-subsampling", description = "activate subsampling (for PDFs with huge images)") private boolean subsampling; @Option(names = {"-i", "--input"}, description = "the PDF files to convert.", required = true) private File infile; /** * Constructor. */ public PDFToImage() { SYSERR = System.err; } /** * Infamous main method. * * @param args Command line arguments, should be one and a reference to a file. * */ public static void main( String[] args ) { // suppress the Dock icon on OS X System.setProperty("apple.awt.UIElement", "true"); int exitCode = new CommandLine(new PDFToImage()).execute(args); System.exit(exitCode); } public Integer call() {<FILL_FUNCTION_BODY>} private static void changeCropBox(PDDocument document, float a, float b, float c, float d) { for (PDPage page : document.getPages()) { PDRectangle rectangle = new PDRectangle(); rectangle.setLowerLeftX(a); rectangle.setLowerLeftY(b); rectangle.setUpperRightX(c); rectangle.setUpperRightY(d); page.setCropBox(rectangle); } } }
if (outputPrefix == null) { outputPrefix = FilenameUtils.removeExtension(infile.getAbsolutePath()); } if (!List.of(ImageIO.getWriterFormatNames()).contains(imageFormat)) { SYSERR.println("Error: Invalid image format " + imageFormat + " - supported formats: " + String.join(", ", ImageIO.getWriterFormatNames())); return 2; } if (quality < 0) { quality = "png".equals(imageFormat) ? 0f : 1f; } if (dpi == 0) { try { dpi = Toolkit.getDefaultToolkit().getScreenResolution(); } catch (HeadlessException e) { dpi = 96; } } try (PDDocument document = Loader.loadPDF(infile, password)) { PDAcroForm acroForm = document.getDocumentCatalog().getAcroForm(); if (acroForm != null && acroForm.getNeedAppearances()) { acroForm.refreshAppearances(); } if (cropbox != null) { changeCropBox(document, cropbox[0], cropbox[1], cropbox[2], cropbox[3]); } long startTime = System.nanoTime(); // render the pages boolean success = true; endPage = Math.min(endPage, document.getNumberOfPages()); PDFRenderer renderer = new PDFRenderer(document); renderer.setSubsamplingAllowed(subsampling); for (int i = startPage - 1; i < endPage; i++) { BufferedImage image = renderer.renderImageWithDPI(i, dpi, imageType); String fileName = outputPrefix + "-" + (i + 1) + "." + imageFormat; success &= ImageIOUtil.writeImage(image, fileName, dpi, quality); } // performance stats long endTime = System.nanoTime(); long duration = endTime - startTime; int count = 1 + endPage - startPage; if (showTime) { SYSERR.printf("Rendered %d page%s in %dms%n", count, count == 1 ? "" : "s", duration / 1000000); } if (!success) { SYSERR.println( "Error: no writer found for image format '" + imageFormat + "'" ); return 1; } } catch (IOException ioe) { SYSERR.println( "Error converting document [" + ioe.getClass().getSimpleName() + "]: " + ioe.getMessage()); return 4; } return 0;
885
730
1,615
<no_super_class>
apache_pdfbox
pdfbox/tools/src/main/java/org/apache/pdfbox/tools/Version.java
Version
main
class Version implements Callable<Integer>, IVersionProvider { // Expected for CLI app to write to System.out/System.err @SuppressWarnings("squid:S106") private final PrintStream SYSOUT; @Spec CommandSpec spec; /** * Get the version of PDFBox or unknown if it is not known. * * @return The version of pdfbox that is being used. */ public String[] getVersion() { String version = org.apache.pdfbox.util.Version.getVersion(); if (version != null) { return new String[] { spec.qualifiedName() + " [" + version + "]" }; } else { return new String[] { "unknown" }; } } /** * Constructor. */ public Version() { SYSOUT = System.out; } /** * This will print out the version of PDF to System.out. * * @param args Command line arguments. */ public static void main(String[] args) {<FILL_FUNCTION_BODY>} public Integer call() { SYSOUT.println(getVersion()[0]); return 0; } }
// suppress the Dock icon on OS X System.setProperty("apple.awt.UIElement", "true"); int exitCode = new CommandLine(new Version()).execute(args); System.exit(exitCode);
333
59
392
<no_super_class>
apache_pdfbox
pdfbox/tools/src/main/java/org/apache/pdfbox/tools/WriteDecodedDoc.java
WriteDecodedDoc
processObject
class WriteDecodedDoc implements Callable<Integer> { // Expected for CLI app to write to System.out/System.err @SuppressWarnings("squid:S106") private final PrintStream SYSERR; @Option(names = "-password", description = "the password to decrypt the document", arity = "0..1", interactive = true) private String password; @Option(names = "-skipImages", description = "don't uncompress images") private boolean skipImages; @Parameters(paramLabel = "inputfile", index="0", description = "the PDF document to be decompressed") private File infile; @Parameters(paramLabel = "outputfile", arity = "0..1", description = "the PDF file to save to.") private File outfile; /** * Constructor. */ public WriteDecodedDoc() { SYSERR = System.err; } /** * This will perform the document reading, decoding and writing. * * @param in The filename used for input. * @param out The filename used for output. * @param password The password to open the document. * @param skipImages Whether to skip decoding images. * * @throws IOException if the output could not be written */ public void doIt(String in, String out, String password, boolean skipImages) throws IOException { try (PDDocument doc = Loader.loadPDF(new File(in), password)) { doc.setAllSecurityToBeRemoved(true); COSDocument cosDocument = doc.getDocument(); cosDocument.getXrefTable().keySet().stream() .forEach(o -> processObject(cosDocument.getObjectFromPool(o), skipImages)); doc.getDocumentCatalog(); doc.getDocument().setIsXRefStream(false); doc.save(out, CompressParameters.NO_COMPRESSION); } } private void processObject(COSObject cosObject, boolean skipImages) {<FILL_FUNCTION_BODY>} /** * This will write a PDF document with completely decoded streams. * <br> * see usage() for commandline * * @param args command line arguments */ public static void main(String[] args) { // suppress the Dock icon on OS X System.setProperty("apple.awt.UIElement", "true"); int exitCode = new CommandLine(new WriteDecodedDoc()).execute(args); System.exit(exitCode); } public Integer call() { String outputFilename; if (outfile == null) { outputFilename = calculateOutputFilename(infile.getAbsolutePath()); } else { outputFilename = outfile.getAbsolutePath(); } try { doIt(infile.getAbsolutePath(), outputFilename, password, skipImages); } catch (IOException ioe) { SYSERR.println( "Error writing decoded PDF [" + ioe.getClass().getSimpleName() + "]: " + ioe.getMessage()); return 4; } return 0; } private static String calculateOutputFilename(String filename) { String outputFilename; if (filename.toLowerCase().endsWith(".pdf")) { outputFilename = filename.substring(0,filename.length()-4); } else { outputFilename = filename; } outputFilename += "_unc.pdf"; return outputFilename; } }
COSBase base = cosObject.getObject(); if (base instanceof COSStream) { COSStream stream = (COSStream) base; if (skipImages && COSName.XOBJECT.equals(stream.getItem(COSName.TYPE)) && COSName.IMAGE.equals(stream.getItem(COSName.SUBTYPE))) { return; } try { byte[] bytes = new PDStream(stream).toByteArray(); stream.removeItem(COSName.FILTER); try (OutputStream streamOut = stream.createOutputStream()) { streamOut.write(bytes); } } catch (IOException ex) { SYSERR.println("skip " + cosObject.getKey() + " obj: " + ex.getMessage()); } }
931
218
1,149
<no_super_class>
apache_pdfbox
pdfbox/tools/src/main/java/org/apache/pdfbox/tools/imageio/JPEGUtil.java
JPEGUtil
updateMetadata
class JPEGUtil { private JPEGUtil() { } /** * Set dpi in a JPEG file * * @param metadata the meta data * @param dpi the dpi * * @throws IIOInvalidTreeException if something goes wrong */ static void updateMetadata(IIOMetadata metadata, int dpi) throws IIOInvalidTreeException {<FILL_FUNCTION_BODY>} }
MetaUtil.debugLogMetadata(metadata, MetaUtil.JPEG_NATIVE_FORMAT); // https://svn.apache.org/viewvc/xmlgraphics/commons/trunk/src/java/org/apache/xmlgraphics/image/writer/imageio/ImageIOJPEGImageWriter.java // http://docs.oracle.com/javase/6/docs/api/javax/imageio/metadata/doc-files/jpeg_metadata.html Element root = (Element) metadata.getAsTree(MetaUtil.JPEG_NATIVE_FORMAT); NodeList jvarNodeList = root.getElementsByTagName("JPEGvariety"); Element jvarChild; if (jvarNodeList.getLength() == 0) { jvarChild = new IIOMetadataNode("JPEGvariety"); root.appendChild(jvarChild); } else { jvarChild = (Element) jvarNodeList.item(0); } NodeList jfifNodeList = jvarChild.getElementsByTagName("app0JFIF"); Element jfifChild; if (jfifNodeList.getLength() == 0) { jfifChild = new IIOMetadataNode("app0JFIF"); jvarChild.appendChild(jfifChild); } else { jfifChild = (Element) jfifNodeList.item(0); } if (jfifChild.getAttribute("majorVersion").isEmpty()) { jfifChild.setAttribute("majorVersion", "1"); } if (jfifChild.getAttribute("minorVersion").isEmpty()) { jfifChild.setAttribute("minorVersion", "2"); } jfifChild.setAttribute("resUnits", "1"); // inch jfifChild.setAttribute("Xdensity", Integer.toString(dpi)); jfifChild.setAttribute("Ydensity", Integer.toString(dpi)); if (jfifChild.getAttribute("thumbWidth").isEmpty()) { jfifChild.setAttribute("thumbWidth", "0"); } if (jfifChild.getAttribute("thumbHeight").isEmpty()) { jfifChild.setAttribute("thumbHeight", "0"); } // mergeTree doesn't work for ARGB metadata.setFromTree(MetaUtil.JPEG_NATIVE_FORMAT, root);
121
628
749
<no_super_class>
apache_pdfbox
pdfbox/tools/src/main/java/org/apache/pdfbox/tools/imageio/MetaUtil.java
MetaUtil
debugLogMetadata
class MetaUtil { private static final Logger LOG = LogManager.getLogger(MetaUtil.class); static final String SUN_TIFF_FORMAT = "com_sun_media_imageio_plugins_tiff_image_1.0"; static final String JPEG_NATIVE_FORMAT = "javax_imageio_jpeg_image_1.0"; static final String STANDARD_METADATA_FORMAT = "javax_imageio_1.0"; private MetaUtil() { } // logs metadata as an XML tree if debug is enabled static void debugLogMetadata(IIOMetadata metadata, String format) {<FILL_FUNCTION_BODY>} }
if (!LOG.isDebugEnabled()) { return; } // see http://docs.oracle.com/javase/7/docs/api/javax/imageio/ // metadata/doc-files/standard_metadata.html IIOMetadataNode root = (IIOMetadataNode) metadata.getAsTree(format); try { StringWriter xmlStringWriter = new StringWriter(); StreamResult streamResult = new StreamResult(xmlStringWriter); TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, ""); transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); Transformer transformer = transformerFactory.newTransformer(); // see http://stackoverflow.com/a/1264872/535646 transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); DOMSource domSource = new DOMSource(root); transformer.transform(domSource, streamResult); LOG.debug("\n{}", xmlStringWriter); } catch (IllegalArgumentException | TransformerException ex) { LOG.error(ex, ex); }
185
366
551
<no_super_class>
apache_pdfbox
pdfbox/tools/src/main/java/org/apache/pdfbox/tools/imageio/TIFFUtil.java
TIFFUtil
createRationalField
class TIFFUtil { private static final Logger LOG = LogManager.getLogger(TIFFUtil.class); private TIFFUtil() { } /** * Sets the ImageIO parameter compression type based on the given image. * @param image buffered image used to decide compression type * @param param ImageIO write parameter to update */ public static void setCompressionType(ImageWriteParam param, BufferedImage image) { // avoid error: first compression type is RLE, not optimal and incorrect for color images // TODO expose this choice to the user? if (image.getType() == BufferedImage.TYPE_BYTE_BINARY && image.getColorModel().getPixelSize() == 1) { param.setCompressionType("CCITT T.6"); } else { param.setCompressionType("LZW"); } } /** * Updates the given ImageIO metadata with Sun's custom TIFF tags, as described in * the <a href="https://svn.apache.org/repos/asf/xmlgraphics/commons/tags/commons-1_3_1/src/java/org/apache/xmlgraphics/image/writer/imageio/ImageIOTIFFImageWriter.java">org.apache.xmlgraphics.image.writer.imageio.ImageIOTIFFImageWriter * sources</a>, * the <a href="http://download.java.net/media/jai-imageio/javadoc/1.0_01/com/sun/media/imageio/plugins/tiff/package-summary.html">com.sun.media.imageio.plugins.tiff * package javadoc</a> * and the <a href="http://partners.adobe.com/public/developer/tiff/index.html">TIFF * specification</a>. * * @param image buffered image which will be written * @param metadata ImageIO metadata * @param dpi image dots per inch * @throws IIOInvalidTreeException if something goes wrong */ static void updateMetadata(IIOMetadata metadata, BufferedImage image, int dpi) throws IIOInvalidTreeException { String metaDataFormat = metadata.getNativeMetadataFormatName(); if (metaDataFormat == null) { LOG.debug("TIFF image writer doesn't support any data format"); return; } debugLogMetadata(metadata, metaDataFormat); IIOMetadataNode root = new IIOMetadataNode(metaDataFormat); IIOMetadataNode ifd; NodeList nodeListTIFFIFD = root.getElementsByTagName("TIFFIFD"); if (nodeListTIFFIFD.getLength() == 0) { ifd = new IIOMetadataNode("TIFFIFD"); root.appendChild(ifd); } else { ifd = (IIOMetadataNode) nodeListTIFFIFD.item(0); } // standard metadata does not work, so we set the DPI manually ifd.appendChild(createRationalField(282, "XResolution", dpi, 1)); ifd.appendChild(createRationalField(283, "YResolution", dpi, 1)); ifd.appendChild(createShortField(296, "ResolutionUnit", 2)); // Inch ifd.appendChild(createLongField(278, "RowsPerStrip", image.getHeight())); ifd.appendChild(createAsciiField(305, "Software", "PDFBOX")); if (image.getType() == BufferedImage.TYPE_BYTE_BINARY && image.getColorModel().getPixelSize() == 1) { // set PhotometricInterpretation WhiteIsZero // because of bug in Windows XP preview ifd.appendChild(createShortField(262, "PhotometricInterpretation", 0)); } metadata.mergeTree(metaDataFormat, root); debugLogMetadata(metadata, metaDataFormat); } private static IIOMetadataNode createShortField(int tiffTagNumber, String name, int val) { IIOMetadataNode field, arrayNode, valueNode; field = new IIOMetadataNode("TIFFField"); field.setAttribute("number", Integer.toString(tiffTagNumber)); field.setAttribute("name", name); arrayNode = new IIOMetadataNode("TIFFShorts"); field.appendChild(arrayNode); valueNode = new IIOMetadataNode("TIFFShort"); arrayNode.appendChild(valueNode); valueNode.setAttribute("value", Integer.toString(val)); return field; } private static IIOMetadataNode createAsciiField(int number, String name, String val) { IIOMetadataNode field, arrayNode, valueNode; field = new IIOMetadataNode("TIFFField"); field.setAttribute("number", Integer.toString(number)); field.setAttribute("name", name); arrayNode = new IIOMetadataNode("TIFFAsciis"); field.appendChild(arrayNode); valueNode = new IIOMetadataNode("TIFFAscii"); arrayNode.appendChild(valueNode); valueNode.setAttribute("value", val); return field; } private static IIOMetadataNode createLongField(int number, String name, long val) { IIOMetadataNode field, arrayNode, valueNode; field = new IIOMetadataNode("TIFFField"); field.setAttribute("number", Integer.toString(number)); field.setAttribute("name", name); arrayNode = new IIOMetadataNode("TIFFLongs"); field.appendChild(arrayNode); valueNode = new IIOMetadataNode("TIFFLong"); arrayNode.appendChild(valueNode); valueNode.setAttribute("value", Long.toString(val)); return field; } private static IIOMetadataNode createRationalField(int number, String name, int numerator, int denominator) {<FILL_FUNCTION_BODY>} }
IIOMetadataNode field, arrayNode, valueNode; field = new IIOMetadataNode("TIFFField"); field.setAttribute("number", Integer.toString(number)); field.setAttribute("name", name); arrayNode = new IIOMetadataNode("TIFFRationals"); field.appendChild(arrayNode); valueNode = new IIOMetadataNode("TIFFRational"); arrayNode.appendChild(valueNode); valueNode.setAttribute("value", numerator + "/" + denominator); return field;
1,593
139
1,732
<no_super_class>
apache_pdfbox
pdfbox/xmpbox/src/main/java/org/apache/xmpbox/schema/AdobePDFSchema.java
AdobePDFSchema
getPDFVersionProperty
class AdobePDFSchema extends XMPSchema { @PropertyType(type = Types.Text, card = Cardinality.Simple) public static final String KEYWORDS = "Keywords"; @PropertyType(type = Types.Text, card = Cardinality.Simple) public static final String PDF_VERSION = "PDFVersion"; @PropertyType(type = Types.Text, card = Cardinality.Simple) public static final String PRODUCER = "Producer"; /** * Constructor of an Adobe PDF schema with preferred prefix * * @param metadata * The metadata to attach this schema */ public AdobePDFSchema(XMPMetadata metadata) { super(metadata); } /** * Constructor of an Adobe PDF schema with specified prefix * * @param metadata * The metadata to attach this schema * @param ownPrefix * The prefix to assign */ public AdobePDFSchema(XMPMetadata metadata, String ownPrefix) { super(metadata, ownPrefix); } /** * Set the PDF keywords * * @param value * Value to set */ public void setKeywords(String value) { TextType keywords; keywords = createTextType(KEYWORDS, value); addProperty(keywords); } /** * Set the PDF keywords * * @param keywords * Property to set */ public void setKeywordsProperty(TextType keywords) { addProperty(keywords); } /** * Set the PDFVersion * * @param value * Value to set */ public void setPDFVersion(String value) { TextType version; version = createTextType(PDF_VERSION, value); addProperty(version); } /** * Set the PDFVersion * * @param version * Property to set */ public void setPDFVersionProperty(TextType version) { addProperty(version); } /** * Set the PDFProducer * * @param value * Value to set */ public void setProducer(String value) { TextType producer; producer = createTextType(PRODUCER, value); addProperty(producer); } /** * Set the PDFProducer * * @param producer * Property to set */ public void setProducerProperty(TextType producer) { addProperty(producer); } /** * Give the PDF Keywords property * * @return The property object */ public TextType getKeywordsProperty() { AbstractField tmp = getProperty(KEYWORDS); if (tmp instanceof TextType) { return (TextType) tmp; } return null; } /** * Give the PDF Keywords property value (string) * * @return The property value */ public String getKeywords() { AbstractField tmp = getProperty(KEYWORDS); if (tmp instanceof TextType) { return ((TextType) tmp).getStringValue(); } return null; } /** * Give the PDFVersion property * * @return The property object */ public TextType getPDFVersionProperty() {<FILL_FUNCTION_BODY>} /** * Give the PDFVersion property value (string) * * @return The property value */ public String getPDFVersion() { AbstractField tmp = getProperty(PDF_VERSION); if (tmp instanceof TextType) { return ((TextType) tmp).getStringValue(); } return null; } /** * Give the producer property * * @return The property object */ public TextType getProducerProperty() { AbstractField tmp = getProperty(PRODUCER); if (tmp instanceof TextType) { return (TextType) tmp; } return null; } /** * Give the producer property value (string) * * @return The property value */ public String getProducer() { AbstractField tmp = getProperty(PRODUCER); if (tmp instanceof TextType) { return ((TextType) tmp).getStringValue(); } return null; } }
AbstractField tmp = getProperty(PDF_VERSION); if (tmp instanceof TextType) { return (TextType) tmp; } return null;
1,173
45
1,218
<methods>public void <init>(org.apache.xmpbox.XMPMetadata, java.lang.String, java.lang.String, java.lang.String) ,public void <init>(org.apache.xmpbox.XMPMetadata) ,public void <init>(org.apache.xmpbox.XMPMetadata, java.lang.String) ,public void <init>(org.apache.xmpbox.XMPMetadata, java.lang.String, java.lang.String) ,public void addBagValue(java.lang.String, org.apache.xmpbox.type.AbstractField) ,public void addBagValueAsSimple(java.lang.String, java.lang.String) ,public void addQualifiedBagValue(java.lang.String, java.lang.String) ,public void addSequenceDateValueAsSimple(java.lang.String, java.util.Calendar) ,public void addUnqualifiedSequenceDateValue(java.lang.String, java.util.Calendar) ,public void addUnqualifiedSequenceValue(java.lang.String, java.lang.String) ,public void addUnqualifiedSequenceValue(java.lang.String, org.apache.xmpbox.type.AbstractField) ,public org.apache.xmpbox.type.Attribute getAboutAttribute() ,public java.lang.String getAboutValue() ,public org.apache.xmpbox.type.AbstractField getAbstractProperty(java.lang.String) ,public org.apache.xmpbox.type.BooleanType getBooleanProperty(java.lang.String) throws org.apache.xmpbox.type.BadFieldValueException,public java.lang.Boolean getBooleanPropertyValue(java.lang.String) throws org.apache.xmpbox.type.BadFieldValueException,public java.lang.Boolean getBooleanPropertyValueAsSimple(java.lang.String) throws org.apache.xmpbox.type.BadFieldValueException,public org.apache.xmpbox.type.DateType getDateProperty(java.lang.String) throws org.apache.xmpbox.type.BadFieldValueException,public java.util.Calendar getDatePropertyValue(java.lang.String) throws org.apache.xmpbox.type.BadFieldValueException,public java.util.Calendar getDatePropertyValueAsSimple(java.lang.String) throws org.apache.xmpbox.type.BadFieldValueException,public org.apache.xmpbox.type.IntegerType getIntegerProperty(java.lang.String) throws org.apache.xmpbox.type.BadFieldValueException,public java.lang.Integer getIntegerPropertyValue(java.lang.String) throws org.apache.xmpbox.type.BadFieldValueException,public java.lang.Integer getIntegerPropertyValueAsSimple(java.lang.String) throws org.apache.xmpbox.type.BadFieldValueException,public List<org.apache.xmpbox.type.AbstractField> getUnqualifiedArrayList(java.lang.String) throws org.apache.xmpbox.type.BadFieldValueException,public List<java.lang.String> getUnqualifiedBagValueList(java.lang.String) ,public List<java.lang.String> getUnqualifiedLanguagePropertyLanguagesValue(java.lang.String) throws org.apache.xmpbox.type.BadFieldValueException,public java.lang.String getUnqualifiedLanguagePropertyValue(java.lang.String, java.lang.String) throws org.apache.xmpbox.type.BadFieldValueException,public List<java.util.Calendar> getUnqualifiedSequenceDateValueList(java.lang.String) ,public List<java.lang.String> getUnqualifiedSequenceValueList(java.lang.String) ,public org.apache.xmpbox.type.TextType getUnqualifiedTextProperty(java.lang.String) throws org.apache.xmpbox.type.BadFieldValueException,public java.lang.String getUnqualifiedTextPropertyValue(java.lang.String) throws org.apache.xmpbox.type.BadFieldValueException,public void merge(org.apache.xmpbox.schema.XMPSchema) throws java.io.IOException,public void removeUnqualifiedArrayValue(java.lang.String, org.apache.xmpbox.type.AbstractField) ,public void removeUnqualifiedBagValue(java.lang.String, java.lang.String) ,public void removeUnqualifiedSequenceDateValue(java.lang.String, java.util.Calendar) ,public void removeUnqualifiedSequenceValue(java.lang.String, java.lang.String) ,public void removeUnqualifiedSequenceValue(java.lang.String, org.apache.xmpbox.type.AbstractField) ,public void reorganizeAltOrder(org.apache.xmpbox.type.ComplexPropertyContainer) ,public void setAbout(org.apache.xmpbox.type.Attribute) throws org.apache.xmpbox.type.BadFieldValueException,public void setAboutAsSimple(java.lang.String) ,public void setBooleanProperty(org.apache.xmpbox.type.BooleanType) ,public void setBooleanPropertyValue(java.lang.String, java.lang.Boolean) ,public void setBooleanPropertyValueAsSimple(java.lang.String, java.lang.Boolean) ,public void setDateProperty(org.apache.xmpbox.type.DateType) ,public void setDatePropertyValue(java.lang.String, java.util.Calendar) ,public void setDatePropertyValueAsSimple(java.lang.String, java.util.Calendar) ,public void setIntegerProperty(org.apache.xmpbox.type.IntegerType) ,public void setIntegerPropertyValue(java.lang.String, java.lang.Integer) ,public void setIntegerPropertyValueAsSimple(java.lang.String, java.lang.Integer) ,public void setTextProperty(org.apache.xmpbox.type.TextType) ,public void setTextPropertyValue(java.lang.String, java.lang.String) ,public void setTextPropertyValueAsSimple(java.lang.String, java.lang.String) ,public void setUnqualifiedLanguagePropertyValue(java.lang.String, java.lang.String, java.lang.String) <variables>
apache_pdfbox
pdfbox/xmpbox/src/main/java/org/apache/xmpbox/schema/PDFAIdentificationSchema.java
PDFAIdentificationSchema
setConformanceProperty
class PDFAIdentificationSchema extends XMPSchema { @PropertyType(type = Types.Integer, card = Cardinality.Simple) public static final String PART = "part"; @PropertyType(type = Types.Text, card = Cardinality.Simple) public static final String AMD = "amd"; @PropertyType(type = Types.Text, card = Cardinality.Simple) public static final String CONFORMANCE = "conformance"; /* * <rdf:Description rdf:about="" xmlns:pdfaid="http://www.aiim.org/pdfa/ns/id/"> * <pdfaid:conformance>B</pdfaid:conformance> <pdfaid:part>1</pdfaid:part> </rdf:Description> */ /** * Constructor of a PDF/A Identification schema * * @param metadata * The metadata to attach this schema */ public PDFAIdentificationSchema(XMPMetadata metadata) { super(metadata); } public PDFAIdentificationSchema(XMPMetadata metadata, String prefix) { super(metadata, prefix); } /** * Set the PDFA Version identifier (with string) * * @param value * The version Id value to set * */ public void setPartValueWithString(String value) { IntegerType part = (IntegerType) instanciateSimple(PART, value); addProperty(part); } /** * Set the PDFA Version identifier (with an int) * * @param value * The version Id value to set */ public void setPartValueWithInt(int value) { IntegerType part = (IntegerType) instanciateSimple(PART, value); addProperty(part); } /** * Set the PDF/A Version identifier (with an int) * * @param value * The version Id property to set */ public void setPart(Integer value) { setPartValueWithInt(value); } /** * Set the PDF/A Version identifier * * @param part * set the PDF/A Version id property */ public void setPartProperty(IntegerType part) { addProperty(part); } /** * Set the PDF/A amendment identifier * * @param value * The amendment identifier value to set */ public void setAmd(String value) { TextType amd = createTextType(AMD, value); addProperty(amd); } /** * Set the PDF/A amendment identifier * * @param amd * The amendment identifier property to set */ public void setAmdProperty(TextType amd) { addProperty(amd); } /** * Set the PDF/A conformance level * * @param value * The conformance level value to set * @throws BadFieldValueException * If Conformance Value not 'A', 'B' or 'U' (PDF/A-2 and PDF/A-3) */ public void setConformance(String value) throws BadFieldValueException { if (value.equals("A") || value.equals("B") || value.equals("U")) { TextType conf = createTextType(CONFORMANCE, value); addProperty(conf); } else { throw new BadFieldValueException( "The property given not seems to be a PDF/A conformance level (must be A, B or U)"); } } /** * Set the PDF/A conformance level * * @param conf * The conformance level property to set * @throws BadFieldValueException * If Conformance Value not 'A', 'B' or 'U' (PDF/A-2 and PDF/A-3) */ public void setConformanceProperty(TextType conf) throws BadFieldValueException {<FILL_FUNCTION_BODY>} /** * Give the PDFAVersionId (as an integer) * * @return Part value (Integer) or null if it is missing */ public Integer getPart() { IntegerType tmp = getPartProperty(); if (tmp == null) { return null; } return tmp.getValue(); } /** * Give the property corresponding to the PDFA Version id * * @return Part property */ public IntegerType getPartProperty() { AbstractField tmp = getProperty(PART); if (tmp instanceof IntegerType) { return (IntegerType) tmp; } return null; } /** * Give the PDFAAmendmentId (as an String) * * @return Amendment value */ public String getAmendment() { AbstractField tmp = getProperty(AMD); if (tmp instanceof TextType) { return ((TextType) tmp).getStringValue(); } return null; } /** * Give the property corresponding to the PDFA Amendment id * * @return Amendment property */ public TextType getAmdProperty() { AbstractField tmp = getProperty(AMD); if (tmp instanceof TextType) { return (TextType) tmp; } return null; } /** * Give the PDFA Amendment Id (as an String) * * @return Amendment Value */ public String getAmd() { TextType tmp = getAmdProperty(); if (tmp == null) { for (Attribute attribute : getAllAttributes()) { if (attribute.getName().equals(AMD)) { return attribute.getValue(); } } return null; } else { return tmp.getStringValue(); } } /** * Give the property corresponding to the PDFA Conformance id * * @return conformance property */ public TextType getConformanceProperty() { AbstractField tmp = getProperty(CONFORMANCE); if (tmp instanceof TextType) { return (TextType) tmp; } return null; } /** * Give the Conformance id * * @return conformance id value */ public String getConformance() { TextType tt = getConformanceProperty(); if (tt == null) { for (Attribute attribute : getAllAttributes()) { if (attribute.getName().equals(CONFORMANCE)) { return attribute.getValue(); } } return null; } else { return tt.getStringValue(); } } }
String value = conf.getStringValue(); if (value.equals("A") || value.equals("B") || value.equals("U")) { addProperty(conf); } else { throw new BadFieldValueException( "The property given not seems to be a PDF/A conformance level (must be A, B or U)"); }
1,803
95
1,898
<methods>public void <init>(org.apache.xmpbox.XMPMetadata, java.lang.String, java.lang.String, java.lang.String) ,public void <init>(org.apache.xmpbox.XMPMetadata) ,public void <init>(org.apache.xmpbox.XMPMetadata, java.lang.String) ,public void <init>(org.apache.xmpbox.XMPMetadata, java.lang.String, java.lang.String) ,public void addBagValue(java.lang.String, org.apache.xmpbox.type.AbstractField) ,public void addBagValueAsSimple(java.lang.String, java.lang.String) ,public void addQualifiedBagValue(java.lang.String, java.lang.String) ,public void addSequenceDateValueAsSimple(java.lang.String, java.util.Calendar) ,public void addUnqualifiedSequenceDateValue(java.lang.String, java.util.Calendar) ,public void addUnqualifiedSequenceValue(java.lang.String, java.lang.String) ,public void addUnqualifiedSequenceValue(java.lang.String, org.apache.xmpbox.type.AbstractField) ,public org.apache.xmpbox.type.Attribute getAboutAttribute() ,public java.lang.String getAboutValue() ,public org.apache.xmpbox.type.AbstractField getAbstractProperty(java.lang.String) ,public org.apache.xmpbox.type.BooleanType getBooleanProperty(java.lang.String) throws org.apache.xmpbox.type.BadFieldValueException,public java.lang.Boolean getBooleanPropertyValue(java.lang.String) throws org.apache.xmpbox.type.BadFieldValueException,public java.lang.Boolean getBooleanPropertyValueAsSimple(java.lang.String) throws org.apache.xmpbox.type.BadFieldValueException,public org.apache.xmpbox.type.DateType getDateProperty(java.lang.String) throws org.apache.xmpbox.type.BadFieldValueException,public java.util.Calendar getDatePropertyValue(java.lang.String) throws org.apache.xmpbox.type.BadFieldValueException,public java.util.Calendar getDatePropertyValueAsSimple(java.lang.String) throws org.apache.xmpbox.type.BadFieldValueException,public org.apache.xmpbox.type.IntegerType getIntegerProperty(java.lang.String) throws org.apache.xmpbox.type.BadFieldValueException,public java.lang.Integer getIntegerPropertyValue(java.lang.String) throws org.apache.xmpbox.type.BadFieldValueException,public java.lang.Integer getIntegerPropertyValueAsSimple(java.lang.String) throws org.apache.xmpbox.type.BadFieldValueException,public List<org.apache.xmpbox.type.AbstractField> getUnqualifiedArrayList(java.lang.String) throws org.apache.xmpbox.type.BadFieldValueException,public List<java.lang.String> getUnqualifiedBagValueList(java.lang.String) ,public List<java.lang.String> getUnqualifiedLanguagePropertyLanguagesValue(java.lang.String) throws org.apache.xmpbox.type.BadFieldValueException,public java.lang.String getUnqualifiedLanguagePropertyValue(java.lang.String, java.lang.String) throws org.apache.xmpbox.type.BadFieldValueException,public List<java.util.Calendar> getUnqualifiedSequenceDateValueList(java.lang.String) ,public List<java.lang.String> getUnqualifiedSequenceValueList(java.lang.String) ,public org.apache.xmpbox.type.TextType getUnqualifiedTextProperty(java.lang.String) throws org.apache.xmpbox.type.BadFieldValueException,public java.lang.String getUnqualifiedTextPropertyValue(java.lang.String) throws org.apache.xmpbox.type.BadFieldValueException,public void merge(org.apache.xmpbox.schema.XMPSchema) throws java.io.IOException,public void removeUnqualifiedArrayValue(java.lang.String, org.apache.xmpbox.type.AbstractField) ,public void removeUnqualifiedBagValue(java.lang.String, java.lang.String) ,public void removeUnqualifiedSequenceDateValue(java.lang.String, java.util.Calendar) ,public void removeUnqualifiedSequenceValue(java.lang.String, java.lang.String) ,public void removeUnqualifiedSequenceValue(java.lang.String, org.apache.xmpbox.type.AbstractField) ,public void reorganizeAltOrder(org.apache.xmpbox.type.ComplexPropertyContainer) ,public void setAbout(org.apache.xmpbox.type.Attribute) throws org.apache.xmpbox.type.BadFieldValueException,public void setAboutAsSimple(java.lang.String) ,public void setBooleanProperty(org.apache.xmpbox.type.BooleanType) ,public void setBooleanPropertyValue(java.lang.String, java.lang.Boolean) ,public void setBooleanPropertyValueAsSimple(java.lang.String, java.lang.Boolean) ,public void setDateProperty(org.apache.xmpbox.type.DateType) ,public void setDatePropertyValue(java.lang.String, java.util.Calendar) ,public void setDatePropertyValueAsSimple(java.lang.String, java.util.Calendar) ,public void setIntegerProperty(org.apache.xmpbox.type.IntegerType) ,public void setIntegerPropertyValue(java.lang.String, java.lang.Integer) ,public void setIntegerPropertyValueAsSimple(java.lang.String, java.lang.Integer) ,public void setTextProperty(org.apache.xmpbox.type.TextType) ,public void setTextPropertyValue(java.lang.String, java.lang.String) ,public void setTextPropertyValueAsSimple(java.lang.String, java.lang.String) ,public void setUnqualifiedLanguagePropertyValue(java.lang.String, java.lang.String, java.lang.String) <variables>
apache_pdfbox
pdfbox/xmpbox/src/main/java/org/apache/xmpbox/schema/XMPBasicJobTicketSchema.java
XMPBasicJobTicketSchema
addJob
class XMPBasicJobTicketSchema extends XMPSchema { @PropertyType(type = Types.Job, card = Cardinality.Bag) public static final String JOB_REF = "JobRef"; private ArrayProperty bagJobs; public XMPBasicJobTicketSchema(XMPMetadata metadata) { this(metadata, null); } public XMPBasicJobTicketSchema(XMPMetadata metadata, String ownPrefix) { super(metadata, ownPrefix); } public void addJob(String id, String name, String url) { addJob(id, name, url, null); } public void addJob(String id, String name, String url, String fieldPrefix) {<FILL_FUNCTION_BODY>} public void addJob(JobType job) { String prefix = getNamespacePrefix(job.getNamespace()); if (prefix != null) { // use same prefix for all jobs job.setPrefix(prefix); } else { // add prefix addNamespace(job.getNamespace(), job.getPrefix()); } // create bag if not existing if (bagJobs == null) { bagJobs = createArrayProperty(JOB_REF, Cardinality.Bag); addProperty(bagJobs); } // add job bagJobs.getContainer().addProperty(job); } public List<JobType> getJobs() throws BadFieldValueException { List<AbstractField> tmp = getUnqualifiedArrayList(JOB_REF); if (tmp != null) { List<JobType> layers = new ArrayList<>(); for (AbstractField abstractField : tmp) { if (abstractField instanceof JobType) { layers.add((JobType) abstractField); } else { throw new BadFieldValueException("Job expected and " + abstractField.getClass().getName() + " found."); } } return layers; } return null; } }
JobType job = new JobType(getMetadata(), fieldPrefix); job.setId(id); job.setName(name); job.setUrl(url); addJob(job);
541
53
594
<methods>public void <init>(org.apache.xmpbox.XMPMetadata, java.lang.String, java.lang.String, java.lang.String) ,public void <init>(org.apache.xmpbox.XMPMetadata) ,public void <init>(org.apache.xmpbox.XMPMetadata, java.lang.String) ,public void <init>(org.apache.xmpbox.XMPMetadata, java.lang.String, java.lang.String) ,public void addBagValue(java.lang.String, org.apache.xmpbox.type.AbstractField) ,public void addBagValueAsSimple(java.lang.String, java.lang.String) ,public void addQualifiedBagValue(java.lang.String, java.lang.String) ,public void addSequenceDateValueAsSimple(java.lang.String, java.util.Calendar) ,public void addUnqualifiedSequenceDateValue(java.lang.String, java.util.Calendar) ,public void addUnqualifiedSequenceValue(java.lang.String, java.lang.String) ,public void addUnqualifiedSequenceValue(java.lang.String, org.apache.xmpbox.type.AbstractField) ,public org.apache.xmpbox.type.Attribute getAboutAttribute() ,public java.lang.String getAboutValue() ,public org.apache.xmpbox.type.AbstractField getAbstractProperty(java.lang.String) ,public org.apache.xmpbox.type.BooleanType getBooleanProperty(java.lang.String) throws org.apache.xmpbox.type.BadFieldValueException,public java.lang.Boolean getBooleanPropertyValue(java.lang.String) throws org.apache.xmpbox.type.BadFieldValueException,public java.lang.Boolean getBooleanPropertyValueAsSimple(java.lang.String) throws org.apache.xmpbox.type.BadFieldValueException,public org.apache.xmpbox.type.DateType getDateProperty(java.lang.String) throws org.apache.xmpbox.type.BadFieldValueException,public java.util.Calendar getDatePropertyValue(java.lang.String) throws org.apache.xmpbox.type.BadFieldValueException,public java.util.Calendar getDatePropertyValueAsSimple(java.lang.String) throws org.apache.xmpbox.type.BadFieldValueException,public org.apache.xmpbox.type.IntegerType getIntegerProperty(java.lang.String) throws org.apache.xmpbox.type.BadFieldValueException,public java.lang.Integer getIntegerPropertyValue(java.lang.String) throws org.apache.xmpbox.type.BadFieldValueException,public java.lang.Integer getIntegerPropertyValueAsSimple(java.lang.String) throws org.apache.xmpbox.type.BadFieldValueException,public List<org.apache.xmpbox.type.AbstractField> getUnqualifiedArrayList(java.lang.String) throws org.apache.xmpbox.type.BadFieldValueException,public List<java.lang.String> getUnqualifiedBagValueList(java.lang.String) ,public List<java.lang.String> getUnqualifiedLanguagePropertyLanguagesValue(java.lang.String) throws org.apache.xmpbox.type.BadFieldValueException,public java.lang.String getUnqualifiedLanguagePropertyValue(java.lang.String, java.lang.String) throws org.apache.xmpbox.type.BadFieldValueException,public List<java.util.Calendar> getUnqualifiedSequenceDateValueList(java.lang.String) ,public List<java.lang.String> getUnqualifiedSequenceValueList(java.lang.String) ,public org.apache.xmpbox.type.TextType getUnqualifiedTextProperty(java.lang.String) throws org.apache.xmpbox.type.BadFieldValueException,public java.lang.String getUnqualifiedTextPropertyValue(java.lang.String) throws org.apache.xmpbox.type.BadFieldValueException,public void merge(org.apache.xmpbox.schema.XMPSchema) throws java.io.IOException,public void removeUnqualifiedArrayValue(java.lang.String, org.apache.xmpbox.type.AbstractField) ,public void removeUnqualifiedBagValue(java.lang.String, java.lang.String) ,public void removeUnqualifiedSequenceDateValue(java.lang.String, java.util.Calendar) ,public void removeUnqualifiedSequenceValue(java.lang.String, java.lang.String) ,public void removeUnqualifiedSequenceValue(java.lang.String, org.apache.xmpbox.type.AbstractField) ,public void reorganizeAltOrder(org.apache.xmpbox.type.ComplexPropertyContainer) ,public void setAbout(org.apache.xmpbox.type.Attribute) throws org.apache.xmpbox.type.BadFieldValueException,public void setAboutAsSimple(java.lang.String) ,public void setBooleanProperty(org.apache.xmpbox.type.BooleanType) ,public void setBooleanPropertyValue(java.lang.String, java.lang.Boolean) ,public void setBooleanPropertyValueAsSimple(java.lang.String, java.lang.Boolean) ,public void setDateProperty(org.apache.xmpbox.type.DateType) ,public void setDatePropertyValue(java.lang.String, java.util.Calendar) ,public void setDatePropertyValueAsSimple(java.lang.String, java.util.Calendar) ,public void setIntegerProperty(org.apache.xmpbox.type.IntegerType) ,public void setIntegerPropertyValue(java.lang.String, java.lang.Integer) ,public void setIntegerPropertyValueAsSimple(java.lang.String, java.lang.Integer) ,public void setTextProperty(org.apache.xmpbox.type.TextType) ,public void setTextPropertyValue(java.lang.String, java.lang.String) ,public void setTextPropertyValueAsSimple(java.lang.String, java.lang.String) ,public void setUnqualifiedLanguagePropertyValue(java.lang.String, java.lang.String, java.lang.String) <variables>
apache_pdfbox
pdfbox/xmpbox/src/main/java/org/apache/xmpbox/schema/XMPSchemaFactory.java
XMPSchemaFactory
createXMPSchema
class XMPSchemaFactory { private final String namespace; private final Class<? extends XMPSchema> schemaClass; private final PropertiesDescription propDef; /** * Factory Constructor for basic known schemas * * @param namespace * namespace URI to treat * @param schemaClass * Class representation associated to this URI * @param propDef * Properties Types list associated */ public XMPSchemaFactory(String namespace, Class<? extends XMPSchema> schemaClass, PropertiesDescription propDef) { this.namespace = namespace; this.schemaClass = schemaClass; this.propDef = propDef; } /** * Get namespace URI treated by this factory * * @return The namespace URI */ public String getNamespace() { return namespace; } /** * Get type declared for the name property given * * @param name * The property name * @return null if property name is unknown */ public PropertyType getPropertyType(String name) { return propDef.getPropertyType(name); } /** * Create a schema that corresponding to this factory and add it to metadata * * @param metadata * Metadata to attach the Schema created * @param prefix * The namespace prefix (optional) * @return the schema created and added to metadata * @throws XmpSchemaException * When Instancing specified Object Schema failed */ public XMPSchema createXMPSchema(XMPMetadata metadata, String prefix) throws XmpSchemaException {<FILL_FUNCTION_BODY>} public PropertiesDescription getPropertyDefinition() { return this.propDef; } }
XMPSchema schema; Class<?>[] argsClass; Object[] schemaArgs; if (schemaClass == XMPSchema.class) { argsClass = new Class[] { XMPMetadata.class, String.class, String.class }; schemaArgs = new Object[] { metadata, namespace, prefix }; } else if (prefix != null && !prefix.isEmpty()) { argsClass = new Class[] { XMPMetadata.class, String.class }; schemaArgs = new Object[] { metadata, prefix }; } else { argsClass = new Class[] { XMPMetadata.class }; schemaArgs = new Object[] { metadata }; } try { schema = schemaClass.getDeclaredConstructor(argsClass).newInstance(schemaArgs); metadata.addSchema(schema); return schema; } catch (Exception e) { throw new XmpSchemaException("Cannot instantiate specified object schema", e); }
467
253
720
<no_super_class>
apache_pdfbox
pdfbox/xmpbox/src/main/java/org/apache/xmpbox/type/AbstractComplexProperty.java
AbstractComplexProperty
addProperty
class AbstractComplexProperty extends AbstractField { private final ComplexPropertyContainer container; private final Map<String, String> namespaceToPrefix; public AbstractComplexProperty(XMPMetadata metadata, String propertyName) { super(metadata, propertyName); container = new ComplexPropertyContainer(); this.namespaceToPrefix = new HashMap<>(); } public void addNamespace(String namespace, String prefix) { this.namespaceToPrefix.put(namespace, prefix); } public String getNamespacePrefix(String namespace) { return this.namespaceToPrefix.get(namespace); } public Map<String, String> getAllNamespacesWithPrefix() { return this.namespaceToPrefix; } /** * Add a property to the current structure * * @param obj * the property to add */ public final void addProperty(AbstractField obj) {<FILL_FUNCTION_BODY>} /** * Remove a property * * @param property * The property to remove */ public final void removeProperty(AbstractField property) { container.removeProperty(property); } // /** // * Return the container of this Array // * // * @return The complex property container that represents content of this // * property // */ public final ComplexPropertyContainer getContainer() { return container; } public final List<AbstractField> getAllProperties() { return container.getAllProperties(); } public final AbstractField getProperty(String fieldName) { List<AbstractField> list = container.getPropertiesByLocalName(fieldName); // return null if no property if (list == null) { return null; } // return the first element of the list return list.get(0); } public final ArrayProperty getArrayProperty(String fieldName) { List<AbstractField> list = container.getPropertiesByLocalName(fieldName); // return null if no property if (list == null) { return null; } // return the first element of the list return (ArrayProperty) list.get(0); } protected final AbstractField getFirstEquivalentProperty(String localName, Class<? extends AbstractField> type) { return container.getFirstEquivalentProperty(localName, type); } }
// https://www.adobe.com/content/dam/Adobe/en/devnet/xmp/pdfs/cs6/XMPSpecificationPart1.pdf // "Each property name in an XMP packet shall be unique within that packet" // "Multiple values are represented using an XMP array value" // "The nested element's element content shall consist of zero or more rdf:li elements, // one for each item in the array" // thus delete existing elements of a property, except for arrays ("li") if (!(this instanceof ArrayProperty)) { container.removePropertiesByName(obj.getPropertyName()); } container.addProperty(obj);
632
172
804
<methods>public void <init>(org.apache.xmpbox.XMPMetadata, java.lang.String) ,public final boolean containsAttribute(java.lang.String) ,public final List<org.apache.xmpbox.type.Attribute> getAllAttributes() ,public final org.apache.xmpbox.type.Attribute getAttribute(java.lang.String) ,public final org.apache.xmpbox.XMPMetadata getMetadata() ,public abstract java.lang.String getNamespace() ,public abstract java.lang.String getPrefix() ,public final java.lang.String getPropertyName() ,public final void removeAttribute(java.lang.String) ,public final void setAttribute(org.apache.xmpbox.type.Attribute) ,public final void setPropertyName(java.lang.String) <variables>private final non-sealed Map<java.lang.String,org.apache.xmpbox.type.Attribute> attributes,private final non-sealed org.apache.xmpbox.XMPMetadata metadata,private java.lang.String propertyName
apache_pdfbox
pdfbox/xmpbox/src/main/java/org/apache/xmpbox/type/AbstractSimpleProperty.java
AbstractSimpleProperty
toString
class AbstractSimpleProperty extends AbstractField { private final String namespace; private final String prefix; private final Object rawValue; /** * Property specific type constructor (namespaceURI is given) * * @param metadata * The metadata to attach to this property * @param namespaceURI * the specified namespace URI associated to this property * @param prefix * The prefix to set for this property * @param propertyName * The local Name of this property * @param value * the value to give */ public AbstractSimpleProperty(XMPMetadata metadata, String namespaceURI, String prefix, String propertyName, Object value) { super(metadata, propertyName); setValue(value); this.namespace = namespaceURI; this.prefix = prefix; this.rawValue = value; } /** * Check and set new property value (in Element and in its Object Representation) * * @param value * Object value to set */ public abstract void setValue(Object value); /** * Return the property value * * @return a string */ public abstract String getStringValue(); public abstract Object getValue(); /** * Return the properties raw value. * <p> * The properties raw value is how it has been * serialized into the XML. Allows to retrieve the * low level date for validation purposes. * </p> * * @return the raw value. */ public Object getRawValue() { return rawValue; } @Override public String toString() {<FILL_FUNCTION_BODY>} /** * Get the namespace URI of this entity * * @return the namespace URI */ @Override public final String getNamespace() { return namespace; } /** * Get the prefix of this entity * * @return the prefix specified */ @Override public String getPrefix() { return prefix; } }
return "[" + this.getClass().getSimpleName() + ":" + getStringValue() + "]";
552
30
582
<methods>public void <init>(org.apache.xmpbox.XMPMetadata, java.lang.String) ,public final boolean containsAttribute(java.lang.String) ,public final List<org.apache.xmpbox.type.Attribute> getAllAttributes() ,public final org.apache.xmpbox.type.Attribute getAttribute(java.lang.String) ,public final org.apache.xmpbox.XMPMetadata getMetadata() ,public abstract java.lang.String getNamespace() ,public abstract java.lang.String getPrefix() ,public final java.lang.String getPropertyName() ,public final void removeAttribute(java.lang.String) ,public final void setAttribute(org.apache.xmpbox.type.Attribute) ,public final void setPropertyName(java.lang.String) <variables>private final non-sealed Map<java.lang.String,org.apache.xmpbox.type.Attribute> attributes,private final non-sealed org.apache.xmpbox.XMPMetadata metadata,private java.lang.String propertyName
apache_pdfbox
pdfbox/xmpbox/src/main/java/org/apache/xmpbox/type/AbstractStructuredType.java
AbstractStructuredType
addSimpleProperty
class AbstractStructuredType extends AbstractComplexProperty { protected static final String STRUCTURE_ARRAY_NAME = "li"; private String namespace; private String preferedPrefix; private String prefix; public AbstractStructuredType(XMPMetadata metadata) { this(metadata, null, null, null); } public AbstractStructuredType(XMPMetadata metadata, String namespaceURI) { this(metadata, namespaceURI, null, null); StructuredType st = this.getClass().getAnnotation(StructuredType.class); if (st != null) { // init with annotation this.namespace = st.namespace(); this.preferedPrefix = st.preferedPrefix(); } else { throw new IllegalArgumentException(" StructuredType annotation cannot be null"); } this.prefix = this.preferedPrefix; } public AbstractStructuredType(XMPMetadata metadata, String namespaceURI, String fieldPrefix, String propertyName) { super(metadata, propertyName); StructuredType st = this.getClass().getAnnotation(StructuredType.class); if (st != null) { // init with annotation this.namespace = st.namespace(); this.preferedPrefix = st.preferedPrefix(); } else { // init with parameters if (namespaceURI == null) { throw new IllegalArgumentException( "Both StructuredType annotation and namespace parameter cannot be null"); } this.namespace = namespaceURI; this.preferedPrefix = fieldPrefix; } this.prefix = fieldPrefix == null ? this.preferedPrefix : fieldPrefix; } /** * Get the namespace URI of this entity * * @return the namespace URI */ public final String getNamespace() { return namespace; } public final void setNamespace(String ns) { this.namespace = ns; } /** * Get the prefix of this entity * * @return the prefix specified */ public final String getPrefix() { return prefix; } public final void setPrefix(String pf) { this.prefix = pf; } public final String getPreferedPrefix() { return preferedPrefix; } protected void addSimpleProperty(String propertyName, Object value) {<FILL_FUNCTION_BODY>} protected String getPropertyValueAsString(String fieldName) { AbstractSimpleProperty absProp = (AbstractSimpleProperty) getProperty(fieldName); if (absProp == null) { return null; } else { return absProp.getStringValue(); } } protected Calendar getDatePropertyAsCalendar(String fieldName) { DateType absProp = (DateType) getFirstEquivalentProperty(fieldName, DateType.class); if (absProp != null) { return absProp.getValue(); } else { return null; } } public TextType createTextType(String propertyName, String value) { return getMetadata().getTypeMapping().createText(getNamespace(), getPrefix(), propertyName, value); } public ArrayProperty createArrayProperty(String propertyName, Cardinality type) { return getMetadata().getTypeMapping().createArrayProperty(getNamespace(), getPrefix(), propertyName, type); } }
TypeMapping tm = getMetadata().getTypeMapping(); AbstractSimpleProperty asp = tm.instanciateSimpleField(getClass(), null, getPrefix(), propertyName, value); addProperty(asp);
892
53
945
<methods>public void <init>(org.apache.xmpbox.XMPMetadata, java.lang.String) ,public void addNamespace(java.lang.String, java.lang.String) ,public final void addProperty(org.apache.xmpbox.type.AbstractField) ,public Map<java.lang.String,java.lang.String> getAllNamespacesWithPrefix() ,public final List<org.apache.xmpbox.type.AbstractField> getAllProperties() ,public final org.apache.xmpbox.type.ArrayProperty getArrayProperty(java.lang.String) ,public final org.apache.xmpbox.type.ComplexPropertyContainer getContainer() ,public java.lang.String getNamespacePrefix(java.lang.String) ,public final org.apache.xmpbox.type.AbstractField getProperty(java.lang.String) ,public final void removeProperty(org.apache.xmpbox.type.AbstractField) <variables>private final non-sealed org.apache.xmpbox.type.ComplexPropertyContainer container,private final non-sealed Map<java.lang.String,java.lang.String> namespaceToPrefix
apache_pdfbox
pdfbox/xmpbox/src/main/java/org/apache/xmpbox/type/ArrayProperty.java
ArrayProperty
getElementsAsString
class ArrayProperty extends AbstractComplexProperty { private final Cardinality arrayType; private final String namespace; private final String prefix; /** * Constructor of a complex property * * @param metadata * The metadata to attach to this property * @param namespace * The namespace URI to associate to this property * @param prefix * The prefix to set for this property * @param propertyName * The local Name of this property * @param type * type of complexProperty (Bag, Seq, Alt) */ public ArrayProperty(XMPMetadata metadata, String namespace, String prefix, String propertyName, Cardinality type) { super(metadata, propertyName); this.arrayType = type; this.namespace = namespace; this.prefix = prefix; } public Cardinality getArrayType() { return arrayType; } public List<String> getElementsAsString() {<FILL_FUNCTION_BODY>} /** * Get the namespace URI of this entity * * @return the namespace URI */ @Override public final String getNamespace() { return namespace; } /** * Get the prefix of this entity * * @return the prefix specified */ @Override public String getPrefix() { return prefix; } }
List<AbstractField> allProperties = getContainer().getAllProperties(); List<String> retval = new ArrayList<>(allProperties.size()); allProperties.forEach(tmp -> retval.add(((AbstractSimpleProperty) tmp).getStringValue())); return Collections.unmodifiableList(retval);
372
77
449
<methods>public void <init>(org.apache.xmpbox.XMPMetadata, java.lang.String) ,public void addNamespace(java.lang.String, java.lang.String) ,public final void addProperty(org.apache.xmpbox.type.AbstractField) ,public Map<java.lang.String,java.lang.String> getAllNamespacesWithPrefix() ,public final List<org.apache.xmpbox.type.AbstractField> getAllProperties() ,public final org.apache.xmpbox.type.ArrayProperty getArrayProperty(java.lang.String) ,public final org.apache.xmpbox.type.ComplexPropertyContainer getContainer() ,public java.lang.String getNamespacePrefix(java.lang.String) ,public final org.apache.xmpbox.type.AbstractField getProperty(java.lang.String) ,public final void removeProperty(org.apache.xmpbox.type.AbstractField) <variables>private final non-sealed org.apache.xmpbox.type.ComplexPropertyContainer container,private final non-sealed Map<java.lang.String,java.lang.String> namespaceToPrefix
apache_pdfbox
pdfbox/xmpbox/src/main/java/org/apache/xmpbox/type/Attribute.java
Attribute
toString
class Attribute { private String nsURI; private String name; private String value; /** * Constructor of a new Attribute * * @param nsURI * namespaceURI of this attribute (could be null) * @param localName * localName of this attribute * @param value * value given to this attribute */ public Attribute(String nsURI, String localName, String value) { this.nsURI = nsURI; this.name = localName; this.value = value; } /** * Get the localName of this attribute * * @return local name of this attribute */ public String getName() { return name; } /** * Set the localName of this attribute * * @param lname * the local name to set */ public void setName(String lname) { name = lname; } /** * Get the namespace URI of this attribute * * @return the namespace URI associated to this attribute (could be null) */ public String getNamespace() { return nsURI; } /** * Set the namespace URI of this attribute * * @param nsURI * the namespace URI to set */ public void setNsURI(String nsURI) { this.nsURI = nsURI; } /** * Get value of this attribute * * @return value of this attribute */ public String getValue() { return value; } /** * Set value of this attribute * * @param value * the value to set for this attribute */ public void setValue(String value) { this.value = value; } public String toString() {<FILL_FUNCTION_BODY>} }
return "[attr:{" + nsURI + "}" + name + "=" + value + "]";
516
28
544
<no_super_class>
apache_pdfbox
pdfbox/xmpbox/src/main/java/org/apache/xmpbox/type/BooleanType.java
BooleanType
setValue
class BooleanType extends AbstractSimpleProperty { public static final String TRUE = "True"; public static final String FALSE = "False"; private boolean booleanValue; /** * Property Boolean type constructor (namespaceURI is given) * * @param metadata * The metadata to attach to this property * @param namespaceURI * the namespace URI to associate to this property * @param prefix * The prefix to set for this property * @param propertyName * The local Name of this property * @param value * the value to give */ public BooleanType(XMPMetadata metadata, String namespaceURI, String prefix, String propertyName, Object value) { super(metadata, namespaceURI, prefix, propertyName, value); } /** * return the property value * * @return boolean the property value */ @Override public Boolean getValue() { return booleanValue; } /** * Set value of this property BooleanTypeObject accept String value or a boolean * * @param value * The value to set * */ @Override public void setValue(Object value) {<FILL_FUNCTION_BODY>} @Override public String getStringValue() { return booleanValue ? TRUE : FALSE; } }
if (value instanceof Boolean) { booleanValue = (Boolean) value; } else if (value instanceof String) { // NumberFormatException is thrown (sub of InvalidArgumentException) String s = value.toString().trim().toUpperCase(); if ("TRUE".equals(s)) { booleanValue = true; } else if ("FALSE".equals(s)) { booleanValue = false; } else { // unknown value throw new IllegalArgumentException("Not a valid boolean value : '" + value + "'"); } } else { // invalid type of value throw new IllegalArgumentException("Value given is not allowed for the Boolean type."); }
354
185
539
<methods>public void <init>(org.apache.xmpbox.XMPMetadata, java.lang.String, java.lang.String, java.lang.String, java.lang.Object) ,public final java.lang.String getNamespace() ,public java.lang.String getPrefix() ,public java.lang.Object getRawValue() ,public abstract java.lang.String getStringValue() ,public abstract java.lang.Object getValue() ,public abstract void setValue(java.lang.Object) ,public java.lang.String toString() <variables>private final non-sealed java.lang.String namespace,private final non-sealed java.lang.String prefix,private final non-sealed java.lang.Object rawValue
apache_pdfbox
pdfbox/xmpbox/src/main/java/org/apache/xmpbox/type/ComplexPropertyContainer.java
ComplexPropertyContainer
removePropertiesByName
class ComplexPropertyContainer { private final List<AbstractField> properties; /** * Complex Property type constructor (namespaceURI is given) * */ public ComplexPropertyContainer() { properties = new ArrayList<>(); } /** * Give the first property found in this container with type and localname expected * * @param localName * the localname of property wanted * @param type * the property type of property wanted * @return the property wanted */ protected AbstractField getFirstEquivalentProperty(String localName, Class<? extends AbstractField> type) { List<AbstractField> list = getPropertiesByLocalName(localName); if (list != null) { for (AbstractField abstractField : list) { if (abstractField.getClass().equals(type)) { return abstractField; } } } return null; } /** * Add a property to the current structure * * @param obj * the property to add */ public void addProperty(AbstractField obj) { removeProperty(obj); properties.add(obj); } /** * Return all children associated to this property * * @return All Properties contained in this container, never null. */ public List<AbstractField> getAllProperties() { return properties; } /** * Return all properties with this specified localName. * * @param localName the local name wanted * @return All properties with local name which match with localName given, or null if there are * none. */ public List<AbstractField> getPropertiesByLocalName(String localName) { List<AbstractField> list = getAllProperties().stream(). filter(abstractField -> (abstractField.getPropertyName().equals(localName))). collect(Collectors.toList()); if (list.isEmpty()) { return null; } else { return list; } } /** * Check if two properties are equal. * * @param prop1 * First property * @param prop2 * Second property * @return True if these properties are equal. */ public boolean isSameProperty(AbstractField prop1, AbstractField prop2) { if (prop1.getClass().equals(prop2.getClass())) { String pn1 = prop1.getPropertyName(); String pn2 = prop2.getPropertyName(); if (pn1 == null) { return pn2 == null; } else { if (pn1.equals(pn2)) { return prop1.equals(prop2); } } } return false; } /** * Check if a XMPFieldObject is in the complex property * * @param property * The property to check * @return True if property is present in this container */ public boolean containsProperty(AbstractField property) { Iterator<AbstractField> it = getAllProperties().iterator(); AbstractField tmp; while (it.hasNext()) { tmp = it.next(); if (isSameProperty(tmp, property)) { return true; } } return false; } /** * Remove a property * * @param property * The property to remove */ public void removeProperty(AbstractField property) { properties.remove(property); } /** * Remove all properties with a specified LocalName. * * @param localName The name for which to remove all. */ public void removePropertiesByName(String localName) {<FILL_FUNCTION_BODY>} }
if (properties.isEmpty()) { return; } List<AbstractField> propList = getPropertiesByLocalName(localName); if (propList == null) { return; } propList.forEach(properties::remove);
1,012
70
1,082
<no_super_class>
apache_pdfbox
pdfbox/xmpbox/src/main/java/org/apache/xmpbox/type/DateType.java
DateType
isGoodType
class DateType extends AbstractSimpleProperty { private Calendar dateValue; /** * Property Date type constructor (namespaceURI is given) * * @param metadata * The metadata to attach to this property * @param namespaceURI * the namespace URI to associate to this property * @param prefix * The prefix to set for this property * @param propertyName * The local Name of this property * @param value * The value to set for this property */ public DateType(XMPMetadata metadata, String namespaceURI, String prefix, String propertyName, Object value) { super(metadata, namespaceURI, prefix, propertyName, value); } /** * Set property value * * @param value the new Calendar element value */ private void setValueFromCalendar(Calendar value) { dateValue = value; } /** * return the property value * * @return boolean */ @Override public Calendar getValue() { return dateValue; } /** * Check if the value has a type which can be understood * * @param value * Object value to check * @return True if types are compatibles */ private boolean isGoodType(Object value) {<FILL_FUNCTION_BODY>} /** * Set value of this property * * @param value * The value to set */ @Override public void setValue(Object value) { if (!isGoodType(value)) { if (value == null) { throw new IllegalArgumentException( "Value null is not allowed for the Date type"); } throw new IllegalArgumentException( "Value given is not allowed for the Date type: " + value.getClass() + ", value: " + value); } else { // if string object if (value instanceof String) { setValueFromString((String) value); } else { // if Calendar setValueFromCalendar((Calendar) value); } } } @Override public String getStringValue() { return DateConverter.toISO8601(dateValue); } /** * Set the property value with a String * * @param value * The String value */ private void setValueFromString(String value) { try { setValueFromCalendar(DateConverter.toCalendar(value)); } catch (IOException e) { // SHOULD NEVER HAPPEN // STRING HAS BEEN CHECKED BEFORE throw new IllegalArgumentException(e); } } }
if (value instanceof Calendar) { return true; } else if (value instanceof String) { try { DateConverter.toCalendar((String) value); return true; } catch (IOException e) { return false; } } return false;
722
86
808
<methods>public void <init>(org.apache.xmpbox.XMPMetadata, java.lang.String, java.lang.String, java.lang.String, java.lang.Object) ,public final java.lang.String getNamespace() ,public java.lang.String getPrefix() ,public java.lang.Object getRawValue() ,public abstract java.lang.String getStringValue() ,public abstract java.lang.Object getValue() ,public abstract void setValue(java.lang.Object) ,public java.lang.String toString() <variables>private final non-sealed java.lang.String namespace,private final non-sealed java.lang.String prefix,private final non-sealed java.lang.Object rawValue
apache_pdfbox
pdfbox/xmpbox/src/main/java/org/apache/xmpbox/type/IntegerType.java
IntegerType
setValue
class IntegerType extends AbstractSimpleProperty { private int integerValue; /** * Property Integer type constructor (namespaceURI is given) * * @param metadata * The metadata to attach to this property * @param namespaceURI * the namespace URI to associate to this property * @param prefix * The prefix to set for this property * @param propertyName * The local Name of this property * @param value * The value to set */ public IntegerType(XMPMetadata metadata, String namespaceURI, String prefix, String propertyName, Object value) { super(metadata, namespaceURI, prefix, propertyName, value); } /** * return the property value * * @return the property value */ @Override public Integer getValue() { return integerValue; } /** * Set the property value * * @param value * The value to set */ @Override public void setValue(Object value) {<FILL_FUNCTION_BODY>} @Override public String getStringValue() { return Integer.toString(integerValue); } }
if (value instanceof Integer) { integerValue = (Integer) value; } else if (value instanceof String) { integerValue = Integer.parseInt((String) value); // NumberFormatException is thrown (sub of InvalidArgumentException) } else { // invalid type of value throw new IllegalArgumentException("Value given is not allowed for the Integer type: " + value); }
316
107
423
<methods>public void <init>(org.apache.xmpbox.XMPMetadata, java.lang.String, java.lang.String, java.lang.String, java.lang.Object) ,public final java.lang.String getNamespace() ,public java.lang.String getPrefix() ,public java.lang.Object getRawValue() ,public abstract java.lang.String getStringValue() ,public abstract java.lang.Object getValue() ,public abstract void setValue(java.lang.Object) ,public java.lang.String toString() <variables>private final non-sealed java.lang.String namespace,private final non-sealed java.lang.String prefix,private final non-sealed java.lang.Object rawValue
apache_pdfbox
pdfbox/xmpbox/src/main/java/org/apache/xmpbox/type/LayerType.java
LayerType
getLayerName
class LayerType extends AbstractStructuredType { @PropertyType(type = Types.Text, card = Cardinality.Simple) public static final String LAYER_NAME = "LayerName"; @PropertyType(type = Types.Text, card = Cardinality.Simple) public static final String LAYER_TEXT = "LayerText"; public LayerType(XMPMetadata metadata) { super(metadata); setAttribute(new Attribute(XmpConstants.RDF_NAMESPACE, "parseType", "Resource")); } /** * Get The LayerName data * * @return the LayerName */ public String getLayerName() {<FILL_FUNCTION_BODY>} /** * Set LayerName * * @param image * the value of LayerName property to set */ public void setLayerName(String image) { this.addProperty(createTextType(LAYER_NAME, image)); } /** * Get The LayerText data * * @return the LayerText */ public String getLayerText() { AbstractField absProp = getFirstEquivalentProperty(LAYER_TEXT, TextType.class); if (absProp != null) { return ((TextType) absProp).getStringValue(); } return null; } /** * Set LayerText * * @param image * the value of LayerText property to set */ public void setLayerText(String image) { this.addProperty(createTextType(LAYER_TEXT, image)); } }
AbstractField absProp = getFirstEquivalentProperty(LAYER_NAME, TextType.class); if (absProp != null) { return ((TextType) absProp).getStringValue(); } return null;
440
60
500
<methods>public void <init>(org.apache.xmpbox.XMPMetadata) ,public void <init>(org.apache.xmpbox.XMPMetadata, java.lang.String) ,public void <init>(org.apache.xmpbox.XMPMetadata, java.lang.String, java.lang.String, java.lang.String) ,public org.apache.xmpbox.type.ArrayProperty createArrayProperty(java.lang.String, org.apache.xmpbox.type.Cardinality) ,public org.apache.xmpbox.type.TextType createTextType(java.lang.String, java.lang.String) ,public final java.lang.String getNamespace() ,public final java.lang.String getPreferedPrefix() ,public final java.lang.String getPrefix() ,public final void setNamespace(java.lang.String) ,public final void setPrefix(java.lang.String) <variables>protected static final java.lang.String STRUCTURE_ARRAY_NAME,private java.lang.String namespace,private java.lang.String preferedPrefix,private java.lang.String prefix
apache_pdfbox
pdfbox/xmpbox/src/main/java/org/apache/xmpbox/type/RealType.java
RealType
setValue
class RealType extends AbstractSimpleProperty { private float realValue; /** * Property Real type constructor (namespaceURI is given) * * @param metadata * The metadata to attach to this property * @param namespaceURI * the namespace URI to associate to this property * @param prefix * The prefix to set for this property * @param propertyName * The local Name of this property * @param value * The value to set */ public RealType(XMPMetadata metadata, String namespaceURI, String prefix, String propertyName, Object value) { super(metadata, namespaceURI, prefix, propertyName, value); } /** * return the property value * * @return float the property value */ @Override public Float getValue() { return realValue; } /** * Set the property value * * @param value * The value to set */ @Override public void setValue(Object value) {<FILL_FUNCTION_BODY>} @Override public String getStringValue() { return Float.toString(realValue); } }
if (value instanceof Float) { realValue = (Float) value; } else if (value instanceof String) { // NumberFormatException is thrown (sub of InvalidArgumentException) realValue = Float.parseFloat((String) value); } else { // invalid type of value throw new IllegalArgumentException("Value given is not allowed for the Real type: " + value); }
319
109
428
<methods>public void <init>(org.apache.xmpbox.XMPMetadata, java.lang.String, java.lang.String, java.lang.String, java.lang.Object) ,public final java.lang.String getNamespace() ,public java.lang.String getPrefix() ,public java.lang.Object getRawValue() ,public abstract java.lang.String getStringValue() ,public abstract java.lang.Object getValue() ,public abstract void setValue(java.lang.Object) ,public java.lang.String toString() <variables>private final non-sealed java.lang.String namespace,private final non-sealed java.lang.String prefix,private final non-sealed java.lang.Object rawValue
apache_pdfbox
pdfbox/xmpbox/src/main/java/org/apache/xmpbox/type/TextType.java
TextType
setValue
class TextType extends AbstractSimpleProperty { private String textValue; /** * Property Text type constructor (namespaceURI is given) * * @param metadata * The metadata to attach to this property * @param namespaceURI * the namespace URI to associate to this property * @param prefix * The prefix to set for this property * @param propertyName * The local Name of this property * @param value * The value to set */ public TextType(XMPMetadata metadata, String namespaceURI, String prefix, String propertyName, Object value) { super(metadata, namespaceURI, prefix, propertyName, value); } /** * Set the property value * * @param value * The value to set */ @Override public void setValue(Object value) {<FILL_FUNCTION_BODY>} @Override public String getStringValue() { return textValue; } @Override public Object getValue() { return textValue; } }
if (!(value instanceof String)) { throw new IllegalArgumentException("Value given is not allowed for the Text type : '" + value + "'"); } else { textValue = (String) value; }
287
61
348
<methods>public void <init>(org.apache.xmpbox.XMPMetadata, java.lang.String, java.lang.String, java.lang.String, java.lang.Object) ,public final java.lang.String getNamespace() ,public java.lang.String getPrefix() ,public java.lang.Object getRawValue() ,public abstract java.lang.String getStringValue() ,public abstract java.lang.Object getValue() ,public abstract void setValue(java.lang.Object) ,public java.lang.String toString() <variables>private final non-sealed java.lang.String namespace,private final non-sealed java.lang.String prefix,private final non-sealed java.lang.Object rawValue
apache_pdfbox
pdfbox/xmpbox/src/main/java/org/apache/xmpbox/type/ThumbnailType.java
ThumbnailType
getHeight
class ThumbnailType extends AbstractStructuredType { @PropertyType(type = Types.Choice, card = Cardinality.Simple) public static final String FORMAT = "format"; @PropertyType(type = Types.Integer, card = Cardinality.Simple) public static final String HEIGHT = "height"; @PropertyType(type = Types.Integer, card = Cardinality.Simple) public static final String WIDTH = "width"; @PropertyType(type = Types.Text, card = Cardinality.Simple) public static final String IMAGE = "image"; /** * * @param metadata * The metadata to attach to this property */ public ThumbnailType(XMPMetadata metadata) { super(metadata); setAttribute(new Attribute(XmpConstants.RDF_NAMESPACE, "parseType", "Resource")); } /** * Get Height * * @return the height */ public Integer getHeight() {<FILL_FUNCTION_BODY>} /** * Set Height * * @param height * the value of Height property to set */ public void setHeight(Integer height) { addSimpleProperty(HEIGHT, height); } /** * Get Width * * @return the width */ public Integer getWidth() { AbstractField absProp = getFirstEquivalentProperty(WIDTH, IntegerType.class); if (absProp != null) { return ((IntegerType) absProp).getValue(); } return null; } /** * Set Width * * @param width * the value of width property to set */ public void setWidth(Integer width) { addSimpleProperty(WIDTH, width); } /** * Get The img data * * @return the img */ public String getImage() { AbstractField absProp = getFirstEquivalentProperty(IMAGE, TextType.class); if (absProp != null) { return ((TextType) absProp).getStringValue(); } return null; } /** * Set Image data * * @param image * the value of image property to set */ public void setImage(String image) { addSimpleProperty(IMAGE, image); } /** * Get Format * * @return the format */ public String getFormat() { AbstractField absProp = getFirstEquivalentProperty(FORMAT, ChoiceType.class); if (absProp != null) { return ((TextType) absProp).getStringValue(); } return null; } /** * Set Format * * @param format * the value of format property to set */ public void setFormat(String format) { addSimpleProperty(FORMAT, format); } }
AbstractField absProp = getFirstEquivalentProperty(HEIGHT, IntegerType.class); if (absProp != null) { return ((IntegerType) absProp).getValue(); } return null;
799
57
856
<methods>public void <init>(org.apache.xmpbox.XMPMetadata) ,public void <init>(org.apache.xmpbox.XMPMetadata, java.lang.String) ,public void <init>(org.apache.xmpbox.XMPMetadata, java.lang.String, java.lang.String, java.lang.String) ,public org.apache.xmpbox.type.ArrayProperty createArrayProperty(java.lang.String, org.apache.xmpbox.type.Cardinality) ,public org.apache.xmpbox.type.TextType createTextType(java.lang.String, java.lang.String) ,public final java.lang.String getNamespace() ,public final java.lang.String getPreferedPrefix() ,public final java.lang.String getPrefix() ,public final void setNamespace(java.lang.String) ,public final void setPrefix(java.lang.String) <variables>protected static final java.lang.String STRUCTURE_ARRAY_NAME,private java.lang.String namespace,private java.lang.String preferedPrefix,private java.lang.String prefix
apache_pdfbox
pdfbox/xmpbox/src/main/java/org/apache/xmpbox/xml/DomHelper.java
DomHelper
getUniqueElementChild
class DomHelper { private DomHelper() { } public static Element getUniqueElementChild(Element description) throws XmpParsingException {<FILL_FUNCTION_BODY>} /** * Return the first child element of the element parameter. If there is no child, null is returned * * @param description the parent element * @return the first child element. Might be null. */ public static Element getFirstChildElement(Element description) { NodeList nl = description.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { if (nl.item(i) instanceof Element) { return (Element) nl.item(i); } } return null; } public static List<Element> getElementChildren(Element description) { NodeList nl = description.getChildNodes(); List<Element> ret = new ArrayList<>(nl.getLength()); for (int i = 0; i < nl.getLength(); i++) { if (nl.item(i) instanceof Element) { ret.add((Element) nl.item(i)); } } return ret; } public static QName getQName(Element element) { return new QName(element.getNamespaceURI(), element.getLocalName(), element.getPrefix()); } public static boolean isRdfDescription(Element element) { return (XmpConstants.DEFAULT_RDF_PREFIX.equals(element.getPrefix()) && XmpConstants.DESCRIPTION_NAME .equals(element.getLocalName())); } public static boolean isParseTypeResource(Element element) { Attr parseType = element.getAttributeNodeNS(XmpConstants.RDF_NAMESPACE, XmpConstants.PARSE_TYPE); return parseType != null && XmpConstants.RESOURCE_NAME.equals(parseType.getValue()); } }
NodeList nl = description.getChildNodes(); int pos = -1; for (int i = 0; i < nl.getLength(); i++) { if (nl.item(i) instanceof Element) { if (pos >= 0) { // invalid : found two child elements throw new XmpParsingException(ErrorType.Undefined, "Found two child elements in " + description); } else { pos = i; } } } return (Element) nl.item(pos);
517
148
665
<no_super_class>
pf4j_pf4j
pf4j/demo/app/src/main/java/org/pf4j/demo/Boot.java
Boot
main
class Boot { private static final Logger log = LoggerFactory.getLogger(Boot.class); public static void main(String[] args) {<FILL_FUNCTION_BODY>} private static void printLogo() { log.info(StringUtils.repeat("#", 40)); log.info(StringUtils.center("PF4J-DEMO", 40)); log.info(StringUtils.repeat("#", 40)); } }
// print logo printLogo(); // create the plugin manager PluginManager pluginManager = new DemoPluginManager(); // load the plugins pluginManager.loadPlugins(); // enable a disabled plugin // pluginManager.enablePlugin("welcome-plugin"); // start (active/resolved) the plugins pluginManager.startPlugins(); // retrieves the extensions for Greeting extension point List<Greeting> greetings = pluginManager.getExtensions(Greeting.class); log.info("Found {} extensions for extension point '{}'", greetings.size(), Greeting.class.getName()); for (Greeting greeting : greetings) { log.info(">>> {}", greeting.getGreeting()); } // print extensions from classpath (non plugin) log.info("Extensions added by classpath:"); Set<String> extensionClassNames = pluginManager.getExtensionClassNames(null); for (String extension : extensionClassNames) { log.info(" {}", extension); } log.info("Extension classes by classpath:"); List<Class<? extends Greeting>> greetingsClasses = pluginManager.getExtensionClasses(Greeting.class); for (Class<? extends Greeting> greeting : greetingsClasses) { log.info(" Class: {}", greeting.getCanonicalName()); } // print extensions ids for each started plugin List<PluginWrapper> startedPlugins = pluginManager.getStartedPlugins(); for (PluginWrapper plugin : startedPlugins) { String pluginId = plugin.getDescriptor().getPluginId(); log.info("Extensions added by plugin '{}}':", pluginId); extensionClassNames = pluginManager.getExtensionClassNames(pluginId); for (String extension : extensionClassNames) { log.info(" {}", extension); } } // print the extensions instances for Greeting extension point for each started plugin for (PluginWrapper plugin : startedPlugins) { String pluginId = plugin.getDescriptor().getPluginId(); log.info("Extensions instances added by plugin '{}' for extension point '{}':", pluginId, Greeting.class.getName()); List<Greeting> extensions = pluginManager.getExtensions(Greeting.class, pluginId); for (Object extension : extensions) { log.info(" {}", extension); } } // print extensions instances from classpath (non plugin) log.info("Extensions instances added by classpath:"); List<?> extensions = pluginManager.getExtensions((String) null); for (Object extension : extensions) { log.info(" {}", extension); } // print extensions instances for each started plugin for (PluginWrapper plugin : startedPlugins) { String pluginId = plugin.getDescriptor().getPluginId(); log.info("Extensions instances added by plugin '{}':", pluginId); extensions = pluginManager.getExtensions(pluginId); for (Object extension : extensions) { log.info(" {}", extension); } } // stop the plugins pluginManager.stopPlugins(); /* Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { pluginManager.stopPlugins(); } }); */
122
857
979
<no_super_class>
pf4j_pf4j
pf4j/demo/app/src/main/java/org/pf4j/demo/DemoPluginFactory.java
DemoPluginFactory
createInstance
class DemoPluginFactory extends DefaultPluginFactory { private static final Logger log = LoggerFactory.getLogger(DemoPluginFactory.class); @Override protected Plugin createInstance(Class<?> pluginClass, PluginWrapper pluginWrapper) {<FILL_FUNCTION_BODY>} }
PluginContext context = new PluginContext(pluginWrapper.getRuntimeMode()); try { Constructor<?> constructor = pluginClass.getConstructor(PluginContext.class); return (Plugin) constructor.newInstance(context); } catch (Exception e) { log.error(e.getMessage(), e); } return null;
77
89
166
<methods>public non-sealed void <init>() ,public org.pf4j.Plugin create(org.pf4j.PluginWrapper) <variables>private static final org.slf4j.Logger log
pf4j_pf4j
pf4j/demo/plugins/plugin1/src/main/java/org/pf4j/demo/welcome/WelcomePlugin.java
WelcomePlugin
start
class WelcomePlugin extends DemoPlugin { public WelcomePlugin(PluginContext context) { super(context); } @Override public void start() {<FILL_FUNCTION_BODY>} @Override public void stop() { log.info("WelcomePlugin.stop()"); } @Extension public static class WelcomeGreeting implements Greeting { @Override public String getGreeting() { return "Welcome"; } } }
log.info("WelcomePlugin.start()"); // for testing the development mode if (RuntimeMode.DEVELOPMENT.equals(context.getRuntimeMode())) { log.info(StringUtils.upperCase("WelcomePlugin")); }
131
63
194
<methods><variables>protected final non-sealed org.pf4j.demo.api.PluginContext context
pf4j_pf4j
pf4j/pf4j/src/main/java/org/pf4j/BasePluginLoader.java
BasePluginLoader
loadJars
class BasePluginLoader implements PluginLoader { protected PluginManager pluginManager; protected PluginClasspath pluginClasspath; public BasePluginLoader(PluginManager pluginManager, PluginClasspath pluginClasspath) { this.pluginManager = pluginManager; this.pluginClasspath = pluginClasspath; } @Override public boolean isApplicable(Path pluginPath) { return Files.exists(pluginPath); } @Override public ClassLoader loadPlugin(Path pluginPath, PluginDescriptor pluginDescriptor) { PluginClassLoader pluginClassLoader = createPluginClassLoader(pluginPath, pluginDescriptor); loadClasses(pluginPath, pluginClassLoader); loadJars(pluginPath, pluginClassLoader); return pluginClassLoader; } protected PluginClassLoader createPluginClassLoader(Path pluginPath, PluginDescriptor pluginDescriptor) { return new PluginClassLoader(pluginManager, pluginDescriptor, getClass().getClassLoader()); } /** * Add all {@code *.class} files from {@link PluginClasspath#getClassesDirectories()} * to the plugin's {@link ClassLoader}. */ protected void loadClasses(Path pluginPath, PluginClassLoader pluginClassLoader) { for (String directory : pluginClasspath.getClassesDirectories()) { File file = pluginPath.resolve(directory).toFile(); if (file.exists() && file.isDirectory()) { pluginClassLoader.addFile(file); } } } /** * Add all {@code *.jar} files from {@link PluginClasspath#getJarsDirectories()} * to the plugin's {@link ClassLoader}. */ protected void loadJars(Path pluginPath, PluginClassLoader pluginClassLoader) {<FILL_FUNCTION_BODY>} }
for (String jarsDirectory : pluginClasspath.getJarsDirectories()) { Path file = pluginPath.resolve(jarsDirectory); List<File> jars = FileUtils.getJars(file); for (File jar : jars) { pluginClassLoader.addFile(jar); } }
457
83
540
<no_super_class>
pf4j_pf4j
pf4j/pf4j/src/main/java/org/pf4j/BasePluginRepository.java
BasePluginRepository
getPluginPaths
class BasePluginRepository implements PluginRepository { protected final List<Path> pluginsRoots; protected FileFilter filter; protected Comparator<File> comparator; public BasePluginRepository(Path... pluginsRoots) { this(Arrays.asList(pluginsRoots)); } public BasePluginRepository(List<Path> pluginsRoots) { this(pluginsRoots, null); } public BasePluginRepository(List<Path> pluginsRoots, FileFilter filter) { this.pluginsRoots = pluginsRoots; this.filter = filter; // last modified file is first this.comparator = Comparator.comparingLong(File::lastModified); } public void setFilter(FileFilter filter) { this.filter = filter; } /** * Set a {@link File} {@link Comparator} used to sort the listed files from {@code pluginsRoot}. * This comparator is used in {@link #getPluginPaths()} method. * By default is used a file comparator that returns the last modified files first. * If you don't want a file comparator, then call this method with {@code null}. */ public void setComparator(Comparator<File> comparator) { this.comparator = comparator; } @Override public List<Path> getPluginPaths() {<FILL_FUNCTION_BODY>} @Override public boolean deletePluginPath(Path pluginPath) { if (!filter.accept(pluginPath.toFile())) { return false; } try { FileUtils.delete(pluginPath); return true; } catch (NoSuchFileException e) { return false; // Return false on not found to be compatible with previous API (#135) } catch (IOException e) { throw new PluginRuntimeException(e); } } protected Stream<File> streamFiles(Path directory, FileFilter filter) { File[] files = directory.toFile().listFiles(filter); return files != null ? Arrays.stream(files) : Stream.empty(); } }
return pluginsRoots.stream() .flatMap(path -> streamFiles(path, filter)) .sorted(comparator) .map(File::toPath) .collect(Collectors.toList());
549
59
608
<no_super_class>
pf4j_pf4j
pf4j/pf4j/src/main/java/org/pf4j/CompoundPluginDescriptorFinder.java
CompoundPluginDescriptorFinder
add
class CompoundPluginDescriptorFinder implements PluginDescriptorFinder { private static final Logger log = LoggerFactory.getLogger(CompoundPluginDescriptorFinder.class); private List<PluginDescriptorFinder> finders = new ArrayList<>(); public CompoundPluginDescriptorFinder add(PluginDescriptorFinder finder) {<FILL_FUNCTION_BODY>} public int size() { return finders.size(); } @Override public boolean isApplicable(Path pluginPath) { for (PluginDescriptorFinder finder : finders) { if (finder.isApplicable(pluginPath)) { return true; } } return false; } @Override public PluginDescriptor find(Path pluginPath) { for (PluginDescriptorFinder finder : finders) { if (finder.isApplicable(pluginPath)) { log.debug("'{}' is applicable for plugin '{}'", finder, pluginPath); try { PluginDescriptor pluginDescriptor = finder.find(pluginPath); if (pluginDescriptor != null) { return pluginDescriptor; } } catch (Exception e) { if (finders.indexOf(finder) == finders.size() - 1) { // it's the last finder log.error(e.getMessage(), e); } else { // log the exception and continue with the next finder log.debug(e.getMessage()); log.debug("Try to continue with the next finder"); } } } else { log.debug("'{}' is not applicable for plugin '{}'", finder, pluginPath); } } throw new PluginRuntimeException("No PluginDescriptorFinder for plugin '{}'", pluginPath); } }
if (finder == null) { throw new IllegalArgumentException("null not allowed"); } finders.add(finder); return this;
461
44
505
<no_super_class>
pf4j_pf4j
pf4j/pf4j/src/main/java/org/pf4j/CompoundPluginLoader.java
CompoundPluginLoader
add
class CompoundPluginLoader implements PluginLoader { private static final Logger log = LoggerFactory.getLogger(CompoundPluginLoader.class); private List<PluginLoader> loaders = new ArrayList<>(); public CompoundPluginLoader add(PluginLoader loader) {<FILL_FUNCTION_BODY>} /** * Add a {@link PluginLoader} only if the {@code condition} is satisfied. * * @param loader * @param condition * @return */ public CompoundPluginLoader add(PluginLoader loader, BooleanSupplier condition) { if (condition.getAsBoolean()) { return add(loader); } return this; } public int size() { return loaders.size(); } @Override public boolean isApplicable(Path pluginPath) { for (PluginLoader loader : loaders) { if (loader.isApplicable(pluginPath)) { return true; } } return false; } @Override public ClassLoader loadPlugin(Path pluginPath, PluginDescriptor pluginDescriptor) { for (PluginLoader loader : loaders) { if (loader.isApplicable(pluginPath)) { log.debug("'{}' is applicable for plugin '{}'", loader, pluginPath); try { ClassLoader classLoader = loader.loadPlugin(pluginPath, pluginDescriptor); if (classLoader != null) { return classLoader; } } catch (Exception e) { // log the exception and continue with the next loader log.error(e.getMessage()); // ?! } } else { log.debug("'{}' is not applicable for plugin '{}'", loader, pluginPath); } } throw new RuntimeException("No PluginLoader for plugin '" + pluginPath + "' and descriptor '" + pluginDescriptor + "'"); } }
if (loader == null) { throw new IllegalArgumentException("null not allowed"); } loaders.add(loader); return this;
481
42
523
<no_super_class>
pf4j_pf4j
pf4j/pf4j/src/main/java/org/pf4j/CompoundPluginRepository.java
CompoundPluginRepository
deletePluginPath
class CompoundPluginRepository implements PluginRepository { private List<PluginRepository> repositories = new ArrayList<>(); public CompoundPluginRepository add(PluginRepository repository) { if (repository == null) { throw new IllegalArgumentException("null not allowed"); } repositories.add(repository); return this; } /** * Add a {@link PluginRepository} only if the {@code condition} is satisfied. * * @param repository * @param condition * @return */ public CompoundPluginRepository add(PluginRepository repository, BooleanSupplier condition) { if (condition.getAsBoolean()) { return add(repository); } return this; } @Override public List<Path> getPluginPaths() { Set<Path> paths = new LinkedHashSet<>(); for (PluginRepository repository : repositories) { paths.addAll(repository.getPluginPaths()); } return new ArrayList<>(paths); } @Override public boolean deletePluginPath(Path pluginPath) {<FILL_FUNCTION_BODY>} }
for (PluginRepository repository : repositories) { if (repository.deletePluginPath(pluginPath)) { return true; } } return false;
288
46
334
<no_super_class>
pf4j_pf4j
pf4j/pf4j/src/main/java/org/pf4j/DefaultExtensionFactory.java
DefaultExtensionFactory
create
class DefaultExtensionFactory implements ExtensionFactory { private static final Logger log = LoggerFactory.getLogger(DefaultExtensionFactory.class); /** * Creates an extension instance. */ @Override public <T> T create(Class<T> extensionClass) {<FILL_FUNCTION_BODY>} }
log.debug("Create instance for extension '{}'", extensionClass.getName()); try { return extensionClass.newInstance(); } catch (Exception e) { throw new PluginRuntimeException(e); }
84
58
142
<no_super_class>
pf4j_pf4j
pf4j/pf4j/src/main/java/org/pf4j/DefaultExtensionFinder.java
DefaultExtensionFinder
findClassNames
class DefaultExtensionFinder implements ExtensionFinder, PluginStateListener { protected PluginManager pluginManager; protected List<ExtensionFinder> finders = new ArrayList<>(); public DefaultExtensionFinder(PluginManager pluginManager) { this.pluginManager = pluginManager; add(new LegacyExtensionFinder(pluginManager)); // add(new ServiceProviderExtensionFinder(pluginManager)); } @Override public <T> List<ExtensionWrapper<T>> find(Class<T> type) { List<ExtensionWrapper<T>> extensions = new ArrayList<>(); for (ExtensionFinder finder : finders) { extensions.addAll(finder.find(type)); } return extensions; } @Override public <T> List<ExtensionWrapper<T>> find(Class<T> type, String pluginId) { List<ExtensionWrapper<T>> extensions = new ArrayList<>(); for (ExtensionFinder finder : finders) { extensions.addAll(finder.find(type, pluginId)); } return extensions; } @Override public List<ExtensionWrapper> find(String pluginId) { List<ExtensionWrapper> extensions = new ArrayList<>(); for (ExtensionFinder finder : finders) { extensions.addAll(finder.find(pluginId)); } return extensions; } @Override public Set<String> findClassNames(String pluginId) {<FILL_FUNCTION_BODY>} @Override public void pluginStateChanged(PluginStateEvent event) { for (ExtensionFinder finder : finders) { if (finder instanceof PluginStateListener) { ((PluginStateListener) finder).pluginStateChanged(event); } } } public DefaultExtensionFinder addServiceProviderExtensionFinder() { return add(new ServiceProviderExtensionFinder(pluginManager)); } public DefaultExtensionFinder add(ExtensionFinder finder) { finders.add(finder); return this; } }
Set<String> classNames = new HashSet<>(); for (ExtensionFinder finder : finders) { classNames.addAll(finder.findClassNames(pluginId)); } return classNames;
522
59
581
<no_super_class>
pf4j_pf4j
pf4j/pf4j/src/main/java/org/pf4j/DefaultPluginDescriptor.java
DefaultPluginDescriptor
setDependencies
class DefaultPluginDescriptor implements PluginDescriptor { private String pluginId; private String pluginDescription; private String pluginClass = Plugin.class.getName(); private String version; private String requires = "*"; // SemVer format private String provider; private List<PluginDependency> dependencies; private String license; public DefaultPluginDescriptor() { dependencies = new ArrayList<>(); } public DefaultPluginDescriptor(String pluginId, String pluginDescription, String pluginClass, String version, String requires, String provider, String license) { this(); this.pluginId = pluginId; this.pluginDescription = pluginDescription; this.pluginClass = pluginClass; this.version = version; this.requires = requires; this.provider = provider; this.license = license; } public void addDependency(PluginDependency dependency) { this.dependencies.add(dependency); } /** * Returns the unique identifier of this plugin. */ @Override public String getPluginId() { return pluginId; } /** * Returns the description of this plugin. */ @Override public String getPluginDescription() { return pluginDescription; } /** * Returns the name of the class that implements Plugin interface. */ @Override public String getPluginClass() { return pluginClass; } /** * Returns the version of this plugin. */ @Override public String getVersion() { return version; } /** * Returns string version of requires * * @return String with requires expression on SemVer format */ @Override public String getRequires() { return requires; } /** * Returns the provider name of this plugin. */ @Override public String getProvider() { return provider; } /** * Returns the legal license of this plugin, e.g. "Apache-2.0", "MIT" etc */ @Override public String getLicense() { return license; } /** * Returns all dependencies declared by this plugin. * Returns an empty array if this plugin does not declare any require. */ @Override public List<PluginDependency> getDependencies() { return dependencies; } @Override public String toString() { return "PluginDescriptor [pluginId=" + pluginId + ", pluginClass=" + pluginClass + ", version=" + version + ", provider=" + provider + ", dependencies=" + dependencies + ", description=" + pluginDescription + ", requires=" + requires + ", license=" + license + "]"; } protected DefaultPluginDescriptor setPluginId(String pluginId) { this.pluginId = pluginId; return this; } protected PluginDescriptor setPluginDescription(String pluginDescription) { this.pluginDescription = pluginDescription; return this; } protected PluginDescriptor setPluginClass(String pluginClassName) { this.pluginClass = pluginClassName; return this; } protected DefaultPluginDescriptor setPluginVersion(String version) { this.version = version; return this; } protected PluginDescriptor setProvider(String provider) { this.provider = provider; return this; } protected PluginDescriptor setRequires(String requires) { this.requires = requires; return this; } protected PluginDescriptor setDependencies(String dependencies) {<FILL_FUNCTION_BODY>} public PluginDescriptor setLicense(String license) { this.license = license; return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof DefaultPluginDescriptor)) return false; DefaultPluginDescriptor that = (DefaultPluginDescriptor) o; return Objects.equals(pluginId, that.pluginId) && Objects.equals(pluginDescription, that.pluginDescription) && Objects.equals(pluginClass, that.pluginClass) && Objects.equals(version, that.version) && Objects.equals(requires, that.requires) && Objects.equals(provider, that.provider) && dependencies.equals(that.dependencies) && Objects.equals(license, that.license); } @Override public int hashCode() { return Objects.hash(pluginId, pluginDescription, pluginClass, version, requires, provider, dependencies, license); } }
this.dependencies = new ArrayList<>(); if (dependencies != null) { dependencies = dependencies.trim(); if (!dependencies.isEmpty()) { String[] tokens = dependencies.split(","); for (String dependency : tokens) { dependency = dependency.trim(); if (!dependency.isEmpty()) { this.dependencies.add(new PluginDependency(dependency)); } } } } return this;
1,170
117
1,287
<no_super_class>
pf4j_pf4j
pf4j/pf4j/src/main/java/org/pf4j/DefaultPluginFactory.java
DefaultPluginFactory
createInstance
class DefaultPluginFactory implements PluginFactory { private static final Logger log = LoggerFactory.getLogger(DefaultPluginFactory.class); /** * Creates a plugin instance. If an error occurs than that error is logged and the method returns {@code null}. */ @Override public Plugin create(final PluginWrapper pluginWrapper) { String pluginClassName = pluginWrapper.getDescriptor().getPluginClass(); log.debug("Create instance for plugin '{}'", pluginClassName); Class<?> pluginClass; try { pluginClass = pluginWrapper.getPluginClassLoader().loadClass(pluginClassName); } catch (ClassNotFoundException e) { log.error(e.getMessage(), e); return null; } // once we have the class, we can do some checks on it to ensure // that it is a valid implementation of a plugin. int modifiers = pluginClass.getModifiers(); if (Modifier.isAbstract(modifiers) || Modifier.isInterface(modifiers) || (!Plugin.class.isAssignableFrom(pluginClass))) { log.error("The plugin class '{}' is not valid", pluginClassName); return null; } return createInstance(pluginClass, pluginWrapper); } protected Plugin createInstance(Class<?> pluginClass, PluginWrapper pluginWrapper) {<FILL_FUNCTION_BODY>} protected Plugin createUsingNoParametersConstructor(Class<?> pluginClass) { try { Constructor<?> constructor = pluginClass.getConstructor(); return (Plugin) constructor.newInstance(); } catch (Exception e) { log.error(e.getMessage(), e); } return null; } }
try { Constructor<?> constructor = pluginClass.getConstructor(PluginWrapper.class); return (Plugin) constructor.newInstance(pluginWrapper); } catch (NoSuchMethodException e) { return createUsingNoParametersConstructor(pluginClass); } catch (Exception e) { log.error(e.getMessage(), e); } return null;
436
95
531
<no_super_class>
pf4j_pf4j
pf4j/pf4j/src/main/java/org/pf4j/DefaultPluginManager.java
DefaultPluginManager
loadPluginFromPath
class DefaultPluginManager extends AbstractPluginManager { private static final Logger log = LoggerFactory.getLogger(DefaultPluginManager.class); public static final String PLUGINS_DIR_CONFIG_PROPERTY_NAME = "pf4j.pluginsConfigDir"; public DefaultPluginManager() { super(); } public DefaultPluginManager(Path... pluginsRoots) { super(pluginsRoots); } public DefaultPluginManager(List<Path> pluginsRoots) { super(pluginsRoots); } @Override protected PluginDescriptorFinder createPluginDescriptorFinder() { return new CompoundPluginDescriptorFinder() .add(new PropertiesPluginDescriptorFinder()) .add(new ManifestPluginDescriptorFinder()); } @Override protected ExtensionFinder createExtensionFinder() { DefaultExtensionFinder extensionFinder = new DefaultExtensionFinder(this); addPluginStateListener(extensionFinder); return extensionFinder; } @Override protected PluginFactory createPluginFactory() { return new DefaultPluginFactory(); } @Override protected ExtensionFactory createExtensionFactory() { return new DefaultExtensionFactory(); } @Override protected PluginStatusProvider createPluginStatusProvider() { String configDir = System.getProperty(PLUGINS_DIR_CONFIG_PROPERTY_NAME); Path configPath = configDir != null ? Paths.get(configDir) : getPluginsRoots().stream() .findFirst() .orElseThrow(() -> new IllegalArgumentException("No pluginsRoot configured")); return new DefaultPluginStatusProvider(configPath); } @Override protected PluginRepository createPluginRepository() { return new CompoundPluginRepository() .add(new DevelopmentPluginRepository(getPluginsRoots()), this::isDevelopment) .add(new JarPluginRepository(getPluginsRoots()), this::isNotDevelopment) .add(new DefaultPluginRepository(getPluginsRoots()), this::isNotDevelopment); } @Override protected PluginLoader createPluginLoader() { return new CompoundPluginLoader() .add(new DevelopmentPluginLoader(this), this::isDevelopment) .add(new JarPluginLoader(this), this::isNotDevelopment) .add(new DefaultPluginLoader(this), this::isNotDevelopment); } @Override protected VersionManager createVersionManager() { return new DefaultVersionManager(); } @Override protected void initialize() { super.initialize(); if (isDevelopment()) { addPluginStateListener(new LoggingPluginStateListener()); } log.info("PF4J version {} in '{}' mode", getVersion(), getRuntimeMode()); } /** * Load a plugin from disk. If the path is a zip file, first unpack. * * @param pluginPath plugin location on disk * @return PluginWrapper for the loaded plugin or null if not loaded * @throws PluginRuntimeException if problems during load */ @Override protected PluginWrapper loadPluginFromPath(Path pluginPath) {<FILL_FUNCTION_BODY>} }
// First unzip any ZIP files try { pluginPath = FileUtils.expandIfZip(pluginPath); } catch (Exception e) { log.warn("Failed to unzip " + pluginPath, e); return null; } return super.loadPluginFromPath(pluginPath);
812
81
893
<methods>public synchronized void addPluginStateListener(org.pf4j.PluginStateListener) ,public boolean deletePlugin(java.lang.String) ,public boolean disablePlugin(java.lang.String) ,public boolean enablePlugin(java.lang.String) ,public Set<java.lang.String> getExtensionClassNames(java.lang.String) ,public List<Class<?>> getExtensionClasses(java.lang.String) ,public List<Class<? extends T>> getExtensionClasses(Class<T>) ,public List<Class<? extends T>> getExtensionClasses(Class<T>, java.lang.String) ,public org.pf4j.ExtensionFactory getExtensionFactory() ,public List<T> getExtensions(Class<T>) ,public List<T> getExtensions(Class<T>, java.lang.String) ,public List#RAW getExtensions(java.lang.String) ,public org.pf4j.PluginWrapper getPlugin(java.lang.String) ,public java.lang.ClassLoader getPluginClassLoader(java.lang.String) ,public org.pf4j.PluginLoader getPluginLoader() ,public List<org.pf4j.PluginWrapper> getPlugins() ,public List<org.pf4j.PluginWrapper> getPlugins(org.pf4j.PluginState) ,public java.nio.file.Path getPluginsRoot() ,public List<java.nio.file.Path> getPluginsRoots() ,public List<org.pf4j.PluginWrapper> getResolvedPlugins() ,public org.pf4j.RuntimeMode getRuntimeMode() ,public List<org.pf4j.PluginWrapper> getStartedPlugins() ,public java.lang.String getSystemVersion() ,public List<org.pf4j.PluginWrapper> getUnresolvedPlugins() ,public java.lang.String getVersion() ,public org.pf4j.VersionManager getVersionManager() ,public boolean isExactVersionAllowed() ,public java.lang.String loadPlugin(java.nio.file.Path) ,public void loadPlugins() ,public synchronized void removePluginStateListener(org.pf4j.PluginStateListener) ,public void setExactVersionAllowed(boolean) ,public void setSystemVersion(java.lang.String) ,public org.pf4j.PluginState startPlugin(java.lang.String) ,public void startPlugins() ,public org.pf4j.PluginState stopPlugin(java.lang.String) ,public void stopPlugins() ,public boolean unloadPlugin(java.lang.String) ,public void unloadPlugins() ,public org.pf4j.PluginWrapper whichPlugin(Class<?>) <variables>public static final java.lang.String DEFAULT_PLUGINS_DIR,public static final java.lang.String DEVELOPMENT_PLUGINS_DIR,public static final java.lang.String MODE_PROPERTY_NAME,public static final java.lang.String PLUGINS_DIR_PROPERTY_NAME,protected org.pf4j.DependencyResolver dependencyResolver,protected boolean exactVersionAllowed,protected org.pf4j.ExtensionFactory extensionFactory,protected org.pf4j.ExtensionFinder extensionFinder,private static final org.slf4j.Logger log,protected Map<java.lang.String,java.lang.ClassLoader> pluginClassLoaders,protected org.pf4j.PluginDescriptorFinder pluginDescriptorFinder,protected org.pf4j.PluginFactory pluginFactory,protected org.pf4j.PluginLoader pluginLoader,protected org.pf4j.PluginRepository pluginRepository,protected List<org.pf4j.PluginStateListener> pluginStateListeners,protected org.pf4j.PluginStatusProvider pluginStatusProvider,protected Map<java.lang.String,org.pf4j.PluginWrapper> plugins,protected final List<java.nio.file.Path> pluginsRoots,protected org.pf4j.AbstractPluginManager.ResolveRecoveryStrategy resolveRecoveryStrategy,protected List<org.pf4j.PluginWrapper> resolvedPlugins,protected org.pf4j.RuntimeMode runtimeMode,protected List<org.pf4j.PluginWrapper> startedPlugins,protected java.lang.String systemVersion,protected List<org.pf4j.PluginWrapper> unresolvedPlugins,protected org.pf4j.VersionManager versionManager
pf4j_pf4j
pf4j/pf4j/src/main/java/org/pf4j/DefaultPluginRepository.java
DefaultPluginRepository
expandIfZip
class DefaultPluginRepository extends BasePluginRepository { private static final Logger log = LoggerFactory.getLogger(DefaultPluginRepository.class); public DefaultPluginRepository(Path... pluginsRoots) { this(Arrays.asList(pluginsRoots)); } public DefaultPluginRepository(List<Path> pluginsRoots) { super(pluginsRoots); AndFileFilter pluginsFilter = new AndFileFilter(new DirectoryFileFilter()); pluginsFilter.addFileFilter(new NotFileFilter(createHiddenPluginFilter())); setFilter(pluginsFilter); } @Override public List<Path> getPluginPaths() { extractZipFiles(); return super.getPluginPaths(); } @Override public boolean deletePluginPath(Path pluginPath) { FileUtils.optimisticDelete(FileUtils.findWithEnding(pluginPath, ".zip", ".ZIP", ".Zip")); return super.deletePluginPath(pluginPath); } protected FileFilter createHiddenPluginFilter() { return new OrFileFilter(new HiddenFilter()); } private void extractZipFiles() { // expand plugins zip files pluginsRoots.stream() .flatMap(path -> streamFiles(path, new ZipFileFilter())) .map(File::toPath) .forEach(this::expandIfZip); } private void expandIfZip(Path filePath) {<FILL_FUNCTION_BODY>} }
try { FileUtils.expandIfZip(filePath); } catch (IOException e) { log.error("Cannot expand plugin zip '{}'", filePath); log.error(e.getMessage(), e); }
372
61
433
<methods>public transient void <init>(java.nio.file.Path[]) ,public void <init>(List<java.nio.file.Path>) ,public void <init>(List<java.nio.file.Path>, java.io.FileFilter) ,public boolean deletePluginPath(java.nio.file.Path) ,public List<java.nio.file.Path> getPluginPaths() ,public void setComparator(Comparator<java.io.File>) ,public void setFilter(java.io.FileFilter) <variables>protected Comparator<java.io.File> comparator,protected java.io.FileFilter filter,protected final non-sealed List<java.nio.file.Path> pluginsRoots
pf4j_pf4j
pf4j/pf4j/src/main/java/org/pf4j/DefaultPluginStatusProvider.java
DefaultPluginStatusProvider
enablePlugin
class DefaultPluginStatusProvider implements PluginStatusProvider { private static final Logger log = LoggerFactory.getLogger(DefaultPluginStatusProvider.class); private final Path pluginsRoot; private List<String> enabledPlugins; private List<String> disabledPlugins; public DefaultPluginStatusProvider(Path pluginsRoot) { this.pluginsRoot = pluginsRoot; try { // create a list with plugin identifiers that should be only accepted by this manager (whitelist from plugins/enabled.txt file) enabledPlugins = FileUtils.readLines(getEnabledFilePath(), true); log.info("Enabled plugins: {}", enabledPlugins); // create a list with plugin identifiers that should not be accepted by this manager (blacklist from plugins/disabled.txt file) disabledPlugins = FileUtils.readLines(getDisabledFilePath(), true); log.info("Disabled plugins: {}", disabledPlugins); } catch (IOException e) { log.error(e.getMessage(), e); } } @Override public boolean isPluginDisabled(String pluginId) { if (disabledPlugins.contains(pluginId)) { return true; } return !enabledPlugins.isEmpty() && !enabledPlugins.contains(pluginId); } @Override public void disablePlugin(String pluginId) { if (isPluginDisabled(pluginId)) { // do nothing return; } if (Files.exists(getEnabledFilePath())) { enabledPlugins.remove(pluginId); try { FileUtils.writeLines(enabledPlugins, getEnabledFilePath()); } catch (IOException e) { throw new PluginRuntimeException(e); } } else { disabledPlugins.add(pluginId); try { FileUtils.writeLines(disabledPlugins, getDisabledFilePath()); } catch (IOException e) { throw new PluginRuntimeException(e); } } } @Override public void enablePlugin(String pluginId) {<FILL_FUNCTION_BODY>} public Path getEnabledFilePath() { return getEnabledFilePath(pluginsRoot); } public Path getDisabledFilePath() { return getDisabledFilePath(pluginsRoot); } public static Path getEnabledFilePath(Path pluginsRoot) { return pluginsRoot.resolve("enabled.txt"); } public static Path getDisabledFilePath(Path pluginsRoot) { return pluginsRoot.resolve("disabled.txt"); } }
if (!isPluginDisabled(pluginId)) { // do nothing return; } if (Files.exists(getEnabledFilePath())) { enabledPlugins.add(pluginId); try { FileUtils.writeLines(enabledPlugins, getEnabledFilePath()); } catch (IOException e) { throw new PluginRuntimeException(e); } } else { disabledPlugins.remove(pluginId); try { FileUtils.writeLines(disabledPlugins, getDisabledFilePath()); } catch (IOException e) { throw new PluginRuntimeException(e); } }
666
170
836
<no_super_class>
pf4j_pf4j
pf4j/pf4j/src/main/java/org/pf4j/DevelopmentPluginRepository.java
DevelopmentPluginRepository
createHiddenPluginFilter
class DevelopmentPluginRepository extends BasePluginRepository { public static final String MAVEN_BUILD_DIR = "target"; public static final String GRADLE_BUILD_DIR = "build"; public DevelopmentPluginRepository(Path... pluginsRoots) { this(Arrays.asList(pluginsRoots)); } public DevelopmentPluginRepository(List<Path> pluginsRoots) { super(pluginsRoots); AndFileFilter pluginsFilter = new AndFileFilter(new DirectoryFileFilter()); pluginsFilter.addFileFilter(new NotFileFilter(createHiddenPluginFilter())); setFilter(pluginsFilter); } protected FileFilter createHiddenPluginFilter() {<FILL_FUNCTION_BODY>} }
OrFileFilter hiddenPluginFilter = new OrFileFilter(new HiddenFilter()); // skip default build output folders since these will cause errors in the logs hiddenPluginFilter .addFileFilter(new NameFileFilter(MAVEN_BUILD_DIR)) .addFileFilter(new NameFileFilter(GRADLE_BUILD_DIR)); return hiddenPluginFilter;
182
94
276
<methods>public transient void <init>(java.nio.file.Path[]) ,public void <init>(List<java.nio.file.Path>) ,public void <init>(List<java.nio.file.Path>, java.io.FileFilter) ,public boolean deletePluginPath(java.nio.file.Path) ,public List<java.nio.file.Path> getPluginPaths() ,public void setComparator(Comparator<java.io.File>) ,public void setFilter(java.io.FileFilter) <variables>protected Comparator<java.io.File> comparator,protected java.io.FileFilter filter,protected final non-sealed List<java.nio.file.Path> pluginsRoots
pf4j_pf4j
pf4j/pf4j/src/main/java/org/pf4j/ExtensionWrapper.java
ExtensionWrapper
getExtension
class ExtensionWrapper<T> implements Comparable<ExtensionWrapper<T>> { private final ExtensionDescriptor descriptor; private final ExtensionFactory extensionFactory; private T extension; // cache public ExtensionWrapper(ExtensionDescriptor descriptor, ExtensionFactory extensionFactory) { this.descriptor = descriptor; this.extensionFactory = extensionFactory; } @SuppressWarnings("unchecked") public T getExtension() {<FILL_FUNCTION_BODY>} public ExtensionDescriptor getDescriptor() { return descriptor; } public int getOrdinal() { return descriptor.ordinal; } @Override public int compareTo(ExtensionWrapper<T> o) { return (getOrdinal() - o.getOrdinal()); } }
if (extension == null) { extension = (T) extensionFactory.create(descriptor.extensionClass); } return extension;
199
39
238
<no_super_class>
pf4j_pf4j
pf4j/pf4j/src/main/java/org/pf4j/JarPluginLoader.java
JarPluginLoader
loadPlugin
class JarPluginLoader implements PluginLoader { protected PluginManager pluginManager; public JarPluginLoader(PluginManager pluginManager) { this.pluginManager = pluginManager; } @Override public boolean isApplicable(Path pluginPath) { return Files.exists(pluginPath) && FileUtils.isJarFile(pluginPath); } @Override public ClassLoader loadPlugin(Path pluginPath, PluginDescriptor pluginDescriptor) {<FILL_FUNCTION_BODY>} }
PluginClassLoader pluginClassLoader = new PluginClassLoader(pluginManager, pluginDescriptor, getClass().getClassLoader()); pluginClassLoader.addFile(pluginPath.toFile()); return pluginClassLoader;
130
55
185
<no_super_class>
pf4j_pf4j
pf4j/pf4j/src/main/java/org/pf4j/JarPluginManager.java
JarPluginManager
createPluginRepository
class JarPluginManager extends DefaultPluginManager { public JarPluginManager() { super(); } public JarPluginManager(Path... pluginsRoots) { super(pluginsRoots); } @Override protected PluginDescriptorFinder createPluginDescriptorFinder() { return new ManifestPluginDescriptorFinder(); } @Override protected PluginLoader createPluginLoader() { return new CompoundPluginLoader() .add(new DevelopmentPluginLoader(this), this::isDevelopment) .add(new JarPluginLoader(this), this::isNotDevelopment); } @Override protected PluginRepository createPluginRepository() {<FILL_FUNCTION_BODY>} }
return new CompoundPluginRepository() .add(new DevelopmentPluginRepository(getPluginsRoots()), this::isDevelopment) .add(new JarPluginRepository(getPluginsRoots()), this::isNotDevelopment);
182
59
241
<methods>public void <init>() ,public transient void <init>(java.nio.file.Path[]) ,public void <init>(List<java.nio.file.Path>) <variables>public static final java.lang.String PLUGINS_DIR_CONFIG_PROPERTY_NAME,private static final org.slf4j.Logger log
pf4j_pf4j
pf4j/pf4j/src/main/java/org/pf4j/LegacyExtensionFinder.java
LegacyExtensionFinder
readPluginsStorages
class LegacyExtensionFinder extends AbstractExtensionFinder { private static final Logger log = LoggerFactory.getLogger(LegacyExtensionFinder.class); public static final String EXTENSIONS_RESOURCE = LegacyExtensionStorage.EXTENSIONS_RESOURCE; public LegacyExtensionFinder(PluginManager pluginManager) { super(pluginManager); } @Override public Map<String, Set<String>> readClasspathStorages() { log.debug("Reading extensions storages from classpath"); Map<String, Set<String>> result = new LinkedHashMap<>(); Set<String> bucket = new HashSet<>(); try { Enumeration<URL> urls = getClass().getClassLoader().getResources(EXTENSIONS_RESOURCE); if (urls.hasMoreElements()) { collectExtensions(urls, bucket); } else { log.debug("Cannot find '{}'", EXTENSIONS_RESOURCE); } debugExtensions(bucket); result.put(null, bucket); } catch (IOException e) { log.error(e.getMessage(), e); } return result; } @Override public Map<String, Set<String>> readPluginsStorages() {<FILL_FUNCTION_BODY>} private void collectExtensions(Enumeration<URL> urls, Set<String> bucket) throws IOException { while (urls.hasMoreElements()) { URL url = urls.nextElement(); log.debug("Read '{}'", url.getFile()); collectExtensions(url.openStream(), bucket); } } private void collectExtensions(InputStream inputStream, Set<String> bucket) throws IOException { try (Reader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8)) { ExtensionStorage.read(reader, bucket); } } }
log.debug("Reading extensions storages from plugins"); Map<String, Set<String>> result = new LinkedHashMap<>(); List<PluginWrapper> plugins = pluginManager.getPlugins(); for (PluginWrapper plugin : plugins) { String pluginId = plugin.getDescriptor().getPluginId(); log.debug("Reading extensions storage from plugin '{}'", pluginId); Set<String> bucket = new HashSet<>(); try { log.debug("Read '{}'", EXTENSIONS_RESOURCE); ClassLoader pluginClassLoader = plugin.getPluginClassLoader(); try (InputStream resourceStream = pluginClassLoader.getResourceAsStream(EXTENSIONS_RESOURCE)) { if (resourceStream == null) { log.debug("Cannot find '{}'", EXTENSIONS_RESOURCE); } else { collectExtensions(resourceStream, bucket); } } debugExtensions(bucket); result.put(pluginId, bucket); } catch (IOException e) { log.error(e.getMessage(), e); } } return result;
495
287
782
<methods>public List<ExtensionWrapper<T>> find(Class<T>) ,public List<ExtensionWrapper<T>> find(Class<T>, java.lang.String) ,public List<ExtensionWrapper#RAW> find(java.lang.String) ,public Set<java.lang.String> findClassNames(java.lang.String) ,public static org.pf4j.Extension findExtensionAnnotation(Class<?>) ,public final boolean isCheckForExtensionDependencies() ,public void pluginStateChanged(org.pf4j.PluginStateEvent) ,public abstract Map<java.lang.String,Set<java.lang.String>> readClasspathStorages() ,public abstract Map<java.lang.String,Set<java.lang.String>> readPluginsStorages() ,public void setCheckForExtensionDependencies(boolean) <variables>protected java.lang.Boolean checkForExtensionDependencies,protected volatile Map<java.lang.String,Set<java.lang.String>> entries,protected volatile Map<java.lang.String,org.pf4j.asm.ExtensionInfo> extensionInfos,private static final org.slf4j.Logger log,protected org.pf4j.PluginManager pluginManager
pf4j_pf4j
pf4j/pf4j/src/main/java/org/pf4j/LoggingPluginStateListener.java
LoggingPluginStateListener
pluginStateChanged
class LoggingPluginStateListener implements PluginStateListener { private static final Logger log = LoggerFactory.getLogger(LoggingPluginStateListener.class); @Override public void pluginStateChanged(PluginStateEvent event) {<FILL_FUNCTION_BODY>} }
log.debug("The state of plugin '{}' has changed from '{}' to '{}'", event.getPlugin().getPluginId(), event.getOldState(), event.getPluginState());
72
50
122
<no_super_class>
pf4j_pf4j
pf4j/pf4j/src/main/java/org/pf4j/ManifestPluginDescriptorFinder.java
ManifestPluginDescriptorFinder
readManifest
class ManifestPluginDescriptorFinder implements PluginDescriptorFinder { private static final Logger log = LoggerFactory.getLogger(ManifestPluginDescriptorFinder.class); public static final String PLUGIN_ID = "Plugin-Id"; public static final String PLUGIN_DESCRIPTION = "Plugin-Description"; public static final String PLUGIN_CLASS = "Plugin-Class"; public static final String PLUGIN_VERSION = "Plugin-Version"; public static final String PLUGIN_PROVIDER = "Plugin-Provider"; public static final String PLUGIN_DEPENDENCIES = "Plugin-Dependencies"; public static final String PLUGIN_REQUIRES = "Plugin-Requires"; public static final String PLUGIN_LICENSE = "Plugin-License"; @Override public boolean isApplicable(Path pluginPath) { return Files.exists(pluginPath) && (Files.isDirectory(pluginPath) || FileUtils.isZipOrJarFile(pluginPath)); } @Override public PluginDescriptor find(Path pluginPath) { Manifest manifest = readManifest(pluginPath); return createPluginDescriptor(manifest); } protected Manifest readManifest(Path pluginPath) {<FILL_FUNCTION_BODY>} protected PluginDescriptor createPluginDescriptor(Manifest manifest) { DefaultPluginDescriptor pluginDescriptor = createPluginDescriptorInstance(); // TODO validate !!! Attributes attributes = manifest.getMainAttributes(); String id = attributes.getValue(PLUGIN_ID); pluginDescriptor.setPluginId(id); String description = attributes.getValue(PLUGIN_DESCRIPTION); if (StringUtils.isNullOrEmpty(description)) { pluginDescriptor.setPluginDescription(""); } else { pluginDescriptor.setPluginDescription(description); } String clazz = attributes.getValue(PLUGIN_CLASS); if (StringUtils.isNotNullOrEmpty(clazz)) { pluginDescriptor.setPluginClass(clazz); } String version = attributes.getValue(PLUGIN_VERSION); if (StringUtils.isNotNullOrEmpty(version)) { pluginDescriptor.setPluginVersion(version); } String provider = attributes.getValue(PLUGIN_PROVIDER); pluginDescriptor.setProvider(provider); String dependencies = attributes.getValue(PLUGIN_DEPENDENCIES); pluginDescriptor.setDependencies(dependencies); String requires = attributes.getValue(PLUGIN_REQUIRES); if (StringUtils.isNotNullOrEmpty(requires)) { pluginDescriptor.setRequires(requires); } pluginDescriptor.setLicense(attributes.getValue(PLUGIN_LICENSE)); return pluginDescriptor; } protected DefaultPluginDescriptor createPluginDescriptorInstance() { return new DefaultPluginDescriptor(); } protected Manifest readManifestFromJar(Path jarPath) { try (JarFile jar = new JarFile(jarPath.toFile())) { return jar.getManifest(); } catch (IOException e) { throw new PluginRuntimeException(e, "Cannot read manifest from {}", jarPath); } } protected Manifest readManifestFromZip(Path zipPath) { try (ZipFile zip = new ZipFile(zipPath.toFile())) { ZipEntry manifestEntry = zip.getEntry("classes/META-INF/MANIFEST.MF"); try (InputStream manifestInput = zip.getInputStream(manifestEntry)) { return new Manifest(manifestInput); } } catch (IOException e) { throw new PluginRuntimeException(e, "Cannot read manifest from {}", zipPath); } } protected Manifest readManifestFromDirectory(Path pluginPath) { // legacy (the path is something like "classes/META-INF/MANIFEST.MF") Path manifestPath = FileUtils.findFile(pluginPath,"MANIFEST.MF"); if (manifestPath == null) { throw new PluginRuntimeException("Cannot find the manifest path"); } log.debug("Lookup plugin descriptor in '{}'", manifestPath); if (Files.notExists(manifestPath)) { throw new PluginRuntimeException("Cannot find '{}' path", manifestPath); } try (InputStream input = Files.newInputStream(manifestPath)) { return new Manifest(input); } catch (IOException e) { throw new PluginRuntimeException(e, "Cannot read manifest from {}", pluginPath); } } }
if (FileUtils.isJarFile(pluginPath)) { return readManifestFromJar(pluginPath); } if (FileUtils.isZipFile(pluginPath)) { return readManifestFromZip(pluginPath); } return readManifestFromDirectory(pluginPath);
1,138
81
1,219
<no_super_class>
pf4j_pf4j
pf4j/pf4j/src/main/java/org/pf4j/PluginClasspath.java
PluginClasspath
equals
class PluginClasspath { private final Set<String> classesDirectories = new HashSet<>(); private final Set<String> jarsDirectories = new HashSet<>(); /** * Get the classes directories. * * @return a set of directories that contain classes files */ public Set<String> getClassesDirectories() { return classesDirectories; } /** * Add classes directories. * * @param classesDirectories a set of directories that contain classes files * @return this object for chaining */ public PluginClasspath addClassesDirectories(String... classesDirectories) { return addClassesDirectories(Arrays.asList(classesDirectories)); } /** * Add classes directories. * * @param classesDirectories a collection of directories that contain classes files * @return this object for chaining */ public PluginClasspath addClassesDirectories(Collection<String> classesDirectories) { this.classesDirectories.addAll(classesDirectories); return this; } /** * Get the jars directories. * * @return a set of directories that contain jars files */ public Set<String> getJarsDirectories() { return jarsDirectories; } /** * Add jars directories. * * @param jarsDirectories a set of directories that contain jars files * @return this object for chaining */ public PluginClasspath addJarsDirectories(String... jarsDirectories) { return addJarsDirectories(Arrays.asList(jarsDirectories)); } /** * Add jars directories. * * @param jarsDirectories a collection of directories that contain jars files * @return this object for chaining */ public PluginClasspath addJarsDirectories(Collection<String> jarsDirectories) { this.jarsDirectories.addAll(jarsDirectories); return this; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(classesDirectories, jarsDirectories); } }
if (this == o) return true; if (!(o instanceof PluginClasspath)) return false; PluginClasspath that = (PluginClasspath) o; return classesDirectories.equals(that.classesDirectories) && jarsDirectories.equals(that.jarsDirectories);
574
76
650
<no_super_class>
pf4j_pf4j
pf4j/pf4j/src/main/java/org/pf4j/PluginDependency.java
PluginDependency
equals
class PluginDependency { private String pluginId; private String pluginVersionSupport = "*"; private final boolean optional; public PluginDependency(String dependency) { int index = dependency.indexOf('@'); if (index == -1) { this.pluginId = dependency; } else { this.pluginId = dependency.substring(0, index); if (dependency.length() > index + 1) { this.pluginVersionSupport = dependency.substring(index + 1); } } // A dependency is considered as optional, if the plugin id ends with a question mark. this.optional = this.pluginId.endsWith("?"); if (this.optional) { this.pluginId = this.pluginId.substring(0, this.pluginId.length() - 1); } } /** * Returns the unique identifier of the plugin. * * @return the plugin id */ public String getPluginId() { return pluginId; } /** * Returns the version of the plugin that is required. * * @return the version of the plugin that is required */ public String getPluginVersionSupport() { return pluginVersionSupport; } /** * Returns {@code true} if the dependency is optional, {@code false} otherwise. * * @return {@code true} if the dependency is optional, {@code false} otherwise */ public boolean isOptional() { return optional; } @Override public String toString() { return "PluginDependency [pluginId=" + pluginId + ", pluginVersionSupport=" + pluginVersionSupport + ", optional=" + optional + "]"; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(pluginId, pluginVersionSupport, optional); } }
if (this == o) return true; if (!(o instanceof PluginDependency)) return false; PluginDependency that = (PluginDependency) o; return optional == that.optional && pluginId.equals(that.pluginId) && pluginVersionSupport.equals(that.pluginVersionSupport);
500
77
577
<no_super_class>
pf4j_pf4j
pf4j/pf4j/src/main/java/org/pf4j/PluginStateEvent.java
PluginStateEvent
toString
class PluginStateEvent extends EventObject { private final PluginWrapper plugin; private final PluginState oldState; public PluginStateEvent(PluginManager source, PluginWrapper plugin, PluginState oldState) { super(source); this.plugin = plugin; this.oldState = oldState; } /** * The object on which the Event initially occurred. * * @return the PluginManager that changed the state of the plugin */ @Override public PluginManager getSource() { return (PluginManager) super.getSource(); } /** * The plugin that changed its state. * * @return the plugin that changed its state */ public PluginWrapper getPlugin() { return plugin; } /** * The new state of the plugin. * * @return the new state of the plugin */ public PluginState getPluginState() { return plugin.getPluginState(); } /** * The old state of the plugin. * * @return the old state of the plugin */ public PluginState getOldState() { return oldState; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "PluginStateEvent [plugin=" + plugin.getPluginId() + ", newState=" + getPluginState() + ", oldState=" + oldState + ']';
332
51
383
<methods>public void <init>(java.lang.Object) ,public java.lang.Object getSource() ,public java.lang.String toString() <variables>private static final long serialVersionUID,protected transient java.lang.Object source
pf4j_pf4j
pf4j/pf4j/src/main/java/org/pf4j/PluginWrapper.java
PluginWrapper
toString
class PluginWrapper { private final PluginManager pluginManager; private final PluginDescriptor descriptor; private final Path pluginPath; private final ClassLoader pluginClassLoader; private PluginFactory pluginFactory; private PluginState pluginState; private final RuntimeMode runtimeMode; private Throwable failedException; Plugin plugin; // cache public PluginWrapper(PluginManager pluginManager, PluginDescriptor descriptor, Path pluginPath, ClassLoader pluginClassLoader) { this.pluginManager = pluginManager; this.descriptor = descriptor; this.pluginPath = pluginPath; this.pluginClassLoader = pluginClassLoader; pluginState = PluginState.CREATED; runtimeMode = pluginManager.getRuntimeMode(); } /** * Returns the plugin manager. * * @return the plugin manager */ public PluginManager getPluginManager() { return pluginManager; } /** * Returns the plugin descriptor. * * @return the plugin descriptor */ public PluginDescriptor getDescriptor() { return descriptor; } /** * Returns the path of this plugin. * * @return the path of this plugin */ public Path getPluginPath() { return pluginPath; } /** * Returns the plugin {@link ClassLoader} used to load classes and resources for this plug-in. * <p> * The class loader can be used to directly access plug-in resources and classes. * * @return the plugin class loader */ public ClassLoader getPluginClassLoader() { return pluginClassLoader; } /** * Returns the plugin instance. * * @return the plugin instance */ public Plugin getPlugin() { if (plugin == null) { plugin = pluginFactory.create(this); } return plugin; } /** * Returns the plugin factory. * * @return the plugin factory */ public PluginState getPluginState() { return pluginState; } /** * Returns the runtime mode. * * @return the runtime mode */ public RuntimeMode getRuntimeMode() { return runtimeMode; } /** * Shortcut for {@code getDescriptor().getPluginId()}. */ public String getPluginId() { return getDescriptor().getPluginId(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + descriptor.getPluginId().hashCode(); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } PluginWrapper other = (PluginWrapper) obj; return descriptor.getPluginId().equals(other.descriptor.getPluginId()); } @Override public String toString() {<FILL_FUNCTION_BODY>} /** * Used internally by the framework to set the plugin factory. * * @param pluginState the plugin state */ public void setPluginState(PluginState pluginState) { this.pluginState = pluginState; } /** * Used internally by the framework to set the plugin factory. * * @param pluginFactory the plugin factory */ public void setPluginFactory(PluginFactory pluginFactory) { this.pluginFactory = pluginFactory; } /** * Returns the exception with which the plugin fails to start. * See @{link PluginStatus#FAILED}. * * @return the exception with which the plugin fails to start */ public Throwable getFailedException() { return failedException; } /** * Used internally by the framework to set the exception with which the plugin fails to start. * * @param failedException the exception with which the plugin fails to start */ public void setFailedException(Throwable failedException) { this.failedException = failedException; } }
return "PluginWrapper [descriptor=" + descriptor + ", pluginPath=" + pluginPath + "]";
1,084
29
1,113
<no_super_class>
pf4j_pf4j
pf4j/pf4j/src/main/java/org/pf4j/PropertiesPluginDescriptorFinder.java
PropertiesPluginDescriptorFinder
readProperties
class PropertiesPluginDescriptorFinder implements PluginDescriptorFinder { private static final Logger log = LoggerFactory.getLogger(PropertiesPluginDescriptorFinder.class); public static final String DEFAULT_PROPERTIES_FILE_NAME = "plugin.properties"; public static final String PLUGIN_ID = "plugin.id"; public static final String PLUGIN_DESCRIPTION = "plugin.description"; public static final String PLUGIN_CLASS = "plugin.class"; public static final String PLUGIN_VERSION = "plugin.version"; public static final String PLUGIN_PROVIDER = "plugin.provider"; public static final String PLUGIN_DEPENDENCIES = "plugin.dependencies"; public static final String PLUGIN_REQUIRES = "plugin.requires"; public static final String PLUGIN_LICENSE = "plugin.license"; protected String propertiesFileName; public PropertiesPluginDescriptorFinder() { this(DEFAULT_PROPERTIES_FILE_NAME); } public PropertiesPluginDescriptorFinder(String propertiesFileName) { this.propertiesFileName = propertiesFileName; } @Override public boolean isApplicable(Path pluginPath) { return Files.exists(pluginPath) && (Files.isDirectory(pluginPath) || FileUtils.isZipOrJarFile(pluginPath)); } @Override public PluginDescriptor find(Path pluginPath) { Properties properties = readProperties(pluginPath); return createPluginDescriptor(properties); } protected Properties readProperties(Path pluginPath) {<FILL_FUNCTION_BODY>} protected Path getPropertiesPath(Path pluginPath, String propertiesFileName) { if (Files.isDirectory(pluginPath)) { return pluginPath.resolve(Paths.get(propertiesFileName)); } // it's a zip or jar file try { return FileUtils.getPath(pluginPath, propertiesFileName); } catch (IOException e) { throw new PluginRuntimeException(e); } } protected PluginDescriptor createPluginDescriptor(Properties properties) { DefaultPluginDescriptor pluginDescriptor = createPluginDescriptorInstance(); // TODO validate !!! String id = properties.getProperty(PLUGIN_ID); pluginDescriptor.setPluginId(id); String description = properties.getProperty(PLUGIN_DESCRIPTION); if (StringUtils.isNullOrEmpty(description)) { pluginDescriptor.setPluginDescription(""); } else { pluginDescriptor.setPluginDescription(description); } String clazz = properties.getProperty(PLUGIN_CLASS); if (StringUtils.isNotNullOrEmpty(clazz)) { pluginDescriptor.setPluginClass(clazz); } String version = properties.getProperty(PLUGIN_VERSION); if (StringUtils.isNotNullOrEmpty(version)) { pluginDescriptor.setPluginVersion(version); } String provider = properties.getProperty(PLUGIN_PROVIDER); pluginDescriptor.setProvider(provider); String dependencies = properties.getProperty(PLUGIN_DEPENDENCIES); pluginDescriptor.setDependencies(dependencies); String requires = properties.getProperty(PLUGIN_REQUIRES); if (StringUtils.isNotNullOrEmpty(requires)) { pluginDescriptor.setRequires(requires); } pluginDescriptor.setLicense(properties.getProperty(PLUGIN_LICENSE)); return pluginDescriptor; } protected DefaultPluginDescriptor createPluginDescriptorInstance() { return new DefaultPluginDescriptor(); } }
Path propertiesPath = getPropertiesPath(pluginPath, propertiesFileName); if (propertiesPath == null) { throw new PluginRuntimeException("Cannot find the properties path"); } Properties properties = new Properties(); try { log.debug("Lookup plugin descriptor in '{}'", propertiesPath); if (Files.notExists(propertiesPath)) { throw new PluginRuntimeException("Cannot find '{}' path", propertiesPath); } try (InputStream input = Files.newInputStream(propertiesPath)) { properties.load(input); } catch (IOException e) { throw new PluginRuntimeException(e); } } finally { FileUtils.closePath(propertiesPath); } return properties;
899
186
1,085
<no_super_class>
pf4j_pf4j
pf4j/pf4j/src/main/java/org/pf4j/ServiceProviderExtensionFinder.java
ServiceProviderExtensionFinder
readPluginsStorages
class ServiceProviderExtensionFinder extends AbstractExtensionFinder { private static final Logger log = LoggerFactory.getLogger(ServiceProviderExtensionFinder.class); public static final String EXTENSIONS_RESOURCE = ServiceProviderExtensionStorage.EXTENSIONS_RESOURCE; public ServiceProviderExtensionFinder(PluginManager pluginManager) { super(pluginManager); } @Override public Map<String, Set<String>> readClasspathStorages() { log.debug("Reading extensions storages from classpath"); Map<String, Set<String>> result = new LinkedHashMap<>(); final Set<String> bucket = new HashSet<>(); try { Enumeration<URL> urls = getClass().getClassLoader().getResources(EXTENSIONS_RESOURCE); if (urls.hasMoreElements()) { collectExtensions(urls, bucket); } else { log.debug("Cannot find '{}'", EXTENSIONS_RESOURCE); } debugExtensions(bucket); result.put(null, bucket); } catch (IOException | URISyntaxException e) { log.error(e.getMessage(), e); } return result; } @Override public Map<String, Set<String>> readPluginsStorages() {<FILL_FUNCTION_BODY>} private void collectExtensions(Enumeration<URL> urls, Set<String> bucket) throws URISyntaxException, IOException { while (urls.hasMoreElements()) { URL url = urls.nextElement(); log.debug("Read '{}'", url.getFile()); collectExtensions(url, bucket); } } private void collectExtensions(URL url, Set<String> bucket) throws URISyntaxException, IOException { Path extensionPath; if (url.toURI().getScheme().equals("jar")) { extensionPath = FileUtils.getPath(url.toURI(), EXTENSIONS_RESOURCE); } else { extensionPath = Paths.get(url.toURI()); } try { bucket.addAll(readExtensions(extensionPath)); } finally { FileUtils.closePath(extensionPath); } } private Set<String> readExtensions(Path extensionPath) throws IOException { final Set<String> result = new HashSet<>(); Files.walkFileTree(extensionPath, Collections.<FileVisitOption>emptySet(), 1, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { log.debug("Read '{}'", file); try (Reader reader = Files.newBufferedReader(file, StandardCharsets.UTF_8)) { ExtensionStorage.read(reader, result); } return FileVisitResult.CONTINUE; } }); return result; } }
log.debug("Reading extensions storages from plugins"); Map<String, Set<String>> result = new LinkedHashMap<>(); List<PluginWrapper> plugins = pluginManager.getPlugins(); for (PluginWrapper plugin : plugins) { String pluginId = plugin.getDescriptor().getPluginId(); log.debug("Reading extensions storages for plugin '{}'", pluginId); final Set<String> bucket = new HashSet<>(); try { Enumeration<URL> urls = ((PluginClassLoader) plugin.getPluginClassLoader()).findResources(EXTENSIONS_RESOURCE); if (urls.hasMoreElements()) { collectExtensions(urls, bucket); } else { log.debug("Cannot find '{}'", EXTENSIONS_RESOURCE); } debugExtensions(bucket); result.put(pluginId, bucket); } catch (IOException | URISyntaxException e) { log.error(e.getMessage(), e); } } return result;
758
267
1,025
<methods>public List<ExtensionWrapper<T>> find(Class<T>) ,public List<ExtensionWrapper<T>> find(Class<T>, java.lang.String) ,public List<ExtensionWrapper#RAW> find(java.lang.String) ,public Set<java.lang.String> findClassNames(java.lang.String) ,public static org.pf4j.Extension findExtensionAnnotation(Class<?>) ,public final boolean isCheckForExtensionDependencies() ,public void pluginStateChanged(org.pf4j.PluginStateEvent) ,public abstract Map<java.lang.String,Set<java.lang.String>> readClasspathStorages() ,public abstract Map<java.lang.String,Set<java.lang.String>> readPluginsStorages() ,public void setCheckForExtensionDependencies(boolean) <variables>protected java.lang.Boolean checkForExtensionDependencies,protected volatile Map<java.lang.String,Set<java.lang.String>> entries,protected volatile Map<java.lang.String,org.pf4j.asm.ExtensionInfo> extensionInfos,private static final org.slf4j.Logger log,protected org.pf4j.PluginManager pluginManager
pf4j_pf4j
pf4j/pf4j/src/main/java/org/pf4j/SingletonExtensionFactory.java
SingletonExtensionFactory
create
class SingletonExtensionFactory extends DefaultExtensionFactory { private final List<String> extensionClassNames; private final Map<ClassLoader, Map<String, Object>> cache; public SingletonExtensionFactory(PluginManager pluginManager, String... extensionClassNames) { this.extensionClassNames = Arrays.asList(extensionClassNames); cache = new HashMap<>(); pluginManager.addPluginStateListener(event -> { if (event.getPluginState() != PluginState.STARTED) { cache.remove(event.getPlugin().getPluginClassLoader()); } }); } @Override @SuppressWarnings("unchecked") public <T> T create(Class<T> extensionClass) {<FILL_FUNCTION_BODY>} }
String extensionClassName = extensionClass.getName(); ClassLoader extensionClassLoader = extensionClass.getClassLoader(); if (!cache.containsKey(extensionClassLoader)) { cache.put(extensionClassLoader, new HashMap<>()); } Map<String, Object> classLoaderBucket = cache.get(extensionClassLoader); if (classLoaderBucket.containsKey(extensionClassName)) { return (T) classLoaderBucket.get(extensionClassName); } T extension = super.create(extensionClass); if (extensionClassNames.isEmpty() || extensionClassNames.contains(extensionClassName)) { classLoaderBucket.put(extensionClassName, extension); } return extension;
200
182
382
<methods>public non-sealed void <init>() ,public T create(Class<T>) <variables>private static final org.slf4j.Logger log
pf4j_pf4j
pf4j/pf4j/src/main/java/org/pf4j/ZipPluginManager.java
ZipPluginManager
createPluginRepository
class ZipPluginManager extends DefaultPluginManager { @Override protected PluginDescriptorFinder createPluginDescriptorFinder() { return new PropertiesPluginDescriptorFinder(); } @Override protected PluginLoader createPluginLoader() { return new CompoundPluginLoader() .add(new DevelopmentPluginLoader(this), this::isDevelopment) .add(new DefaultPluginLoader(this), this::isNotDevelopment); } @Override protected PluginRepository createPluginRepository() {<FILL_FUNCTION_BODY>} }
return new CompoundPluginRepository() .add(new DevelopmentPluginRepository(getPluginsRoots()), this::isDevelopment) .add(new DefaultPluginRepository(getPluginsRoots()), this::isNotDevelopment);
140
59
199
<methods>public void <init>() ,public transient void <init>(java.nio.file.Path[]) ,public void <init>(List<java.nio.file.Path>) <variables>public static final java.lang.String PLUGINS_DIR_CONFIG_PROPERTY_NAME,private static final org.slf4j.Logger log
pf4j_pf4j
pf4j/pf4j/src/main/java/org/pf4j/asm/ExtensionInfo.java
ExtensionInfo
load
class ExtensionInfo { private static final Logger log = LoggerFactory.getLogger(ExtensionInfo.class); private final String className; int ordinal = 0; List<String> plugins = new ArrayList<>(); List<String> points = new ArrayList<>(); private ExtensionInfo(String className) { this.className = className; } /** * Get the name of the class, for which extension info was created. * * @return absolute class name */ public String getClassName() { return className; } /** * Get the {@link Extension#ordinal()} value, that was assigned to the extension. * * @return ordinal value */ public int getOrdinal() { return ordinal; } /** * Get the {@link Extension#plugins()} value, that was assigned to the extension. * * @return ordinal value */ public List<String> getPlugins() { return Collections.unmodifiableList(plugins); } /** * Get the {@link Extension#points()} value, that was assigned to the extension. * * @return ordinal value */ public List<String> getPoints() { return Collections.unmodifiableList(points); } /** * Load an {@link ExtensionInfo} for a certain class. * * @param className absolute class name * @param classLoader class loader to access the class * @return the {@link ExtensionInfo}, if the class was annotated with an {@link Extension}, otherwise null */ public static ExtensionInfo load(String className, ClassLoader classLoader) {<FILL_FUNCTION_BODY>} }
try (InputStream input = classLoader.getResourceAsStream(className.replace('.', '/') + ".class")) { ExtensionInfo info = new ExtensionInfo(className); new ClassReader(input).accept(new ExtensionVisitor(info), ClassReader.SKIP_DEBUG); return info; } catch (IOException e) { log.error(e.getMessage(), e); return null; }
439
102
541
<no_super_class>
pf4j_pf4j
pf4j/pf4j/src/main/java/org/pf4j/asm/ExtensionVisitor.java
ExtensionVisitor
visit
class ExtensionVisitor extends ClassVisitor { private static final Logger log = LoggerFactory.getLogger(ExtensionVisitor.class); private static final int ASM_VERSION = Opcodes.ASM7; private final ExtensionInfo extensionInfo; ExtensionVisitor(ExtensionInfo extensionInfo) { super(ASM_VERSION); this.extensionInfo = extensionInfo; } @Override public AnnotationVisitor visitAnnotation(String descriptor, boolean visible) { //if (!descriptor.equals("Lorg/pf4j/Extension;")) { if (!Type.getType(descriptor).getClassName().equals(Extension.class.getName())) { return super.visitAnnotation(descriptor, visible); } return new AnnotationVisitor(ASM_VERSION) { @Override public AnnotationVisitor visitArray(final String name) { if ("ordinal".equals(name) || "plugins".equals(name) || "points".equals(name)) { return new AnnotationVisitor(ASM_VERSION, super.visitArray(name)) { @Override public void visit(String key, Object value) {<FILL_FUNCTION_BODY>} }; } return super.visitArray(name); } }; } }
log.debug("Load annotation attribute {} = {} ({})", name, value, value.getClass().getName()); if ("ordinal".equals(name)) { extensionInfo.ordinal = Integer.parseInt(value.toString()); } else if ("plugins".equals(name)) { if (value instanceof String) { log.debug("Found plugin {}", value); extensionInfo.plugins.add((String) value); } else if (value instanceof String[]) { log.debug("Found plugins {}", Arrays.toString((String[]) value)); extensionInfo.plugins.addAll(Arrays.asList((String[]) value)); } else { log.debug("Found plugin {}", value.toString()); extensionInfo.plugins.add(value.toString()); } } else { String pointClassName = ((Type) value).getClassName(); log.debug("Found point " + pointClassName); extensionInfo.points.add(pointClassName); } super.visit(key, value);
332
257
589
<methods>public void <init>(int) ,public void <init>(int, org.objectweb.asm.ClassVisitor) ,public void visit(int, int, java.lang.String, java.lang.String, java.lang.String, java.lang.String[]) ,public org.objectweb.asm.AnnotationVisitor visitAnnotation(java.lang.String, boolean) ,public void visitAttribute(org.objectweb.asm.Attribute) ,public void visitEnd() ,public org.objectweb.asm.FieldVisitor visitField(int, java.lang.String, java.lang.String, java.lang.String, java.lang.Object) ,public void visitInnerClass(java.lang.String, java.lang.String, java.lang.String, int) ,public org.objectweb.asm.MethodVisitor visitMethod(int, java.lang.String, java.lang.String, java.lang.String, java.lang.String[]) ,public org.objectweb.asm.ModuleVisitor visitModule(java.lang.String, int, java.lang.String) ,public void visitNestHost(java.lang.String) ,public void visitNestMember(java.lang.String) ,public void visitOuterClass(java.lang.String, java.lang.String, java.lang.String) ,public void visitPermittedSubclass(java.lang.String) ,public org.objectweb.asm.RecordComponentVisitor visitRecordComponent(java.lang.String, java.lang.String, java.lang.String) ,public void visitSource(java.lang.String, java.lang.String) ,public org.objectweb.asm.AnnotationVisitor visitTypeAnnotation(int, org.objectweb.asm.TypePath, java.lang.String, boolean) <variables>protected final int api,protected org.objectweb.asm.ClassVisitor cv
pf4j_pf4j
pf4j/pf4j/src/main/java/org/pf4j/processor/ExtensionStorage.java
ExtensionStorage
read
class ExtensionStorage { private static final Pattern COMMENT = Pattern.compile("#.*"); private static final Pattern WHITESPACE = Pattern.compile("\\s+"); protected final ExtensionAnnotationProcessor processor; public ExtensionStorage(ExtensionAnnotationProcessor processor) { this.processor = processor; } public abstract Map<String, Set<String>> read(); public abstract void write(Map<String, Set<String>> extensions); /** * Helper method. */ protected Filer getFiler() { return processor.getProcessingEnvironment().getFiler(); } /** * Helper method. */ protected void error(String message, Object... args) { processor.error(message, args); } /** * Helper method. */ protected void error(Element element, String message, Object... args) { processor.error(element, message, args); } /** * Helper method. */ protected void info(String message, Object... args) { processor.info(message, args); } /** * Helper method. */ protected void info(Element element, String message, Object... args) { processor.info(element, message, args); } public static void read(Reader reader, Set<String> entries) throws IOException {<FILL_FUNCTION_BODY>} }
try (BufferedReader bufferedReader = new BufferedReader(reader)) { String line; while ((line = bufferedReader.readLine()) != null) { line = COMMENT.matcher(line).replaceFirst(""); line = WHITESPACE.matcher(line).replaceAll(""); if (line.length() > 0) { entries.add(line); } } }
362
109
471
<no_super_class>
pf4j_pf4j
pf4j/pf4j/src/main/java/org/pf4j/processor/LegacyExtensionStorage.java
LegacyExtensionStorage
write
class LegacyExtensionStorage extends ExtensionStorage { public static final String EXTENSIONS_RESOURCE = "META-INF/extensions.idx"; public LegacyExtensionStorage(ExtensionAnnotationProcessor processor) { super(processor); } @Override public Map<String, Set<String>> read() { Map<String, Set<String>> extensions = new HashMap<>(); try { FileObject file = getFiler().getResource(StandardLocation.CLASS_OUTPUT, "", EXTENSIONS_RESOURCE); // TODO try to calculate the extension point Set<String> entries = new HashSet<>(); ExtensionStorage.read(file.openReader(true), entries); extensions.put(null, entries); } catch (FileNotFoundException | NoSuchFileException e) { // doesn't exist, ignore } catch (FilerException e) { // re-opening the file for reading or after writing is ignorable } catch (IOException e) { error(e.getMessage()); } return extensions; } @Override public void write(Map<String, Set<String>> extensions) {<FILL_FUNCTION_BODY>} }
try { FileObject file = getFiler().createResource(StandardLocation.CLASS_OUTPUT, "", EXTENSIONS_RESOURCE); try (BufferedWriter writer = new BufferedWriter(file.openWriter())) { writer.write("# Generated by PF4J"); // write header writer.newLine(); for (Map.Entry<String, Set<String>> entry : extensions.entrySet()) { for (String extension : entry.getValue()) { writer.write(extension); writer.newLine(); } } } } catch (FileNotFoundException e) { // it's the first time, create the file } catch (FilerException e) { // re-opening the file for reading or after writing is ignorable } catch (IOException e) { error(e.toString()); }
303
213
516
<methods>public void <init>(org.pf4j.processor.ExtensionAnnotationProcessor) ,public abstract Map<java.lang.String,Set<java.lang.String>> read() ,public static void read(java.io.Reader, Set<java.lang.String>) throws java.io.IOException,public abstract void write(Map<java.lang.String,Set<java.lang.String>>) <variables>private static final java.util.regex.Pattern COMMENT,private static final java.util.regex.Pattern WHITESPACE,protected final non-sealed org.pf4j.processor.ExtensionAnnotationProcessor processor
pf4j_pf4j
pf4j/pf4j/src/main/java/org/pf4j/processor/ServiceProviderExtensionStorage.java
ServiceProviderExtensionStorage
read
class ServiceProviderExtensionStorage extends ExtensionStorage { public static final String EXTENSIONS_RESOURCE = "META-INF/services"; public ServiceProviderExtensionStorage(ExtensionAnnotationProcessor processor) { super(processor); } @Override public Map<String, Set<String>> read() {<FILL_FUNCTION_BODY>} @Override public void write(Map<String, Set<String>> extensions) { for (Map.Entry<String, Set<String>> entry : extensions.entrySet()) { String extensionPoint = entry.getKey(); try { FileObject file = getFiler().createResource(StandardLocation.CLASS_OUTPUT, "", EXTENSIONS_RESOURCE + "/" + extensionPoint); try (BufferedWriter writer = new BufferedWriter(file.openWriter())) { // write header writer.write("# Generated by PF4J"); // write header writer.newLine(); // write extensions for (String extension : entry.getValue()) { writer.write(extension); if (!isExtensionOld(extensionPoint, extension)) { writer.write(" # pf4j extension"); } writer.newLine(); } } } catch (FileNotFoundException e) { // it's the first time, create the file } catch (FilerException e) { // re-opening the file for reading or after writing is ignorable } catch (IOException e) { error(e.toString()); } } } private boolean isExtensionOld(String extensionPoint, String extension) { return processor.getOldExtensions().containsKey(extensionPoint) && processor.getOldExtensions().get(extensionPoint).contains(extension); } }
Map<String, Set<String>> extensions = new HashMap<>(); for (String extensionPoint : processor.getExtensions().keySet()) { try { FileObject file = getFiler().getResource(StandardLocation.CLASS_OUTPUT, "", EXTENSIONS_RESOURCE + "/" + extensionPoint); Set<String> entries = new HashSet<>(); ExtensionStorage.read(file.openReader(true), entries); extensions.put(extensionPoint, entries); } catch (FileNotFoundException | NoSuchFileException e) { // doesn't exist, ignore } catch (FilerException e) { // re-opening the file for reading or after writing is ignorable } catch (IOException e) { error(e.getMessage()); } } return extensions;
443
205
648
<methods>public void <init>(org.pf4j.processor.ExtensionAnnotationProcessor) ,public abstract Map<java.lang.String,Set<java.lang.String>> read() ,public static void read(java.io.Reader, Set<java.lang.String>) throws java.io.IOException,public abstract void write(Map<java.lang.String,Set<java.lang.String>>) <variables>private static final java.util.regex.Pattern COMMENT,private static final java.util.regex.Pattern WHITESPACE,protected final non-sealed org.pf4j.processor.ExtensionAnnotationProcessor processor
pf4j_pf4j
pf4j/pf4j/src/main/java/org/pf4j/util/AndFileFilter.java
AndFileFilter
accept
class AndFileFilter implements FileFilter { /** The list of file filters. */ private List<FileFilter> fileFilters; public AndFileFilter() { this(new ArrayList<>()); } public AndFileFilter(FileFilter... fileFilters) { this(Arrays.asList(fileFilters)); } public AndFileFilter(List<FileFilter> fileFilters) { this.fileFilters = new ArrayList<>(fileFilters); } public AndFileFilter addFileFilter(FileFilter fileFilter) { fileFilters.add(fileFilter); return this; } public List<FileFilter> getFileFilters() { return Collections.unmodifiableList(fileFilters); } public boolean removeFileFilter(FileFilter fileFilter) { return fileFilters.remove(fileFilter); } public void setFileFilters(List<FileFilter> fileFilters) { this.fileFilters = new ArrayList<>(fileFilters); } @Override public boolean accept(File file) {<FILL_FUNCTION_BODY>} }
if (this.fileFilters.isEmpty()) { return false; } for (FileFilter fileFilter : this.fileFilters) { if (!fileFilter.accept(file)) { return false; } } return true;
291
70
361
<no_super_class>
pf4j_pf4j
pf4j/pf4j/src/main/java/org/pf4j/util/ClassUtils.java
ClassUtils
getAnnotationMirror
class ClassUtils { private ClassUtils() {} public static List<String> getAllInterfacesNames(Class<?> aClass) { return toString(getAllInterfaces(aClass)); } public static List<Class<?>> getAllInterfaces(Class<?> aClass) { List<Class<?>> list = new ArrayList<>(); while (aClass != null) { Class<?>[] interfaces = aClass.getInterfaces(); for (Class<?> anInterface : interfaces) { if (!list.contains(anInterface)) { list.add(anInterface); } List<Class<?>> superInterfaces = getAllInterfaces(anInterface); for (Class<?> superInterface : superInterfaces) { if (!list.contains(superInterface)) { list.add(superInterface); } } } aClass = aClass.getSuperclass(); } return list; } /** * Get a certain annotation of a {@link TypeElement}. * See <a href="https://stackoverflow.com/a/10167558">stackoverflow.com</a> for more information. * * @param typeElement the type element, that contains the requested annotation * @param annotationClass the class of the requested annotation * @return the requested annotation or null, if no annotation of the provided class was found * @throws NullPointerException if <code>typeElement</code> or <code>annotationClass</code> is null */ public static AnnotationMirror getAnnotationMirror(TypeElement typeElement, Class<?> annotationClass) {<FILL_FUNCTION_BODY>} /** * Get a certain parameter of an {@link AnnotationMirror}. * See <a href="https://stackoverflow.com/a/10167558">stackoverflow.com</a> for more information. * * @param annotationMirror the annotation, that contains the requested parameter * @param annotationParameter the name of the requested annotation parameter * @return the requested parameter or null, if no parameter of the provided name was found * @throws NullPointerException if <code>annotationMirror</code> is null */ public static AnnotationValue getAnnotationValue(AnnotationMirror annotationMirror, String annotationParameter) { for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : annotationMirror.getElementValues().entrySet()) { if (entry.getKey().getSimpleName().toString().equals(annotationParameter)) { return entry.getValue(); } } return null; } /** * Get a certain annotation parameter of a {@link TypeElement}. * See <a href="https://stackoverflow.com/a/10167558">stackoverflow.com</a> for more information. * * @param typeElement the type element, that contains the requested annotation * @param annotationClass the class of the requested annotation * @param annotationParameter the name of the requested annotation parameter * @return the requested parameter or null, if no annotation for the provided class was found or no annotation parameter was found * @throws NullPointerException if <code>typeElement</code> or <code>annotationClass</code> is null */ public static AnnotationValue getAnnotationValue(TypeElement typeElement, Class<?> annotationClass, String annotationParameter) { AnnotationMirror annotationMirror = getAnnotationMirror(typeElement, annotationClass); return annotationMirror != null ? getAnnotationValue(annotationMirror, annotationParameter) : null; } /** * Uses {@link Class#getSimpleName()} to convert from {@link Class} to {@link String}. */ private static List<String> toString(List<Class<?>> classes) { List<String> list = new ArrayList<>(); for (Class<?> aClass : classes) { list.add(aClass.getSimpleName()); } return list; } }
String annotationClassName = annotationClass.getName(); for (AnnotationMirror m : typeElement.getAnnotationMirrors()) { if (m.getAnnotationType().toString().equals(annotationClassName)) { return m; } } return null;
1,027
71
1,098
<no_super_class>
pf4j_pf4j
pf4j/pf4j/src/main/java/org/pf4j/util/DirectedGraph.java
DirectedGraph
topologicalSort
class DirectedGraph<V> { /** * The implementation here is basically an adjacency list, but instead * of an array of lists, a Map is used to map each vertex to its list of * adjacent vertices. */ private Map<V, List<V>> neighbors = new HashMap<>(); /** * Add a vertex to the graph. Nothing happens if vertex is already in graph. */ public void addVertex(V vertex) { if (containsVertex(vertex)) { return; } neighbors.put(vertex, new ArrayList<>()); } /** * True if graph contains vertex. */ public boolean containsVertex(V vertex) { return neighbors.containsKey(vertex); } public void removeVertex(V vertex) { neighbors.remove(vertex); } /** * Add an edge to the graph; if either vertex does not exist, it's added. * This implementation allows the creation of multi-edges and self-loops. */ public void addEdge(V from, V to) { addVertex(from); addVertex(to); neighbors.get(from).add(to); } /** * Remove an edge from the graph. Nothing happens if no such edge. * @throws {@link IllegalArgumentException} if either vertex doesn't exist. */ public void removeEdge(V from, V to) { if (!containsVertex(from)) { throw new IllegalArgumentException("Nonexistent vertex " + from); } if (!containsVertex(to)) { throw new IllegalArgumentException("Nonexistent vertex " + to); } neighbors.get(from).remove(to); } public List<V> getNeighbors(V vertex) { return containsVertex(vertex) ? neighbors.get(vertex) : new ArrayList<>(); } /** * Report (as a Map) the out-degree (the number of tail ends adjacent to a vertex) of each vertex. */ public Map<V, Integer> outDegree() { Map<V, Integer> result = new HashMap<>(); for (V vertex : neighbors.keySet()) { result.put(vertex, neighbors.get(vertex).size()); } return result; } /** * Report (as a {@link Map}) the in-degree (the number of head ends adjacent to a vertex) of each vertex. */ public Map<V, Integer> inDegree() { Map<V, Integer> result = new HashMap<>(); for (V vertex : neighbors.keySet()) { result.put(vertex, 0); // all in-degrees are 0 } for (V from : neighbors.keySet()) { for (V to : neighbors.get(from)) { result.put(to, result.get(to) + 1); // increment in-degree } } return result; } /** * Report (as a List) the topological sort of the vertices; null for no such sort. * See <a href="https://en.wikipedia.org/wiki/Topological_sorting">this</a> for more information. */ public List<V> topologicalSort() {<FILL_FUNCTION_BODY>} /** * Report (as a List) the reverse topological sort of the vertices; null for no such sort. */ public List<V> reverseTopologicalSort() { List<V> list = topologicalSort(); if (list == null) { return null; } Collections.reverse(list); return list; } /** * True if graph is a dag (directed acyclic graph). */ public boolean isDag () { return topologicalSort() != null; } /** * String representation of graph. */ @Override public String toString() { StringBuilder sb = new StringBuilder(); for (V vertex : neighbors.keySet()) { sb.append("\n ").append(vertex).append(" -> ").append(neighbors.get(vertex)); } return sb.toString(); } }
Map<V, Integer> degree = inDegree(); // determine all vertices with zero in-degree Stack<V> zeroVertices = new Stack<>(); // stack as good as any here for (V v : degree.keySet()) { if (degree.get(v) == 0) { zeroVertices.push(v); } } // determine the topological order List<V> result = new ArrayList<>(); while (!zeroVertices.isEmpty()) { V vertex = zeroVertices.pop(); // choose a vertex with zero in-degree result.add(vertex); // vertex 'v' is next in topological order // "remove" vertex 'v' by updating its neighbors for (V neighbor : neighbors.get(vertex)) { degree.put(neighbor, degree.get(neighbor) - 1); // remember any vertices that now have zero in-degree if (degree.get(neighbor) == 0) { zeroVertices.push(neighbor); } } } // check that we have used the entire graph (if not, there was a cycle) if (result.size() != neighbors.size()) { return null; } return result;
1,067
309
1,376
<no_super_class>
pf4j_pf4j
pf4j/pf4j/src/main/java/org/pf4j/util/OrFileFilter.java
OrFileFilter
accept
class OrFileFilter implements FileFilter { /** The list of file filters. */ private List<FileFilter> fileFilters; public OrFileFilter() { this(new ArrayList<>()); } public OrFileFilter(FileFilter... fileFilters) { this(Arrays.asList(fileFilters)); } public OrFileFilter(List<FileFilter> fileFilters) { this.fileFilters = new ArrayList<>(fileFilters); } public OrFileFilter addFileFilter(FileFilter fileFilter) { fileFilters.add(fileFilter); return this; } public List<FileFilter> getFileFilters() { return Collections.unmodifiableList(fileFilters); } public boolean removeFileFilter(FileFilter fileFilter) { return fileFilters.remove(fileFilter); } public void setFileFilters(List<FileFilter> fileFilters) { this.fileFilters = new ArrayList<>(fileFilters); } @Override public boolean accept(File file) {<FILL_FUNCTION_BODY>} }
if (this.fileFilters.isEmpty()) { return true; } for (FileFilter fileFilter : this.fileFilters) { if (fileFilter.accept(file)) { return true; } } return false;
291
70
361
<no_super_class>
pf4j_pf4j
pf4j/pf4j/src/main/java/org/pf4j/util/StringUtils.java
StringUtils
addStart
class StringUtils { private StringUtils() {} public static boolean isNullOrEmpty(String str) { return (str == null) || str.isEmpty(); } public static boolean isNotNullOrEmpty(String str) { return !isNullOrEmpty(str); } /** * Format the string. Replace "{}" with %s and format the string using {@link String#format(String, Object...)}. */ public static String format(String str, Object... args) { str = str.replaceAll("\\{}", "%s"); return String.format(str, args); } /** * <p>Adds a substring only if the source string does not already start with the substring, * otherwise returns the source string.</p> * <p/> * <p>A {@code null} source string will return {@code null}. * An empty ("") source string will return the empty string. * A {@code null} search string will return the source string.</p> * <p/> * <pre> * StringUtils.addStart(null, *) = * * StringUtils.addStart("", *) = * * StringUtils.addStart(*, null) = * * StringUtils.addStart("domain.com", "www.") = "www.domain.com" * StringUtils.addStart("abc123", "abc") = "abc123" * </pre> * * @param str the source String to search, may be null * @param add the String to search for and add, may be null * @return the substring with the string added if required */ public static String addStart(String str, String add) {<FILL_FUNCTION_BODY>} }
if (isNullOrEmpty(add)) { return str; } if (isNullOrEmpty(str)) { return add; } if (!str.startsWith(add)) { return add + str; } return str;
453
74
527
<no_super_class>
pf4j_pf4j
pf4j/pf4j/src/main/java/org/pf4j/util/Unzip.java
Unzip
extract
class Unzip { private static final Logger log = LoggerFactory.getLogger(Unzip.class); /** * Holds the destination directory. * File will be unzipped into the destination directory. */ private File destination; /** * Holds path to zip file. */ private File source; public Unzip() { } public Unzip(File source, File destination) { this.source = source; this.destination = destination; } public void setSource(File source) { this.source = source; } public void setDestination(File destination) { this.destination = destination; } /** * Extract the content of zip file ({@code source}) to destination directory. * If destination directory already exists it will be deleted before. */ public void extract() throws IOException {<FILL_FUNCTION_BODY>} private static void mkdirsOrThrow(File dir) throws IOException { if (!dir.exists() && !dir.mkdirs()) { throw new IOException("Failed to create directory " + dir); } } }
log.debug("Extract content of '{}' to '{}'", source, destination); // delete destination directory if exists if (destination.exists() && destination.isDirectory()) { FileUtils.delete(destination.toPath()); } String destinationCanonicalPath = destination.getCanonicalPath(); try (ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(source))) { ZipEntry zipEntry; while ((zipEntry = zipInputStream.getNextEntry()) != null) { File file = new File(destination, zipEntry.getName()); String fileCanonicalPath = file.getCanonicalPath(); if (!fileCanonicalPath.startsWith(destinationCanonicalPath)) { throw new ZipException("The file "+ zipEntry.getName() + " is trying to leave the target output directory of "+ destination); } // create intermediary directories - sometimes zip don't add them File dir = new File(file.getParent()); mkdirsOrThrow(dir); if (zipEntry.isDirectory()) { mkdirsOrThrow(file); } else { byte[] buffer = new byte[1024]; int length; try (FileOutputStream fos = new FileOutputStream(file)) { while ((length = zipInputStream.read(buffer)) >= 0) { fos.write(buffer, 0, length); } } } } }
299
365
664
<no_super_class>
pig-mesh_pig
pig/pig-auth/src/main/java/com/pig4cloud/pig/auth/config/AuthorizationServerConfiguration.java
AuthorizationServerConfiguration
authorizationServerSecurityFilterChain
class AuthorizationServerConfiguration { private final OAuth2AuthorizationService authorizationService; private final PasswordDecoderFilter passwordDecoderFilter; private final ValidateCodeFilter validateCodeFilter; @Bean @Order(Ordered.HIGHEST_PRECEDENCE) @ConditionalOnProperty(value = "security.micro", matchIfMissing = true) public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {<FILL_FUNCTION_BODY>} /** * 令牌生成规则实现 </br> * client:username:uuid * @return OAuth2TokenGenerator */ @Bean public OAuth2TokenGenerator oAuth2TokenGenerator() { CustomeOAuth2AccessTokenGenerator accessTokenGenerator = new CustomeOAuth2AccessTokenGenerator(); // 注入Token 增加关联用户信息 accessTokenGenerator.setAccessTokenCustomizer(new CustomeOAuth2TokenCustomizer()); return new DelegatingOAuth2TokenGenerator(accessTokenGenerator, new OAuth2RefreshTokenGenerator()); } /** * request -> xToken 注入请求转换器 * @return DelegatingAuthenticationConverter */ @Bean public AuthenticationConverter accessTokenRequestConverter() { return new DelegatingAuthenticationConverter(Arrays.asList( new OAuth2ResourceOwnerPasswordAuthenticationConverter(), new OAuth2ResourceOwnerSmsAuthenticationConverter(), new OAuth2RefreshTokenAuthenticationConverter(), new OAuth2ClientCredentialsAuthenticationConverter(), new OAuth2AuthorizationCodeAuthenticationConverter(), new OAuth2AuthorizationCodeRequestAuthenticationConverter())); } /** * 注入授权模式实现提供方 * <p> * 1. 密码模式 </br> * 2. 短信登录 </br> */ @SuppressWarnings("unchecked") private void addCustomOAuth2GrantAuthenticationProvider(HttpSecurity http) { AuthenticationManager authenticationManager = http.getSharedObject(AuthenticationManager.class); OAuth2AuthorizationService authorizationService = http.getSharedObject(OAuth2AuthorizationService.class); OAuth2ResourceOwnerPasswordAuthenticationProvider resourceOwnerPasswordAuthenticationProvider = new OAuth2ResourceOwnerPasswordAuthenticationProvider( authenticationManager, authorizationService, oAuth2TokenGenerator()); OAuth2ResourceOwnerSmsAuthenticationProvider resourceOwnerSmsAuthenticationProvider = new OAuth2ResourceOwnerSmsAuthenticationProvider( authenticationManager, authorizationService, oAuth2TokenGenerator()); // 处理 UsernamePasswordAuthenticationToken http.authenticationProvider(new PigDaoAuthenticationProvider()); // 处理 OAuth2ResourceOwnerPasswordAuthenticationToken http.authenticationProvider(resourceOwnerPasswordAuthenticationProvider); // 处理 OAuth2ResourceOwnerSmsAuthenticationToken http.authenticationProvider(resourceOwnerSmsAuthenticationProvider); } }
OAuth2AuthorizationServerConfigurer authorizationServerConfigurer = new OAuth2AuthorizationServerConfigurer(); // 增加验证码过滤器 http.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class); // 增加密码解密过滤器 http.addFilterBefore(passwordDecoderFilter, UsernamePasswordAuthenticationFilter.class); http.with(authorizationServerConfigurer.tokenEndpoint((tokenEndpoint) -> {// 个性化认证授权端点 tokenEndpoint.accessTokenRequestConverter(accessTokenRequestConverter()) // 注入自定义的授权认证Converter .accessTokenResponseHandler(new PigAuthenticationSuccessEventHandler()) // 登录成功处理器 .errorResponseHandler(new PigAuthenticationFailureEventHandler());// 登录失败处理器 }).clientAuthentication(oAuth2ClientAuthenticationConfigurer -> // 个性化客户端认证 oAuth2ClientAuthenticationConfigurer.errorResponseHandler(new PigAuthenticationFailureEventHandler()))// 处理客户端认证异常 .authorizationEndpoint(authorizationEndpoint -> authorizationEndpoint// 授权码端点个性化confirm页面 .consentPage(SecurityConstants.CUSTOM_CONSENT_PAGE_URI)), Customizer.withDefaults()); AntPathRequestMatcher[] requestMatchers = new AntPathRequestMatcher[] { AntPathRequestMatcher.antMatcher("/token/**"), AntPathRequestMatcher.antMatcher("/actuator/**"), AntPathRequestMatcher.antMatcher("/code/image"), AntPathRequestMatcher.antMatcher("/css/**"), AntPathRequestMatcher.antMatcher("/error") }; http.authorizeHttpRequests(authorizeRequests -> { // 自定义接口、端点暴露 authorizeRequests.requestMatchers(requestMatchers).permitAll(); authorizeRequests.anyRequest().authenticated(); }) .with(authorizationServerConfigurer.authorizationService(authorizationService)// redis存储token的实现 .authorizationServerSettings( AuthorizationServerSettings.builder().issuer(SecurityConstants.PROJECT_LICENSE).build()), Customizer.withDefaults()); http.with(new FormIdentityLoginConfigurer(), Customizer.withDefaults()); DefaultSecurityFilterChain securityFilterChain = http.build(); // 注入自定义授权模式实现 addCustomOAuth2GrantAuthenticationProvider(http); return securityFilterChain;
719
633
1,352
<no_super_class>
pig-mesh_pig
pig/pig-auth/src/main/java/com/pig4cloud/pig/auth/config/WebSecurityConfiguration.java
WebSecurityConfiguration
resources
class WebSecurityConfiguration { /** * spring security 默认的安全策略 * @param http security注入点 * @return SecurityFilterChain * @throws Exception */ @Bean SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception { http.authorizeHttpRequests(authorizeRequests -> authorizeRequests.requestMatchers("/token/*") .permitAll()// 开放自定义的部分端点 .anyRequest() .authenticated()).headers(header -> header.frameOptions(HeadersConfigurer.FrameOptionsConfig::sameOrigin)// 避免iframe同源无法登录许iframe ).with(new FormIdentityLoginConfigurer(), Customizer.withDefaults()); // 表单登录个性化 // 处理 UsernamePasswordAuthenticationToken http.authenticationProvider(new PigDaoAuthenticationProvider()); return http.build(); } /** * 暴露静态资源 * * https://github.com/spring-projects/spring-security/issues/10938 * @param http * @return * @throws Exception */ @Bean @Order(0) SecurityFilterChain resources(HttpSecurity http) throws Exception {<FILL_FUNCTION_BODY>} }
http.securityMatchers((matchers) -> matchers.requestMatchers("/actuator/**", "/css/**", "/error")) .authorizeHttpRequests((authorize) -> authorize.anyRequest().permitAll()) .requestCache(RequestCacheConfigurer::disable) .securityContext(AbstractHttpConfigurer::disable) .sessionManagement(AbstractHttpConfigurer::disable); return http.build();
324
109
433
<no_super_class>
pig-mesh_pig
pig/pig-auth/src/main/java/com/pig4cloud/pig/auth/endpoint/ImageCodeEndpoint.java
ImageCodeEndpoint
image
class ImageCodeEndpoint { private static final Integer DEFAULT_IMAGE_WIDTH = 100; private static final Integer DEFAULT_IMAGE_HEIGHT = 40; private final RedisTemplate redisTemplate; /** * 创建图形验证码 */ @SneakyThrows @GetMapping("/image") public void image(String randomStr, HttpServletResponse response) {<FILL_FUNCTION_BODY>} }
ArithmeticCaptcha captcha = new ArithmeticCaptcha(DEFAULT_IMAGE_WIDTH, DEFAULT_IMAGE_HEIGHT); String result = captcha.text(); redisTemplate.opsForValue() .set(CacheConstants.DEFAULT_CODE_KEY + randomStr, result, SecurityConstants.CODE_TIME, TimeUnit.SECONDS); // 转换流信息写出 captcha.out(response.getOutputStream());
112
115
227
<no_super_class>
pig-mesh_pig
pig/pig-auth/src/main/java/com/pig4cloud/pig/auth/endpoint/PigTokenEndpoint.java
PigTokenEndpoint
confirm
class PigTokenEndpoint { private final HttpMessageConverter<OAuth2AccessTokenResponse> accessTokenHttpResponseConverter = new OAuth2AccessTokenResponseHttpMessageConverter(); private final AuthenticationFailureHandler authenticationFailureHandler = new PigAuthenticationFailureEventHandler(); private final OAuth2AuthorizationService authorizationService; private final RemoteClientDetailsService clientDetailsService; private final RedisTemplate<String, Object> redisTemplate; private final CacheManager cacheManager; /** * 认证页面 * @param modelAndView * @param error 表单登录失败处理回调的错误信息 * @return ModelAndView */ @GetMapping("/login") public ModelAndView require(ModelAndView modelAndView, @RequestParam(required = false) String error) { modelAndView.setViewName("ftl/login"); modelAndView.addObject("error", error); return modelAndView; } @GetMapping("/confirm_access") public ModelAndView confirm(Principal principal, ModelAndView modelAndView, @RequestParam(OAuth2ParameterNames.CLIENT_ID) String clientId, @RequestParam(OAuth2ParameterNames.SCOPE) String scope, @RequestParam(OAuth2ParameterNames.STATE) String state) {<FILL_FUNCTION_BODY>} /** * 退出并删除token * @param authHeader Authorization */ @DeleteMapping("/logout") public R<Boolean> logout(@RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String authHeader) { if (StrUtil.isBlank(authHeader)) { return R.ok(); } String tokenValue = authHeader.replace(OAuth2AccessToken.TokenType.BEARER.getValue(), StrUtil.EMPTY).trim(); return removeToken(tokenValue); } /** * 校验token * @param token 令牌 */ @SneakyThrows @GetMapping("/check_token") public void checkToken(String token, HttpServletResponse response, HttpServletRequest request) { ServletServerHttpResponse httpResponse = new ServletServerHttpResponse(response); if (StrUtil.isBlank(token)) { httpResponse.setStatusCode(HttpStatus.UNAUTHORIZED); this.authenticationFailureHandler.onAuthenticationFailure(request, response, new InvalidBearerTokenException(OAuth2ErrorCodesExpand.TOKEN_MISSING)); return; } OAuth2Authorization authorization = authorizationService.findByToken(token, OAuth2TokenType.ACCESS_TOKEN); // 如果令牌不存在 返回401 if (authorization == null || authorization.getAccessToken() == null) { this.authenticationFailureHandler.onAuthenticationFailure(request, response, new InvalidBearerTokenException(OAuth2ErrorCodesExpand.INVALID_BEARER_TOKEN)); return; } Map<String, Object> claims = authorization.getAccessToken().getClaims(); OAuth2AccessTokenResponse sendAccessTokenResponse = OAuth2EndpointUtils.sendAccessTokenResponse(authorization, claims); this.accessTokenHttpResponseConverter.write(sendAccessTokenResponse, MediaType.APPLICATION_JSON, httpResponse); } /** * 令牌管理调用 * @param token token */ @Inner @DeleteMapping("/remove/{token}") public R<Boolean> removeToken(@PathVariable("token") String token) { OAuth2Authorization authorization = authorizationService.findByToken(token, OAuth2TokenType.ACCESS_TOKEN); if (authorization == null) { return R.ok(); } OAuth2Authorization.Token<OAuth2AccessToken> accessToken = authorization.getAccessToken(); if (accessToken == null || StrUtil.isBlank(accessToken.getToken().getTokenValue())) { return R.ok(); } // 清空用户信息(立即删除) cacheManager.getCache(CacheConstants.USER_DETAILS).evictIfPresent(authorization.getPrincipalName()); // 清空access token authorizationService.remove(authorization); // 处理自定义退出事件,保存相关日志 SpringContextHolder.publishEvent(new LogoutSuccessEvent(new PreAuthenticatedAuthenticationToken( authorization.getPrincipalName(), authorization.getRegisteredClientId()))); return R.ok(); } /** * 查询token * @param params 分页参数 * @return */ @Inner @PostMapping("/page") public R<Page> tokenList(@RequestBody Map<String, Object> params) { // 根据分页参数获取对应数据 String key = String.format("%s::*", CacheConstants.PROJECT_OAUTH_ACCESS); int current = MapUtil.getInt(params, CommonConstants.CURRENT); int size = MapUtil.getInt(params, CommonConstants.SIZE); Set<String> keys = redisTemplate.keys(key); List<String> pages = keys.stream().skip((current - 1) * size).limit(size).collect(Collectors.toList()); Page result = new Page(current, size); List<TokenVo> tokenVoList = redisTemplate.opsForValue().multiGet(pages).stream().map(obj -> { OAuth2Authorization authorization = (OAuth2Authorization) obj; TokenVo tokenVo = new TokenVo(); tokenVo.setClientId(authorization.getRegisteredClientId()); tokenVo.setId(authorization.getId()); tokenVo.setUsername(authorization.getPrincipalName()); OAuth2Authorization.Token<OAuth2AccessToken> accessToken = authorization.getAccessToken(); tokenVo.setAccessToken(accessToken.getToken().getTokenValue()); String expiresAt = TemporalAccessorUtil.format(accessToken.getToken().getExpiresAt(), DatePattern.NORM_DATETIME_PATTERN); tokenVo.setExpiresAt(expiresAt); String issuedAt = TemporalAccessorUtil.format(accessToken.getToken().getIssuedAt(), DatePattern.NORM_DATETIME_PATTERN); tokenVo.setIssuedAt(issuedAt); return tokenVo; }).collect(Collectors.toList()); result.setRecords(tokenVoList); result.setTotal(keys.size()); return R.ok(result); } }
SysOauthClientDetails clientDetails = RetOps .of(clientDetailsService.getClientDetailsById(clientId, SecurityConstants.FROM_IN)) .getData() .orElseThrow(() -> new OAuthClientException("clientId 不合法")); Set<String> authorizedScopes = StringUtils.commaDelimitedListToSet(clientDetails.getScope()); modelAndView.addObject("clientId", clientId); modelAndView.addObject("state", state); modelAndView.addObject("scopeList", authorizedScopes); modelAndView.addObject("principalName", principal.getName()); modelAndView.setViewName("ftl/confirm"); return modelAndView;
1,705
189
1,894
<no_super_class>
pig-mesh_pig
pig/pig-auth/src/main/java/com/pig4cloud/pig/auth/support/CustomeOAuth2AccessTokenGenerator.java
CustomeOAuth2AccessTokenGenerator
generate
class CustomeOAuth2AccessTokenGenerator implements OAuth2TokenGenerator<OAuth2AccessToken> { private OAuth2TokenCustomizer<OAuth2TokenClaimsContext> accessTokenCustomizer; private final StringKeyGenerator accessTokenGenerator = new Base64StringKeyGenerator( Base64.getUrlEncoder().withoutPadding(), 96); @Nullable @Override public OAuth2AccessToken generate(OAuth2TokenContext context) {<FILL_FUNCTION_BODY>} /** * Sets the {@link OAuth2TokenCustomizer} that customizes the * {@link OAuth2TokenClaimsContext#getClaims() claims} for the * {@link OAuth2AccessToken}. * @param accessTokenCustomizer the {@link OAuth2TokenCustomizer} that customizes the * claims for the {@code OAuth2AccessToken} */ public void setAccessTokenCustomizer(OAuth2TokenCustomizer<OAuth2TokenClaimsContext> accessTokenCustomizer) { Assert.notNull(accessTokenCustomizer, "accessTokenCustomizer cannot be null"); this.accessTokenCustomizer = accessTokenCustomizer; } private static final class OAuth2AccessTokenClaims extends OAuth2AccessToken implements ClaimAccessor { private final Map<String, Object> claims; private OAuth2AccessTokenClaims(TokenType tokenType, String tokenValue, Instant issuedAt, Instant expiresAt, Set<String> scopes, Map<String, Object> claims) { super(tokenType, tokenValue, issuedAt, expiresAt, scopes); this.claims = claims; } @Override public Map<String, Object> getClaims() { return this.claims; } } }
if (!OAuth2TokenType.ACCESS_TOKEN.equals(context.getTokenType()) || !OAuth2TokenFormat.REFERENCE .equals(context.getRegisteredClient().getTokenSettings().getAccessTokenFormat())) { return null; } String issuer = null; if (context.getAuthorizationServerContext() != null) { issuer = context.getAuthorizationServerContext().getIssuer(); } RegisteredClient registeredClient = context.getRegisteredClient(); Instant issuedAt = Instant.now(); Instant expiresAt = issuedAt.plus(registeredClient.getTokenSettings().getAccessTokenTimeToLive()); // @formatter:off OAuth2TokenClaimsSet.Builder claimsBuilder = OAuth2TokenClaimsSet.builder(); if (StringUtils.hasText(issuer)) { claimsBuilder.issuer(issuer); } claimsBuilder .subject(context.getPrincipal().getName()) .audience(Collections.singletonList(registeredClient.getClientId())) .issuedAt(issuedAt) .expiresAt(expiresAt) .notBefore(issuedAt) .id(UUID.randomUUID().toString()); if (!CollectionUtils.isEmpty(context.getAuthorizedScopes())) { claimsBuilder.claim(OAuth2ParameterNames.SCOPE, context.getAuthorizedScopes()); } // @formatter:on if (this.accessTokenCustomizer != null) { // @formatter:off OAuth2TokenClaimsContext.Builder accessTokenContextBuilder = OAuth2TokenClaimsContext.with(claimsBuilder) .registeredClient(context.getRegisteredClient()) .principal(context.getPrincipal()) .authorizationServerContext(context.getAuthorizationServerContext()) .authorizedScopes(context.getAuthorizedScopes()) .tokenType(context.getTokenType()) .authorizationGrantType(context.getAuthorizationGrantType()); if (context.getAuthorization() != null) { accessTokenContextBuilder.authorization(context.getAuthorization()); } if (context.getAuthorizationGrant() != null) { accessTokenContextBuilder.authorizationGrant(context.getAuthorizationGrant()); } // @formatter:on OAuth2TokenClaimsContext accessTokenContext = accessTokenContextBuilder.build(); this.accessTokenCustomizer.customize(accessTokenContext); } OAuth2TokenClaimsSet accessTokenClaimsSet = claimsBuilder.build(); return new CustomeOAuth2AccessTokenGenerator.OAuth2AccessTokenClaims(OAuth2AccessToken.TokenType.BEARER, this.accessTokenGenerator.generateKey(), accessTokenClaimsSet.getIssuedAt(), accessTokenClaimsSet.getExpiresAt(), context.getAuthorizedScopes(), accessTokenClaimsSet.getClaims());
442
747
1,189
<no_super_class>
pig-mesh_pig
pig/pig-auth/src/main/java/com/pig4cloud/pig/auth/support/base/OAuth2ResourceOwnerBaseAuthenticationConverter.java
OAuth2ResourceOwnerBaseAuthenticationConverter
convert
class OAuth2ResourceOwnerBaseAuthenticationConverter<T extends OAuth2ResourceOwnerBaseAuthenticationToken> implements AuthenticationConverter { /** * 是否支持此convert * @param grantType 授权类型 * @return */ public abstract boolean support(String grantType); /** * 校验参数 * @param request 请求 */ public void checkParams(HttpServletRequest request) { } /** * 构建具体类型的token * @param clientPrincipal * @param requestedScopes * @param additionalParameters * @return */ public abstract T buildToken(Authentication clientPrincipal, Set<String> requestedScopes, Map<String, Object> additionalParameters); @Override public Authentication convert(HttpServletRequest request) {<FILL_FUNCTION_BODY>} }
// grant_type (REQUIRED) String grantType = request.getParameter(OAuth2ParameterNames.GRANT_TYPE); if (!support(grantType)) { return null; } MultiValueMap<String, String> parameters = OAuth2EndpointUtils.getParameters(request); // scope (OPTIONAL) String scope = parameters.getFirst(OAuth2ParameterNames.SCOPE); if (StringUtils.hasText(scope) && parameters.get(OAuth2ParameterNames.SCOPE).size() != 1) { OAuth2EndpointUtils.throwError(OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.SCOPE, OAuth2EndpointUtils.ACCESS_TOKEN_REQUEST_ERROR_URI); } Set<String> requestedScopes = null; if (StringUtils.hasText(scope)) { requestedScopes = new HashSet<>(Arrays.asList(StringUtils.delimitedListToStringArray(scope, " "))); } // 校验个性化参数 checkParams(request); // 获取当前已经认证的客户端信息 Authentication clientPrincipal = SecurityContextHolder.getContext().getAuthentication(); if (clientPrincipal == null) { OAuth2EndpointUtils.throwError(OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ErrorCodes.INVALID_CLIENT, OAuth2EndpointUtils.ACCESS_TOKEN_REQUEST_ERROR_URI); } // 扩展信息 Map<String, Object> additionalParameters = parameters.entrySet() .stream() .filter(e -> !e.getKey().equals(OAuth2ParameterNames.GRANT_TYPE) && !e.getKey().equals(OAuth2ParameterNames.SCOPE)) .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().get(0))); // 创建token return buildToken(clientPrincipal, requestedScopes, additionalParameters);
213
521
734
<no_super_class>
pig-mesh_pig
pig/pig-auth/src/main/java/com/pig4cloud/pig/auth/support/core/CustomeOAuth2TokenCustomizer.java
CustomeOAuth2TokenCustomizer
customize
class CustomeOAuth2TokenCustomizer implements OAuth2TokenCustomizer<OAuth2TokenClaimsContext> { /** * Customize the OAuth 2.0 Token attributes. * @param context the context containing the OAuth 2.0 Token attributes */ @Override public void customize(OAuth2TokenClaimsContext context) {<FILL_FUNCTION_BODY>} }
OAuth2TokenClaimsSet.Builder claims = context.getClaims(); claims.claim(SecurityConstants.DETAILS_LICENSE, SecurityConstants.PROJECT_LICENSE); String clientId = context.getAuthorizationGrant().getName(); claims.claim(SecurityConstants.CLIENT_ID, clientId); // 客户端模式不返回具体用户信息 if (SecurityConstants.CLIENT_CREDENTIALS.equals(context.getAuthorizationGrantType().getValue())) { return; } PigUser pigUser = (PigUser) context.getPrincipal().getPrincipal(); claims.claim(SecurityConstants.DETAILS_USER, pigUser); claims.claim(SecurityConstants.DETAILS_USER_ID, pigUser.getId()); claims.claim(SecurityConstants.USERNAME, pigUser.getUsername());
102
227
329
<no_super_class>
pig-mesh_pig
pig/pig-auth/src/main/java/com/pig4cloud/pig/auth/support/core/FormIdentityLoginConfigurer.java
FormIdentityLoginConfigurer
init
class FormIdentityLoginConfigurer extends AbstractHttpConfigurer<FormIdentityLoginConfigurer, HttpSecurity> { @Override public void init(HttpSecurity http) throws Exception {<FILL_FUNCTION_BODY>} }
http.formLogin(formLogin -> { formLogin.loginPage("/token/login"); formLogin.loginProcessingUrl("/token/form"); formLogin.failureHandler(new FormAuthenticationFailureHandler()); }) .logout(logout -> logout.logoutSuccessHandler(new SsoLogoutSuccessHandler()) .deleteCookies("JSESSIONID") .invalidateHttpSession(true)) // SSO登出成功处理 .csrf(AbstractHttpConfigurer::disable);
61
134
195
<methods>public void <init>() ,public org.springframework.security.config.annotation.web.builders.HttpSecurity disable() ,public com.pig4cloud.pig.auth.support.core.FormIdentityLoginConfigurer withObjectPostProcessor(ObjectPostProcessor<?>) <variables>
pig-mesh_pig
pig/pig-auth/src/main/java/com/pig4cloud/pig/auth/support/core/PigDaoAuthenticationProvider.java
PigDaoAuthenticationProvider
additionalAuthenticationChecks
class PigDaoAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider { /** * The plaintext password used to perform PasswordEncoder#matches(CharSequence, * String)} on when the user is not found to avoid SEC-2056. */ private static final String USER_NOT_FOUND_PASSWORD = "userNotFoundPassword"; private final static BasicAuthenticationConverter basicConvert = new BasicAuthenticationConverter(); private PasswordEncoder passwordEncoder; /** * The password used to perform {@link PasswordEncoder#matches(CharSequence, String)} * on when the user is not found to avoid SEC-2056. This is necessary, because some * {@link PasswordEncoder} implementations will short circuit if the password is not * in a valid format. */ private volatile String userNotFoundEncodedPassword; private UserDetailsService userDetailsService; private UserDetailsPasswordService userDetailsPasswordService; public PigDaoAuthenticationProvider() { setMessageSource(SpringUtil.getBean("securityMessageSource")); setPasswordEncoder(PasswordEncoderFactories.createDelegatingPasswordEncoder()); } @Override protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {<FILL_FUNCTION_BODY>} @SneakyThrows @Override protected final UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) { prepareTimingAttackProtection(); HttpServletRequest request = WebUtils.getRequest() .orElseThrow( (Supplier<Throwable>) () -> new InternalAuthenticationServiceException("web request is empty")); String grantType = WebUtils.getRequest().get().getParameter(OAuth2ParameterNames.GRANT_TYPE); String clientId = WebUtils.getRequest().get().getParameter(OAuth2ParameterNames.CLIENT_ID); if (StrUtil.isBlank(clientId)) { clientId = basicConvert.convert(request).getName(); } Map<String, PigUserDetailsService> userDetailsServiceMap = SpringUtil .getBeansOfType(PigUserDetailsService.class); String finalClientId = clientId; Optional<PigUserDetailsService> optional = userDetailsServiceMap.values() .stream() .filter(service -> service.support(finalClientId, grantType)) .max(Comparator.comparingInt(Ordered::getOrder)); if (optional.isEmpty()) { throw new InternalAuthenticationServiceException("UserDetailsService error , not register"); } try { UserDetails loadedUser = optional.get().loadUserByUsername(username); if (loadedUser == null) { throw new InternalAuthenticationServiceException( "UserDetailsService returned null, which is an interface contract violation"); } return loadedUser; } catch (UsernameNotFoundException ex) { mitigateAgainstTimingAttack(authentication); throw ex; } catch (InternalAuthenticationServiceException ex) { throw ex; } catch (Exception ex) { throw new InternalAuthenticationServiceException(ex.getMessage(), ex); } } @Override protected Authentication createSuccessAuthentication(Object principal, Authentication authentication, UserDetails user) { boolean upgradeEncoding = this.userDetailsPasswordService != null && this.passwordEncoder.upgradeEncoding(user.getPassword()); if (upgradeEncoding) { String presentedPassword = authentication.getCredentials().toString(); String newPassword = this.passwordEncoder.encode(presentedPassword); user = this.userDetailsPasswordService.updatePassword(user, newPassword); } return super.createSuccessAuthentication(principal, authentication, user); } private void prepareTimingAttackProtection() { if (this.userNotFoundEncodedPassword == null) { this.userNotFoundEncodedPassword = this.passwordEncoder.encode(USER_NOT_FOUND_PASSWORD); } } private void mitigateAgainstTimingAttack(UsernamePasswordAuthenticationToken authentication) { if (authentication.getCredentials() != null) { String presentedPassword = authentication.getCredentials().toString(); this.passwordEncoder.matches(presentedPassword, this.userNotFoundEncodedPassword); } } /** * Sets the PasswordEncoder instance to be used to encode and validate passwords. If * not set, the password will be compared using * {@link PasswordEncoderFactories#createDelegatingPasswordEncoder()} * @param passwordEncoder must be an instance of one of the {@code PasswordEncoder} * types. */ public void setPasswordEncoder(PasswordEncoder passwordEncoder) { Assert.notNull(passwordEncoder, "passwordEncoder cannot be null"); this.passwordEncoder = passwordEncoder; this.userNotFoundEncodedPassword = null; } protected PasswordEncoder getPasswordEncoder() { return this.passwordEncoder; } public void setUserDetailsService(UserDetailsService userDetailsService) { this.userDetailsService = userDetailsService; } protected UserDetailsService getUserDetailsService() { return this.userDetailsService; } public void setUserDetailsPasswordService(UserDetailsPasswordService userDetailsPasswordService) { this.userDetailsPasswordService = userDetailsPasswordService; } }
// 只有密码模式需要校验密码 String grantType = WebUtils.getRequest().get().getParameter(OAuth2ParameterNames.GRANT_TYPE); if (!StrUtil.equals(AuthorizationGrantType.PASSWORD.getValue(), grantType)) { return; } if (authentication.getCredentials() == null) { this.logger.debug("Failed to authenticate since no credentials provided"); throw new BadCredentialsException(this.messages .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials")); } String presentedPassword = authentication.getCredentials().toString(); if (!this.passwordEncoder.matches(presentedPassword, userDetails.getPassword())) { this.logger.debug("Failed to authenticate since password does not match stored value"); throw new BadCredentialsException(this.messages .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials")); }
1,357
237
1,594
<methods>public void <init>() ,public final void afterPropertiesSet() throws java.lang.Exception,public org.springframework.security.core.Authentication authenticate(org.springframework.security.core.Authentication) throws org.springframework.security.core.AuthenticationException,public org.springframework.security.core.userdetails.UserCache getUserCache() ,public boolean isForcePrincipalAsString() ,public boolean isHideUserNotFoundExceptions() ,public void setAuthoritiesMapper(org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper) ,public void setForcePrincipalAsString(boolean) ,public void setHideUserNotFoundExceptions(boolean) ,public void setMessageSource(org.springframework.context.MessageSource) ,public void setPostAuthenticationChecks(org.springframework.security.core.userdetails.UserDetailsChecker) ,public void setPreAuthenticationChecks(org.springframework.security.core.userdetails.UserDetailsChecker) ,public void setUserCache(org.springframework.security.core.userdetails.UserCache) ,public boolean supports(Class<?>) <variables>private org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper authoritiesMapper,private boolean forcePrincipalAsString,protected boolean hideUserNotFoundExceptions,protected final org.apache.commons.logging.Log logger,protected org.springframework.context.support.MessageSourceAccessor messages,private org.springframework.security.core.userdetails.UserDetailsChecker postAuthenticationChecks,private org.springframework.security.core.userdetails.UserDetailsChecker preAuthenticationChecks,private org.springframework.security.core.userdetails.UserCache userCache
pig-mesh_pig
pig/pig-auth/src/main/java/com/pig4cloud/pig/auth/support/filter/PasswordDecoderFilter.java
PasswordDecoderFilter
doFilterInternal
class PasswordDecoderFilter extends OncePerRequestFilter { private final AuthSecurityConfigProperties authSecurityConfigProperties; private static final String PASSWORD = "password"; private static final String KEY_ALGORITHM = "AES"; static { // 关闭hutool 强制关闭Bouncy Castle库的依赖 SecureUtil.disableBouncyCastle(); } @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {<FILL_FUNCTION_BODY>} }
// 不是登录请求,直接向下执行 if (!StrUtil.containsAnyIgnoreCase(request.getRequestURI(), SecurityConstants.OAUTH_TOKEN_URL)) { chain.doFilter(request, response); return; } // 将请求流转换为可多次读取的请求流 RepeatBodyRequestWrapper requestWrapper = new RepeatBodyRequestWrapper(request); Map<String, String[]> parameterMap = requestWrapper.getParameterMap(); // 构建前端对应解密AES 因子 AES aes = new AES(Mode.CFB, Padding.NoPadding, new SecretKeySpec(authSecurityConfigProperties.getEncodeKey().getBytes(), KEY_ALGORITHM), new IvParameterSpec(authSecurityConfigProperties.getEncodeKey().getBytes())); parameterMap.forEach((k, v) -> { String[] values = parameterMap.get(k); if (!PASSWORD.equals(k) || ArrayUtil.isEmpty(values)) { return; } // 解密密码 String decryptPassword = aes.decryptStr(values[0]); parameterMap.put(k, new String[] { decryptPassword }); }); chain.doFilter(requestWrapper, response);
151
334
485
<methods>public void <init>() ,public final void doFilter(jakarta.servlet.ServletRequest, jakarta.servlet.ServletResponse, jakarta.servlet.FilterChain) throws jakarta.servlet.ServletException, java.io.IOException<variables>public static final java.lang.String ALREADY_FILTERED_SUFFIX
pig-mesh_pig
pig/pig-auth/src/main/java/com/pig4cloud/pig/auth/support/filter/ValidateCodeFilter.java
ValidateCodeFilter
doFilterInternal
class ValidateCodeFilter extends OncePerRequestFilter { private final AuthSecurityConfigProperties authSecurityConfigProperties; @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {<FILL_FUNCTION_BODY>} /** * 校验验证码 */ private void checkCode() throws ValidateCodeException { Optional<HttpServletRequest> request = WebUtils.getRequest(); String code = request.get().getParameter("code"); if (StrUtil.isBlank(code)) { throw new ValidateCodeException("验证码不能为空"); } String randomStr = request.get().getParameter("randomStr"); // https://gitee.com/log4j/pig/issues/IWA0D String mobile = request.get().getParameter("mobile"); if (StrUtil.isNotBlank(mobile)) { randomStr = mobile; } String key = CacheConstants.DEFAULT_CODE_KEY + randomStr; RedisTemplate<String, String> redisTemplate = SpringContextHolder.getBean(RedisTemplate.class); if (Boolean.FALSE.equals(redisTemplate.hasKey(key))) { throw new ValidateCodeException("验证码不合法"); } Object codeObj = redisTemplate.opsForValue().get(key); if (codeObj == null) { throw new ValidateCodeException("验证码不合法"); } String saveCode = codeObj.toString(); if (StrUtil.isBlank(saveCode)) { redisTemplate.delete(key); throw new ValidateCodeException("验证码不合法"); } if (!StrUtil.equals(saveCode, code)) { redisTemplate.delete(key); throw new ValidateCodeException("验证码不合法"); } redisTemplate.delete(key); } }
String requestUrl = request.getServletPath(); // 不是登录URL 请求直接跳过 if (!SecurityConstants.OAUTH_TOKEN_URL.equals(requestUrl)) { filterChain.doFilter(request, response); return; } // 如果登录URL 但是刷新token的请求,直接向下执行 String grantType = request.getParameter(OAuth2ParameterNames.GRANT_TYPE); if (StrUtil.equals(SecurityConstants.REFRESH_TOKEN, grantType)) { filterChain.doFilter(request, response); return; } // 客户端配置跳过验证码 boolean isIgnoreClient = authSecurityConfigProperties.getIgnoreClients().contains(WebUtils.getClientId()); if (isIgnoreClient) { filterChain.doFilter(request, response); return; } // 校验验证码 1. 客户端开启验证码 2. 短信模式 try { checkCode(); filterChain.doFilter(request, response); } catch (ValidateCodeException validateCodeException) { throw new OAuth2AuthenticationException(validateCodeException.getMessage()); }
504
318
822
<methods>public void <init>() ,public final void doFilter(jakarta.servlet.ServletRequest, jakarta.servlet.ServletResponse, jakarta.servlet.FilterChain) throws jakarta.servlet.ServletException, java.io.IOException<variables>public static final java.lang.String ALREADY_FILTERED_SUFFIX
pig-mesh_pig
pig/pig-auth/src/main/java/com/pig4cloud/pig/auth/support/handler/FormAuthenticationFailureHandler.java
FormAuthenticationFailureHandler
onAuthenticationFailure
class FormAuthenticationFailureHandler implements AuthenticationFailureHandler { /** * Called when an authentication attempt fails. * @param request the request during which the authentication attempt occurred. * @param response the response. * @param exception the exception which was thrown to reject the authentication */ @Override @SneakyThrows public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) {<FILL_FUNCTION_BODY>} }
log.debug("表单登录失败:{}", exception.getLocalizedMessage()); String url = HttpUtil.encodeParams(String.format("/token/login?error=%s", exception.getMessage()), CharsetUtil.CHARSET_UTF_8); WebUtils.getResponse().sendRedirect(url);
118
82
200
<no_super_class>
pig-mesh_pig
pig/pig-auth/src/main/java/com/pig4cloud/pig/auth/support/handler/PigAuthenticationFailureEventHandler.java
PigAuthenticationFailureEventHandler
sendErrorResponse
class PigAuthenticationFailureEventHandler implements AuthenticationFailureHandler { private final MappingJackson2HttpMessageConverter errorHttpResponseConverter = new MappingJackson2HttpMessageConverter(); /** * Called when an authentication attempt fails. * @param request the request during which the authentication attempt occurred. * @param response the response. * @param exception the exception which was thrown to reject the authentication * request. */ @Override @SneakyThrows public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) { String username = request.getParameter(OAuth2ParameterNames.USERNAME); log.info("用户:{} 登录失败,异常:{}", username, exception.getLocalizedMessage()); SysLog logVo = SysLogUtils.getSysLog(); logVo.setTitle("登录失败"); logVo.setLogType(LogTypeEnum.ERROR.getType()); logVo.setException(exception.getLocalizedMessage()); // 发送异步日志事件 String startTimeStr = request.getHeader(CommonConstants.REQUEST_START_TIME); if (StrUtil.isNotBlank(startTimeStr)) { Long startTime = Long.parseLong(startTimeStr); Long endTime = System.currentTimeMillis(); logVo.setTime(endTime - startTime); } logVo.setCreateBy(username); SpringContextHolder.publishEvent(new SysLogEvent(logVo)); // 写出错误信息 sendErrorResponse(request, response, exception); } private void sendErrorResponse(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException {<FILL_FUNCTION_BODY>} }
ServletServerHttpResponse httpResponse = new ServletServerHttpResponse(response); httpResponse.setStatusCode(HttpStatus.UNAUTHORIZED); String errorMessage; if (exception instanceof OAuth2AuthenticationException) { OAuth2AuthenticationException authorizationException = (OAuth2AuthenticationException) exception; errorMessage = StrUtil.isBlank(authorizationException.getError().getDescription()) ? authorizationException.getError().getErrorCode() : authorizationException.getError().getDescription(); } else { errorMessage = exception.getLocalizedMessage(); } this.errorHttpResponseConverter.write(R.failed(errorMessage), MediaType.APPLICATION_JSON, httpResponse);
457
189
646
<no_super_class>
pig-mesh_pig
pig/pig-auth/src/main/java/com/pig4cloud/pig/auth/support/handler/PigAuthenticationSuccessEventHandler.java
PigAuthenticationSuccessEventHandler
sendAccessTokenResponse
class PigAuthenticationSuccessEventHandler implements AuthenticationSuccessHandler { private final HttpMessageConverter<OAuth2AccessTokenResponse> accessTokenHttpResponseConverter = new PigCustomOAuth2AccessTokenResponseHttpMessageConverter(); /** * Called when a user has been successfully authenticated. * @param request the request which caused the successful authentication * @param response the response * @param authentication the <tt>Authentication</tt> object which was created during * the authentication process. */ @SneakyThrows @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = (OAuth2AccessTokenAuthenticationToken) authentication; Map<String, Object> map = accessTokenAuthentication.getAdditionalParameters(); if (MapUtil.isNotEmpty(map)) { // 发送异步日志事件 PigUser userInfo = (PigUser) map.get(SecurityConstants.DETAILS_USER); log.info("用户:{} 登录成功", userInfo.getName()); SecurityContextHolder.getContext().setAuthentication(accessTokenAuthentication); SysLog logVo = SysLogUtils.getSysLog(); logVo.setTitle("登录成功"); String startTimeStr = request.getHeader(CommonConstants.REQUEST_START_TIME); if (StrUtil.isNotBlank(startTimeStr)) { Long startTime = Long.parseLong(startTimeStr); Long endTime = System.currentTimeMillis(); logVo.setTime(endTime - startTime); } logVo.setCreateBy(userInfo.getName()); SpringContextHolder.publishEvent(new SysLogEvent(logVo)); } // 输出token sendAccessTokenResponse(request, response, authentication); } private void sendAccessTokenResponse(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {<FILL_FUNCTION_BODY>} }
OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = (OAuth2AccessTokenAuthenticationToken) authentication; OAuth2AccessToken accessToken = accessTokenAuthentication.getAccessToken(); OAuth2RefreshToken refreshToken = accessTokenAuthentication.getRefreshToken(); Map<String, Object> additionalParameters = accessTokenAuthentication.getAdditionalParameters(); OAuth2AccessTokenResponse.Builder builder = OAuth2AccessTokenResponse.withToken(accessToken.getTokenValue()) .tokenType(accessToken.getTokenType()) .scopes(accessToken.getScopes()); if (accessToken.getIssuedAt() != null && accessToken.getExpiresAt() != null) { builder.expiresIn(ChronoUnit.SECONDS.between(accessToken.getIssuedAt(), accessToken.getExpiresAt())); } if (refreshToken != null) { builder.refreshToken(refreshToken.getTokenValue()); } if (!CollectionUtils.isEmpty(additionalParameters)) { builder.additionalParameters(additionalParameters); } OAuth2AccessTokenResponse accessTokenResponse = builder.build(); ServletServerHttpResponse httpResponse = new ServletServerHttpResponse(response); // 无状态 注意删除 context 上下文的信息 SecurityContextHolder.clearContext(); this.accessTokenHttpResponseConverter.write(accessTokenResponse, null, httpResponse);
514
362
876
<no_super_class>
pig-mesh_pig
pig/pig-auth/src/main/java/com/pig4cloud/pig/auth/support/handler/PigLogoutSuccessEventHandler.java
PigLogoutSuccessEventHandler
onApplicationEvent
class PigLogoutSuccessEventHandler implements ApplicationListener<LogoutSuccessEvent> { @Override public void onApplicationEvent(LogoutSuccessEvent event) {<FILL_FUNCTION_BODY>} /** * 处理退出成功方法 * <p> * 获取到登录的authentication 对象 * @param authentication 登录对象 */ public void handle(Authentication authentication) { log.info("用户:{} 退出成功", authentication.getPrincipal()); SysLog logVo = SysLogUtils.getSysLog(); logVo.setTitle("退出成功"); // 发送异步日志事件 Long startTime = System.currentTimeMillis(); Long endTime = System.currentTimeMillis(); logVo.setTime(endTime - startTime); // 设置对应的token WebUtils.getRequest().ifPresent(request -> logVo.setParams(request.getHeader(HttpHeaders.AUTHORIZATION))); // 这边设置ServiceId if (authentication instanceof PreAuthenticatedAuthenticationToken) { logVo.setServiceId(authentication.getCredentials().toString()); } logVo.setCreateBy(authentication.getName()); SpringContextHolder.publishEvent(new SysLogEvent(logVo)); } }
Authentication authentication = (Authentication) event.getSource(); if (authentication instanceof PreAuthenticatedAuthenticationToken) { handle(authentication); }
350
43
393
<no_super_class>
pig-mesh_pig
pig/pig-auth/src/main/java/com/pig4cloud/pig/auth/support/handler/SsoLogoutSuccessHandler.java
SsoLogoutSuccessHandler
onLogoutSuccess
class SsoLogoutSuccessHandler implements LogoutSuccessHandler { private static final String REDIRECT_URL = "redirect_url"; @Override public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {<FILL_FUNCTION_BODY>} }
if (response == null) { return; } // 获取请求参数中是否包含 回调地址 String redirectUrl = request.getParameter(REDIRECT_URL); if (StrUtil.isNotBlank(redirectUrl)) { response.sendRedirect(redirectUrl); } else if (StrUtil.isNotBlank(request.getHeader(HttpHeaders.REFERER))) { // 默认跳转referer 地址 String referer = request.getHeader(HttpHeaders.REFERER); response.sendRedirect(referer); }
80
155
235
<no_super_class>
pig-mesh_pig
pig/pig-auth/src/main/java/com/pig4cloud/pig/auth/support/password/OAuth2ResourceOwnerPasswordAuthenticationConverter.java
OAuth2ResourceOwnerPasswordAuthenticationConverter
checkParams
class OAuth2ResourceOwnerPasswordAuthenticationConverter extends OAuth2ResourceOwnerBaseAuthenticationConverter<OAuth2ResourceOwnerPasswordAuthenticationToken> { /** * 支持密码模式 * @param grantType 授权类型 */ @Override public boolean support(String grantType) { return AuthorizationGrantType.PASSWORD.getValue().equals(grantType); } @Override public OAuth2ResourceOwnerPasswordAuthenticationToken buildToken(Authentication clientPrincipal, Set requestedScopes, Map additionalParameters) { return new OAuth2ResourceOwnerPasswordAuthenticationToken(AuthorizationGrantType.PASSWORD, clientPrincipal, requestedScopes, additionalParameters); } /** * 校验扩展参数 密码模式密码必须不为空 * @param request 参数列表 */ @Override public void checkParams(HttpServletRequest request) {<FILL_FUNCTION_BODY>} }
MultiValueMap<String, String> parameters = OAuth2EndpointUtils.getParameters(request); // username (REQUIRED) String username = parameters.getFirst(OAuth2ParameterNames.USERNAME); if (!StringUtils.hasText(username) || parameters.get(OAuth2ParameterNames.USERNAME).size() != 1) { OAuth2EndpointUtils.throwError(OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.USERNAME, OAuth2EndpointUtils.ACCESS_TOKEN_REQUEST_ERROR_URI); } // password (REQUIRED) String password = parameters.getFirst(OAuth2ParameterNames.PASSWORD); if (!StringUtils.hasText(password) || parameters.get(OAuth2ParameterNames.PASSWORD).size() != 1) { OAuth2EndpointUtils.throwError(OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.PASSWORD, OAuth2EndpointUtils.ACCESS_TOKEN_REQUEST_ERROR_URI); }
233
266
499
<methods>public non-sealed void <init>() ,public abstract com.pig4cloud.pig.auth.support.password.OAuth2ResourceOwnerPasswordAuthenticationToken buildToken(org.springframework.security.core.Authentication, Set<java.lang.String>, Map<java.lang.String,java.lang.Object>) ,public void checkParams(jakarta.servlet.http.HttpServletRequest) ,public org.springframework.security.core.Authentication convert(jakarta.servlet.http.HttpServletRequest) ,public abstract boolean support(java.lang.String) <variables>
pig-mesh_pig
pig/pig-auth/src/main/java/com/pig4cloud/pig/auth/support/password/OAuth2ResourceOwnerPasswordAuthenticationProvider.java
OAuth2ResourceOwnerPasswordAuthenticationProvider
buildToken
class OAuth2ResourceOwnerPasswordAuthenticationProvider extends OAuth2ResourceOwnerBaseAuthenticationProvider<OAuth2ResourceOwnerPasswordAuthenticationToken> { private static final Logger LOGGER = LogManager.getLogger(OAuth2ResourceOwnerPasswordAuthenticationProvider.class); /** * Constructs an {@code OAuth2AuthorizationCodeAuthenticationProvider} using the * provided parameters. * @param authenticationManager * @param authorizationService the authorization service * @param tokenGenerator the token generator * @since 0.2.3 */ public OAuth2ResourceOwnerPasswordAuthenticationProvider(AuthenticationManager authenticationManager, OAuth2AuthorizationService authorizationService, OAuth2TokenGenerator<? extends OAuth2Token> tokenGenerator) { super(authenticationManager, authorizationService, tokenGenerator); } @Override public UsernamePasswordAuthenticationToken buildToken(Map<String, Object> reqParameters) {<FILL_FUNCTION_BODY>} @Override public boolean supports(Class<?> authentication) { boolean supports = OAuth2ResourceOwnerPasswordAuthenticationToken.class.isAssignableFrom(authentication); LOGGER.debug("supports authentication=" + authentication + " returning " + supports); return supports; } @Override public void checkClient(RegisteredClient registeredClient) { assert registeredClient != null; if (!registeredClient.getAuthorizationGrantTypes().contains(AuthorizationGrantType.PASSWORD)) { throw new OAuth2AuthenticationException(OAuth2ErrorCodes.UNAUTHORIZED_CLIENT); } } }
String username = (String) reqParameters.get(OAuth2ParameterNames.USERNAME); String password = (String) reqParameters.get(OAuth2ParameterNames.PASSWORD); return new UsernamePasswordAuthenticationToken(username, password);
395
61
456
<methods>public void <init>(org.springframework.security.authentication.AuthenticationManager, OAuth2AuthorizationService, OAuth2TokenGenerator<? extends OAuth2Token>) ,public org.springframework.security.core.Authentication authenticate(org.springframework.security.core.Authentication) throws org.springframework.security.core.AuthenticationException,public abstract org.springframework.security.authentication.UsernamePasswordAuthenticationToken buildToken(Map<java.lang.String,java.lang.Object>) ,public abstract void checkClient(RegisteredClient) ,public void setRefreshTokenGenerator(Supplier<java.lang.String>) ,public abstract boolean supports(Class<?>) <variables>private static final java.lang.String ERROR_URI,private static final org.apache.logging.log4j.Logger LOGGER,private final non-sealed org.springframework.security.authentication.AuthenticationManager authenticationManager,private final non-sealed OAuth2AuthorizationService authorizationService,private final non-sealed org.springframework.context.support.MessageSourceAccessor messages,private Supplier<java.lang.String> refreshTokenGenerator,private final non-sealed OAuth2TokenGenerator<? extends OAuth2Token> tokenGenerator
pig-mesh_pig
pig/pig-auth/src/main/java/com/pig4cloud/pig/auth/support/sms/OAuth2ResourceOwnerSmsAuthenticationConverter.java
OAuth2ResourceOwnerSmsAuthenticationConverter
checkParams
class OAuth2ResourceOwnerSmsAuthenticationConverter extends OAuth2ResourceOwnerBaseAuthenticationConverter<OAuth2ResourceOwnerSmsAuthenticationToken> { /** * 是否支持此convert * @param grantType 授权类型 * @return */ @Override public boolean support(String grantType) { return SecurityConstants.MOBILE.equals(grantType); } @Override public OAuth2ResourceOwnerSmsAuthenticationToken buildToken(Authentication clientPrincipal, Set requestedScopes, Map additionalParameters) { return new OAuth2ResourceOwnerSmsAuthenticationToken(new AuthorizationGrantType(SecurityConstants.MOBILE), clientPrincipal, requestedScopes, additionalParameters); } /** * 校验扩展参数 密码模式密码必须不为空 * @param request 参数列表 */ @Override public void checkParams(HttpServletRequest request) {<FILL_FUNCTION_BODY>} }
MultiValueMap<String, String> parameters = OAuth2EndpointUtils.getParameters(request); // PHONE (REQUIRED) String phone = parameters.getFirst(SecurityConstants.SMS_PARAMETER_NAME); if (!StringUtils.hasText(phone) || parameters.get(SecurityConstants.SMS_PARAMETER_NAME).size() != 1) { OAuth2EndpointUtils.throwError(OAuth2ErrorCodes.INVALID_REQUEST, SecurityConstants.SMS_PARAMETER_NAME, OAuth2EndpointUtils.ACCESS_TOKEN_REQUEST_ERROR_URI); }
242
156
398
<methods>public non-sealed void <init>() ,public abstract com.pig4cloud.pig.auth.support.sms.OAuth2ResourceOwnerSmsAuthenticationToken buildToken(org.springframework.security.core.Authentication, Set<java.lang.String>, Map<java.lang.String,java.lang.Object>) ,public void checkParams(jakarta.servlet.http.HttpServletRequest) ,public org.springframework.security.core.Authentication convert(jakarta.servlet.http.HttpServletRequest) ,public abstract boolean support(java.lang.String) <variables>